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