1 package templates
2
3 import (
4 "bytes"
5 "testing"
6
7 "gotest.tools/v3/assert"
8 is "gotest.tools/v3/assert/cmp"
9 )
10
11
12 func TestParseJSONFunctions(t *testing.T) {
13 tm, err := Parse(`{{json .Ports}}`)
14 assert.NilError(t, err)
15
16 var b bytes.Buffer
17 assert.NilError(t, tm.Execute(&b, map[string]string{"Ports": "0.0.0.0:2->8/udp"}))
18 want := "\"0.0.0.0:2->8/udp\""
19 assert.Check(t, is.Equal(want, b.String()))
20 }
21
22 func TestParseStringFunctions(t *testing.T) {
23 tm, err := Parse(`{{join (split . ":") "/"}}`)
24 assert.NilError(t, err)
25
26 var b bytes.Buffer
27 assert.NilError(t, tm.Execute(&b, "text:with:colon"))
28 want := "text/with/colon"
29 assert.Check(t, is.Equal(want, b.String()))
30 }
31
32 func TestNewParse(t *testing.T) {
33 tm, err := NewParse("foo", "this is a {{ . }}")
34 assert.NilError(t, err)
35
36 var b bytes.Buffer
37 assert.NilError(t, tm.Execute(&b, "string"))
38 want := "this is a string"
39 assert.Check(t, is.Equal(want, b.String()))
40 }
41
42 func TestParseTruncateFunction(t *testing.T) {
43 source := "tupx5xzf6hvsrhnruz5cr8gwp"
44
45 testCases := []struct {
46 template string
47 expected string
48 }{
49 {
50 template: `{{truncate . 5}}`,
51 expected: "tupx5",
52 },
53 {
54 template: `{{truncate . 25}}`,
55 expected: "tupx5xzf6hvsrhnruz5cr8gwp",
56 },
57 {
58 template: `{{truncate . 30}}`,
59 expected: "tupx5xzf6hvsrhnruz5cr8gwp",
60 },
61 {
62 template: `{{pad . 3 3}}`,
63 expected: " tupx5xzf6hvsrhnruz5cr8gwp ",
64 },
65 }
66
67 for _, testCase := range testCases {
68 testCase := testCase
69
70 tm, err := Parse(testCase.template)
71 assert.NilError(t, err)
72
73 t.Run("Non Empty Source Test with template: "+testCase.template, func(t *testing.T) {
74 var b bytes.Buffer
75 assert.NilError(t, tm.Execute(&b, source))
76 assert.Check(t, is.Equal(testCase.expected, b.String()))
77 })
78
79 t.Run("Empty Source Test with template: "+testCase.template, func(t *testing.T) {
80 var c bytes.Buffer
81 assert.NilError(t, tm.Execute(&c, ""))
82 assert.Check(t, is.Equal("", c.String()))
83 })
84
85 t.Run("Nil Source Test with template: "+testCase.template, func(t *testing.T) {
86 var c bytes.Buffer
87 assert.Check(t, tm.Execute(&c, nil) != nil)
88 assert.Check(t, is.Equal("", c.String()))
89 })
90 }
91 }
92
View as plain text