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