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