1
2
3
4
5 package template
6
7 import (
8 "bytes"
9 "errors"
10 "flag"
11 "fmt"
12 "io"
13 "iter"
14 "reflect"
15 "strings"
16 "sync"
17 "testing"
18 "unsafe"
19 )
20
21 var debug = flag.Bool("debug", false, "show the errors produced by the tests")
22
23
24 type T struct {
25
26 True bool
27 I int
28 U16 uint16
29 X, S string
30 FloatZero float64
31 ComplexZero complex128
32
33 U *U
34
35 V0 V
36 V1, V2 *V
37
38 W0 W
39 W1, W2 *W
40
41 SI []int
42 SICap []int
43 SIEmpty []int
44 SB []bool
45
46 AI [3]int
47
48 MSI map[string]int
49 MSIone map[string]int
50 MSIEmpty map[string]int
51 MXI map[any]int
52 MII map[int]int
53 MI32S map[int32]string
54 MI64S map[int64]string
55 MUI32S map[uint32]string
56 MUI64S map[uint64]string
57 MI8S map[int8]string
58 MUI8S map[uint8]string
59 SMSI []map[string]int
60
61 Empty0 any
62 Empty1 any
63 Empty2 any
64 Empty3 any
65 Empty4 any
66
67 NonEmptyInterface I
68 NonEmptyInterfacePtS *I
69 NonEmptyInterfaceNil I
70 NonEmptyInterfaceTypedNil I
71
72 Str fmt.Stringer
73 Err error
74
75 PI *int
76 PS *string
77 PSI *[]int
78 NIL *int
79 UPI unsafe.Pointer
80 EmptyUPI unsafe.Pointer
81
82 BinaryFunc func(string, string) string
83 VariadicFunc func(...string) string
84 VariadicFuncInt func(int, ...string) string
85 NilOKFunc func(*int) bool
86 ErrFunc func() (string, error)
87 PanicFunc func() string
88 TooFewReturnCountFunc func()
89 TooManyReturnCountFunc func() (string, error, int)
90 InvalidReturnTypeFunc func() (string, bool)
91
92 Tmpl *Template
93
94 unexported int
95 }
96
97 type S []string
98
99 func (S) Method0() string {
100 return "M0"
101 }
102
103 type U struct {
104 V string
105 }
106
107 type V struct {
108 j int
109 }
110
111 func (v *V) String() string {
112 if v == nil {
113 return "nilV"
114 }
115 return fmt.Sprintf("<%d>", v.j)
116 }
117
118 type W struct {
119 k int
120 }
121
122 func (w *W) Error() string {
123 if w == nil {
124 return "nilW"
125 }
126 return fmt.Sprintf("[%d]", w.k)
127 }
128
129 var siVal = I(S{"a", "b"})
130
131 var tVal = &T{
132 True: true,
133 I: 17,
134 U16: 16,
135 X: "x",
136 S: "xyz",
137 U: &U{"v"},
138 V0: V{6666},
139 V1: &V{7777},
140 W0: W{888},
141 W1: &W{999},
142 SI: []int{3, 4, 5},
143 SICap: make([]int, 5, 10),
144 AI: [3]int{3, 4, 5},
145 SB: []bool{true, false},
146 MSI: map[string]int{"one": 1, "two": 2, "three": 3},
147 MSIone: map[string]int{"one": 1},
148 MXI: map[any]int{"one": 1},
149 MII: map[int]int{1: 1},
150 MI32S: map[int32]string{1: "one", 2: "two"},
151 MI64S: map[int64]string{2: "i642", 3: "i643"},
152 MUI32S: map[uint32]string{2: "u322", 3: "u323"},
153 MUI64S: map[uint64]string{2: "ui642", 3: "ui643"},
154 MI8S: map[int8]string{2: "i82", 3: "i83"},
155 MUI8S: map[uint8]string{2: "u82", 3: "u83"},
156 SMSI: []map[string]int{
157 {"one": 1, "two": 2},
158 {"eleven": 11, "twelve": 12},
159 },
160 Empty1: 3,
161 Empty2: "empty2",
162 Empty3: []int{7, 8},
163 Empty4: &U{"UinEmpty"},
164 NonEmptyInterface: &T{X: "x"},
165 NonEmptyInterfacePtS: &siVal,
166 NonEmptyInterfaceTypedNil: (*T)(nil),
167 Str: bytes.NewBuffer([]byte("foozle")),
168 Err: errors.New("erroozle"),
169 PI: newInt(23),
170 PS: newString("a string"),
171 PSI: newIntSlice(21, 22, 23),
172 UPI: newUnsafePointer(23),
173 BinaryFunc: func(a, b string) string { return fmt.Sprintf("[%s=%s]", a, b) },
174 VariadicFunc: func(s ...string) string { return fmt.Sprint("<", strings.Join(s, "+"), ">") },
175 VariadicFuncInt: func(a int, s ...string) string { return fmt.Sprint(a, "=<", strings.Join(s, "+"), ">") },
176 NilOKFunc: func(s *int) bool { return s == nil },
177 ErrFunc: func() (string, error) { return "bla", nil },
178 PanicFunc: func() string { panic("test panic") },
179 TooFewReturnCountFunc: func() {},
180 TooManyReturnCountFunc: func() (string, error, int) { return "", nil, 0 },
181 InvalidReturnTypeFunc: func() (string, bool) { return "", false },
182 Tmpl: Must(New("x").Parse("test template")),
183 }
184
185 var tSliceOfNil = []*T{nil}
186
187
188 type I interface {
189 Method0() string
190 }
191
192 var iVal I = tVal
193
194
195 func newInt(n int) *int {
196 return &n
197 }
198
199 func newUnsafePointer(n int) unsafe.Pointer {
200 return unsafe.Pointer(&n)
201 }
202
203 func newString(s string) *string {
204 return &s
205 }
206
207 func newIntSlice(n ...int) *[]int {
208 p := new([]int)
209 *p = make([]int, len(n))
210 copy(*p, n)
211 return p
212 }
213
214
215 func (t *T) Method0() string {
216 return "M0"
217 }
218
219 func (t *T) Method1(a int) int {
220 return a
221 }
222
223 func (t *T) Method2(a uint16, b string) string {
224 return fmt.Sprintf("Method2: %d %s", a, b)
225 }
226
227 func (t *T) Method3(v any) string {
228 return fmt.Sprintf("Method3: %v", v)
229 }
230
231 func (t *T) Copy() *T {
232 n := new(T)
233 *n = *t
234 return n
235 }
236
237 func (t *T) MAdd(a int, b []int) []int {
238 v := make([]int, len(b))
239 for i, x := range b {
240 v[i] = x + a
241 }
242 return v
243 }
244
245 var myError = errors.New("my error")
246
247
248 func (t *T) MyError(error bool) (bool, error) {
249 if error {
250 return true, myError
251 }
252 return false, nil
253 }
254
255
256 func (t *T) GetU() *U {
257 return t.U
258 }
259
260 func (u *U) TrueFalse(b bool) string {
261 if b {
262 return "true"
263 }
264 return ""
265 }
266
267 func typeOf(arg any) string {
268 return fmt.Sprintf("%T", arg)
269 }
270
271 type execTest struct {
272 name string
273 input string
274 output string
275 data any
276 ok bool
277 }
278
279
280
281
282 var (
283 bigInt = fmt.Sprintf("0x%x", int(1<<uint(reflect.TypeFor[int]().Bits()-1)-1))
284 bigUint = fmt.Sprintf("0x%x", uint(1<<uint(reflect.TypeFor[int]().Bits()-1)))
285 )
286
287 var execTests = []execTest{
288
289 {"empty", "", "", nil, true},
290 {"text", "some text", "some text", nil, true},
291 {"nil action", "{{nil}}", "", nil, false},
292
293
294 {"ideal int", "{{typeOf 3}}", "int", 0, true},
295 {"ideal float", "{{typeOf 1.0}}", "float64", 0, true},
296 {"ideal exp float", "{{typeOf 1e1}}", "float64", 0, true},
297 {"ideal complex", "{{typeOf 1i}}", "complex128", 0, true},
298 {"ideal int", "{{typeOf " + bigInt + "}}", "int", 0, true},
299 {"ideal too big", "{{typeOf " + bigUint + "}}", "", 0, false},
300 {"ideal nil without type", "{{nil}}", "", 0, false},
301
302
303 {".X", "-{{.X}}-", "-x-", tVal, true},
304 {".U.V", "-{{.U.V}}-", "-v-", tVal, true},
305 {".unexported", "{{.unexported}}", "", tVal, false},
306
307
308 {"map .one", "{{.MSI.one}}", "1", tVal, true},
309 {"map .two", "{{.MSI.two}}", "2", tVal, true},
310 {"map .NO", "{{.MSI.NO}}", "<no value>", tVal, true},
311 {"map .one interface", "{{.MXI.one}}", "1", tVal, true},
312 {"map .WRONG args", "{{.MSI.one 1}}", "", tVal, false},
313 {"map .WRONG type", "{{.MII.one}}", "", tVal, false},
314
315
316 {"dot int", "<{{.}}>", "<13>", 13, true},
317 {"dot uint", "<{{.}}>", "<14>", uint(14), true},
318 {"dot float", "<{{.}}>", "<15.1>", 15.1, true},
319 {"dot bool", "<{{.}}>", "<true>", true, true},
320 {"dot complex", "<{{.}}>", "<(16.2-17i)>", 16.2 - 17i, true},
321 {"dot string", "<{{.}}>", "<hello>", "hello", true},
322 {"dot slice", "<{{.}}>", "<[-1 -2 -3]>", []int{-1, -2, -3}, true},
323 {"dot map", "<{{.}}>", "<map[two:22]>", map[string]int{"two": 22}, true},
324 {"dot struct", "<{{.}}>", "<{7 seven}>", struct {
325 a int
326 b string
327 }{7, "seven"}, true},
328
329
330 {"$ int", "{{$}}", "123", 123, true},
331 {"$.I", "{{$.I}}", "17", tVal, true},
332 {"$.U.V", "{{$.U.V}}", "v", tVal, true},
333 {"declare in action", "{{$x := $.U.V}}{{$x}}", "v", tVal, true},
334 {"simple assignment", "{{$x := 2}}{{$x = 3}}{{$x}}", "3", tVal, true},
335 {"nested assignment",
336 "{{$x := 2}}{{if true}}{{$x = 3}}{{end}}{{$x}}",
337 "3", tVal, true},
338 {"nested assignment changes the last declaration",
339 "{{$x := 1}}{{if true}}{{$x := 2}}{{if true}}{{$x = 3}}{{end}}{{end}}{{$x}}",
340 "1", tVal, true},
341
342
343 {"V{6666}.String()", "-{{.V0}}-", "-<6666>-", tVal, true},
344 {"&V{7777}.String()", "-{{.V1}}-", "-<7777>-", tVal, true},
345 {"(*V)(nil).String()", "-{{.V2}}-", "-nilV-", tVal, true},
346
347
348 {"W{888}.Error()", "-{{.W0}}-", "-[888]-", tVal, true},
349 {"&W{999}.Error()", "-{{.W1}}-", "-[999]-", tVal, true},
350 {"(*W)(nil).Error()", "-{{.W2}}-", "-nilW-", tVal, true},
351
352
353 {"*int", "{{.PI}}", "23", tVal, true},
354 {"*string", "{{.PS}}", "a string", tVal, true},
355 {"*[]int", "{{.PSI}}", "[21 22 23]", tVal, true},
356 {"*[]int[1]", "{{index .PSI 1}}", "22", tVal, true},
357 {"NIL", "{{.NIL}}", "<nil>", tVal, true},
358
359
360 {"empty nil", "{{.Empty0}}", "<no value>", tVal, true},
361 {"empty with int", "{{.Empty1}}", "3", tVal, true},
362 {"empty with string", "{{.Empty2}}", "empty2", tVal, true},
363 {"empty with slice", "{{.Empty3}}", "[7 8]", tVal, true},
364 {"empty with struct", "{{.Empty4}}", "{UinEmpty}", tVal, true},
365 {"empty with struct, field", "{{.Empty4.V}}", "UinEmpty", tVal, true},
366
367
368 {"field on interface", "{{.foo}}", "<no value>", nil, true},
369 {"field on parenthesized interface", "{{(.).foo}}", "<no value>", nil, true},
370
371
372
373 {"unparenthesized non-function", "{{1 2}}", "", nil, false},
374 {"parenthesized non-function", "{{(1) 2}}", "", nil, false},
375 {"parenthesized non-function with no args", "{{(1)}}", "1", nil, true},
376
377
378 {".Method0", "-{{.Method0}}-", "-M0-", tVal, true},
379 {".Method1(1234)", "-{{.Method1 1234}}-", "-1234-", tVal, true},
380 {".Method1(.I)", "-{{.Method1 .I}}-", "-17-", tVal, true},
381 {".Method2(3, .X)", "-{{.Method2 3 .X}}-", "-Method2: 3 x-", tVal, true},
382 {".Method2(.U16, `str`)", "-{{.Method2 .U16 `str`}}-", "-Method2: 16 str-", tVal, true},
383 {".Method2(.U16, $x)", "{{if $x := .X}}-{{.Method2 .U16 $x}}{{end}}-", "-Method2: 16 x-", tVal, true},
384 {".Method3(nil constant)", "-{{.Method3 nil}}-", "-Method3: <nil>-", tVal, true},
385 {".Method3(nil value)", "-{{.Method3 .MXI.unset}}-", "-Method3: <nil>-", tVal, true},
386 {"method on var", "{{if $x := .}}-{{$x.Method2 .U16 $x.X}}{{end}}-", "-Method2: 16 x-", tVal, true},
387 {"method on chained var",
388 "{{range .MSIone}}{{if $.U.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}",
389 "true", tVal, true},
390 {"chained method",
391 "{{range .MSIone}}{{if $.GetU.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}",
392 "true", tVal, true},
393 {"chained method on variable",
394 "{{with $x := .}}{{with .SI}}{{$.GetU.TrueFalse $.True}}{{end}}{{end}}",
395 "true", tVal, true},
396 {".NilOKFunc not nil", "{{call .NilOKFunc .PI}}", "false", tVal, true},
397 {".NilOKFunc nil", "{{call .NilOKFunc nil}}", "true", tVal, true},
398 {"method on nil value from slice", "-{{range .}}{{.Method1 1234}}{{end}}-", "-1234-", tSliceOfNil, true},
399 {"method on typed nil interface value", "{{.NonEmptyInterfaceTypedNil.Method0}}", "M0", tVal, true},
400
401
402 {".BinaryFunc", "{{call .BinaryFunc `1` `2`}}", "[1=2]", tVal, true},
403 {".VariadicFunc0", "{{call .VariadicFunc}}", "<>", tVal, true},
404 {".VariadicFunc2", "{{call .VariadicFunc `he` `llo`}}", "<he+llo>", tVal, true},
405 {".VariadicFuncInt", "{{call .VariadicFuncInt 33 `he` `llo`}}", "33=<he+llo>", tVal, true},
406 {"if .BinaryFunc call", "{{ if .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{end}}", "[1=2]", tVal, true},
407 {"if not .BinaryFunc call", "{{ if not .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{else}}No{{end}}", "No", tVal, true},
408 {"Interface Call", `{{stringer .S}}`, "foozle", map[string]any{"S": bytes.NewBufferString("foozle")}, true},
409 {".ErrFunc", "{{call .ErrFunc}}", "bla", tVal, true},
410 {"call nil", "{{call nil}}", "", tVal, false},
411 {"empty call", "{{call}}", "", tVal, false},
412 {"empty call after pipe valid", "{{.ErrFunc | call}}", "bla", tVal, true},
413 {"empty call after pipe invalid", "{{1 | call}}", "", tVal, false},
414
415
416 {".BinaryFuncTooFew", "{{call .BinaryFunc `1`}}", "", tVal, false},
417 {".BinaryFuncTooMany", "{{call .BinaryFunc `1` `2` `3`}}", "", tVal, false},
418 {".BinaryFuncBad0", "{{call .BinaryFunc 1 3}}", "", tVal, false},
419 {".BinaryFuncBad1", "{{call .BinaryFunc `1` 3}}", "", tVal, false},
420 {".VariadicFuncBad0", "{{call .VariadicFunc 3}}", "", tVal, false},
421 {".VariadicFuncIntBad0", "{{call .VariadicFuncInt}}", "", tVal, false},
422 {".VariadicFuncIntBad`", "{{call .VariadicFuncInt `x`}}", "", tVal, false},
423 {".VariadicFuncNilBad", "{{call .VariadicFunc nil}}", "", tVal, false},
424
425
426 {"pipeline", "-{{.Method0 | .Method2 .U16}}-", "-Method2: 16 M0-", tVal, true},
427 {"pipeline func", "-{{call .VariadicFunc `llo` | call .VariadicFunc `he` }}-", "-<he+<llo>>-", tVal, true},
428
429
430 {"nil pipeline", "{{ .Empty0 | call .NilOKFunc }}", "true", tVal, true},
431 {"nil call arg", "{{ call .NilOKFunc .Empty0 }}", "true", tVal, true},
432 {"bad nil pipeline", "{{ .Empty0 | .VariadicFunc }}", "", tVal, false},
433
434
435 {"parens in pipeline", "{{printf `%d %d %d` (1) (2 | add 3) (add 4 (add 5 6))}}", "1 5 15", tVal, true},
436
437
438 {"parens: $ in paren", "{{($).X}}", "x", tVal, true},
439 {"parens: $.GetU in paren", "{{($.GetU).V}}", "v", tVal, true},
440 {"parens: $ in paren in pipe", "{{($ | echo).X}}", "x", tVal, true},
441 {"parens: spaces and args", `{{(makemap "up" "down" "left" "right").left}}`, "right", tVal, true},
442
443
444 {"if true", "{{if true}}TRUE{{end}}", "TRUE", tVal, true},
445 {"if false", "{{if false}}TRUE{{else}}FALSE{{end}}", "FALSE", tVal, true},
446 {"if nil", "{{if nil}}TRUE{{end}}", "", tVal, false},
447 {"if on typed nil interface value", "{{if .NonEmptyInterfaceTypedNil}}TRUE{{ end }}", "", tVal, true},
448 {"if 1", "{{if 1}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
449 {"if 0", "{{if 0}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
450 {"if 1.5", "{{if 1.5}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
451 {"if 0.0", "{{if .FloatZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
452 {"if 1.5i", "{{if 1.5i}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
453 {"if 0.0i", "{{if .ComplexZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
454 {"if nonNilPointer", "{{if .PI}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
455 {"if nilPointer", "{{if .NIL}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
456 {"if UPI", "{{if .UPI}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
457 {"if EmptyUPI", "{{if .EmptyUPI}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
458 {"if emptystring", "{{if ``}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
459 {"if string", "{{if `notempty`}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
460 {"if emptyslice", "{{if .SIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
461 {"if slice", "{{if .SI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
462 {"if emptymap", "{{if .MSIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
463 {"if map", "{{if .MSI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
464 {"if map unset", "{{if .MXI.none}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
465 {"if map not unset", "{{if not .MXI.none}}ZERO{{else}}NON-ZERO{{end}}", "ZERO", tVal, true},
466 {"if $x with $y int", "{{if $x := true}}{{with $y := .I}}{{$x}},{{$y}}{{end}}{{end}}", "true,17", tVal, true},
467 {"if $x with $x int", "{{if $x := true}}{{with $x := .I}}{{$x}},{{end}}{{$x}}{{end}}", "17,true", tVal, true},
468 {"if else if", "{{if false}}FALSE{{else if true}}TRUE{{end}}", "TRUE", tVal, true},
469 {"if else chain", "{{if eq 1 3}}1{{else if eq 2 3}}2{{else if eq 3 3}}3{{end}}", "3", tVal, true},
470
471
472 {"print", `{{print "hello, print"}}`, "hello, print", tVal, true},
473 {"print 123", `{{print 1 2 3}}`, "1 2 3", tVal, true},
474 {"print nil", `{{print nil}}`, "<nil>", tVal, true},
475 {"println", `{{println 1 2 3}}`, "1 2 3\n", tVal, true},
476 {"printf int", `{{printf "%04x" 127}}`, "007f", tVal, true},
477 {"printf float", `{{printf "%g" 3.5}}`, "3.5", tVal, true},
478 {"printf complex", `{{printf "%g" 1+7i}}`, "(1+7i)", tVal, true},
479 {"printf string", `{{printf "%s" "hello"}}`, "hello", tVal, true},
480 {"printf function", `{{printf "%#q" zeroArgs}}`, "`zeroArgs`", tVal, true},
481 {"printf field", `{{printf "%s" .U.V}}`, "v", tVal, true},
482 {"printf method", `{{printf "%s" .Method0}}`, "M0", tVal, true},
483 {"printf dot", `{{with .I}}{{printf "%d" .}}{{end}}`, "17", tVal, true},
484 {"printf var", `{{with $x := .I}}{{printf "%d" $x}}{{end}}`, "17", tVal, true},
485 {"printf lots", `{{printf "%d %s %g %s" 127 "hello" 7-3i .Method0}}`, "127 hello (7-3i) M0", tVal, true},
486
487
488 {"html", `{{html "<script>alert(\"XSS\");</script>"}}`,
489 "<script>alert("XSS");</script>", nil, true},
490 {"html pipeline", `{{printf "<script>alert(\"XSS\");</script>" | html}}`,
491 "<script>alert("XSS");</script>", nil, true},
492 {"html", `{{html .PS}}`, "a string", tVal, true},
493 {"html typed nil", `{{html .NIL}}`, "<nil>", tVal, true},
494 {"html untyped nil", `{{html .Empty0}}`, "<no value>", tVal, true},
495
496
497 {"js", `{{js .}}`, `It\'d be nice.`, `It'd be nice.`, true},
498
499
500 {"urlquery", `{{"http://www.example.org/"|urlquery}}`, "http%3A%2F%2Fwww.example.org%2F", nil, true},
501
502
503 {"not", "{{not true}} {{not false}}", "false true", nil, true},
504 {"and", "{{and false 0}} {{and 1 0}} {{and 0 true}} {{and 1 1}}", "false 0 0 1", nil, true},
505 {"or", "{{or 0 0}} {{or 1 0}} {{or 0 true}} {{or 1 1}}", "0 1 true 1", nil, true},
506 {"or short-circuit", "{{or 0 1 (die)}}", "1", nil, true},
507 {"and short-circuit", "{{and 1 0 (die)}}", "0", nil, true},
508 {"or short-circuit2", "{{or 0 0 (die)}}", "", nil, false},
509 {"and short-circuit2", "{{and 1 1 (die)}}", "", nil, false},
510 {"and pipe-true", "{{1 | and 1}}", "1", nil, true},
511 {"and pipe-false", "{{0 | and 1}}", "0", nil, true},
512 {"or pipe-true", "{{1 | or 0}}", "1", nil, true},
513 {"or pipe-false", "{{0 | or 0}}", "0", nil, true},
514 {"and undef", "{{and 1 .Unknown}}", "<no value>", nil, true},
515 {"or undef", "{{or 0 .Unknown}}", "<no value>", nil, true},
516 {"boolean if", "{{if and true 1 `hi`}}TRUE{{else}}FALSE{{end}}", "TRUE", tVal, true},
517 {"boolean if not", "{{if and true 1 `hi` | not}}TRUE{{else}}FALSE{{end}}", "FALSE", nil, true},
518 {"boolean if pipe", "{{if true | not | and 1}}TRUE{{else}}FALSE{{end}}", "FALSE", nil, true},
519
520
521 {"slice[0]", "{{index .SI 0}}", "3", tVal, true},
522 {"slice[1]", "{{index .SI 1}}", "4", tVal, true},
523 {"slice[HUGE]", "{{index .SI 10}}", "", tVal, false},
524 {"slice[WRONG]", "{{index .SI `hello`}}", "", tVal, false},
525 {"slice[nil]", "{{index .SI nil}}", "", tVal, false},
526 {"map[one]", "{{index .MSI `one`}}", "1", tVal, true},
527 {"map[two]", "{{index .MSI `two`}}", "2", tVal, true},
528 {"map[NO]", "{{index .MSI `XXX`}}", "0", tVal, true},
529 {"map[nil]", "{{index .MSI nil}}", "", tVal, false},
530 {"map[``]", "{{index .MSI ``}}", "0", tVal, true},
531 {"map[WRONG]", "{{index .MSI 10}}", "", tVal, false},
532 {"double index", "{{index .SMSI 1 `eleven`}}", "11", tVal, true},
533 {"nil[1]", "{{index nil 1}}", "", tVal, false},
534 {"map MI64S", "{{index .MI64S 2}}", "i642", tVal, true},
535 {"map MI32S", "{{index .MI32S 2}}", "two", tVal, true},
536 {"map MUI64S", "{{index .MUI64S 3}}", "ui643", tVal, true},
537 {"map MI8S", "{{index .MI8S 3}}", "i83", tVal, true},
538 {"map MUI8S", "{{index .MUI8S 2}}", "u82", tVal, true},
539 {"index of an interface field", "{{index .Empty3 0}}", "7", tVal, true},
540
541
542 {"slice[:]", "{{slice .SI}}", "[3 4 5]", tVal, true},
543 {"slice[1:]", "{{slice .SI 1}}", "[4 5]", tVal, true},
544 {"slice[1:2]", "{{slice .SI 1 2}}", "[4]", tVal, true},
545 {"slice[-1:]", "{{slice .SI -1}}", "", tVal, false},
546 {"slice[1:-2]", "{{slice .SI 1 -2}}", "", tVal, false},
547 {"slice[1:2:-1]", "{{slice .SI 1 2 -1}}", "", tVal, false},
548 {"slice[2:1]", "{{slice .SI 2 1}}", "", tVal, false},
549 {"slice[2:2:1]", "{{slice .SI 2 2 1}}", "", tVal, false},
550 {"out of range", "{{slice .SI 4 5}}", "", tVal, false},
551 {"out of range", "{{slice .SI 2 2 5}}", "", tVal, false},
552 {"len(s) < indexes < cap(s)", "{{slice .SICap 6 10}}", "[0 0 0 0]", tVal, true},
553 {"len(s) < indexes < cap(s)", "{{slice .SICap 6 10 10}}", "[0 0 0 0]", tVal, true},
554 {"indexes > cap(s)", "{{slice .SICap 10 11}}", "", tVal, false},
555 {"indexes > cap(s)", "{{slice .SICap 6 10 11}}", "", tVal, false},
556 {"array[:]", "{{slice .AI}}", "[3 4 5]", tVal, true},
557 {"array[1:]", "{{slice .AI 1}}", "[4 5]", tVal, true},
558 {"array[1:2]", "{{slice .AI 1 2}}", "[4]", tVal, true},
559 {"string[:]", "{{slice .S}}", "xyz", tVal, true},
560 {"string[0:1]", "{{slice .S 0 1}}", "x", tVal, true},
561 {"string[1:]", "{{slice .S 1}}", "yz", tVal, true},
562 {"string[1:2]", "{{slice .S 1 2}}", "y", tVal, true},
563 {"out of range", "{{slice .S 1 5}}", "", tVal, false},
564 {"3-index slice of string", "{{slice .S 1 2 2}}", "", tVal, false},
565 {"slice of an interface field", "{{slice .Empty3 0 1}}", "[7]", tVal, true},
566
567
568 {"slice", "{{len .SI}}", "3", tVal, true},
569 {"map", "{{len .MSI }}", "3", tVal, true},
570 {"len of int", "{{len 3}}", "", tVal, false},
571 {"len of nothing", "{{len .Empty0}}", "", tVal, false},
572 {"len of an interface field", "{{len .Empty3}}", "2", tVal, true},
573
574
575 {"with true", "{{with true}}{{.}}{{end}}", "true", tVal, true},
576 {"with false", "{{with false}}{{.}}{{else}}FALSE{{end}}", "FALSE", tVal, true},
577 {"with 1", "{{with 1}}{{.}}{{else}}ZERO{{end}}", "1", tVal, true},
578 {"with 0", "{{with 0}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
579 {"with 1.5", "{{with 1.5}}{{.}}{{else}}ZERO{{end}}", "1.5", tVal, true},
580 {"with 0.0", "{{with .FloatZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
581 {"with 1.5i", "{{with 1.5i}}{{.}}{{else}}ZERO{{end}}", "(0+1.5i)", tVal, true},
582 {"with 0.0i", "{{with .ComplexZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
583 {"with emptystring", "{{with ``}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
584 {"with string", "{{with `notempty`}}{{.}}{{else}}EMPTY{{end}}", "notempty", tVal, true},
585 {"with emptyslice", "{{with .SIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
586 {"with slice", "{{with .SI}}{{.}}{{else}}EMPTY{{end}}", "[3 4 5]", tVal, true},
587 {"with emptymap", "{{with .MSIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
588 {"with map", "{{with .MSIone}}{{.}}{{else}}EMPTY{{end}}", "map[one:1]", tVal, true},
589 {"with empty interface, struct field", "{{with .Empty4}}{{.V}}{{end}}", "UinEmpty", tVal, true},
590 {"with $x int", "{{with $x := .I}}{{$x}}{{end}}", "17", tVal, true},
591 {"with $x struct.U.V", "{{with $x := $}}{{$x.U.V}}{{end}}", "v", tVal, true},
592 {"with variable and action", "{{with $x := $}}{{$y := $.U.V}}{{$y}}{{end}}", "v", tVal, true},
593 {"with on typed nil interface value", "{{with .NonEmptyInterfaceTypedNil}}TRUE{{ end }}", "", tVal, true},
594 {"with else with", "{{with 0}}{{.}}{{else with true}}{{.}}{{end}}", "true", tVal, true},
595 {"with else with chain", "{{with 0}}{{.}}{{else with false}}{{.}}{{else with `notempty`}}{{.}}{{end}}", "notempty", tVal, true},
596
597
598 {"range []int", "{{range .SI}}-{{.}}-{{end}}", "-3--4--5-", tVal, true},
599 {"range empty no else", "{{range .SIEmpty}}-{{.}}-{{end}}", "", tVal, true},
600 {"range []int else", "{{range .SI}}-{{.}}-{{else}}EMPTY{{end}}", "-3--4--5-", tVal, true},
601 {"range empty else", "{{range .SIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
602 {"range []int break else", "{{range .SI}}-{{.}}-{{break}}NOTREACHED{{else}}EMPTY{{end}}", "-3-", tVal, true},
603 {"range []int continue else", "{{range .SI}}-{{.}}-{{continue}}NOTREACHED{{else}}EMPTY{{end}}", "-3--4--5-", tVal, true},
604 {"range []bool", "{{range .SB}}-{{.}}-{{end}}", "-true--false-", tVal, true},
605 {"range []int method", "{{range .SI | .MAdd .I}}-{{.}}-{{end}}", "-20--21--22-", tVal, true},
606 {"range map", "{{range .MSI}}-{{.}}-{{end}}", "-1--3--2-", tVal, true},
607 {"range empty map no else", "{{range .MSIEmpty}}-{{.}}-{{end}}", "", tVal, true},
608 {"range map else", "{{range .MSI}}-{{.}}-{{else}}EMPTY{{end}}", "-1--3--2-", tVal, true},
609 {"range empty map else", "{{range .MSIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
610 {"range empty interface", "{{range .Empty3}}-{{.}}-{{else}}EMPTY{{end}}", "-7--8-", tVal, true},
611 {"range empty nil", "{{range .Empty0}}-{{.}}-{{end}}", "", tVal, true},
612 {"range $x SI", "{{range $x := .SI}}<{{$x}}>{{end}}", "<3><4><5>", tVal, true},
613 {"range $x $y SI", "{{range $x, $y := .SI}}<{{$x}}={{$y}}>{{end}}", "<0=3><1=4><2=5>", tVal, true},
614 {"range $x MSIone", "{{range $x := .MSIone}}<{{$x}}>{{end}}", "<1>", tVal, true},
615 {"range $x $y MSIone", "{{range $x, $y := .MSIone}}<{{$x}}={{$y}}>{{end}}", "<one=1>", tVal, true},
616 {"range $x PSI", "{{range $x := .PSI}}<{{$x}}>{{end}}", "<21><22><23>", tVal, true},
617 {"declare in range", "{{range $x := .PSI}}<{{$foo:=$x}}{{$x}}>{{end}}", "<21><22><23>", tVal, true},
618 {"range count", `{{range $i, $x := count 5}}[{{$i}}]{{$x}}{{end}}`, "[0]a[1]b[2]c[3]d[4]e", tVal, true},
619 {"range nil count", `{{range $i, $x := count 0}}{{else}}empty{{end}}`, "empty", tVal, true},
620 {"range iter.Seq[int]", `{{range $i := .}}{{$i}}{{end}}`, "01", fVal1(2), true},
621 {"i = range iter.Seq[int]", `{{$i := 0}}{{range $i = .}}{{$i}}{{end}}`, "01", fVal1(2), true},
622 {"range iter.Seq[int] over two var", `{{range $i, $c := .}}{{$c}}{{end}}`, "", fVal1(2), false},
623 {"i, c := range iter.Seq2[int,int]", `{{range $i, $c := .}}{{$i}}{{$c}}{{end}}`, "0112", fVal2(2), true},
624 {"i, c = range iter.Seq2[int,int]", `{{$i := 0}}{{$c := 0}}{{range $i, $c = .}}{{$i}}{{$c}}{{end}}`, "0112", fVal2(2), true},
625 {"i = range iter.Seq2[int,int]", `{{$i := 0}}{{range $i = .}}{{$i}}{{end}}`, "01", fVal2(2), true},
626 {"i := range iter.Seq2[int,int]", `{{range $i := .}}{{$i}}{{end}}`, "01", fVal2(2), true},
627 {"i,c,x range iter.Seq2[int,int]", `{{$i := 0}}{{$c := 0}}{{$x := 0}}{{range $i, $c = .}}{{$i}}{{$c}}{{end}}`, "0112", fVal2(2), true},
628 {"i,x range iter.Seq[int]", `{{$i := 0}}{{$x := 0}}{{range $i = .}}{{$i}}{{end}}`, "01", fVal1(2), true},
629 {"range iter.Seq[int] else", `{{range $i := .}}{{$i}}{{else}}empty{{end}}`, "empty", fVal1(0), true},
630 {"range iter.Seq2[int,int] else", `{{range $i := .}}{{$i}}{{else}}empty{{end}}`, "empty", fVal2(0), true},
631 {"range int8", rangeTestInt, rangeTestData[int8](), int8(5), true},
632 {"range int16", rangeTestInt, rangeTestData[int16](), int16(5), true},
633 {"range int32", rangeTestInt, rangeTestData[int32](), int32(5), true},
634 {"range int64", rangeTestInt, rangeTestData[int64](), int64(5), true},
635 {"range int", rangeTestInt, rangeTestData[int](), int(5), true},
636 {"range uint8", rangeTestInt, rangeTestData[uint8](), uint8(5), true},
637 {"range uint16", rangeTestInt, rangeTestData[uint16](), uint16(5), true},
638 {"range uint32", rangeTestInt, rangeTestData[uint32](), uint32(5), true},
639 {"range uint64", rangeTestInt, rangeTestData[uint64](), uint64(5), true},
640 {"range uint", rangeTestInt, rangeTestData[uint](), uint(5), true},
641 {"range uintptr", rangeTestInt, rangeTestData[uintptr](), uintptr(5), true},
642 {"range uintptr(0)", `{{range $v := .}}{{print $v}}{{else}}empty{{end}}`, "empty", uintptr(0), true},
643 {"range 5", `{{range $v := 5}}{{printf "%T%d" $v $v}}{{end}}`, rangeTestData[int](), nil, true},
644
645
646 {"or as if true", `{{or .SI "slice is empty"}}`, "[3 4 5]", tVal, true},
647 {"or as if false", `{{or .SIEmpty "slice is empty"}}`, "slice is empty", tVal, true},
648
649
650 {"error method, error", "{{.MyError true}}", "", tVal, false},
651 {"error method, no error", "{{.MyError false}}", "false", tVal, true},
652
653
654 {"decimal", "{{print 1234}}", "1234", tVal, true},
655 {"decimal _", "{{print 12_34}}", "1234", tVal, true},
656 {"binary", "{{print 0b101}}", "5", tVal, true},
657 {"binary _", "{{print 0b_1_0_1}}", "5", tVal, true},
658 {"BINARY", "{{print 0B101}}", "5", tVal, true},
659 {"octal0", "{{print 0377}}", "255", tVal, true},
660 {"octal", "{{print 0o377}}", "255", tVal, true},
661 {"octal _", "{{print 0o_3_7_7}}", "255", tVal, true},
662 {"OCTAL", "{{print 0O377}}", "255", tVal, true},
663 {"hex", "{{print 0x123}}", "291", tVal, true},
664 {"hex _", "{{print 0x1_23}}", "291", tVal, true},
665 {"HEX", "{{print 0X123ABC}}", "1194684", tVal, true},
666 {"float", "{{print 123.4}}", "123.4", tVal, true},
667 {"float _", "{{print 0_0_1_2_3.4}}", "123.4", tVal, true},
668 {"hex float", "{{print +0x1.ep+2}}", "7.5", tVal, true},
669 {"hex float _", "{{print +0x_1.e_0p+0_2}}", "7.5", tVal, true},
670 {"HEX float", "{{print +0X1.EP+2}}", "7.5", tVal, true},
671 {"print multi", "{{print 1_2_3_4 7.5_00_00_00}}", "1234 7.5", tVal, true},
672 {"print multi2", "{{print 1234 0x0_1.e_0p+02}}", "1234 7.5", tVal, true},
673
674
675
676 {"bug0", "{{range .MSIone}}{{if $.Method1 .}}X{{end}}{{end}}", "X", tVal, true},
677
678
679 {"bug1", "{{.Method0}}", "M0", &iVal, true},
680
681 {"bug2", "{{$.NonEmptyInterface.Method0}}", "M0", tVal, true},
682
683 {"bug3", "{{with $}}{{.Method0}}{{end}}", "M0", tVal, true},
684
685 {"bug4", "{{if .Empty0}}non-nil{{else}}nil{{end}}", "nil", tVal, true},
686
687 {"bug5", "{{.Str}}", "foozle", tVal, true},
688 {"bug5a", "{{.Err}}", "erroozle", tVal, true},
689
690 {"bug6a", "{{vfunc .V0 .V1}}", "vfunc", tVal, true},
691 {"bug6b", "{{vfunc .V0 .V0}}", "vfunc", tVal, true},
692 {"bug6c", "{{vfunc .V1 .V0}}", "vfunc", tVal, true},
693 {"bug6d", "{{vfunc .V1 .V1}}", "vfunc", tVal, true},
694
695 {"bug7a", "{{3 2}}", "", tVal, false},
696 {"bug7b", "{{$x := 1}}{{$x 2}}", "", tVal, false},
697 {"bug7c", "{{$x := 1}}{{3 | $x}}", "", tVal, false},
698
699 {"bug8a", "{{3|oneArg}}", "", tVal, false},
700 {"bug8b", "{{4|dddArg 3}}", "", tVal, false},
701
702 {"bug9", "{{.cause}}", "neglect", map[string]string{"cause": "neglect"}, true},
703
704 {"bug10", "{{mapOfThree.three}}-{{(mapOfThree).three}}", "3-3", 0, true},
705
706 {"bug11", "{{valueString .PS}}", "", T{}, false},
707
708 {"bug12xe", "{{printf `%T` 0xef}}", "int", T{}, true},
709 {"bug12xE", "{{printf `%T` 0xEE}}", "int", T{}, true},
710 {"bug12Xe", "{{printf `%T` 0Xef}}", "int", T{}, true},
711 {"bug12XE", "{{printf `%T` 0XEE}}", "int", T{}, true},
712
713 {"bug13", "{{print (.Copy).I}}", "17", tVal, true},
714
715 {"bug14a", "{{(nil).True}}", "", tVal, false},
716 {"bug14b", "{{$x := nil}}{{$x.anything}}", "", tVal, false},
717 {"bug14c", `{{$x := (1.0)}}{{$y := ("hello")}}{{$x.anything}}{{$y.true}}`, "", tVal, false},
718
719 {"bug15", "{{valueString returnInt}}", "", tVal, false},
720
721 {"bug16a", "{{true|printf}}", "", tVal, false},
722 {"bug16b", "{{1|printf}}", "", tVal, false},
723 {"bug16c", "{{1.1|printf}}", "", tVal, false},
724 {"bug16d", "{{'x'|printf}}", "", tVal, false},
725 {"bug16e", "{{0i|printf}}", "", tVal, false},
726 {"bug16f", "{{true|twoArgs \"xxx\"}}", "", tVal, false},
727 {"bug16g", "{{\"aaa\" |twoArgs \"bbb\"}}", "twoArgs=bbbaaa", tVal, true},
728 {"bug16h", "{{1|oneArg}}", "", tVal, false},
729 {"bug16i", "{{\"aaa\"|oneArg}}", "oneArg=aaa", tVal, true},
730 {"bug16j", "{{1+2i|printf \"%v\"}}", "(1+2i)", tVal, true},
731 {"bug16k", "{{\"aaa\"|printf }}", "aaa", tVal, true},
732 {"bug17a", "{{.NonEmptyInterface.X}}", "x", tVal, true},
733 {"bug17b", "-{{.NonEmptyInterface.Method1 1234}}-", "-1234-", tVal, true},
734 {"bug17c", "{{len .NonEmptyInterfacePtS}}", "2", tVal, true},
735 {"bug17d", "{{index .NonEmptyInterfacePtS 0}}", "a", tVal, true},
736 {"bug17e", "{{range .NonEmptyInterfacePtS}}-{{.}}-{{end}}", "-a--b-", tVal, true},
737
738
739
740 {"bug18a", "{{eq . '.'}}", "true", '.', true},
741 {"bug18b", "{{eq . 'e'}}", "true", 'e', true},
742 {"bug18c", "{{eq . 'P'}}", "true", 'P', true},
743
744 {"issue56490", "{{$i := 0}}{{$x := 0}}{{range $i = .AI}}{{end}}{{$i}}", "5", tVal, true},
745 {"issue60801", "{{$k := 0}}{{$v := 0}}{{range $k, $v = .AI}}{{$k}}={{$v}} {{end}}", "0=3 1=4 2=5 ", tVal, true},
746 }
747
748 func fVal1(i int) iter.Seq[int] {
749 return func(yield func(int) bool) {
750 for v := range i {
751 if !yield(v) {
752 break
753 }
754 }
755 }
756 }
757
758 func fVal2(i int) iter.Seq2[int, int] {
759 return func(yield func(int, int) bool) {
760 for v := range i {
761 if !yield(v, v+1) {
762 break
763 }
764 }
765 }
766 }
767
768 const rangeTestInt = `{{range $v := .}}{{printf "%T%d" $v $v}}{{end}}`
769
770 func rangeTestData[T int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | uintptr]() string {
771 I := T(5)
772 var buf strings.Builder
773 for i := T(0); i < I; i++ {
774 fmt.Fprintf(&buf, "%T%d", i, i)
775 }
776 return buf.String()
777 }
778
779 func zeroArgs() string {
780 return "zeroArgs"
781 }
782
783 func oneArg(a string) string {
784 return "oneArg=" + a
785 }
786
787 func twoArgs(a, b string) string {
788 return "twoArgs=" + a + b
789 }
790
791 func dddArg(a int, b ...string) string {
792 return fmt.Sprintln(a, b)
793 }
794
795
796 func count(n int) chan string {
797 if n == 0 {
798 return nil
799 }
800 c := make(chan string)
801 go func() {
802 for i := 0; i < n; i++ {
803 c <- "abcdefghijklmnop"[i : i+1]
804 }
805 close(c)
806 }()
807 return c
808 }
809
810
811 func vfunc(V, *V) string {
812 return "vfunc"
813 }
814
815
816 func valueString(v string) string {
817 return "value is ignored"
818 }
819
820
821 func returnInt() int {
822 return 7
823 }
824
825 func add(args ...int) int {
826 sum := 0
827 for _, x := range args {
828 sum += x
829 }
830 return sum
831 }
832
833 func echo(arg any) any {
834 return arg
835 }
836
837 func makemap(arg ...string) map[string]string {
838 if len(arg)%2 != 0 {
839 panic("bad makemap")
840 }
841 m := make(map[string]string)
842 for i := 0; i < len(arg); i += 2 {
843 m[arg[i]] = arg[i+1]
844 }
845 return m
846 }
847
848 func stringer(s fmt.Stringer) string {
849 return s.String()
850 }
851
852 func mapOfThree() any {
853 return map[string]int{"three": 3}
854 }
855
856 func testExecute(execTests []execTest, template *Template, t *testing.T) {
857 b := new(strings.Builder)
858 funcs := FuncMap{
859 "add": add,
860 "count": count,
861 "dddArg": dddArg,
862 "die": func() bool { panic("die") },
863 "echo": echo,
864 "makemap": makemap,
865 "mapOfThree": mapOfThree,
866 "oneArg": oneArg,
867 "returnInt": returnInt,
868 "stringer": stringer,
869 "twoArgs": twoArgs,
870 "typeOf": typeOf,
871 "valueString": valueString,
872 "vfunc": vfunc,
873 "zeroArgs": zeroArgs,
874 }
875 for _, test := range execTests {
876 var tmpl *Template
877 var err error
878 if template == nil {
879 tmpl, err = New(test.name).Funcs(funcs).Parse(test.input)
880 } else {
881 tmpl, err = template.New(test.name).Funcs(funcs).Parse(test.input)
882 }
883 if err != nil {
884 t.Errorf("%s: parse error: %s", test.name, err)
885 continue
886 }
887 b.Reset()
888 err = tmpl.Execute(b, test.data)
889 switch {
890 case !test.ok && err == nil:
891 t.Errorf("%s: expected error; got none", test.name)
892 continue
893 case test.ok && err != nil:
894 t.Errorf("%s: unexpected execute error: %s", test.name, err)
895 continue
896 case !test.ok && err != nil:
897
898 if *debug {
899 fmt.Printf("%s: %s\n\t%s\n", test.name, test.input, err)
900 }
901 }
902 result := b.String()
903 if result != test.output {
904 t.Errorf("%s: expected\n\t%q\ngot\n\t%q", test.name, test.output, result)
905 }
906 }
907 }
908
909 func TestExecute(t *testing.T) {
910 testExecute(execTests, nil, t)
911 }
912
913 var delimPairs = []string{
914 "", "",
915 "{{", "}}",
916 "<<", ">>",
917 "|", "|",
918 "(日)", "(本)",
919 }
920
921 func TestDelims(t *testing.T) {
922 const hello = "Hello, world"
923 var value = struct{ Str string }{hello}
924 for i := 0; i < len(delimPairs); i += 2 {
925 text := ".Str"
926 left := delimPairs[i+0]
927 trueLeft := left
928 right := delimPairs[i+1]
929 trueRight := right
930 if left == "" {
931 trueLeft = "{{"
932 }
933 if right == "" {
934 trueRight = "}}"
935 }
936 text = trueLeft + text + trueRight
937
938 text += trueLeft + "/*comment*/" + trueRight
939
940 text += trueLeft + `"` + trueLeft + `"` + trueRight
941
942 tmpl, err := New("delims").Delims(left, right).Parse(text)
943 if err != nil {
944 t.Fatalf("delim %q text %q parse err %s", left, text, err)
945 }
946 var b = new(strings.Builder)
947 err = tmpl.Execute(b, value)
948 if err != nil {
949 t.Fatalf("delim %q exec err %s", left, err)
950 }
951 if b.String() != hello+trueLeft {
952 t.Errorf("expected %q got %q", hello+trueLeft, b.String())
953 }
954 }
955 }
956
957
958 func TestExecuteError(t *testing.T) {
959 b := new(bytes.Buffer)
960 tmpl := New("error")
961 _, err := tmpl.Parse("{{.MyError true}}")
962 if err != nil {
963 t.Fatalf("parse error: %s", err)
964 }
965 err = tmpl.Execute(b, tVal)
966 if err == nil {
967 t.Errorf("expected error; got none")
968 } else if !strings.Contains(err.Error(), myError.Error()) {
969 if *debug {
970 fmt.Printf("test execute error: %s\n", err)
971 }
972 t.Errorf("expected myError; got %s", err)
973 }
974 }
975
976 const execErrorText = `line 1
977 line 2
978 line 3
979 {{template "one" .}}
980 {{define "one"}}{{template "two" .}}{{end}}
981 {{define "two"}}{{template "three" .}}{{end}}
982 {{define "three"}}{{index "hi" $}}{{end}}`
983
984
985 func TestExecError(t *testing.T) {
986 tmpl, err := New("top").Parse(execErrorText)
987 if err != nil {
988 t.Fatal("parse error:", err)
989 }
990 var b bytes.Buffer
991 err = tmpl.Execute(&b, 5)
992 if err == nil {
993 t.Fatal("expected error")
994 }
995 const want = `template: top:7:20: executing "three" at <index "hi" $>: error calling index: index out of range: 5`
996 got := err.Error()
997 if got != want {
998 t.Errorf("expected\n%q\ngot\n%q", want, got)
999 }
1000 }
1001
1002 type CustomError struct{}
1003
1004 func (*CustomError) Error() string { return "heyo !" }
1005
1006
1007 func TestExecError_CustomError(t *testing.T) {
1008 failingFunc := func() (string, error) {
1009 return "", &CustomError{}
1010 }
1011 tmpl := Must(New("top").Funcs(FuncMap{
1012 "err": failingFunc,
1013 }).Parse("{{ err }}"))
1014
1015 var b bytes.Buffer
1016 err := tmpl.Execute(&b, nil)
1017
1018 if _, ok := errors.AsType[*CustomError](err); !ok {
1019 t.Fatalf("expected custom error; got %s", err)
1020 }
1021 }
1022
1023 func TestJSEscaping(t *testing.T) {
1024 testCases := []struct {
1025 in, exp string
1026 }{
1027 {`a`, `a`},
1028 {`'foo`, `\'foo`},
1029 {`Go "jump" \`, `Go \"jump\" \\`},
1030 {`Yukihiro says "今日は世界"`, `Yukihiro says \"今日は世界\"`},
1031 {"unprintable \uFFFE", `unprintable \uFFFE`},
1032 {`<html>`, `\u003Chtml\u003E`},
1033 {`no = in attributes`, `no \u003D in attributes`},
1034 {`' does not become HTML entity`, `\u0026#x27; does not become HTML entity`},
1035 }
1036 for _, tc := range testCases {
1037 s := JSEscapeString(tc.in)
1038 if s != tc.exp {
1039 t.Errorf("JS escaping [%s] got [%s] want [%s]", tc.in, s, tc.exp)
1040 }
1041 }
1042 }
1043
1044
1045
1046 type Tree struct {
1047 Val int
1048 Left, Right *Tree
1049 }
1050
1051
1052
1053 const treeTemplate = `
1054 (- define "tree" -)
1055 [
1056 (- .Val -)
1057 (- with .Left -)
1058 (template "tree" . -)
1059 (- end -)
1060 (- with .Right -)
1061 (- template "tree" . -)
1062 (- end -)
1063 ]
1064 (- end -)
1065 `
1066
1067 func TestTree(t *testing.T) {
1068 var tree = &Tree{
1069 1,
1070 &Tree{
1071 2, &Tree{
1072 3,
1073 &Tree{
1074 4, nil, nil,
1075 },
1076 nil,
1077 },
1078 &Tree{
1079 5,
1080 &Tree{
1081 6, nil, nil,
1082 },
1083 nil,
1084 },
1085 },
1086 &Tree{
1087 7,
1088 &Tree{
1089 8,
1090 &Tree{
1091 9, nil, nil,
1092 },
1093 nil,
1094 },
1095 &Tree{
1096 10,
1097 &Tree{
1098 11, nil, nil,
1099 },
1100 nil,
1101 },
1102 },
1103 }
1104 tmpl, err := New("root").Delims("(", ")").Parse(treeTemplate)
1105 if err != nil {
1106 t.Fatal("parse error:", err)
1107 }
1108 var b strings.Builder
1109 const expect = "[1[2[3[4]][5[6]]][7[8[9]][10[11]]]]"
1110
1111 err = tmpl.Lookup("tree").Execute(&b, tree)
1112 if err != nil {
1113 t.Fatal("exec error:", err)
1114 }
1115 result := b.String()
1116 if result != expect {
1117 t.Errorf("expected %q got %q", expect, result)
1118 }
1119
1120 b.Reset()
1121 err = tmpl.ExecuteTemplate(&b, "tree", tree)
1122 if err != nil {
1123 t.Fatal("exec error:", err)
1124 }
1125 result = b.String()
1126 if result != expect {
1127 t.Errorf("expected %q got %q", expect, result)
1128 }
1129 }
1130
1131 func TestExecuteOnNewTemplate(t *testing.T) {
1132
1133 New("Name").Templates()
1134
1135 new(Template).Templates()
1136 new(Template).Parse("")
1137 new(Template).New("abc").Parse("")
1138 new(Template).Execute(nil, nil)
1139 new(Template).ExecuteTemplate(nil, "XXX", nil)
1140 }
1141
1142 const testTemplates = `{{define "one"}}one{{end}}{{define "two"}}two{{end}}`
1143
1144 func TestMessageForExecuteEmpty(t *testing.T) {
1145
1146 tmpl := New("empty")
1147 var b bytes.Buffer
1148 err := tmpl.Execute(&b, 0)
1149 if err == nil {
1150 t.Fatal("expected initial error")
1151 }
1152 got := err.Error()
1153 want := `template: empty: "empty" is an incomplete or empty template`
1154 if got != want {
1155 t.Errorf("expected error %s got %s", want, got)
1156 }
1157
1158 tests, err := New("").Parse(testTemplates)
1159 if err != nil {
1160 t.Fatal(err)
1161 }
1162 tmpl.AddParseTree("secondary", tests.Tree)
1163 err = tmpl.Execute(&b, 0)
1164 if err == nil {
1165 t.Fatal("expected second error")
1166 }
1167 got = err.Error()
1168 want = `template: empty: "empty" is an incomplete or empty template`
1169 if got != want {
1170 t.Errorf("expected error %s got %s", want, got)
1171 }
1172
1173 err = tmpl.ExecuteTemplate(&b, "secondary", 0)
1174 if err != nil {
1175 t.Fatal(err)
1176 }
1177 }
1178
1179 func TestFinalForPrintf(t *testing.T) {
1180 tmpl, err := New("").Parse(`{{"x" | printf}}`)
1181 if err != nil {
1182 t.Fatal(err)
1183 }
1184 var b bytes.Buffer
1185 err = tmpl.Execute(&b, 0)
1186 if err != nil {
1187 t.Fatal(err)
1188 }
1189 }
1190
1191 type cmpTest struct {
1192 expr string
1193 truth string
1194 ok bool
1195 }
1196
1197 var cmpTests = []cmpTest{
1198 {"eq true true", "true", true},
1199 {"eq true false", "false", true},
1200 {"eq 1+2i 1+2i", "true", true},
1201 {"eq 1+2i 1+3i", "false", true},
1202 {"eq 1.5 1.5", "true", true},
1203 {"eq 1.5 2.5", "false", true},
1204 {"eq 1 1", "true", true},
1205 {"eq 1 2", "false", true},
1206 {"eq `xy` `xy`", "true", true},
1207 {"eq `xy` `xyz`", "false", true},
1208 {"eq .Uthree .Uthree", "true", true},
1209 {"eq .Uthree .Ufour", "false", true},
1210 {"eq 3 4 5 6 3", "true", true},
1211 {"eq 3 4 5 6 7", "false", true},
1212 {"ne true true", "false", true},
1213 {"ne true false", "true", true},
1214 {"ne 1+2i 1+2i", "false", true},
1215 {"ne 1+2i 1+3i", "true", true},
1216 {"ne 1.5 1.5", "false", true},
1217 {"ne 1.5 2.5", "true", true},
1218 {"ne 1 1", "false", true},
1219 {"ne 1 2", "true", true},
1220 {"ne `xy` `xy`", "false", true},
1221 {"ne `xy` `xyz`", "true", true},
1222 {"ne .Uthree .Uthree", "false", true},
1223 {"ne .Uthree .Ufour", "true", true},
1224 {"lt 1.5 1.5", "false", true},
1225 {"lt 1.5 2.5", "true", true},
1226 {"lt 1 1", "false", true},
1227 {"lt 1 2", "true", true},
1228 {"lt `xy` `xy`", "false", true},
1229 {"lt `xy` `xyz`", "true", true},
1230 {"lt .Uthree .Uthree", "false", true},
1231 {"lt .Uthree .Ufour", "true", true},
1232 {"le 1.5 1.5", "true", true},
1233 {"le 1.5 2.5", "true", true},
1234 {"le 2.5 1.5", "false", true},
1235 {"le 1 1", "true", true},
1236 {"le 1 2", "true", true},
1237 {"le 2 1", "false", true},
1238 {"le `xy` `xy`", "true", true},
1239 {"le `xy` `xyz`", "true", true},
1240 {"le `xyz` `xy`", "false", true},
1241 {"le .Uthree .Uthree", "true", true},
1242 {"le .Uthree .Ufour", "true", true},
1243 {"le .Ufour .Uthree", "false", true},
1244 {"gt 1.5 1.5", "false", true},
1245 {"gt 1.5 2.5", "false", true},
1246 {"gt 1 1", "false", true},
1247 {"gt 2 1", "true", true},
1248 {"gt 1 2", "false", true},
1249 {"gt `xy` `xy`", "false", true},
1250 {"gt `xy` `xyz`", "false", true},
1251 {"gt .Uthree .Uthree", "false", true},
1252 {"gt .Uthree .Ufour", "false", true},
1253 {"gt .Ufour .Uthree", "true", true},
1254 {"ge 1.5 1.5", "true", true},
1255 {"ge 1.5 2.5", "false", true},
1256 {"ge 2.5 1.5", "true", true},
1257 {"ge 1 1", "true", true},
1258 {"ge 1 2", "false", true},
1259 {"ge 2 1", "true", true},
1260 {"ge `xy` `xy`", "true", true},
1261 {"ge `xy` `xyz`", "false", true},
1262 {"ge `xyz` `xy`", "true", true},
1263 {"ge .Uthree .Uthree", "true", true},
1264 {"ge .Uthree .Ufour", "false", true},
1265 {"ge .Ufour .Uthree", "true", true},
1266
1267 {"eq .Uthree .Three", "true", true},
1268 {"eq .Three .Uthree", "true", true},
1269 {"le .Uthree .Three", "true", true},
1270 {"le .Three .Uthree", "true", true},
1271 {"ge .Uthree .Three", "true", true},
1272 {"ge .Three .Uthree", "true", true},
1273 {"lt .Uthree .Three", "false", true},
1274 {"lt .Three .Uthree", "false", true},
1275 {"gt .Uthree .Three", "false", true},
1276 {"gt .Three .Uthree", "false", true},
1277 {"eq .Ufour .Three", "false", true},
1278 {"lt .Ufour .Three", "false", true},
1279 {"gt .Ufour .Three", "true", true},
1280 {"eq .NegOne .Uthree", "false", true},
1281 {"eq .Uthree .NegOne", "false", true},
1282 {"ne .NegOne .Uthree", "true", true},
1283 {"ne .Uthree .NegOne", "true", true},
1284 {"lt .NegOne .Uthree", "true", true},
1285 {"lt .Uthree .NegOne", "false", true},
1286 {"le .NegOne .Uthree", "true", true},
1287 {"le .Uthree .NegOne", "false", true},
1288 {"gt .NegOne .Uthree", "false", true},
1289 {"gt .Uthree .NegOne", "true", true},
1290 {"ge .NegOne .Uthree", "false", true},
1291 {"ge .Uthree .NegOne", "true", true},
1292 {"eq (index `x` 0) 'x'", "true", true},
1293 {"eq (index `x` 0) 'y'", "false", true},
1294 {"eq .V1 .V2", "true", true},
1295 {"eq .Ptr .Ptr", "true", true},
1296 {"eq .Ptr .NilPtr", "false", true},
1297 {"eq .NilPtr .NilPtr", "true", true},
1298 {"eq .Iface1 .Iface1", "true", true},
1299 {"eq .Iface1 .NilIface", "false", true},
1300 {"eq .NilIface .NilIface", "true", true},
1301 {"eq .NilIface .Iface1", "false", true},
1302 {"eq .NilIface 0", "false", true},
1303 {"eq 0 .NilIface", "false", true},
1304 {"eq .Map .Map", "true", true},
1305 {"eq .Map nil", "true", true},
1306 {"eq nil .Map", "true", true},
1307 {"eq .Map .NonNilMap", "false", true},
1308
1309 {"eq `xy` 1", "", false},
1310 {"eq 2 2.0", "", false},
1311 {"lt true true", "", false},
1312 {"lt 1+0i 1+0i", "", false},
1313 {"eq .Ptr 1", "", false},
1314 {"eq .Ptr .NegOne", "", false},
1315 {"eq .Map .V1", "", false},
1316 {"eq .NonNilMap .NonNilMap", "", false},
1317 }
1318
1319 func TestComparison(t *testing.T) {
1320 b := new(strings.Builder)
1321 var cmpStruct = struct {
1322 Uthree, Ufour uint
1323 NegOne, Three int
1324 Ptr, NilPtr *int
1325 NonNilMap map[int]int
1326 Map map[int]int
1327 V1, V2 V
1328 Iface1, NilIface fmt.Stringer
1329 }{
1330 Uthree: 3,
1331 Ufour: 4,
1332 NegOne: -1,
1333 Three: 3,
1334 Ptr: new(int),
1335 NonNilMap: make(map[int]int),
1336 Iface1: b,
1337 }
1338 for _, test := range cmpTests {
1339 text := fmt.Sprintf("{{if %s}}true{{else}}false{{end}}", test.expr)
1340 tmpl, err := New("empty").Parse(text)
1341 if err != nil {
1342 t.Fatalf("%q: %s", test.expr, err)
1343 }
1344 b.Reset()
1345 err = tmpl.Execute(b, &cmpStruct)
1346 if test.ok && err != nil {
1347 t.Errorf("%s errored incorrectly: %s", test.expr, err)
1348 continue
1349 }
1350 if !test.ok && err == nil {
1351 t.Errorf("%s did not error", test.expr)
1352 continue
1353 }
1354 if b.String() != test.truth {
1355 t.Errorf("%s: want %s; got %s", test.expr, test.truth, b.String())
1356 }
1357 }
1358 }
1359
1360 func TestMissingMapKey(t *testing.T) {
1361 data := map[string]int{
1362 "x": 99,
1363 }
1364 tmpl, err := New("t1").Parse("{{.x}} {{.y}}")
1365 if err != nil {
1366 t.Fatal(err)
1367 }
1368 var b strings.Builder
1369
1370 err = tmpl.Execute(&b, data)
1371 if err != nil {
1372 t.Fatal(err)
1373 }
1374 want := "99 <no value>"
1375 got := b.String()
1376 if got != want {
1377 t.Errorf("got %q; expected %q", got, want)
1378 }
1379
1380 tmpl.Option("missingkey=default")
1381 b.Reset()
1382 err = tmpl.Execute(&b, data)
1383 if err != nil {
1384 t.Fatal("default:", err)
1385 }
1386 want = "99 <no value>"
1387 got = b.String()
1388 if got != want {
1389 t.Errorf("got %q; expected %q", got, want)
1390 }
1391
1392 tmpl.Option("missingkey=zero")
1393 b.Reset()
1394 err = tmpl.Execute(&b, data)
1395 if err != nil {
1396 t.Fatal("zero:", err)
1397 }
1398 want = "99 0"
1399 got = b.String()
1400 if got != want {
1401 t.Errorf("got %q; expected %q", got, want)
1402 }
1403
1404 tmpl.Option("missingkey=error")
1405 err = tmpl.Execute(&b, data)
1406 if err == nil {
1407 t.Errorf("expected error; got none")
1408 }
1409
1410 err = tmpl.Execute(&b, nil)
1411 t.Log(err)
1412 if err == nil {
1413 t.Errorf("expected error for nil-interface; got none")
1414 }
1415 }
1416
1417
1418
1419 func TestUnterminatedStringError(t *testing.T) {
1420 _, err := New("X").Parse("hello\n\n{{`unterminated\n\n\n\n}}\n some more\n\n")
1421 if err == nil {
1422 t.Fatal("expected error")
1423 }
1424 str := err.Error()
1425 if !strings.Contains(str, "X:3: unterminated raw quoted string") {
1426 t.Fatalf("unexpected error: %s", str)
1427 }
1428 }
1429
1430 const alwaysErrorText = "always be failing"
1431
1432 var alwaysError = errors.New(alwaysErrorText)
1433
1434 type ErrorWriter int
1435
1436 func (e ErrorWriter) Write(p []byte) (int, error) {
1437 return 0, alwaysError
1438 }
1439
1440 func TestExecuteGivesExecError(t *testing.T) {
1441
1442 tmpl, err := New("X").Parse("hello")
1443 if err != nil {
1444 t.Fatal(err)
1445 }
1446 err = tmpl.Execute(ErrorWriter(0), 0)
1447 if err == nil {
1448 t.Fatal("expected error; got none")
1449 }
1450 if err.Error() != alwaysErrorText {
1451 t.Errorf("expected %q error; got %q", alwaysErrorText, err)
1452 }
1453
1454 tmpl, err = New("X").Parse("hello, {{.X.Y}}")
1455 if err != nil {
1456 t.Fatal(err)
1457 }
1458 err = tmpl.Execute(io.Discard, 0)
1459 if err == nil {
1460 t.Fatal("expected error; got none")
1461 }
1462 eerr, ok := err.(ExecError)
1463 if !ok {
1464 t.Fatalf("did not expect ExecError %s", eerr)
1465 }
1466 expect := "field X in type int"
1467 if !strings.Contains(err.Error(), expect) {
1468 t.Errorf("expected %q; got %q", expect, err)
1469 }
1470 }
1471
1472 func funcNameTestFunc() int {
1473 return 0
1474 }
1475
1476 func TestGoodFuncNames(t *testing.T) {
1477 names := []string{
1478 "_",
1479 "a",
1480 "a1",
1481 "a1",
1482 "Ӵ",
1483 }
1484 for _, name := range names {
1485 tmpl := New("X").Funcs(
1486 FuncMap{
1487 name: funcNameTestFunc,
1488 },
1489 )
1490 if tmpl == nil {
1491 t.Fatalf("nil result for %q", name)
1492 }
1493 }
1494 }
1495
1496 func TestBadFuncNames(t *testing.T) {
1497 names := []string{
1498 "",
1499 "2",
1500 "a-b",
1501 }
1502 for _, name := range names {
1503 testBadFuncName(name, t)
1504 }
1505 }
1506
1507 func TestIsTrue(t *testing.T) {
1508 var nil_ptr *int
1509 var nil_chan chan int
1510 tests := []struct {
1511 v any
1512 want bool
1513 }{
1514 {1, true},
1515 {0, false},
1516 {uint8(1), true},
1517 {uint8(0), false},
1518 {float64(1.0), true},
1519 {float64(0.0), false},
1520 {complex64(1.0), true},
1521 {complex64(0.0), false},
1522 {true, true},
1523 {false, false},
1524 {[2]int{1, 2}, true},
1525 {[0]int{}, false},
1526 {[]byte("abc"), true},
1527 {[]byte(""), false},
1528 {map[string]int{"a": 1, "b": 2}, true},
1529 {map[string]int{}, false},
1530 {make(chan int), true},
1531 {nil_chan, false},
1532 {new(int), true},
1533 {nil_ptr, false},
1534 {unsafe.Pointer(new(int)), true},
1535 {unsafe.Pointer(nil_ptr), false},
1536 }
1537 for _, test_case := range tests {
1538 got, _ := IsTrue(test_case.v)
1539 if got != test_case.want {
1540 t.Fatalf("expect result %v, got %v", test_case.want, got)
1541 }
1542 }
1543 }
1544
1545 func testBadFuncName(name string, t *testing.T) {
1546 t.Helper()
1547 defer func() {
1548 recover()
1549 }()
1550 New("X").Funcs(
1551 FuncMap{
1552 name: funcNameTestFunc,
1553 },
1554 )
1555
1556
1557 t.Errorf("%q succeeded incorrectly as function name", name)
1558 }
1559
1560 func TestBlock(t *testing.T) {
1561 const (
1562 input = `a({{block "inner" .}}bar({{.}})baz{{end}})b`
1563 want = `a(bar(hello)baz)b`
1564 overlay = `{{define "inner"}}foo({{.}})bar{{end}}`
1565 want2 = `a(foo(goodbye)bar)b`
1566 )
1567 tmpl, err := New("outer").Parse(input)
1568 if err != nil {
1569 t.Fatal(err)
1570 }
1571 tmpl2, err := Must(tmpl.Clone()).Parse(overlay)
1572 if err != nil {
1573 t.Fatal(err)
1574 }
1575
1576 var buf strings.Builder
1577 if err := tmpl.Execute(&buf, "hello"); err != nil {
1578 t.Fatal(err)
1579 }
1580 if got := buf.String(); got != want {
1581 t.Errorf("got %q, want %q", got, want)
1582 }
1583
1584 buf.Reset()
1585 if err := tmpl2.Execute(&buf, "goodbye"); err != nil {
1586 t.Fatal(err)
1587 }
1588 if got := buf.String(); got != want2 {
1589 t.Errorf("got %q, want %q", got, want2)
1590 }
1591 }
1592
1593 func TestEvalFieldErrors(t *testing.T) {
1594 tests := []struct {
1595 name, src string
1596 value any
1597 want string
1598 }{
1599 {
1600
1601
1602
1603 "MissingFieldOnNil",
1604 "{{.MissingField}}",
1605 (*T)(nil),
1606 "can't evaluate field MissingField in type *template.T",
1607 },
1608 {
1609 "MissingFieldOnNonNil",
1610 "{{.MissingField}}",
1611 &T{},
1612 "can't evaluate field MissingField in type *template.T",
1613 },
1614 {
1615 "ExistingFieldOnNil",
1616 "{{.X}}",
1617 (*T)(nil),
1618 "nil pointer evaluating *template.T.X",
1619 },
1620 {
1621 "MissingKeyOnNilMap",
1622 "{{.MissingKey}}",
1623 (*map[string]string)(nil),
1624 "nil pointer evaluating *map[string]string.MissingKey",
1625 },
1626 {
1627 "MissingKeyOnNilMapPtr",
1628 "{{.MissingKey}}",
1629 (*map[string]string)(nil),
1630 "nil pointer evaluating *map[string]string.MissingKey",
1631 },
1632 {
1633 "MissingKeyOnMapPtrToNil",
1634 "{{.MissingKey}}",
1635 &map[string]string{},
1636 "<nil>",
1637 },
1638 }
1639 for _, tc := range tests {
1640 t.Run(tc.name, func(t *testing.T) {
1641 tmpl := Must(New("tmpl").Parse(tc.src))
1642 err := tmpl.Execute(io.Discard, tc.value)
1643 got := "<nil>"
1644 if err != nil {
1645 got = err.Error()
1646 }
1647 if !strings.HasSuffix(got, tc.want) {
1648 t.Fatalf("got error %q, want %q", got, tc.want)
1649 }
1650 })
1651 }
1652 }
1653
1654 func TestMaxExecDepth(t *testing.T) {
1655 if testing.Short() {
1656 t.Skip("skipping in -short mode")
1657 }
1658 tmpl := Must(New("tmpl").Parse(`{{template "tmpl" .}}`))
1659 err := tmpl.Execute(io.Discard, nil)
1660 got := "<nil>"
1661 if err != nil {
1662 got = err.Error()
1663 }
1664 const want = "exceeded maximum template depth"
1665 if !strings.Contains(got, want) {
1666 t.Errorf("got error %q; want %q", got, want)
1667 }
1668 }
1669
1670 func TestAddrOfIndex(t *testing.T) {
1671
1672
1673
1674
1675
1676 texts := []string{
1677 `{{range .}}{{.String}}{{end}}`,
1678 `{{with index . 0}}{{.String}}{{end}}`,
1679 }
1680 for _, text := range texts {
1681 tmpl := Must(New("tmpl").Parse(text))
1682 var buf strings.Builder
1683 err := tmpl.Execute(&buf, reflect.ValueOf([]V{{1}}))
1684 if err != nil {
1685 t.Fatalf("%s: Execute: %v", text, err)
1686 }
1687 if buf.String() != "<1>" {
1688 t.Fatalf("%s: template output = %q, want %q", text, &buf, "<1>")
1689 }
1690 }
1691 }
1692
1693 func TestInterfaceValues(t *testing.T) {
1694
1695
1696
1697
1698
1699
1700 tests := []struct {
1701 text string
1702 out string
1703 }{
1704 {`{{index .Nil 1}}`, "ERROR: index of untyped nil"},
1705 {`{{index .Slice 2}}`, "2"},
1706 {`{{index .Slice .Two}}`, "2"},
1707 {`{{call .Nil 1}}`, "ERROR: call of nil"},
1708 {`{{call .PlusOne 1}}`, "2"},
1709 {`{{call .PlusOne .One}}`, "2"},
1710 {`{{and (index .Slice 0) true}}`, "0"},
1711 {`{{and .Zero true}}`, "0"},
1712 {`{{and (index .Slice 1) false}}`, "false"},
1713 {`{{and .One false}}`, "false"},
1714 {`{{or (index .Slice 0) false}}`, "false"},
1715 {`{{or .Zero false}}`, "false"},
1716 {`{{or (index .Slice 1) true}}`, "1"},
1717 {`{{or .One true}}`, "1"},
1718 {`{{not (index .Slice 0)}}`, "true"},
1719 {`{{not .Zero}}`, "true"},
1720 {`{{not (index .Slice 1)}}`, "false"},
1721 {`{{not .One}}`, "false"},
1722 {`{{eq (index .Slice 0) .Zero}}`, "true"},
1723 {`{{eq (index .Slice 1) .One}}`, "true"},
1724 {`{{ne (index .Slice 0) .Zero}}`, "false"},
1725 {`{{ne (index .Slice 1) .One}}`, "false"},
1726 {`{{ge (index .Slice 0) .One}}`, "false"},
1727 {`{{ge (index .Slice 1) .Zero}}`, "true"},
1728 {`{{gt (index .Slice 0) .One}}`, "false"},
1729 {`{{gt (index .Slice 1) .Zero}}`, "true"},
1730 {`{{le (index .Slice 0) .One}}`, "true"},
1731 {`{{le (index .Slice 1) .Zero}}`, "false"},
1732 {`{{lt (index .Slice 0) .One}}`, "true"},
1733 {`{{lt (index .Slice 1) .Zero}}`, "false"},
1734 }
1735
1736 for _, tt := range tests {
1737 tmpl := Must(New("tmpl").Parse(tt.text))
1738 var buf strings.Builder
1739 err := tmpl.Execute(&buf, map[string]any{
1740 "PlusOne": func(n int) int {
1741 return n + 1
1742 },
1743 "Slice": []int{0, 1, 2, 3},
1744 "One": 1,
1745 "Two": 2,
1746 "Nil": nil,
1747 "Zero": 0,
1748 })
1749 if strings.HasPrefix(tt.out, "ERROR:") {
1750 e := strings.TrimSpace(strings.TrimPrefix(tt.out, "ERROR:"))
1751 if err == nil || !strings.Contains(err.Error(), e) {
1752 t.Errorf("%s: Execute: %v, want error %q", tt.text, err, e)
1753 }
1754 continue
1755 }
1756 if err != nil {
1757 t.Errorf("%s: Execute: %v", tt.text, err)
1758 continue
1759 }
1760 if buf.String() != tt.out {
1761 t.Errorf("%s: template output = %q, want %q", tt.text, &buf, tt.out)
1762 }
1763 }
1764 }
1765
1766
1767 func TestExecutePanicDuringCall(t *testing.T) {
1768 funcs := map[string]any{
1769 "doPanic": func() string {
1770 panic("custom panic string")
1771 },
1772 }
1773 tests := []struct {
1774 name string
1775 input string
1776 data any
1777 wantErr string
1778 }{
1779 {
1780 "direct func call panics",
1781 "{{doPanic}}", (*T)(nil),
1782 `template: t:1:2: executing "t" at <doPanic>: error calling doPanic: custom panic string`,
1783 },
1784 {
1785 "indirect func call panics",
1786 "{{call doPanic}}", (*T)(nil),
1787 `template: t:1:7: executing "t" at <doPanic>: error calling doPanic: custom panic string`,
1788 },
1789 {
1790 "direct method call panics",
1791 "{{.GetU}}", (*T)(nil),
1792 `template: t:1:2: executing "t" at <.GetU>: error calling GetU: runtime error: invalid memory address or nil pointer dereference`,
1793 },
1794 {
1795 "indirect method call panics",
1796 "{{call .GetU}}", (*T)(nil),
1797 `template: t:1:7: executing "t" at <.GetU>: error calling GetU: runtime error: invalid memory address or nil pointer dereference`,
1798 },
1799 {
1800 "func field call panics",
1801 "{{call .PanicFunc}}", tVal,
1802 `template: t:1:2: executing "t" at <call .PanicFunc>: error calling call: test panic`,
1803 },
1804 {
1805 "method call on nil interface",
1806 "{{.NonEmptyInterfaceNil.Method0}}", tVal,
1807 `template: t:1:23: executing "t" at <.NonEmptyInterfaceNil.Method0>: nil pointer evaluating template.I.Method0`,
1808 },
1809 }
1810 for _, tc := range tests {
1811 b := new(bytes.Buffer)
1812 tmpl, err := New("t").Funcs(funcs).Parse(tc.input)
1813 if err != nil {
1814 t.Fatalf("parse error: %s", err)
1815 }
1816 err = tmpl.Execute(b, tc.data)
1817 if err == nil {
1818 t.Errorf("%s: expected error; got none", tc.name)
1819 } else if !strings.Contains(err.Error(), tc.wantErr) {
1820 if *debug {
1821 fmt.Printf("%s: test execute error: %s\n", tc.name, err)
1822 }
1823 t.Errorf("%s: expected error:\n%s\ngot:\n%s", tc.name, tc.wantErr, err)
1824 }
1825 }
1826 }
1827
1828 func TestFunctionCheckDuringCall(t *testing.T) {
1829 tests := []struct {
1830 name string
1831 input string
1832 data any
1833 wantErr string
1834 }{{
1835 name: "call nothing",
1836 input: `{{call}}`,
1837 data: tVal,
1838 wantErr: "wrong number of args for call: want at least 1 got 0",
1839 },
1840 {
1841 name: "call non-function",
1842 input: "{{call .True}}",
1843 data: tVal,
1844 wantErr: "error calling call: non-function .True of type bool",
1845 },
1846 {
1847 name: "call func with wrong argument",
1848 input: "{{call .BinaryFunc 1}}",
1849 data: tVal,
1850 wantErr: "error calling call: wrong number of args for .BinaryFunc: got 1 want 2",
1851 },
1852 {
1853 name: "call variadic func with wrong argument",
1854 input: `{{call .VariadicFuncInt}}`,
1855 data: tVal,
1856 wantErr: "error calling call: wrong number of args for .VariadicFuncInt: got 0 want at least 1",
1857 },
1858 {
1859 name: "call too few return number func",
1860 input: `{{call .TooFewReturnCountFunc}}`,
1861 data: tVal,
1862 wantErr: "error calling call: function .TooFewReturnCountFunc has 0 return values; should be 1 or 2",
1863 },
1864 {
1865 name: "call too many return number func",
1866 input: `{{call .TooManyReturnCountFunc}}`,
1867 data: tVal,
1868 wantErr: "error calling call: function .TooManyReturnCountFunc has 3 return values; should be 1 or 2",
1869 },
1870 {
1871 name: "call invalid return type func",
1872 input: `{{call .InvalidReturnTypeFunc}}`,
1873 data: tVal,
1874 wantErr: "error calling call: invalid function signature for .InvalidReturnTypeFunc: second return value should be error; is bool",
1875 },
1876 {
1877 name: "call pipeline",
1878 input: `{{call (len "test")}}`,
1879 data: nil,
1880 wantErr: "error calling call: non-function len \"test\" of type int",
1881 },
1882 }
1883
1884 for _, tc := range tests {
1885 b := new(bytes.Buffer)
1886 tmpl, err := New("t").Parse(tc.input)
1887 if err != nil {
1888 t.Fatalf("parse error: %s", err)
1889 }
1890 err = tmpl.Execute(b, tc.data)
1891 if err == nil {
1892 t.Errorf("%s: expected error; got none", tc.name)
1893 } else if tc.wantErr == "" || !strings.Contains(err.Error(), tc.wantErr) {
1894 if *debug {
1895 fmt.Printf("%s: test execute error: %s\n", tc.name, err)
1896 }
1897 t.Errorf("%s: expected error:\n%s\ngot:\n%s", tc.name, tc.wantErr, err)
1898 }
1899 }
1900 }
1901
1902
1903 func TestIssue31810(t *testing.T) {
1904
1905 var b strings.Builder
1906 const text = "{{ (.) }}"
1907 tmpl, err := New("").Parse(text)
1908 if err != nil {
1909 t.Error(err)
1910 }
1911 err = tmpl.Execute(&b, "result")
1912 if err != nil {
1913 t.Error(err)
1914 }
1915 if b.String() != "result" {
1916 t.Errorf("%s got %q, expected %q", text, b.String(), "result")
1917 }
1918
1919
1920 f := func() string { return "result" }
1921 b.Reset()
1922 err = tmpl.Execute(&b, f)
1923 if err == nil {
1924 t.Error("expected error with no call, got none")
1925 }
1926
1927
1928 const textCall = "{{ (call .) }}"
1929 tmpl, err = New("").Parse(textCall)
1930 b.Reset()
1931 err = tmpl.Execute(&b, f)
1932 if err != nil {
1933 t.Error(err)
1934 }
1935 if b.String() != "result" {
1936 t.Errorf("%s got %q, expected %q", textCall, b.String(), "result")
1937 }
1938 }
1939
1940
1941 func TestIssue43065(t *testing.T) {
1942 var b bytes.Buffer
1943 tmp := Must(New("").Parse(`{{range .}}{{end}}`))
1944 ch := make(chan<- int)
1945 err := tmp.Execute(&b, ch)
1946 if err == nil {
1947 t.Error("expected err got nil")
1948 } else if !strings.Contains(err.Error(), "range over send-only channel") {
1949 t.Errorf("%s", err)
1950 }
1951 }
1952
1953
1954 func TestIssue39807(t *testing.T) {
1955 var wg sync.WaitGroup
1956
1957 tplFoo, err := New("foo").Parse(`{{ template "bar" . }}`)
1958 if err != nil {
1959 t.Error(err)
1960 }
1961
1962 tplBar, err := New("bar").Parse("bar")
1963 if err != nil {
1964 t.Error(err)
1965 }
1966
1967 gofuncs := 10
1968 numTemplates := 10
1969
1970 for i := 1; i <= gofuncs; i++ {
1971 wg.Add(1)
1972 go func() {
1973 defer wg.Done()
1974 for j := 0; j < numTemplates; j++ {
1975 _, err := tplFoo.AddParseTree(tplBar.Name(), tplBar.Tree)
1976 if err != nil {
1977 t.Error(err)
1978 }
1979 err = tplFoo.Execute(io.Discard, nil)
1980 if err != nil {
1981 t.Error(err)
1982 }
1983 }
1984 }()
1985 }
1986
1987 wg.Wait()
1988 }
1989
1990
1991
1992 func TestIssue48215(t *testing.T) {
1993 type A struct {
1994 S string
1995 }
1996 type B struct {
1997 *A
1998 }
1999 tmpl, err := New("").Parse(`{{ .S }}`)
2000 if err != nil {
2001 t.Fatal(err)
2002 }
2003 err = tmpl.Execute(io.Discard, B{})
2004
2005 if err == nil {
2006 t.Fatal("did not get error for nil embedded struct")
2007 }
2008 if !strings.Contains(err.Error(), "reflect: indirection through nil pointer to embedded struct field A") {
2009 t.Fatal(err)
2010 }
2011 }
2012
View as plain text