templates_test.go 2.6 KB

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