templates_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package templates
  2. import (
  3. "bytes"
  4. "testing"
  5. "github.com/stretchr/testify/assert"
  6. )
  7. // Github #32120
  8. func TestParseJSONFunctions(t *testing.T) {
  9. tm, err := Parse(`{{json .Ports}}`)
  10. assert.NoError(t, err)
  11. var b bytes.Buffer
  12. assert.NoError(t, tm.Execute(&b, map[string]string{"Ports": "0.0.0.0:2->8/udp"}))
  13. want := "\"0.0.0.0:2->8/udp\""
  14. assert.Equal(t, want, b.String())
  15. }
  16. func TestParseStringFunctions(t *testing.T) {
  17. tm, err := Parse(`{{join (split . ":") "/"}}`)
  18. assert.NoError(t, err)
  19. var b bytes.Buffer
  20. assert.NoError(t, tm.Execute(&b, "text:with:colon"))
  21. want := "text/with/colon"
  22. assert.Equal(t, want, b.String())
  23. }
  24. func TestNewParse(t *testing.T) {
  25. tm, err := NewParse("foo", "this is a {{ . }}")
  26. assert.NoError(t, err)
  27. var b bytes.Buffer
  28. assert.NoError(t, tm.Execute(&b, "string"))
  29. want := "this is a string"
  30. assert.Equal(t, want, b.String())
  31. }
  32. func TestParseTruncateFunction(t *testing.T) {
  33. source := "tupx5xzf6hvsrhnruz5cr8gwp"
  34. testCases := []struct {
  35. template string
  36. expected string
  37. }{
  38. {
  39. template: `{{truncate . 5}}`,
  40. expected: "tupx5",
  41. },
  42. {
  43. template: `{{truncate . 25}}`,
  44. expected: "tupx5xzf6hvsrhnruz5cr8gwp",
  45. },
  46. {
  47. template: `{{truncate . 30}}`,
  48. expected: "tupx5xzf6hvsrhnruz5cr8gwp",
  49. },
  50. }
  51. for _, testCase := range testCases {
  52. tm, err := Parse(testCase.template)
  53. assert.NoError(t, err)
  54. var b bytes.Buffer
  55. assert.NoError(t, tm.Execute(&b, source))
  56. assert.Equal(t, testCase.expected, b.String())
  57. }
  58. }