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