Debian Codegraph @

debian/go/src/github.com/gohugoio/go-i18n/v2/internal/template_test.go

raw
1 package internal
2
3 import (
4 "strings"
5 "testing"
6 texttemplate "text/template"
7
8 "github.com/gohugoio/go-i18n/v2/i18n/template"
9 )
10
11 func TestExecute(t *testing.T) {
12 tests := []struct {
13 template *Template
14 parser template.Parser
15 data interface{}
16 result string
17 err string
18 noallocs bool
19 }{
20 {
21 template: &Template{
22 Src: "hello",
23 },
24 result: "hello",
25 noallocs: true,
26 },
27 {
28 template: &Template{
29 Src: "hello {{.Noun}}",
30 },
31 data: map[string]string{
32 "Noun": "world",
33 },
34 result: "hello world",
35 },
36 {
37 template: &Template{
38 Src: "hello {{world}}",
39 },
40 parser: &template.TextParser{
41 Funcs: texttemplate.FuncMap{
42 "world": func() string {
43 return "world"
44 },
45 },
46 },
47 result: "hello world",
48 },
49 {
50 template: &Template{
51 Src: "hello {{",
52 },
53 err: "unclosed action",
54 noallocs: true,
55 },
56 }
57
58 for _, test := range tests {
59 t.Run(test.template.Src, func(t *testing.T) {
60 if test.parser == nil {
61 test.parser = &template.TextParser{}
62 }
63 result, err := test.template.Execute(test.parser, test.data)
64 if actual := str(err); !strings.Contains(str(err), test.err) {
65 t.Errorf("expected err %q to contain %q", actual, test.err)
66 }
67 if result != test.result {
68 t.Errorf("expected result %q; got %q", test.result, result)
69 }
70 allocs := testing.AllocsPerRun(10, func() {
71 _, _ = test.template.Execute(test.parser, test.data)
72 })
73 if test.noallocs && allocs > 0 {
74 t.Errorf("expected no allocations; got %f", allocs)
75 }
76 })
77 }
78 }
79
80 func str(err error) string {
81 if err == nil {
82 return ""
83 }
84 return err.Error()
85 }