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