Debian Codegraph @

tpl/internal/go_templates/htmltemplate/exec_test.go

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