|
4 | 4 | package templates
|
5 | 5 |
|
6 | 6 | import (
|
| 7 | + "html/template" |
| 8 | + "io" |
| 9 | + "strings" |
7 | 10 | "testing"
|
8 | 11 |
|
9 | 12 | "github.com/stretchr/testify/assert"
|
@@ -41,3 +44,36 @@ func TestDict(t *testing.T) {
|
41 | 44 | assert.Error(t, err)
|
42 | 45 | }
|
43 | 46 | }
|
| 47 | + |
| 48 | +func TestUtils(t *testing.T) { |
| 49 | + execTmpl := func(code string, data any) string { |
| 50 | + tmpl := template.New("test") |
| 51 | + tmpl.Funcs(template.FuncMap{"SliceUtils": NewSliceUtils, "StringUtils": NewStringUtils}) |
| 52 | + template.Must(tmpl.Parse(code)) |
| 53 | + w := &strings.Builder{} |
| 54 | + assert.NoError(t, tmpl.Execute(w, data)) |
| 55 | + return w.String() |
| 56 | + } |
| 57 | + |
| 58 | + actual := execTmpl("{{SliceUtils.Contains .Slice .Value}}", map[string]any{"Slice": []string{"a", "b"}, "Value": "a"}) |
| 59 | + assert.Equal(t, "true", actual) |
| 60 | + |
| 61 | + actual = execTmpl("{{SliceUtils.Contains .Slice .Value}}", map[string]any{"Slice": []string{"a", "b"}, "Value": "x"}) |
| 62 | + assert.Equal(t, "false", actual) |
| 63 | + |
| 64 | + actual = execTmpl("{{SliceUtils.Contains .Slice .Value}}", map[string]any{"Slice": []int64{1, 2}, "Value": int64(2)}) |
| 65 | + assert.Equal(t, "true", actual) |
| 66 | + |
| 67 | + actual = execTmpl("{{StringUtils.Contains .String .Value}}", map[string]any{"String": "abc", "Value": "b"}) |
| 68 | + assert.Equal(t, "true", actual) |
| 69 | + |
| 70 | + actual = execTmpl("{{StringUtils.Contains .String .Value}}", map[string]any{"String": "abc", "Value": "x"}) |
| 71 | + assert.Equal(t, "false", actual) |
| 72 | + |
| 73 | + tmpl := template.New("test") |
| 74 | + tmpl.Funcs(template.FuncMap{"SliceUtils": NewSliceUtils, "StringUtils": NewStringUtils}) |
| 75 | + template.Must(tmpl.Parse("{{SliceUtils.Contains .Slice .Value}}")) |
| 76 | + // error is like this: `template: test:1:12: executing "test" at <SliceUtils.Contains>: error calling Contains: ...` |
| 77 | + err := tmpl.Execute(io.Discard, map[string]any{"Slice": struct{}{}}) |
| 78 | + assert.ErrorContains(t, err, "invalid type, expected slice or array") |
| 79 | +} |
0 commit comments