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