A go template renderer based on Perl's Template Toolkit
1package gott
2
3import (
4 "testing"
5)
6
7func TestFunctionInMap(t *testing.T) {
8 renderer, err := New(nil)
9 if err != nil {
10 t.Fatalf("Failed to create renderer: %v", err)
11 }
12
13 helpers := map[string]any{
14 "mytest": func() any {
15 return "string-one"
16 },
17 "withArgs": func(args ...string) any {
18 return "args:" + args[0]
19 },
20 "requiresArgs": func(arg string) string {
21 return "got:" + arg
22 },
23 }
24
25 vars := map[string]any{
26 "h": helpers,
27 }
28
29 tests := []struct {
30 name string
31 template string
32 want string
33 }{
34 {
35 name: "function in map - bareword",
36 template: "[% h.mytest %]",
37 want: "string-one",
38 },
39 {
40 name: "function in map - explicit call",
41 template: "[% h.mytest() %]",
42 want: "string-one",
43 },
44 {
45 name: "function with args - explicit call",
46 template: "[% h.withArgs('foo') %]",
47 want: "args:foo",
48 },
49 {
50 name: "function requiring args - bareword returns empty",
51 template: "[% h.requiresArgs %]",
52 want: "",
53 },
54 {
55 name: "function requiring args - explicit call",
56 template: "[% h.requiresArgs('bar') %]",
57 want: "got:bar",
58 },
59 {
60 name: "function in condition",
61 template: "[% IF h.mytest == 'string-one' %]yes[% END %]",
62 want: "yes",
63 },
64 {
65 name: "function in expression",
66 template: "[% h.mytest %]-suffix",
67 want: "string-one-suffix",
68 },
69 }
70
71 for _, tt := range tests {
72 t.Run(tt.name, func(t *testing.T) {
73 got, err := renderer.Process(tt.template, vars)
74 if err != nil {
75 t.Fatalf("Process error: %v", err)
76 }
77 if got != tt.want {
78 t.Errorf("got %q, want %q", got, tt.want)
79 }
80 })
81 }
82}
83
84func TestFunctionInNestedMap(t *testing.T) {
85 renderer, err := New(nil)
86 if err != nil {
87 t.Fatalf("Failed to create renderer: %v", err)
88 }
89
90 nested := map[string]any{
91 "nestedFunc": func() any {
92 return "nested-value"
93 },
94 }
95
96 helpers := map[string]any{
97 "inner": nested,
98 }
99
100 vars := map[string]any{
101 "h": helpers,
102 }
103
104 tests := []struct {
105 name string
106 template string
107 want string
108 }{
109 {
110 name: "nested function - bareword",
111 template: "[% h.inner.nestedFunc %]",
112 want: "nested-value",
113 },
114 {
115 name: "nested function - explicit call",
116 template: "[% h.inner.nestedFunc() %]",
117 want: "nested-value",
118 },
119 }
120
121 for _, tt := range tests {
122 t.Run(tt.name, func(t *testing.T) {
123 got, err := renderer.Process(tt.template, vars)
124 if err != nil {
125 t.Fatalf("Process error: %v", err)
126 }
127 if got != tt.want {
128 t.Errorf("got %q, want %q", got, tt.want)
129 }
130 })
131 }
132}