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[interface{}]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 interface{}
63 Empty1 interface{}
64 Empty2 interface{}
65 Empty3 interface{}
66 Empty4 interface{}
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[interface{}]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 interface{}) 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 interface{}) string {
256 return fmt.Sprintf("%T", arg)
257 }
258
259 type execTest struct {
260 name string
261 input string
262 output string
263 data interface{}
264 ok bool
265 }
266
267
268
269
270 var (
271 bigInt = fmt.Sprintf("0x%x", int(1<<uint(reflect.TypeOf(0).Bits()-1)-1))
272 bigUint = fmt.Sprintf("0x%x", uint(1<<uint(reflect.TypeOf(0).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]interface{}{"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
565
566 {"range []int", "{{range .SI}}-{{.}}-{{end}}", "-3--4--5-", tVal, true},
567 {"range empty no else", "{{range .SIEmpty}}-{{.}}-{{end}}", "", tVal, true},
568 {"range []int else", "{{range .SI}}-{{.}}-{{else}}EMPTY{{end}}", "-3--4--5-", tVal, true},
569 {"range empty else", "{{range .SIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
570 {"range []bool", "{{range .SB}}-{{.}}-{{end}}", "-true--false-", tVal, true},
571 {"range []int method", "{{range .SI | .MAdd .I}}-{{.}}-{{end}}", "-20--21--22-", tVal, true},
572 {"range map", "{{range .MSI}}-{{.}}-{{end}}", "-1--3--2-", tVal, true},
573 {"range empty map no else", "{{range .MSIEmpty}}-{{.}}-{{end}}", "", tVal, true},
574 {"range map else", "{{range .MSI}}-{{.}}-{{else}}EMPTY{{end}}", "-1--3--2-", tVal, true},
575 {"range empty map else", "{{range .MSIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
576 {"range empty interface", "{{range .Empty3}}-{{.}}-{{else}}EMPTY{{end}}", "-7--8-", tVal, true},
577 {"range empty nil", "{{range .Empty0}}-{{.}}-{{end}}", "", tVal, true},
578 {"range $x SI", "{{range $x := .SI}}<{{$x}}>{{end}}", "<3><4><5>", tVal, true},
579 {"range $x $y SI", "{{range $x, $y := .SI}}<{{$x}}={{$y}}>{{end}}", "<0=3><1=4><2=5>", tVal, true},
580 {"range $x MSIone", "{{range $x := .MSIone}}<{{$x}}>{{end}}", "<1>", tVal, true},
581 {"range $x $y MSIone", "{{range $x, $y := .MSIone}}<{{$x}}={{$y}}>{{end}}", "<one=1>", tVal, true},
582 {"range $x PSI", "{{range $x := .PSI}}<{{$x}}>{{end}}", "<21><22><23>", tVal, true},
583 {"declare in range", "{{range $x := .PSI}}<{{$foo:=$x}}{{$x}}>{{end}}", "<21><22><23>", tVal, true},
584 {"range count", `{{range $i, $x := count 5}}[{{$i}}]{{$x}}{{end}}`, "[0]a[1]b[2]c[3]d[4]e", tVal, true},
585 {"range nil count", `{{range $i, $x := count 0}}{{else}}empty{{end}}`, "empty", tVal, true},
586
587
588 {"or as if true", `{{or .SI "slice is empty"}}`, "[3 4 5]", tVal, true},
589 {"or as if false", `{{or .SIEmpty "slice is empty"}}`, "slice is empty", tVal, true},
590
591
592 {"error method, error", "{{.MyError true}}", "", tVal, false},
593 {"error method, no error", "{{.MyError false}}", "false", tVal, true},
594
595
596 {"decimal", "{{print 1234}}", "1234", tVal, true},
597 {"decimal _", "{{print 12_34}}", "1234", tVal, true},
598 {"binary", "{{print 0b101}}", "5", tVal, true},
599 {"binary _", "{{print 0b_1_0_1}}", "5", tVal, true},
600 {"BINARY", "{{print 0B101}}", "5", tVal, true},
601 {"octal0", "{{print 0377}}", "255", tVal, true},
602 {"octal", "{{print 0o377}}", "255", tVal, true},
603 {"octal _", "{{print 0o_3_7_7}}", "255", tVal, true},
604 {"OCTAL", "{{print 0O377}}", "255", tVal, true},
605 {"hex", "{{print 0x123}}", "291", tVal, true},
606 {"hex _", "{{print 0x1_23}}", "291", tVal, true},
607 {"HEX", "{{print 0X123ABC}}", "1194684", tVal, true},
608 {"float", "{{print 123.4}}", "123.4", tVal, true},
609 {"float _", "{{print 0_0_1_2_3.4}}", "123.4", tVal, true},
610 {"hex float", "{{print +0x1.ep+2}}", "7.5", tVal, true},
611 {"hex float _", "{{print +0x_1.e_0p+0_2}}", "7.5", tVal, true},
612 {"HEX float", "{{print +0X1.EP+2}}", "7.5", tVal, true},
613 {"print multi", "{{print 1_2_3_4 7.5_00_00_00}}", "1234 7.5", tVal, true},
614 {"print multi2", "{{print 1234 0x0_1.e_0p+02}}", "1234 7.5", tVal, true},
615
616
617
618 {"bug0", "{{range .MSIone}}{{if $.Method1 .}}X{{end}}{{end}}", "X", tVal, true},
619
620
621 {"bug1", "{{.Method0}}", "M0", &iVal, true},
622
623 {"bug2", "{{$.NonEmptyInterface.Method0}}", "M0", tVal, true},
624
625 {"bug3", "{{with $}}{{.Method0}}{{end}}", "M0", tVal, true},
626
627 {"bug4", "{{if .Empty0}}non-nil{{else}}nil{{end}}", "nil", tVal, true},
628
629 {"bug5", "{{.Str}}", "foozle", tVal, true},
630 {"bug5a", "{{.Err}}", "erroozle", tVal, true},
631
632 {"bug6a", "{{vfunc .V0 .V1}}", "vfunc", tVal, true},
633 {"bug6b", "{{vfunc .V0 .V0}}", "vfunc", tVal, true},
634 {"bug6c", "{{vfunc .V1 .V0}}", "vfunc", tVal, true},
635 {"bug6d", "{{vfunc .V1 .V1}}", "vfunc", tVal, true},
636
637 {"bug7a", "{{3 2}}", "", tVal, false},
638 {"bug7b", "{{$x := 1}}{{$x 2}}", "", tVal, false},
639 {"bug7c", "{{$x := 1}}{{3 | $x}}", "", tVal, false},
640
641 {"bug8a", "{{3|oneArg}}", "", tVal, false},
642 {"bug8b", "{{4|dddArg 3}}", "", tVal, false},
643
644 {"bug9", "{{.cause}}", "neglect", map[string]string{"cause": "neglect"}, true},
645
646 {"bug10", "{{mapOfThree.three}}-{{(mapOfThree).three}}", "3-3", 0, true},
647
648 {"bug11", "{{valueString .PS}}", "", T{}, false},
649
650 {"bug12xe", "{{printf `%T` 0xef}}", "int", T{}, true},
651 {"bug12xE", "{{printf `%T` 0xEE}}", "int", T{}, true},
652 {"bug12Xe", "{{printf `%T` 0Xef}}", "int", T{}, true},
653 {"bug12XE", "{{printf `%T` 0XEE}}", "int", T{}, true},
654
655 {"bug13", "{{print (.Copy).I}}", "17", tVal, true},
656
657 {"bug14a", "{{(nil).True}}", "", tVal, false},
658 {"bug14b", "{{$x := nil}}{{$x.anything}}", "", tVal, false},
659 {"bug14c", `{{$x := (1.0)}}{{$y := ("hello")}}{{$x.anything}}{{$y.true}}`, "", tVal, false},
660
661 {"bug15", "{{valueString returnInt}}", "", tVal, false},
662
663 {"bug16a", "{{true|printf}}", "", tVal, false},
664 {"bug16b", "{{1|printf}}", "", tVal, false},
665 {"bug16c", "{{1.1|printf}}", "", tVal, false},
666 {"bug16d", "{{'x'|printf}}", "", tVal, false},
667 {"bug16e", "{{0i|printf}}", "", tVal, false},
668 {"bug16f", "{{true|twoArgs \"xxx\"}}", "", tVal, false},
669 {"bug16g", "{{\"aaa\" |twoArgs \"bbb\"}}", "twoArgs=bbbaaa", tVal, true},
670 {"bug16h", "{{1|oneArg}}", "", tVal, false},
671 {"bug16i", "{{\"aaa\"|oneArg}}", "oneArg=aaa", tVal, true},
672 {"bug16j", "{{1+2i|printf \"%v\"}}", "(1+2i)", tVal, true},
673 {"bug16k", "{{\"aaa\"|printf }}", "aaa", tVal, true},
674 {"bug17a", "{{.NonEmptyInterface.X}}", "x", tVal, true},
675 {"bug17b", "-{{.NonEmptyInterface.Method1 1234}}-", "-1234-", tVal, true},
676 {"bug17c", "{{len .NonEmptyInterfacePtS}}", "2", tVal, true},
677 {"bug17d", "{{index .NonEmptyInterfacePtS 0}}", "a", tVal, true},
678 {"bug17e", "{{range .NonEmptyInterfacePtS}}-{{.}}-{{end}}", "-a--b-", tVal, true},
679
680
681
682 {"bug18a", "{{eq . '.'}}", "true", '.', true},
683 {"bug18b", "{{eq . 'e'}}", "true", 'e', true},
684 {"bug18c", "{{eq . 'P'}}", "true", 'P', true},
685 }
686
687 func zeroArgs() string {
688 return "zeroArgs"
689 }
690
691 func oneArg(a string) string {
692 return "oneArg=" + a
693 }
694
695 func twoArgs(a, b string) string {
696 return "twoArgs=" + a + b
697 }
698
699 func dddArg(a int, b ...string) string {
700 return fmt.Sprintln(a, b)
701 }
702
703
704 func count(n int) chan string {
705 if n == 0 {
706 return nil
707 }
708 c := make(chan string)
709 go func() {
710 for i := 0; i < n; i++ {
711 c <- "abcdefghijklmnop"[i : i+1]
712 }
713 close(c)
714 }()
715 return c
716 }
717
718
719 func vfunc(V, *V) string {
720 return "vfunc"
721 }
722
723
724 func valueString(v string) string {
725 return "value is ignored"
726 }
727
728
729 func returnInt() int {
730 return 7
731 }
732
733 func add(args ...int) int {
734 sum := 0
735 for _, x := range args {
736 sum += x
737 }
738 return sum
739 }
740
741 func echo(arg interface{}) interface{} {
742 return arg
743 }
744
745 func makemap(arg ...string) map[string]string {
746 if len(arg)%2 != 0 {
747 panic("bad makemap")
748 }
749 m := make(map[string]string)
750 for i := 0; i < len(arg); i += 2 {
751 m[arg[i]] = arg[i+1]
752 }
753 return m
754 }
755
756 func stringer(s fmt.Stringer) string {
757 return s.String()
758 }
759
760 func mapOfThree() interface{} {
761 return map[string]int{"three": 3}
762 }
763
764 func testExecute(execTests []execTest, template *Template, t *testing.T) {
765 b := new(bytes.Buffer)
766 funcs := FuncMap{
767 "add": add,
768 "count": count,
769 "dddArg": dddArg,
770 "echo": echo,
771 "makemap": makemap,
772 "mapOfThree": mapOfThree,
773 "oneArg": oneArg,
774 "returnInt": returnInt,
775 "stringer": stringer,
776 "twoArgs": twoArgs,
777 "typeOf": typeOf,
778 "valueString": valueString,
779 "vfunc": vfunc,
780 "zeroArgs": zeroArgs,
781 }
782 for _, test := range execTests {
783 var tmpl *Template
784 var err error
785 if template == nil {
786 tmpl, err = New(test.name).Funcs(funcs).Parse(test.input)
787 } else {
788 tmpl, err = template.Clone()
789 if err != nil {
790 t.Errorf("%s: clone error: %s", test.name, err)
791 continue
792 }
793 tmpl, err = tmpl.New(test.name).Funcs(funcs).Parse(test.input)
794 }
795 if err != nil {
796 t.Errorf("%s: parse error: %s", test.name, err)
797 continue
798 }
799 b.Reset()
800 err = tmpl.Execute(b, test.data)
801 switch {
802 case !test.ok && err == nil:
803 t.Errorf("%s: expected error; got none", test.name)
804 continue
805 case test.ok && err != nil:
806 t.Errorf("%s: unexpected execute error: %s", test.name, err)
807 continue
808 case !test.ok && err != nil:
809
810 if *debug {
811 fmt.Printf("%s: %s\n\t%s\n", test.name, test.input, err)
812 }
813 }
814 result := b.String()
815 if result != test.output {
816 t.Errorf("%s: expected\n\t%q\ngot\n\t%q", test.name, test.output, result)
817 }
818 }
819 }
820
821 func TestExecute(t *testing.T) {
822 testExecute(execTests, nil, t)
823 }
824
825 var delimPairs = []string{
826 "", "",
827 "{{", "}}",
828 "|", "|",
829 "(日)", "(本)",
830 }
831
832 func TestDelims(t *testing.T) {
833 const hello = "Hello, world"
834 var value = struct{ Str string }{hello}
835 for i := 0; i < len(delimPairs); i += 2 {
836 text := ".Str"
837 left := delimPairs[i+0]
838 trueLeft := left
839 right := delimPairs[i+1]
840 trueRight := right
841 if left == "" {
842 trueLeft = "{{"
843 }
844 if right == "" {
845 trueRight = "}}"
846 }
847 text = trueLeft + text + trueRight
848
849 text += trueLeft + "/*comment*/" + trueRight
850
851 text += trueLeft + `"` + trueLeft + `"` + trueRight
852
853 tmpl, err := New("delims").Delims(left, right).Parse(text)
854 if err != nil {
855 t.Fatalf("delim %q text %q parse err %s", left, text, err)
856 }
857 var b = new(bytes.Buffer)
858 err = tmpl.Execute(b, value)
859 if err != nil {
860 t.Fatalf("delim %q exec err %s", left, err)
861 }
862 if b.String() != hello+trueLeft {
863 t.Errorf("expected %q got %q", hello+trueLeft, b.String())
864 }
865 }
866 }
867
868
869 func TestExecuteError(t *testing.T) {
870 b := new(bytes.Buffer)
871 tmpl := New("error")
872 _, err := tmpl.Parse("{{.MyError true}}")
873 if err != nil {
874 t.Fatalf("parse error: %s", err)
875 }
876 err = tmpl.Execute(b, tVal)
877 if err == nil {
878 t.Errorf("expected error; got none")
879 } else if !strings.Contains(err.Error(), myError.Error()) {
880 if *debug {
881 fmt.Printf("test execute error: %s\n", err)
882 }
883 t.Errorf("expected myError; got %s", err)
884 }
885 }
886
887 const execErrorText = `line 1
888 line 2
889 line 3
890 {{template "one" .}}
891 {{define "one"}}{{template "two" .}}{{end}}
892 {{define "two"}}{{template "three" .}}{{end}}
893 {{define "three"}}{{index "hi" $}}{{end}}`
894
895
896 func TestExecError(t *testing.T) {
897 tmpl, err := New("top").Parse(execErrorText)
898 if err != nil {
899 t.Fatal("parse error:", err)
900 }
901 var b bytes.Buffer
902 err = tmpl.Execute(&b, 5)
903 if err == nil {
904 t.Fatal("expected error")
905 }
906 const want = `template: top:7:20: executing "three" at <index "hi" $>: error calling index: index out of range: 5`
907 got := err.Error()
908 if got != want {
909 t.Errorf("expected\n%q\ngot\n%q", want, got)
910 }
911 }
912
913 func TestJSEscaping(t *testing.T) {
914 testCases := []struct {
915 in, exp string
916 }{
917 {`a`, `a`},
918 {`'foo`, `\'foo`},
919 {`Go "jump" \`, `Go \"jump\" \\`},
920 {`Yukihiro says "今日は世界"`, `Yukihiro says \"今日は世界\"`},
921 {"unprintable \uFDFF", `unprintable \uFDFF`},
922 {`<html>`, `\u003Chtml\u003E`},
923 {`no = in attributes`, `no \u003D in attributes`},
924 {`' does not become HTML entity`, `\u0026#x27; does not become HTML entity`},
925 }
926 for _, tc := range testCases {
927 s := JSEscapeString(tc.in)
928 if s != tc.exp {
929 t.Errorf("JS escaping [%s] got [%s] want [%s]", tc.in, s, tc.exp)
930 }
931 }
932 }
933
934
935
936 type Tree struct {
937 Val int
938 Left, Right *Tree
939 }
940
941
942
943 const treeTemplate = `
944 (- define "tree" -)
945 [
946 (- .Val -)
947 (- with .Left -)
948 (template "tree" . -)
949 (- end -)
950 (- with .Right -)
951 (- template "tree" . -)
952 (- end -)
953 ]
954 (- end -)
955 `
956
957 func TestTree(t *testing.T) {
958 var tree = &Tree{
959 1,
960 &Tree{
961 2, &Tree{
962 3,
963 &Tree{
964 4, nil, nil,
965 },
966 nil,
967 },
968 &Tree{
969 5,
970 &Tree{
971 6, nil, nil,
972 },
973 nil,
974 },
975 },
976 &Tree{
977 7,
978 &Tree{
979 8,
980 &Tree{
981 9, nil, nil,
982 },
983 nil,
984 },
985 &Tree{
986 10,
987 &Tree{
988 11, nil, nil,
989 },
990 nil,
991 },
992 },
993 }
994 tmpl, err := New("root").Delims("(", ")").Parse(treeTemplate)
995 if err != nil {
996 t.Fatal("parse error:", err)
997 }
998 var b bytes.Buffer
999 const expect = "[1[2[3[4]][5[6]]][7[8[9]][10[11]]]]"
1000
1001 err = tmpl.Lookup("tree").Execute(&b, tree)
1002 if err != nil {
1003 t.Fatal("exec error:", err)
1004 }
1005 result := b.String()
1006 if result != expect {
1007 t.Errorf("expected %q got %q", expect, result)
1008 }
1009
1010 b.Reset()
1011 err = tmpl.ExecuteTemplate(&b, "tree", tree)
1012 if err != nil {
1013 t.Fatal("exec error:", err)
1014 }
1015 result = b.String()
1016 if result != expect {
1017 t.Errorf("expected %q got %q", expect, result)
1018 }
1019 }
1020
1021 func TestExecuteOnNewTemplate(t *testing.T) {
1022
1023 New("Name").Templates()
1024
1025
1026
1027
1028
1029
1030 }
1031
1032 const testTemplates = `{{define "one"}}one{{end}}{{define "two"}}two{{end}}`
1033
1034 func TestMessageForExecuteEmpty(t *testing.T) {
1035
1036 tmpl := New("empty")
1037 var b bytes.Buffer
1038 err := tmpl.Execute(&b, 0)
1039 if err == nil {
1040 t.Fatal("expected initial error")
1041 }
1042 got := err.Error()
1043 want := `template: "empty" is an incomplete or empty template`
1044 if got != want {
1045 t.Errorf("expected error %s got %s", want, got)
1046 }
1047
1048
1049 tmpl = New("empty")
1050 tests, err := New("").Parse(testTemplates)
1051 if err != nil {
1052 t.Fatal(err)
1053 }
1054 tmpl.AddParseTree("secondary", tests.Tree)
1055 err = tmpl.Execute(&b, 0)
1056 if err == nil {
1057 t.Fatal("expected second error")
1058 }
1059 got = err.Error()
1060 if got != want {
1061 t.Errorf("expected error %s got %s", want, got)
1062 }
1063
1064 err = tmpl.ExecuteTemplate(&b, "secondary", 0)
1065 if err != nil {
1066 t.Fatal(err)
1067 }
1068 }
1069
1070 func TestFinalForPrintf(t *testing.T) {
1071 tmpl, err := New("").Parse(`{{"x" | printf}}`)
1072 if err != nil {
1073 t.Fatal(err)
1074 }
1075 var b bytes.Buffer
1076 err = tmpl.Execute(&b, 0)
1077 if err != nil {
1078 t.Fatal(err)
1079 }
1080 }
1081
1082 type cmpTest struct {
1083 expr string
1084 truth string
1085 ok bool
1086 }
1087
1088 var cmpTests = []cmpTest{
1089 {"eq true true", "true", true},
1090 {"eq true false", "false", true},
1091 {"eq 1+2i 1+2i", "true", true},
1092 {"eq 1+2i 1+3i", "false", true},
1093 {"eq 1.5 1.5", "true", true},
1094 {"eq 1.5 2.5", "false", true},
1095 {"eq 1 1", "true", true},
1096 {"eq 1 2", "false", true},
1097 {"eq `xy` `xy`", "true", true},
1098 {"eq `xy` `xyz`", "false", true},
1099 {"eq .Uthree .Uthree", "true", true},
1100 {"eq .Uthree .Ufour", "false", true},
1101 {"eq 3 4 5 6 3", "true", true},
1102 {"eq 3 4 5 6 7", "false", true},
1103 {"ne true true", "false", true},
1104 {"ne true false", "true", true},
1105 {"ne 1+2i 1+2i", "false", true},
1106 {"ne 1+2i 1+3i", "true", true},
1107 {"ne 1.5 1.5", "false", true},
1108 {"ne 1.5 2.5", "true", true},
1109 {"ne 1 1", "false", true},
1110 {"ne 1 2", "true", true},
1111 {"ne `xy` `xy`", "false", true},
1112 {"ne `xy` `xyz`", "true", true},
1113 {"ne .Uthree .Uthree", "false", true},
1114 {"ne .Uthree .Ufour", "true", true},
1115 {"lt 1.5 1.5", "false", true},
1116 {"lt 1.5 2.5", "true", true},
1117 {"lt 1 1", "false", true},
1118 {"lt 1 2", "true", true},
1119 {"lt `xy` `xy`", "false", true},
1120 {"lt `xy` `xyz`", "true", true},
1121 {"lt .Uthree .Uthree", "false", true},
1122 {"lt .Uthree .Ufour", "true", true},
1123 {"le 1.5 1.5", "true", true},
1124 {"le 1.5 2.5", "true", true},
1125 {"le 2.5 1.5", "false", true},
1126 {"le 1 1", "true", true},
1127 {"le 1 2", "true", true},
1128 {"le 2 1", "false", true},
1129 {"le `xy` `xy`", "true", true},
1130 {"le `xy` `xyz`", "true", true},
1131 {"le `xyz` `xy`", "false", true},
1132 {"le .Uthree .Uthree", "true", true},
1133 {"le .Uthree .Ufour", "true", true},
1134 {"le .Ufour .Uthree", "false", true},
1135 {"gt 1.5 1.5", "false", true},
1136 {"gt 1.5 2.5", "false", true},
1137 {"gt 1 1", "false", true},
1138 {"gt 2 1", "true", true},
1139 {"gt 1 2", "false", true},
1140 {"gt `xy` `xy`", "false", true},
1141 {"gt `xy` `xyz`", "false", true},
1142 {"gt .Uthree .Uthree", "false", true},
1143 {"gt .Uthree .Ufour", "false", true},
1144 {"gt .Ufour .Uthree", "true", true},
1145 {"ge 1.5 1.5", "true", true},
1146 {"ge 1.5 2.5", "false", true},
1147 {"ge 2.5 1.5", "true", true},
1148 {"ge 1 1", "true", true},
1149 {"ge 1 2", "false", true},
1150 {"ge 2 1", "true", true},
1151 {"ge `xy` `xy`", "true", true},
1152 {"ge `xy` `xyz`", "false", true},
1153 {"ge `xyz` `xy`", "true", true},
1154 {"ge .Uthree .Uthree", "true", true},
1155 {"ge .Uthree .Ufour", "false", true},
1156 {"ge .Ufour .Uthree", "true", true},
1157
1158 {"eq .Uthree .Three", "true", true},
1159 {"eq .Three .Uthree", "true", true},
1160 {"le .Uthree .Three", "true", true},
1161 {"le .Three .Uthree", "true", true},
1162 {"ge .Uthree .Three", "true", true},
1163 {"ge .Three .Uthree", "true", true},
1164 {"lt .Uthree .Three", "false", true},
1165 {"lt .Three .Uthree", "false", true},
1166 {"gt .Uthree .Three", "false", true},
1167 {"gt .Three .Uthree", "false", true},
1168 {"eq .Ufour .Three", "false", true},
1169 {"lt .Ufour .Three", "false", true},
1170 {"gt .Ufour .Three", "true", true},
1171 {"eq .NegOne .Uthree", "false", true},
1172 {"eq .Uthree .NegOne", "false", true},
1173 {"ne .NegOne .Uthree", "true", true},
1174 {"ne .Uthree .NegOne", "true", true},
1175 {"lt .NegOne .Uthree", "true", true},
1176 {"lt .Uthree .NegOne", "false", true},
1177 {"le .NegOne .Uthree", "true", true},
1178 {"le .Uthree .NegOne", "false", true},
1179 {"gt .NegOne .Uthree", "false", true},
1180 {"gt .Uthree .NegOne", "true", true},
1181 {"ge .NegOne .Uthree", "false", true},
1182 {"ge .Uthree .NegOne", "true", true},
1183 {"eq (index `x` 0) 'x'", "true", true},
1184 {"eq (index `x` 0) 'y'", "false", true},
1185 {"eq .V1 .V2", "true", true},
1186 {"eq .Ptr .Ptr", "true", true},
1187 {"eq .Ptr .NilPtr", "false", true},
1188 {"eq .NilPtr .NilPtr", "true", true},
1189 {"eq .Iface1 .Iface1", "true", true},
1190 {"eq .Iface1 .Iface2", "false", true},
1191 {"eq .Iface2 .Iface2", "true", true},
1192
1193 {"eq `xy` 1", "", false},
1194 {"eq 2 2.0", "", false},
1195 {"lt true true", "", false},
1196 {"lt 1+0i 1+0i", "", false},
1197 {"eq .Ptr 1", "", false},
1198 {"eq .Ptr .NegOne", "", false},
1199 {"eq .Map .Map", "", false},
1200 {"eq .Map .V1", "", false},
1201 }
1202
1203 func TestComparison(t *testing.T) {
1204 b := new(bytes.Buffer)
1205 var cmpStruct = struct {
1206 Uthree, Ufour uint
1207 NegOne, Three int
1208 Ptr, NilPtr *int
1209 Map map[int]int
1210 V1, V2 V
1211 Iface1, Iface2 fmt.Stringer
1212 }{
1213 Uthree: 3,
1214 Ufour: 4,
1215 NegOne: -1,
1216 Three: 3,
1217 Ptr: new(int),
1218 Iface1: b,
1219 }
1220 for _, test := range cmpTests {
1221 text := fmt.Sprintf("{{if %s}}true{{else}}false{{end}}", test.expr)
1222 tmpl, err := New("empty").Parse(text)
1223 if err != nil {
1224 t.Fatalf("%q: %s", test.expr, err)
1225 }
1226 b.Reset()
1227 err = tmpl.Execute(b, &cmpStruct)
1228 if test.ok && err != nil {
1229 t.Errorf("%s errored incorrectly: %s", test.expr, err)
1230 continue
1231 }
1232 if !test.ok && err == nil {
1233 t.Errorf("%s did not error", test.expr)
1234 continue
1235 }
1236 if b.String() != test.truth {
1237 t.Errorf("%s: want %s; got %s", test.expr, test.truth, b.String())
1238 }
1239 }
1240 }
1241
1242 func TestMissingMapKey(t *testing.T) {
1243 data := map[string]int{
1244 "x": 99,
1245 }
1246 tmpl, err := New("t1").Parse("{{.x}} {{.y}}")
1247 if err != nil {
1248 t.Fatal(err)
1249 }
1250 var b bytes.Buffer
1251
1252 err = tmpl.Execute(&b, data)
1253 if err != nil {
1254 t.Fatal(err)
1255 }
1256 want := "99 "
1257 got := b.String()
1258 if got != want {
1259 t.Errorf("got %q; expected %q", got, want)
1260 }
1261
1262 tmpl.Option("missingkey=default")
1263 b.Reset()
1264 err = tmpl.Execute(&b, data)
1265 if err != nil {
1266 t.Fatal("default:", err)
1267 }
1268 got = b.String()
1269 if got != want {
1270 t.Errorf("got %q; expected %q", got, want)
1271 }
1272
1273 tmpl.Option("missingkey=zero")
1274 b.Reset()
1275 err = tmpl.Execute(&b, data)
1276 if err != nil {
1277 t.Fatal("zero:", err)
1278 }
1279 want = "99 0"
1280 got = b.String()
1281 if got != want {
1282 t.Errorf("got %q; expected %q", got, want)
1283 }
1284
1285 tmpl.Option("missingkey=error")
1286 err = tmpl.Execute(&b, data)
1287 if err == nil {
1288 t.Errorf("expected error; got none")
1289 }
1290
1291 err = tmpl.Execute(&b, nil)
1292 t.Log(err)
1293 if err == nil {
1294 t.Errorf("expected error for nil-interface; got none")
1295 }
1296 }
1297
1298
1299
1300 func TestUnterminatedStringError(t *testing.T) {
1301 _, err := New("X").Parse("hello\n\n{{`unterminated\n\n\n\n}}\n some more\n\n")
1302 if err == nil {
1303 t.Fatal("expected error")
1304 }
1305 str := err.Error()
1306 if !strings.Contains(str, "X:3: unterminated raw quoted string") {
1307 t.Fatalf("unexpected error: %s", str)
1308 }
1309 }
1310
1311 const alwaysErrorText = "always be failing"
1312
1313 var alwaysError = errors.New(alwaysErrorText)
1314
1315 type ErrorWriter int
1316
1317 func (e ErrorWriter) Write(p []byte) (int, error) {
1318 return 0, alwaysError
1319 }
1320
1321 func TestExecuteGivesExecError(t *testing.T) {
1322
1323 tmpl, err := New("X").Parse("hello")
1324 if err != nil {
1325 t.Fatal(err)
1326 }
1327 err = tmpl.Execute(ErrorWriter(0), 0)
1328 if err == nil {
1329 t.Fatal("expected error; got none")
1330 }
1331 if err.Error() != alwaysErrorText {
1332 t.Errorf("expected %q error; got %q", alwaysErrorText, err)
1333 }
1334
1335 tmpl, err = New("X").Parse("hello, {{.X.Y}}")
1336 if err != nil {
1337 t.Fatal(err)
1338 }
1339 err = tmpl.Execute(io.Discard, 0)
1340 if err == nil {
1341 t.Fatal("expected error; got none")
1342 }
1343 eerr, ok := err.(template.ExecError)
1344 if !ok {
1345 t.Fatalf("did not expect ExecError %s", eerr)
1346 }
1347 expect := "field X in type int"
1348 if !strings.Contains(err.Error(), expect) {
1349 t.Errorf("expected %q; got %q", expect, err)
1350 }
1351 }
1352
1353 func funcNameTestFunc() int {
1354 return 0
1355 }
1356
1357 func TestGoodFuncNames(t *testing.T) {
1358 names := []string{
1359 "_",
1360 "a",
1361 "a1",
1362 "a1",
1363 "Ӵ",
1364 }
1365 for _, name := range names {
1366 tmpl := New("X").Funcs(
1367 FuncMap{
1368 name: funcNameTestFunc,
1369 },
1370 )
1371 if tmpl == nil {
1372 t.Fatalf("nil result for %q", name)
1373 }
1374 }
1375 }
1376
1377 func TestBadFuncNames(t *testing.T) {
1378 names := []string{
1379 "",
1380 "2",
1381 "a-b",
1382 }
1383 for _, name := range names {
1384 testBadFuncName(name, t)
1385 }
1386 }
1387
1388 func testBadFuncName(name string, t *testing.T) {
1389 t.Helper()
1390 defer func() {
1391 recover()
1392 }()
1393 New("X").Funcs(
1394 FuncMap{
1395 name: funcNameTestFunc,
1396 },
1397 )
1398
1399
1400 t.Errorf("%q succeeded incorrectly as function name", name)
1401 }
1402
1403 func TestBlock(t *testing.T) {
1404 const (
1405 input = `a({{block "inner" .}}bar({{.}})baz{{end}})b`
1406 want = `a(bar(hello)baz)b`
1407 overlay = `{{define "inner"}}foo({{.}})bar{{end}}`
1408 want2 = `a(foo(goodbye)bar)b`
1409 )
1410 tmpl, err := New("outer").Parse(input)
1411 if err != nil {
1412 t.Fatal(err)
1413 }
1414 tmpl2, err := Must(tmpl.Clone()).Parse(overlay)
1415 if err != nil {
1416 t.Fatal(err)
1417 }
1418
1419 var buf bytes.Buffer
1420 if err := tmpl.Execute(&buf, "hello"); err != nil {
1421 t.Fatal(err)
1422 }
1423 if got := buf.String(); got != want {
1424 t.Errorf("got %q, want %q", got, want)
1425 }
1426
1427 buf.Reset()
1428 if err := tmpl2.Execute(&buf, "goodbye"); err != nil {
1429 t.Fatal(err)
1430 }
1431 if got := buf.String(); got != want2 {
1432 t.Errorf("got %q, want %q", got, want2)
1433 }
1434 }
1435
1436 func TestEvalFieldErrors(t *testing.T) {
1437 tests := []struct {
1438 name, src string
1439 value interface{}
1440 want string
1441 }{
1442 {
1443
1444
1445
1446 "MissingFieldOnNil",
1447 "{{.MissingField}}",
1448 (*T)(nil),
1449 "can't evaluate field MissingField in type *template.T",
1450 },
1451 {
1452 "MissingFieldOnNonNil",
1453 "{{.MissingField}}",
1454 &T{},
1455 "can't evaluate field MissingField in type *template.T",
1456 },
1457 {
1458 "ExistingFieldOnNil",
1459 "{{.X}}",
1460 (*T)(nil),
1461 "nil pointer evaluating *template.T.X",
1462 },
1463 {
1464 "MissingKeyOnNilMap",
1465 "{{.MissingKey}}",
1466 (*map[string]string)(nil),
1467 "nil pointer evaluating *map[string]string.MissingKey",
1468 },
1469 {
1470 "MissingKeyOnNilMapPtr",
1471 "{{.MissingKey}}",
1472 (*map[string]string)(nil),
1473 "nil pointer evaluating *map[string]string.MissingKey",
1474 },
1475 {
1476 "MissingKeyOnMapPtrToNil",
1477 "{{.MissingKey}}",
1478 &map[string]string{},
1479 "<nil>",
1480 },
1481 }
1482 for _, tc := range tests {
1483 t.Run(tc.name, func(t *testing.T) {
1484 tmpl := Must(New("tmpl").Parse(tc.src))
1485 err := tmpl.Execute(io.Discard, tc.value)
1486 got := "<nil>"
1487 if err != nil {
1488 got = err.Error()
1489 }
1490 if !strings.HasSuffix(got, tc.want) {
1491 t.Fatalf("got error %q, want %q", got, tc.want)
1492 }
1493 })
1494 }
1495 }
1496
1497 func TestMaxExecDepth(t *testing.T) {
1498 if testing.Short() {
1499 t.Skip("skipping in -short mode")
1500 }
1501 tmpl := Must(New("tmpl").Parse(`{{template "tmpl" .}}`))
1502 err := tmpl.Execute(io.Discard, nil)
1503 got := "<nil>"
1504 if err != nil {
1505 got = err.Error()
1506 }
1507 const want = "exceeded maximum template depth"
1508 if !strings.Contains(got, want) {
1509 t.Errorf("got error %q; want %q", got, want)
1510 }
1511 }
1512
1513 func TestAddrOfIndex(t *testing.T) {
1514
1515
1516
1517
1518
1519 texts := []string{
1520 `{{range .}}{{.String}}{{end}}`,
1521 `{{with index . 0}}{{.String}}{{end}}`,
1522 }
1523 for _, text := range texts {
1524 tmpl := Must(New("tmpl").Parse(text))
1525 var buf bytes.Buffer
1526 err := tmpl.Execute(&buf, reflect.ValueOf([]V{{1}}))
1527 if err != nil {
1528 t.Fatalf("%s: Execute: %v", text, err)
1529 }
1530 if buf.String() != "<1>" {
1531 t.Fatalf("%s: template output = %q, want %q", text, &buf, "<1>")
1532 }
1533 }
1534 }
1535
1536 func TestInterfaceValues(t *testing.T) {
1537
1538
1539
1540
1541
1542
1543 tests := []struct {
1544 text string
1545 out string
1546 }{
1547 {`{{index .Nil 1}}`, "ERROR: index of untyped nil"},
1548 {`{{index .Slice 2}}`, "2"},
1549 {`{{index .Slice .Two}}`, "2"},
1550 {`{{call .Nil 1}}`, "ERROR: call of nil"},
1551 {`{{call .PlusOne 1}}`, "2"},
1552 {`{{call .PlusOne .One}}`, "2"},
1553 {`{{and (index .Slice 0) true}}`, "0"},
1554 {`{{and .Zero true}}`, "0"},
1555 {`{{and (index .Slice 1) false}}`, "false"},
1556 {`{{and .One false}}`, "false"},
1557 {`{{or (index .Slice 0) false}}`, "false"},
1558 {`{{or .Zero false}}`, "false"},
1559 {`{{or (index .Slice 1) true}}`, "1"},
1560 {`{{or .One true}}`, "1"},
1561 {`{{not (index .Slice 0)}}`, "true"},
1562 {`{{not .Zero}}`, "true"},
1563 {`{{not (index .Slice 1)}}`, "false"},
1564 {`{{not .One}}`, "false"},
1565 {`{{eq (index .Slice 0) .Zero}}`, "true"},
1566 {`{{eq (index .Slice 1) .One}}`, "true"},
1567 {`{{ne (index .Slice 0) .Zero}}`, "false"},
1568 {`{{ne (index .Slice 1) .One}}`, "false"},
1569 {`{{ge (index .Slice 0) .One}}`, "false"},
1570 {`{{ge (index .Slice 1) .Zero}}`, "true"},
1571 {`{{gt (index .Slice 0) .One}}`, "false"},
1572 {`{{gt (index .Slice 1) .Zero}}`, "true"},
1573 {`{{le (index .Slice 0) .One}}`, "true"},
1574 {`{{le (index .Slice 1) .Zero}}`, "false"},
1575 {`{{lt (index .Slice 0) .One}}`, "true"},
1576 {`{{lt (index .Slice 1) .Zero}}`, "false"},
1577 }
1578
1579 for _, tt := range tests {
1580 tmpl := Must(New("tmpl").Parse(tt.text))
1581 var buf bytes.Buffer
1582 err := tmpl.Execute(&buf, map[string]interface{}{
1583 "PlusOne": func(n int) int {
1584 return n + 1
1585 },
1586 "Slice": []int{0, 1, 2, 3},
1587 "One": 1,
1588 "Two": 2,
1589 "Nil": nil,
1590 "Zero": 0,
1591 })
1592 if strings.HasPrefix(tt.out, "ERROR:") {
1593 e := strings.TrimSpace(strings.TrimPrefix(tt.out, "ERROR:"))
1594 if err == nil || !strings.Contains(err.Error(), e) {
1595 t.Errorf("%s: Execute: %v, want error %q", tt.text, err, e)
1596 }
1597 continue
1598 }
1599 if err != nil {
1600 t.Errorf("%s: Execute: %v", tt.text, err)
1601 continue
1602 }
1603 if buf.String() != tt.out {
1604 t.Errorf("%s: template output = %q, want %q", tt.text, &buf, tt.out)
1605 }
1606 }
1607 }
1608
1609
1610 func TestExecutePanicDuringCall(t *testing.T) {
1611 funcs := map[string]interface{}{
1612 "doPanic": func() string {
1613 panic("custom panic string")
1614 },
1615 }
1616 tests := []struct {
1617 name string
1618 input string
1619 data interface{}
1620 wantErr string
1621 }{
1622 {
1623 "direct func call panics",
1624 "{{doPanic}}", (*T)(nil),
1625 `template: t:1:2: executing "t" at <doPanic>: error calling doPanic: custom panic string`,
1626 },
1627 {
1628 "indirect func call panics",
1629 "{{call doPanic}}", (*T)(nil),
1630 `template: t:1:7: executing "t" at <doPanic>: error calling doPanic: custom panic string`,
1631 },
1632 {
1633 "direct method call panics",
1634 "{{.GetU}}", (*T)(nil),
1635 `template: t:1:2: executing "t" at <.GetU>: error calling GetU: runtime error: invalid memory address or nil pointer dereference`,
1636 },
1637 {
1638 "indirect method call panics",
1639 "{{call .GetU}}", (*T)(nil),
1640 `template: t:1:7: executing "t" at <.GetU>: error calling GetU: runtime error: invalid memory address or nil pointer dereference`,
1641 },
1642 {
1643 "func field call panics",
1644 "{{call .PanicFunc}}", tVal,
1645 `template: t:1:2: executing "t" at <call .PanicFunc>: error calling call: test panic`,
1646 },
1647 {
1648 "method call on nil interface",
1649 "{{.NonEmptyInterfaceNil.Method0}}", tVal,
1650 `template: t:1:23: executing "t" at <.NonEmptyInterfaceNil.Method0>: nil pointer evaluating template.I.Method0`,
1651 },
1652 }
1653 for _, tc := range tests {
1654 b := new(bytes.Buffer)
1655 tmpl, err := New("t").Funcs(funcs).Parse(tc.input)
1656 if err != nil {
1657 t.Fatalf("parse error: %s", err)
1658 }
1659 err = tmpl.Execute(b, tc.data)
1660 if err == nil {
1661 t.Errorf("%s: expected error; got none", tc.name)
1662 } else if !strings.Contains(err.Error(), tc.wantErr) {
1663 if *debug {
1664 fmt.Printf("%s: test execute error: %s\n", tc.name, err)
1665 }
1666 t.Errorf("%s: expected error:\n%s\ngot:\n%s", tc.name, tc.wantErr, err)
1667 }
1668 }
1669 }
1670
1671
1672 func TestIssue31810(t *testing.T) {
1673 t.Skip("broken in html/template")
1674
1675
1676 var b bytes.Buffer
1677 const text = "{{ (.) }}"
1678 tmpl, err := New("").Parse(text)
1679 if err != nil {
1680 t.Error(err)
1681 }
1682 err = tmpl.Execute(&b, "result")
1683 if err != nil {
1684 t.Error(err)
1685 }
1686 if b.String() != "result" {
1687 t.Errorf("%s got %q, expected %q", text, b.String(), "result")
1688 }
1689
1690
1691 f := func() string { return "result" }
1692 b.Reset()
1693 err = tmpl.Execute(&b, f)
1694 if err == nil {
1695 t.Error("expected error with no call, got none")
1696 }
1697
1698
1699 const textCall = "{{ (call .) }}"
1700 tmpl, err = New("").Parse(textCall)
1701 b.Reset()
1702 err = tmpl.Execute(&b, f)
1703 if err != nil {
1704 t.Error(err)
1705 }
1706 if b.String() != "result" {
1707 t.Errorf("%s got %q, expected %q", textCall, b.String(), "result")
1708 }
1709 }
1710
1711
1712
1713 const raceText = `
1714 {{- define "jstempl" -}}
1715 var v = "v";
1716 {{- end -}}
1717 <script type="application/javascript">
1718 {{ template "jstempl" $ }}
1719 </script>
1720 `
1721
1722 func TestEscapeRace(t *testing.T) {
1723 tmpl := New("")
1724 _, err := tmpl.New("templ.html").Parse(raceText)
1725 if err != nil {
1726 t.Fatal(err)
1727 }
1728 const count = 20
1729 for i := 0; i < count; i++ {
1730 _, err := tmpl.New(fmt.Sprintf("x%d.html", i)).Parse(`{{ template "templ.html" .}}`)
1731 if err != nil {
1732 t.Fatal(err)
1733 }
1734 }
1735
1736 var wg sync.WaitGroup
1737 for i := 0; i < 10; i++ {
1738 wg.Add(1)
1739 go func() {
1740 defer wg.Done()
1741 for j := 0; j < count; j++ {
1742 sub := tmpl.Lookup(fmt.Sprintf("x%d.html", j))
1743 if err := sub.Execute(io.Discard, nil); err != nil {
1744 t.Error(err)
1745 }
1746 }
1747 }()
1748 }
1749 wg.Wait()
1750 }
1751
1752 func TestRecursiveExecute(t *testing.T) {
1753 tmpl := New("")
1754
1755 recur := func() (HTML, error) {
1756 var sb strings.Builder
1757 if err := tmpl.ExecuteTemplate(&sb, "subroutine", nil); err != nil {
1758 t.Fatal(err)
1759 }
1760 return HTML(sb.String()), nil
1761 }
1762
1763 m := FuncMap{
1764 "recur": recur,
1765 }
1766
1767 top, err := tmpl.New("x.html").Funcs(m).Parse(`{{recur}}`)
1768 if err != nil {
1769 t.Fatal(err)
1770 }
1771 _, err = tmpl.New("subroutine").Parse(`<a href="/x?p={{"'a<b'"}}">`)
1772 if err != nil {
1773 t.Fatal(err)
1774 }
1775 if err := top.Execute(io.Discard, nil); err != nil {
1776 t.Fatal(err)
1777 }
1778 }
1779
1780
1781 type recursiveInvoker struct {
1782 t *testing.T
1783 tmpl *Template
1784 }
1785
1786 func (r *recursiveInvoker) Recur() (string, error) {
1787 var sb strings.Builder
1788 if err := r.tmpl.ExecuteTemplate(&sb, "subroutine", nil); err != nil {
1789 r.t.Fatal(err)
1790 }
1791 return sb.String(), nil
1792 }
1793
1794 func TestRecursiveExecuteViaMethod(t *testing.T) {
1795 tmpl := New("")
1796 top, err := tmpl.New("x.html").Parse(`{{.Recur}}`)
1797 if err != nil {
1798 t.Fatal(err)
1799 }
1800 _, err = tmpl.New("subroutine").Parse(`<a href="/x?p={{"'a<b'"}}">`)
1801 if err != nil {
1802 t.Fatal(err)
1803 }
1804 r := &recursiveInvoker{
1805 t: t,
1806 tmpl: tmpl,
1807 }
1808 if err := top.Execute(io.Discard, r); err != nil {
1809 t.Fatal(err)
1810 }
1811 }
1812
1813
1814 func TestTemplateFuncsAfterClone(t *testing.T) {
1815 s := `{{ f . }}`
1816 want := "test"
1817 orig := New("orig").Funcs(map[string]interface{}{
1818 "f": func(in string) string {
1819 return in
1820 },
1821 }).New("child")
1822
1823 overviewTmpl := Must(Must(orig.Clone()).Parse(s))
1824 var out strings.Builder
1825 if err := overviewTmpl.Execute(&out, want); err != nil {
1826 t.Fatal(err)
1827 }
1828 if got := out.String(); got != want {
1829 t.Fatalf("got %q; want %q", got, want)
1830 }
1831 }
1832
View as plain text