mirror of
https://github.com/go-gitea/gitea
synced 2025-07-19 16:58:37 +00:00
Improve template helper functions: string/slice (#24266)
Follow #23328 The improvements: 1. The `contains` functions are covered by tests 2. The inconsistent behavior of `containGeneric` is replaced by `StringUtils.Contains` and `SliceUtils.Contains` 3. In the future we can move more help functions into XxxUtils to simplify the `helper.go` and reduce unnecessary global functions. FAQ: 1. Why it's called `StringUtils.Contains` but not `strings.Contains` like Golang? Because our `StringUtils` is not Golang's `strings` package. There will be our own string functions. --------- Co-authored-by: silverwind <me@silverwind.io>
This commit is contained in:
@@ -4,6 +4,9 @@
|
||||
package templates
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -41,3 +44,36 @@ func TestDict(t *testing.T) {
|
||||
assert.Error(t, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUtils(t *testing.T) {
|
||||
execTmpl := func(code string, data any) string {
|
||||
tmpl := template.New("test")
|
||||
tmpl.Funcs(template.FuncMap{"SliceUtils": NewSliceUtils, "StringUtils": NewStringUtils})
|
||||
template.Must(tmpl.Parse(code))
|
||||
w := &strings.Builder{}
|
||||
assert.NoError(t, tmpl.Execute(w, data))
|
||||
return w.String()
|
||||
}
|
||||
|
||||
actual := execTmpl("{{SliceUtils.Contains .Slice .Value}}", map[string]any{"Slice": []string{"a", "b"}, "Value": "a"})
|
||||
assert.Equal(t, "true", actual)
|
||||
|
||||
actual = execTmpl("{{SliceUtils.Contains .Slice .Value}}", map[string]any{"Slice": []string{"a", "b"}, "Value": "x"})
|
||||
assert.Equal(t, "false", actual)
|
||||
|
||||
actual = execTmpl("{{SliceUtils.Contains .Slice .Value}}", map[string]any{"Slice": []int64{1, 2}, "Value": int64(2)})
|
||||
assert.Equal(t, "true", actual)
|
||||
|
||||
actual = execTmpl("{{StringUtils.Contains .String .Value}}", map[string]any{"String": "abc", "Value": "b"})
|
||||
assert.Equal(t, "true", actual)
|
||||
|
||||
actual = execTmpl("{{StringUtils.Contains .String .Value}}", map[string]any{"String": "abc", "Value": "x"})
|
||||
assert.Equal(t, "false", actual)
|
||||
|
||||
tmpl := template.New("test")
|
||||
tmpl.Funcs(template.FuncMap{"SliceUtils": NewSliceUtils, "StringUtils": NewStringUtils})
|
||||
template.Must(tmpl.Parse("{{SliceUtils.Contains .Slice .Value}}"))
|
||||
// error is like this: `template: test:1:12: executing "test" at <SliceUtils.Contains>: error calling Contains: ...`
|
||||
err := tmpl.Execute(io.Discard, map[string]any{"Slice": struct{}{}})
|
||||
assert.ErrorContains(t, err, "invalid type, expected slice or array")
|
||||
}
|
||||
|
Reference in New Issue
Block a user