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