templates_test.go 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package tpl
  2. import (
  3. "encoding/json"
  4. "strings"
  5. "testing"
  6. "github.com/OliveTin/OliveTin/internal/entities"
  7. "github.com/stretchr/testify/assert"
  8. )
  9. func TestParseTemplateWithActionContext_Json(t *testing.T) {
  10. tests := []struct {
  11. name string
  12. source string
  13. ent *entities.Entity
  14. args map[string]string
  15. expectedOutput string
  16. expectError bool
  17. checkJsonOnly bool
  18. }{
  19. {
  20. name: "Arguments piped to Json",
  21. source: `echo {{ .Arguments | Json }}`,
  22. ent: nil,
  23. args: map[string]string{"value": "true", "ot_username": "alice"},
  24. expectedOutput: `echo `,
  25. expectError: false,
  26. checkJsonOnly: true,
  27. },
  28. {
  29. name: "CurrentEntity field piped to Json",
  30. source: `curl -d {{ .CurrentEntity.foo.bar | Json }}`,
  31. ent: &entities.Entity{Data: map[string]any{"foo": map[string]any{"bar": "baz"}}},
  32. args: nil,
  33. expectedOutput: `curl -d "baz"`,
  34. expectError: false,
  35. },
  36. {
  37. name: "CurrentEntity nested object piped to Json",
  38. source: `curl --json -d {{ .CurrentEntity.payload | Json }}`,
  39. ent: &entities.Entity{Data: map[string]any{"payload": map[string]any{"on": true}}},
  40. args: nil,
  41. expectedOutput: `curl --json -d {"on":true}`,
  42. expectError: false,
  43. },
  44. {
  45. name: "Single argument value as Json",
  46. source: `echo {{ .Arguments.value | Json }}`,
  47. ent: nil,
  48. args: map[string]string{"value": "hello"},
  49. expectedOutput: `echo "hello"`,
  50. expectError: false,
  51. },
  52. }
  53. for _, tt := range tests {
  54. t.Run(tt.name, func(t *testing.T) {
  55. output, err := ParseTemplateWithActionContext(tt.source, tt.ent, tt.args)
  56. if tt.expectError {
  57. assert.Error(t, err)
  58. return
  59. }
  60. assert.NoError(t, err)
  61. if tt.checkJsonOnly {
  62. assertJsonOutput(t, output, tt.expectedOutput, tt.args)
  63. } else {
  64. assert.Equal(t, tt.expectedOutput, output)
  65. }
  66. })
  67. }
  68. }
  69. func assertJsonOutput(t *testing.T, output, expectedPrefix string, args map[string]string) {
  70. t.Helper()
  71. prefix := strings.TrimSuffix(expectedPrefix, " ")
  72. assert.True(t, strings.HasPrefix(output, prefix), "output %q should start with %q", output, prefix)
  73. jsonPart := strings.TrimPrefix(output, prefix)
  74. jsonPart = strings.TrimSpace(jsonPart)
  75. var decoded map[string]string
  76. err := json.Unmarshal([]byte(jsonPart), &decoded)
  77. assert.NoError(t, err)
  78. for k, v := range args {
  79. assert.Equal(t, v, decoded[k], "decoded JSON should contain %s=%s", k, v)
  80. }
  81. assert.Len(t, decoded, len(args))
  82. }