Debian Codegraph @

tpl/internal/go_templates/texttemplate/exec_test.go

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