code.gitea.io/gitea@v1.22.3/modules/templates/util_test.go (about) 1 // Copyright 2023 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package templates 5 6 import ( 7 "html/template" 8 "io" 9 "strings" 10 "testing" 11 12 "github.com/stretchr/testify/assert" 13 ) 14 15 func TestDict(t *testing.T) { 16 type M map[string]any 17 cases := []struct { 18 args []any 19 want map[string]any 20 }{ 21 {[]any{"a", 1, "b", 2}, M{"a": 1, "b": 2}}, 22 {[]any{".", M{"base": 1}, "b", 2}, M{"base": 1, "b": 2}}, 23 {[]any{"a", 1, ".", M{"extra": 2}}, M{"a": 1, "extra": 2}}, 24 {[]any{"a", 1, ".", map[string]int{"int": 2}}, M{"a": 1, "int": 2}}, 25 {[]any{".", nil, "b", 2}, M{"b": 2}}, 26 } 27 28 for _, c := range cases { 29 got, err := dict(c.args...) 30 if assert.NoError(t, err) { 31 assert.EqualValues(t, c.want, got) 32 } 33 } 34 35 bads := []struct { 36 args []any 37 }{ 38 {[]any{"a", 1, "b"}}, 39 {[]any{1}}, 40 {[]any{struct{}{}}}, 41 } 42 for _, c := range bads { 43 _, err := dict(c.args...) 44 assert.Error(t, err) 45 } 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 }