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 var e *CustomError
1019 if !errors.As(err, &e) {
1020 t.Fatalf("expected custom error; got %s", err)
1021 }
1022 }
1023
1024 func TestJSEscaping(t *testing.T) {
1025 testCases := []struct {
1026 in, exp string
1027 }{
1028 {`a`, `a`},
1029 {`'foo`, `\'foo`},
1030 {`Go "jump" \`, `Go \"jump\" \\`},
1031 {`Yukihiro says "今日は世界"`, `Yukihiro says \"今日は世界\"`},
1032 {"unprintable \uFFFE", `unprintable \uFFFE`},
1033 {`<html>`, `\u003Chtml\u003E`},
1034 {`no = in attributes`, `no \u003D in attributes`},
1035 {`' does not become HTML entity`, `\u0026#x27; does not become HTML entity`},
1036 }
1037 for _, tc := range testCases {
1038 s := JSEscapeString(tc.in)
1039 if s != tc.exp {
1040 t.Errorf("JS escaping [%s] got [%s] want [%s]", tc.in, s, tc.exp)
1041 }
1042 }
1043 }
1044
1045
1046
1047 type Tree struct {
1048 Val int
1049 Left, Right *Tree
1050 }
1051
1052
1053
1054 const treeTemplate = `
1055 (- define "tree" -)
1056 [
1057 (- .Val -)
1058 (- with .Left -)
1059 (template "tree" . -)
1060 (- end -)
1061 (- with .Right -)
1062 (- template "tree" . -)
1063 (- end -)
1064 ]
1065 (- end -)
1066 `
1067
1068 func TestTree(t *testing.T) {
1069 var tree = &Tree{
1070 1,
1071 &Tree{
1072 2, &Tree{
1073 3,
1074 &Tree{
1075 4, nil, nil,
1076 },
1077 nil,
1078 },
1079 &Tree{
1080 5,
1081 &Tree{
1082 6, nil, nil,
1083 },
1084 nil,
1085 },
1086 },
1087 &Tree{
1088 7,
1089 &Tree{
1090 8,
1091 &Tree{
1092 9, nil, nil,
1093 },
1094 nil,
1095 },
1096 &Tree{
1097 10,
1098 &Tree{
1099 11, nil, nil,
1100 },
1101 nil,
1102 },
1103 },
1104 }
1105 tmpl, err := New("root").Delims("(", ")").Parse(treeTemplate)
1106 if err != nil {
1107 t.Fatal("parse error:", err)
1108 }
1109 var b strings.Builder
1110 const expect = "[1[2[3[4]][5[6]]][7[8[9]][10[11]]]]"
1111
1112 err = tmpl.Lookup("tree").Execute(&b, tree)
1113 if err != nil {
1114 t.Fatal("exec error:", err)
1115 }
1116 result := b.String()
1117 if result != expect {
1118 t.Errorf("expected %q got %q", expect, result)
1119 }
1120
1121 b.Reset()
1122 err = tmpl.ExecuteTemplate(&b, "tree", tree)
1123 if err != nil {
1124 t.Fatal("exec error:", err)
1125 }
1126 result = b.String()
1127 if result != expect {
1128 t.Errorf("expected %q got %q", expect, result)
1129 }
1130 }
1131
1132 func TestExecuteOnNewTemplate(t *testing.T) {
1133
1134 New("Name").Templates()
1135
1136 new(Template).Templates()
1137 new(Template).Parse("")
1138 new(Template).New("abc").Parse("")
1139 new(Template).Execute(nil, nil)
1140 new(Template).ExecuteTemplate(nil, "XXX", nil)
1141 }
1142
1143 const testTemplates = `{{define "one"}}one{{end}}{{define "two"}}two{{end}}`
1144
1145 func TestMessageForExecuteEmpty(t *testing.T) {
1146
1147 tmpl := New("empty")
1148 var b bytes.Buffer
1149 err := tmpl.Execute(&b, 0)
1150 if err == nil {
1151 t.Fatal("expected initial error")
1152 }
1153 got := err.Error()
1154 want := `template: empty: "empty" is an incomplete or empty template`
1155 if got != want {
1156 t.Errorf("expected error %s got %s", want, got)
1157 }
1158
1159 tests, err := New("").Parse(testTemplates)
1160 if err != nil {
1161 t.Fatal(err)
1162 }
1163 tmpl.AddParseTree("secondary", tests.Tree)
1164 err = tmpl.Execute(&b, 0)
1165 if err == nil {
1166 t.Fatal("expected second error")
1167 }
1168 got = err.Error()
1169 want = `template: empty: "empty" is an incomplete or empty template`
1170 if got != want {
1171 t.Errorf("expected error %s got %s", want, got)
1172 }
1173
1174 err = tmpl.ExecuteTemplate(&b, "secondary", 0)
1175 if err != nil {
1176 t.Fatal(err)
1177 }
1178 }
1179
1180 func TestFinalForPrintf(t *testing.T) {
1181 tmpl, err := New("").Parse(`{{"x" | printf}}`)
1182 if err != nil {
1183 t.Fatal(err)
1184 }
1185 var b bytes.Buffer
1186 err = tmpl.Execute(&b, 0)
1187 if err != nil {
1188 t.Fatal(err)
1189 }
1190 }
1191
1192 type cmpTest struct {
1193 expr string
1194 truth string
1195 ok bool
1196 }
1197
1198 var cmpTests = []cmpTest{
1199 {"eq true true", "true", true},
1200 {"eq true false", "false", true},
1201 {"eq 1+2i 1+2i", "true", true},
1202 {"eq 1+2i 1+3i", "false", true},
1203 {"eq 1.5 1.5", "true", true},
1204 {"eq 1.5 2.5", "false", true},
1205 {"eq 1 1", "true", true},
1206 {"eq 1 2", "false", true},
1207 {"eq `xy` `xy`", "true", true},
1208 {"eq `xy` `xyz`", "false", true},
1209 {"eq .Uthree .Uthree", "true", true},
1210 {"eq .Uthree .Ufour", "false", true},
1211 {"eq 3 4 5 6 3", "true", true},
1212 {"eq 3 4 5 6 7", "false", true},
1213 {"ne true true", "false", true},
1214 {"ne true false", "true", true},
1215 {"ne 1+2i 1+2i", "false", true},
1216 {"ne 1+2i 1+3i", "true", true},
1217 {"ne 1.5 1.5", "false", true},
1218 {"ne 1.5 2.5", "true", true},
1219 {"ne 1 1", "false", true},
1220 {"ne 1 2", "true", true},
1221 {"ne `xy` `xy`", "false", true},
1222 {"ne `xy` `xyz`", "true", true},
1223 {"ne .Uthree .Uthree", "false", true},
1224 {"ne .Uthree .Ufour", "true", true},
1225 {"lt 1.5 1.5", "false", true},
1226 {"lt 1.5 2.5", "true", true},
1227 {"lt 1 1", "false", true},
1228 {"lt 1 2", "true", true},
1229 {"lt `xy` `xy`", "false", true},
1230 {"lt `xy` `xyz`", "true", true},
1231 {"lt .Uthree .Uthree", "false", true},
1232 {"lt .Uthree .Ufour", "true", true},
1233 {"le 1.5 1.5", "true", true},
1234 {"le 1.5 2.5", "true", true},
1235 {"le 2.5 1.5", "false", true},
1236 {"le 1 1", "true", true},
1237 {"le 1 2", "true", true},
1238 {"le 2 1", "false", true},
1239 {"le `xy` `xy`", "true", true},
1240 {"le `xy` `xyz`", "true", true},
1241 {"le `xyz` `xy`", "false", true},
1242 {"le .Uthree .Uthree", "true", true},
1243 {"le .Uthree .Ufour", "true", true},
1244 {"le .Ufour .Uthree", "false", true},
1245 {"gt 1.5 1.5", "false", true},
1246 {"gt 1.5 2.5", "false", true},
1247 {"gt 1 1", "false", true},
1248 {"gt 2 1", "true", true},
1249 {"gt 1 2", "false", true},
1250 {"gt `xy` `xy`", "false", true},
1251 {"gt `xy` `xyz`", "false", true},
1252 {"gt .Uthree .Uthree", "false", true},
1253 {"gt .Uthree .Ufour", "false", true},
1254 {"gt .Ufour .Uthree", "true", true},
1255 {"ge 1.5 1.5", "true", true},
1256 {"ge 1.5 2.5", "false", true},
1257 {"ge 2.5 1.5", "true", true},
1258 {"ge 1 1", "true", true},
1259 {"ge 1 2", "false", true},
1260 {"ge 2 1", "true", true},
1261 {"ge `xy` `xy`", "true", true},
1262 {"ge `xy` `xyz`", "false", true},
1263 {"ge `xyz` `xy`", "true", true},
1264 {"ge .Uthree .Uthree", "true", true},
1265 {"ge .Uthree .Ufour", "false", true},
1266 {"ge .Ufour .Uthree", "true", true},
1267
1268 {"eq .Uthree .Three", "true", true},
1269 {"eq .Three .Uthree", "true", true},
1270 {"le .Uthree .Three", "true", true},
1271 {"le .Three .Uthree", "true", true},
1272 {"ge .Uthree .Three", "true", true},
1273 {"ge .Three .Uthree", "true", true},
1274 {"lt .Uthree .Three", "false", true},
1275 {"lt .Three .Uthree", "false", true},
1276 {"gt .Uthree .Three", "false", true},
1277 {"gt .Three .Uthree", "false", true},
1278 {"eq .Ufour .Three", "false", true},
1279 {"lt .Ufour .Three", "false", true},
1280 {"gt .Ufour .Three", "true", true},
1281 {"eq .NegOne .Uthree", "false", true},
1282 {"eq .Uthree .NegOne", "false", true},
1283 {"ne .NegOne .Uthree", "true", true},
1284 {"ne .Uthree .NegOne", "true", true},
1285 {"lt .NegOne .Uthree", "true", true},
1286 {"lt .Uthree .NegOne", "false", true},
1287 {"le .NegOne .Uthree", "true", true},
1288 {"le .Uthree .NegOne", "false", true},
1289 {"gt .NegOne .Uthree", "false", true},
1290 {"gt .Uthree .NegOne", "true", true},
1291 {"ge .NegOne .Uthree", "false", true},
1292 {"ge .Uthree .NegOne", "true", true},
1293 {"eq (index `x` 0) 'x'", "true", true},
1294 {"eq (index `x` 0) 'y'", "false", true},
1295 {"eq .V1 .V2", "true", true},
1296 {"eq .Ptr .Ptr", "true", true},
1297 {"eq .Ptr .NilPtr", "false", true},
1298 {"eq .NilPtr .NilPtr", "true", true},
1299 {"eq .Iface1 .Iface1", "true", true},
1300 {"eq .Iface1 .NilIface", "false", true},
1301 {"eq .NilIface .NilIface", "true", true},
1302 {"eq .NilIface .Iface1", "false", true},
1303 {"eq .NilIface 0", "false", true},
1304 {"eq 0 .NilIface", "false", true},
1305 {"eq .Map .Map", "true", true},
1306 {"eq .Map nil", "true", true},
1307 {"eq nil .Map", "true", true},
1308 {"eq .Map .NonNilMap", "false", true},
1309
1310 {"eq `xy` 1", "", false},
1311 {"eq 2 2.0", "", false},
1312 {"lt true true", "", false},
1313 {"lt 1+0i 1+0i", "", false},
1314 {"eq .Ptr 1", "", false},
1315 {"eq .Ptr .NegOne", "", false},
1316 {"eq .Map .V1", "", false},
1317 {"eq .NonNilMap .NonNilMap", "", false},
1318 }
1319
1320 func TestComparison(t *testing.T) {
1321 b := new(strings.Builder)
1322 var cmpStruct = struct {
1323 Uthree, Ufour uint
1324 NegOne, Three int
1325 Ptr, NilPtr *int
1326 NonNilMap map[int]int
1327 Map map[int]int
1328 V1, V2 V
1329 Iface1, NilIface fmt.Stringer
1330 }{
1331 Uthree: 3,
1332 Ufour: 4,
1333 NegOne: -1,
1334 Three: 3,
1335 Ptr: new(int),
1336 NonNilMap: make(map[int]int),
1337 Iface1: b,
1338 }
1339 for _, test := range cmpTests {
1340 text := fmt.Sprintf("{{if %s}}true{{else}}false{{end}}", test.expr)
1341 tmpl, err := New("empty").Parse(text)
1342 if err != nil {
1343 t.Fatalf("%q: %s", test.expr, err)
1344 }
1345 b.Reset()
1346 err = tmpl.Execute(b, &cmpStruct)
1347 if test.ok && err != nil {
1348 t.Errorf("%s errored incorrectly: %s", test.expr, err)
1349 continue
1350 }
1351 if !test.ok && err == nil {
1352 t.Errorf("%s did not error", test.expr)
1353 continue
1354 }
1355 if b.String() != test.truth {
1356 t.Errorf("%s: want %s; got %s", test.expr, test.truth, b.String())
1357 }
1358 }
1359 }
1360
1361 func TestMissingMapKey(t *testing.T) {
1362 data := map[string]int{
1363 "x": 99,
1364 }
1365 tmpl, err := New("t1").Parse("{{.x}} {{.y}}")
1366 if err != nil {
1367 t.Fatal(err)
1368 }
1369 var b strings.Builder
1370
1371 err = tmpl.Execute(&b, data)
1372 if err != nil {
1373 t.Fatal(err)
1374 }
1375 want := "99 <no value>"
1376 got := b.String()
1377 if got != want {
1378 t.Errorf("got %q; expected %q", got, want)
1379 }
1380
1381 tmpl.Option("missingkey=default")
1382 b.Reset()
1383 err = tmpl.Execute(&b, data)
1384 if err != nil {
1385 t.Fatal("default:", err)
1386 }
1387 want = "99 <no value>"
1388 got = b.String()
1389 if got != want {
1390 t.Errorf("got %q; expected %q", got, want)
1391 }
1392
1393 tmpl.Option("missingkey=zero")
1394 b.Reset()
1395 err = tmpl.Execute(&b, data)
1396 if err != nil {
1397 t.Fatal("zero:", err)
1398 }
1399 want = "99 0"
1400 got = b.String()
1401 if got != want {
1402 t.Errorf("got %q; expected %q", got, want)
1403 }
1404
1405 tmpl.Option("missingkey=error")
1406 err = tmpl.Execute(&b, data)
1407 if err == nil {
1408 t.Errorf("expected error; got none")
1409 }
1410
1411 err = tmpl.Execute(&b, nil)
1412 t.Log(err)
1413 if err == nil {
1414 t.Errorf("expected error for nil-interface; got none")
1415 }
1416 }
1417
1418
1419
1420 func TestUnterminatedStringError(t *testing.T) {
1421 _, err := New("X").Parse("hello\n\n{{`unterminated\n\n\n\n}}\n some more\n\n")
1422 if err == nil {
1423 t.Fatal("expected error")
1424 }
1425 str := err.Error()
1426 if !strings.Contains(str, "X:3: unterminated raw quoted string") {
1427 t.Fatalf("unexpected error: %s", str)
1428 }
1429 }
1430
1431 const alwaysErrorText = "always be failing"
1432
1433 var alwaysError = errors.New(alwaysErrorText)
1434
1435 type ErrorWriter int
1436
1437 func (e ErrorWriter) Write(p []byte) (int, error) {
1438 return 0, alwaysError
1439 }
1440
1441 func TestExecuteGivesExecError(t *testing.T) {
1442
1443 tmpl, err := New("X").Parse("hello")
1444 if err != nil {
1445 t.Fatal(err)
1446 }
1447 err = tmpl.Execute(ErrorWriter(0), 0)
1448 if err == nil {
1449 t.Fatal("expected error; got none")
1450 }
1451 if err.Error() != alwaysErrorText {
1452 t.Errorf("expected %q error; got %q", alwaysErrorText, err)
1453 }
1454
1455 tmpl, err = New("X").Parse("hello, {{.X.Y}}")
1456 if err != nil {
1457 t.Fatal(err)
1458 }
1459 err = tmpl.Execute(io.Discard, 0)
1460 if err == nil {
1461 t.Fatal("expected error; got none")
1462 }
1463 eerr, ok := err.(ExecError)
1464 if !ok {
1465 t.Fatalf("did not expect ExecError %s", eerr)
1466 }
1467 expect := "field X in type int"
1468 if !strings.Contains(err.Error(), expect) {
1469 t.Errorf("expected %q; got %q", expect, err)
1470 }
1471 }
1472
1473 func funcNameTestFunc() int {
1474 return 0
1475 }
1476
1477 func TestGoodFuncNames(t *testing.T) {
1478 names := []string{
1479 "_",
1480 "a",
1481 "a1",
1482 "a1",
1483 "Ӵ",
1484 }
1485 for _, name := range names {
1486 tmpl := New("X").Funcs(
1487 FuncMap{
1488 name: funcNameTestFunc,
1489 },
1490 )
1491 if tmpl == nil {
1492 t.Fatalf("nil result for %q", name)
1493 }
1494 }
1495 }
1496
1497 func TestBadFuncNames(t *testing.T) {
1498 names := []string{
1499 "",
1500 "2",
1501 "a-b",
1502 }
1503 for _, name := range names {
1504 testBadFuncName(name, t)
1505 }
1506 }
1507
1508 func TestIsTrue(t *testing.T) {
1509 var nil_ptr *int
1510 var nil_chan chan int
1511 tests := []struct {
1512 v any
1513 want bool
1514 }{
1515 {1, true},
1516 {0, false},
1517 {uint8(1), true},
1518 {uint8(0), false},
1519 {float64(1.0), true},
1520 {float64(0.0), false},
1521 {complex64(1.0), true},
1522 {complex64(0.0), false},
1523 {true, true},
1524 {false, false},
1525 {[2]int{1, 2}, true},
1526 {[0]int{}, false},
1527 {[]byte("abc"), true},
1528 {[]byte(""), false},
1529 {map[string]int{"a": 1, "b": 2}, true},
1530 {map[string]int{}, false},
1531 {make(chan int), true},
1532 {nil_chan, false},
1533 {new(int), true},
1534 {nil_ptr, false},
1535 {unsafe.Pointer(new(int)), true},
1536 {unsafe.Pointer(nil_ptr), false},
1537 }
1538 for _, test_case := range tests {
1539 got, _ := IsTrue(test_case.v)
1540 if got != test_case.want {
1541 t.Fatalf("expect result %v, got %v", test_case.want, got)
1542 }
1543 }
1544 }
1545
1546 func testBadFuncName(name string, t *testing.T) {
1547 t.Helper()
1548 defer func() {
1549 recover()
1550 }()
1551 New("X").Funcs(
1552 FuncMap{
1553 name: funcNameTestFunc,
1554 },
1555 )
1556
1557
1558 t.Errorf("%q succeeded incorrectly as function name", name)
1559 }
1560
1561 func TestBlock(t *testing.T) {
1562 const (
1563 input = `a({{block "inner" .}}bar({{.}})baz{{end}})b`
1564 want = `a(bar(hello)baz)b`
1565 overlay = `{{define "inner"}}foo({{.}})bar{{end}}`
1566 want2 = `a(foo(goodbye)bar)b`
1567 )
1568 tmpl, err := New("outer").Parse(input)
1569 if err != nil {
1570 t.Fatal(err)
1571 }
1572 tmpl2, err := Must(tmpl.Clone()).Parse(overlay)
1573 if err != nil {
1574 t.Fatal(err)
1575 }
1576
1577 var buf strings.Builder
1578 if err := tmpl.Execute(&buf, "hello"); err != nil {
1579 t.Fatal(err)
1580 }
1581 if got := buf.String(); got != want {
1582 t.Errorf("got %q, want %q", got, want)
1583 }
1584
1585 buf.Reset()
1586 if err := tmpl2.Execute(&buf, "goodbye"); err != nil {
1587 t.Fatal(err)
1588 }
1589 if got := buf.String(); got != want2 {
1590 t.Errorf("got %q, want %q", got, want2)
1591 }
1592 }
1593
1594 func TestEvalFieldErrors(t *testing.T) {
1595 tests := []struct {
1596 name, src string
1597 value any
1598 want string
1599 }{
1600 {
1601
1602
1603
1604 "MissingFieldOnNil",
1605 "{{.MissingField}}",
1606 (*T)(nil),
1607 "can't evaluate field MissingField in type *template.T",
1608 },
1609 {
1610 "MissingFieldOnNonNil",
1611 "{{.MissingField}}",
1612 &T{},
1613 "can't evaluate field MissingField in type *template.T",
1614 },
1615 {
1616 "ExistingFieldOnNil",
1617 "{{.X}}",
1618 (*T)(nil),
1619 "nil pointer evaluating *template.T.X",
1620 },
1621 {
1622 "MissingKeyOnNilMap",
1623 "{{.MissingKey}}",
1624 (*map[string]string)(nil),
1625 "nil pointer evaluating *map[string]string.MissingKey",
1626 },
1627 {
1628 "MissingKeyOnNilMapPtr",
1629 "{{.MissingKey}}",
1630 (*map[string]string)(nil),
1631 "nil pointer evaluating *map[string]string.MissingKey",
1632 },
1633 {
1634 "MissingKeyOnMapPtrToNil",
1635 "{{.MissingKey}}",
1636 &map[string]string{},
1637 "<nil>",
1638 },
1639 }
1640 for _, tc := range tests {
1641 t.Run(tc.name, func(t *testing.T) {
1642 tmpl := Must(New("tmpl").Parse(tc.src))
1643 err := tmpl.Execute(io.Discard, tc.value)
1644 got := "<nil>"
1645 if err != nil {
1646 got = err.Error()
1647 }
1648 if !strings.HasSuffix(got, tc.want) {
1649 t.Fatalf("got error %q, want %q", got, tc.want)
1650 }
1651 })
1652 }
1653 }
1654
1655 func TestMaxExecDepth(t *testing.T) {
1656 if testing.Short() {
1657 t.Skip("skipping in -short mode")
1658 }
1659 tmpl := Must(New("tmpl").Parse(`{{template "tmpl" .}}`))
1660 err := tmpl.Execute(io.Discard, nil)
1661 got := "<nil>"
1662 if err != nil {
1663 got = err.Error()
1664 }
1665 const want = "exceeded maximum template depth"
1666 if !strings.Contains(got, want) {
1667 t.Errorf("got error %q; want %q", got, want)
1668 }
1669 }
1670
1671 func TestAddrOfIndex(t *testing.T) {
1672
1673
1674
1675
1676
1677 texts := []string{
1678 `{{range .}}{{.String}}{{end}}`,
1679 `{{with index . 0}}{{.String}}{{end}}`,
1680 }
1681 for _, text := range texts {
1682 tmpl := Must(New("tmpl").Parse(text))
1683 var buf strings.Builder
1684 err := tmpl.Execute(&buf, reflect.ValueOf([]V{{1}}))
1685 if err != nil {
1686 t.Fatalf("%s: Execute: %v", text, err)
1687 }
1688 if buf.String() != "<1>" {
1689 t.Fatalf("%s: template output = %q, want %q", text, &buf, "<1>")
1690 }
1691 }
1692 }
1693
1694 func TestInterfaceValues(t *testing.T) {
1695
1696
1697
1698
1699
1700
1701 tests := []struct {
1702 text string
1703 out string
1704 }{
1705 {`{{index .Nil 1}}`, "ERROR: index of untyped nil"},
1706 {`{{index .Slice 2}}`, "2"},
1707 {`{{index .Slice .Two}}`, "2"},
1708 {`{{call .Nil 1}}`, "ERROR: call of nil"},
1709 {`{{call .PlusOne 1}}`, "2"},
1710 {`{{call .PlusOne .One}}`, "2"},
1711 {`{{and (index .Slice 0) true}}`, "0"},
1712 {`{{and .Zero true}}`, "0"},
1713 {`{{and (index .Slice 1) false}}`, "false"},
1714 {`{{and .One false}}`, "false"},
1715 {`{{or (index .Slice 0) false}}`, "false"},
1716 {`{{or .Zero false}}`, "false"},
1717 {`{{or (index .Slice 1) true}}`, "1"},
1718 {`{{or .One true}}`, "1"},
1719 {`{{not (index .Slice 0)}}`, "true"},
1720 {`{{not .Zero}}`, "true"},
1721 {`{{not (index .Slice 1)}}`, "false"},
1722 {`{{not .One}}`, "false"},
1723 {`{{eq (index .Slice 0) .Zero}}`, "true"},
1724 {`{{eq (index .Slice 1) .One}}`, "true"},
1725 {`{{ne (index .Slice 0) .Zero}}`, "false"},
1726 {`{{ne (index .Slice 1) .One}}`, "false"},
1727 {`{{ge (index .Slice 0) .One}}`, "false"},
1728 {`{{ge (index .Slice 1) .Zero}}`, "true"},
1729 {`{{gt (index .Slice 0) .One}}`, "false"},
1730 {`{{gt (index .Slice 1) .Zero}}`, "true"},
1731 {`{{le (index .Slice 0) .One}}`, "true"},
1732 {`{{le (index .Slice 1) .Zero}}`, "false"},
1733 {`{{lt (index .Slice 0) .One}}`, "true"},
1734 {`{{lt (index .Slice 1) .Zero}}`, "false"},
1735 }
1736
1737 for _, tt := range tests {
1738 tmpl := Must(New("tmpl").Parse(tt.text))
1739 var buf strings.Builder
1740 err := tmpl.Execute(&buf, map[string]any{
1741 "PlusOne": func(n int) int {
1742 return n + 1
1743 },
1744 "Slice": []int{0, 1, 2, 3},
1745 "One": 1,
1746 "Two": 2,
1747 "Nil": nil,
1748 "Zero": 0,
1749 })
1750 if strings.HasPrefix(tt.out, "ERROR:") {
1751 e := strings.TrimSpace(strings.TrimPrefix(tt.out, "ERROR:"))
1752 if err == nil || !strings.Contains(err.Error(), e) {
1753 t.Errorf("%s: Execute: %v, want error %q", tt.text, err, e)
1754 }
1755 continue
1756 }
1757 if err != nil {
1758 t.Errorf("%s: Execute: %v", tt.text, err)
1759 continue
1760 }
1761 if buf.String() != tt.out {
1762 t.Errorf("%s: template output = %q, want %q", tt.text, &buf, tt.out)
1763 }
1764 }
1765 }
1766
1767
1768 func TestExecutePanicDuringCall(t *testing.T) {
1769 funcs := map[string]any{
1770 "doPanic": func() string {
1771 panic("custom panic string")
1772 },
1773 }
1774 tests := []struct {
1775 name string
1776 input string
1777 data any
1778 wantErr string
1779 }{
1780 {
1781 "direct func call panics",
1782 "{{doPanic}}", (*T)(nil),
1783 `template: t:1:2: executing "t" at <doPanic>: error calling doPanic: custom panic string`,
1784 },
1785 {
1786 "indirect func call panics",
1787 "{{call doPanic}}", (*T)(nil),
1788 `template: t:1:7: executing "t" at <doPanic>: error calling doPanic: custom panic string`,
1789 },
1790 {
1791 "direct method call panics",
1792 "{{.GetU}}", (*T)(nil),
1793 `template: t:1:2: executing "t" at <.GetU>: error calling GetU: runtime error: invalid memory address or nil pointer dereference`,
1794 },
1795 {
1796 "indirect method call panics",
1797 "{{call .GetU}}", (*T)(nil),
1798 `template: t:1:7: executing "t" at <.GetU>: error calling GetU: runtime error: invalid memory address or nil pointer dereference`,
1799 },
1800 {
1801 "func field call panics",
1802 "{{call .PanicFunc}}", tVal,
1803 `template: t:1:2: executing "t" at <call .PanicFunc>: error calling call: test panic`,
1804 },
1805 {
1806 "method call on nil interface",
1807 "{{.NonEmptyInterfaceNil.Method0}}", tVal,
1808 `template: t:1:23: executing "t" at <.NonEmptyInterfaceNil.Method0>: nil pointer evaluating template.I.Method0`,
1809 },
1810 }
1811 for _, tc := range tests {
1812 b := new(bytes.Buffer)
1813 tmpl, err := New("t").Funcs(funcs).Parse(tc.input)
1814 if err != nil {
1815 t.Fatalf("parse error: %s", err)
1816 }
1817 err = tmpl.Execute(b, tc.data)
1818 if err == nil {
1819 t.Errorf("%s: expected error; got none", tc.name)
1820 } else if !strings.Contains(err.Error(), tc.wantErr) {
1821 if *debug {
1822 fmt.Printf("%s: test execute error: %s\n", tc.name, err)
1823 }
1824 t.Errorf("%s: expected error:\n%s\ngot:\n%s", tc.name, tc.wantErr, err)
1825 }
1826 }
1827 }
1828
1829 func TestFunctionCheckDuringCall(t *testing.T) {
1830 tests := []struct {
1831 name string
1832 input string
1833 data any
1834 wantErr string
1835 }{{
1836 name: "call nothing",
1837 input: `{{call}}`,
1838 data: tVal,
1839 wantErr: "wrong number of args for call: want at least 1 got 0",
1840 },
1841 {
1842 name: "call non-function",
1843 input: "{{call .True}}",
1844 data: tVal,
1845 wantErr: "error calling call: non-function .True of type bool",
1846 },
1847 {
1848 name: "call func with wrong argument",
1849 input: "{{call .BinaryFunc 1}}",
1850 data: tVal,
1851 wantErr: "error calling call: wrong number of args for .BinaryFunc: got 1 want 2",
1852 },
1853 {
1854 name: "call variadic func with wrong argument",
1855 input: `{{call .VariadicFuncInt}}`,
1856 data: tVal,
1857 wantErr: "error calling call: wrong number of args for .VariadicFuncInt: got 0 want at least 1",
1858 },
1859 {
1860 name: "call too few return number func",
1861 input: `{{call .TooFewReturnCountFunc}}`,
1862 data: tVal,
1863 wantErr: "error calling call: function .TooFewReturnCountFunc has 0 return values; should be 1 or 2",
1864 },
1865 {
1866 name: "call too many return number func",
1867 input: `{{call .TooManyReturnCountFunc}}`,
1868 data: tVal,
1869 wantErr: "error calling call: function .TooManyReturnCountFunc has 3 return values; should be 1 or 2",
1870 },
1871 {
1872 name: "call invalid return type func",
1873 input: `{{call .InvalidReturnTypeFunc}}`,
1874 data: tVal,
1875 wantErr: "error calling call: invalid function signature for .InvalidReturnTypeFunc: second return value should be error; is bool",
1876 },
1877 {
1878 name: "call pipeline",
1879 input: `{{call (len "test")}}`,
1880 data: nil,
1881 wantErr: "error calling call: non-function len \"test\" of type int",
1882 },
1883 }
1884
1885 for _, tc := range tests {
1886 b := new(bytes.Buffer)
1887 tmpl, err := New("t").Parse(tc.input)
1888 if err != nil {
1889 t.Fatalf("parse error: %s", err)
1890 }
1891 err = tmpl.Execute(b, tc.data)
1892 if err == nil {
1893 t.Errorf("%s: expected error; got none", tc.name)
1894 } else if tc.wantErr == "" || !strings.Contains(err.Error(), tc.wantErr) {
1895 if *debug {
1896 fmt.Printf("%s: test execute error: %s\n", tc.name, err)
1897 }
1898 t.Errorf("%s: expected error:\n%s\ngot:\n%s", tc.name, tc.wantErr, err)
1899 }
1900 }
1901 }
1902
1903
1904 func TestIssue31810(t *testing.T) {
1905
1906 var b strings.Builder
1907 const text = "{{ (.) }}"
1908 tmpl, err := New("").Parse(text)
1909 if err != nil {
1910 t.Error(err)
1911 }
1912 err = tmpl.Execute(&b, "result")
1913 if err != nil {
1914 t.Error(err)
1915 }
1916 if b.String() != "result" {
1917 t.Errorf("%s got %q, expected %q", text, b.String(), "result")
1918 }
1919
1920
1921 f := func() string { return "result" }
1922 b.Reset()
1923 err = tmpl.Execute(&b, f)
1924 if err == nil {
1925 t.Error("expected error with no call, got none")
1926 }
1927
1928
1929 const textCall = "{{ (call .) }}"
1930 tmpl, err = New("").Parse(textCall)
1931 b.Reset()
1932 err = tmpl.Execute(&b, f)
1933 if err != nil {
1934 t.Error(err)
1935 }
1936 if b.String() != "result" {
1937 t.Errorf("%s got %q, expected %q", textCall, b.String(), "result")
1938 }
1939 }
1940
1941
1942 func TestIssue43065(t *testing.T) {
1943 var b bytes.Buffer
1944 tmp := Must(New("").Parse(`{{range .}}{{end}}`))
1945 ch := make(chan<- int)
1946 err := tmp.Execute(&b, ch)
1947 if err == nil {
1948 t.Error("expected err got nil")
1949 } else if !strings.Contains(err.Error(), "range over send-only channel") {
1950 t.Errorf("%s", err)
1951 }
1952 }
1953
1954
1955 func TestIssue39807(t *testing.T) {
1956 var wg sync.WaitGroup
1957
1958 tplFoo, err := New("foo").Parse(`{{ template "bar" . }}`)
1959 if err != nil {
1960 t.Error(err)
1961 }
1962
1963 tplBar, err := New("bar").Parse("bar")
1964 if err != nil {
1965 t.Error(err)
1966 }
1967
1968 gofuncs := 10
1969 numTemplates := 10
1970
1971 for i := 1; i <= gofuncs; i++ {
1972 wg.Add(1)
1973 go func() {
1974 defer wg.Done()
1975 for j := 0; j < numTemplates; j++ {
1976 _, err := tplFoo.AddParseTree(tplBar.Name(), tplBar.Tree)
1977 if err != nil {
1978 t.Error(err)
1979 }
1980 err = tplFoo.Execute(io.Discard, nil)
1981 if err != nil {
1982 t.Error(err)
1983 }
1984 }
1985 }()
1986 }
1987
1988 wg.Wait()
1989 }
1990
1991
1992
1993 func TestIssue48215(t *testing.T) {
1994 type A struct {
1995 S string
1996 }
1997 type B struct {
1998 *A
1999 }
2000 tmpl, err := New("").Parse(`{{ .S }}`)
2001 if err != nil {
2002 t.Fatal(err)
2003 }
2004 err = tmpl.Execute(io.Discard, B{})
2005
2006 if err == nil {
2007 t.Fatal("did not get error for nil embedded struct")
2008 }
2009 if !strings.Contains(err.Error(), "reflect: indirection through nil pointer to embedded struct field A") {
2010 t.Fatal(err)
2011 }
2012 }
2013
View as plain text