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