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