Rebase.
[official-gcc.git] / libgo / go / text / template / exec_test.go
blob868f2cb94c392d649c6ab907e3d9c28cad8e646c
1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 package template
7 import (
8 "bytes"
9 "errors"
10 "flag"
11 "fmt"
12 "reflect"
13 "strings"
14 "testing"
17 var debug = flag.Bool("debug", false, "show the errors produced by the tests")
19 // T has lots of interesting pieces to use to test execution.
20 type T struct {
21 // Basics
22 True bool
23 I int
24 U16 uint16
25 X string
26 FloatZero float64
27 ComplexZero complex128
28 // Nested structs.
29 U *U
30 // Struct with String method.
31 V0 V
32 V1, V2 *V
33 // Struct with Error method.
34 W0 W
35 W1, W2 *W
36 // Slices
37 SI []int
38 SIEmpty []int
39 SB []bool
40 // Maps
41 MSI map[string]int
42 MSIone map[string]int // one element, for deterministic output
43 MSIEmpty map[string]int
44 MXI map[interface{}]int
45 MII map[int]int
46 SMSI []map[string]int
47 // Empty interfaces; used to see if we can dig inside one.
48 Empty0 interface{} // nil
49 Empty1 interface{}
50 Empty2 interface{}
51 Empty3 interface{}
52 Empty4 interface{}
53 // Non-empty interface.
54 NonEmptyInterface I
55 // Stringer.
56 Str fmt.Stringer
57 Err error
58 // Pointers
59 PI *int
60 PS *string
61 PSI *[]int
62 NIL *int
63 // Function (not method)
64 BinaryFunc func(string, string) string
65 VariadicFunc func(...string) string
66 VariadicFuncInt func(int, ...string) string
67 NilOKFunc func(*int) bool
68 ErrFunc func() (string, error)
69 // Template to test evaluation of templates.
70 Tmpl *Template
71 // Unexported field; cannot be accessed by template.
72 unexported int
75 type U struct {
76 V string
79 type V struct {
80 j int
83 func (v *V) String() string {
84 if v == nil {
85 return "nilV"
87 return fmt.Sprintf("<%d>", v.j)
90 type W struct {
91 k int
94 func (w *W) Error() string {
95 if w == nil {
96 return "nilW"
98 return fmt.Sprintf("[%d]", w.k)
101 var tVal = &T{
102 True: true,
103 I: 17,
104 U16: 16,
105 X: "x",
106 U: &U{"v"},
107 V0: V{6666},
108 V1: &V{7777}, // leave V2 as nil
109 W0: W{888},
110 W1: &W{999}, // leave W2 as nil
111 SI: []int{3, 4, 5},
112 SB: []bool{true, false},
113 MSI: map[string]int{"one": 1, "two": 2, "three": 3},
114 MSIone: map[string]int{"one": 1},
115 MXI: map[interface{}]int{"one": 1},
116 MII: map[int]int{1: 1},
117 SMSI: []map[string]int{
118 {"one": 1, "two": 2},
119 {"eleven": 11, "twelve": 12},
121 Empty1: 3,
122 Empty2: "empty2",
123 Empty3: []int{7, 8},
124 Empty4: &U{"UinEmpty"},
125 NonEmptyInterface: new(T),
126 Str: bytes.NewBuffer([]byte("foozle")),
127 Err: errors.New("erroozle"),
128 PI: newInt(23),
129 PS: newString("a string"),
130 PSI: newIntSlice(21, 22, 23),
131 BinaryFunc: func(a, b string) string { return fmt.Sprintf("[%s=%s]", a, b) },
132 VariadicFunc: func(s ...string) string { return fmt.Sprint("<", strings.Join(s, "+"), ">") },
133 VariadicFuncInt: func(a int, s ...string) string { return fmt.Sprint(a, "=<", strings.Join(s, "+"), ">") },
134 NilOKFunc: func(s *int) bool { return s == nil },
135 ErrFunc: func() (string, error) { return "bla", nil },
136 Tmpl: Must(New("x").Parse("test template")), // "x" is the value of .X
139 // A non-empty interface.
140 type I interface {
141 Method0() string
144 var iVal I = tVal
146 // Helpers for creation.
147 func newInt(n int) *int {
148 return &n
151 func newString(s string) *string {
152 return &s
155 func newIntSlice(n ...int) *[]int {
156 p := new([]int)
157 *p = make([]int, len(n))
158 copy(*p, n)
159 return p
162 // Simple methods with and without arguments.
163 func (t *T) Method0() string {
164 return "M0"
167 func (t *T) Method1(a int) int {
168 return a
171 func (t *T) Method2(a uint16, b string) string {
172 return fmt.Sprintf("Method2: %d %s", a, b)
175 func (t *T) Method3(v interface{}) string {
176 return fmt.Sprintf("Method3: %v", v)
179 func (t *T) MAdd(a int, b []int) []int {
180 v := make([]int, len(b))
181 for i, x := range b {
182 v[i] = x + a
184 return v
187 var myError = errors.New("my error")
189 // MyError returns a value and an error according to its argument.
190 func (t *T) MyError(error bool) (bool, error) {
191 if error {
192 return true, myError
194 return false, nil
197 // A few methods to test chaining.
198 func (t *T) GetU() *U {
199 return t.U
202 func (u *U) TrueFalse(b bool) string {
203 if b {
204 return "true"
206 return ""
209 func typeOf(arg interface{}) string {
210 return fmt.Sprintf("%T", arg)
213 type execTest struct {
214 name string
215 input string
216 output string
217 data interface{}
218 ok bool
221 // bigInt and bigUint are hex string representing numbers either side
222 // of the max int boundary.
223 // We do it this way so the test doesn't depend on ints being 32 bits.
224 var (
225 bigInt = fmt.Sprintf("0x%x", int(1<<uint(reflect.TypeOf(0).Bits()-1)-1))
226 bigUint = fmt.Sprintf("0x%x", uint(1<<uint(reflect.TypeOf(0).Bits()-1)))
229 var execTests = []execTest{
230 // Trivial cases.
231 {"empty", "", "", nil, true},
232 {"text", "some text", "some text", nil, true},
233 {"nil action", "{{nil}}", "", nil, false},
235 // Ideal constants.
236 {"ideal int", "{{typeOf 3}}", "int", 0, true},
237 {"ideal float", "{{typeOf 1.0}}", "float64", 0, true},
238 {"ideal exp float", "{{typeOf 1e1}}", "float64", 0, true},
239 {"ideal complex", "{{typeOf 1i}}", "complex128", 0, true},
240 {"ideal int", "{{typeOf " + bigInt + "}}", "int", 0, true},
241 {"ideal too big", "{{typeOf " + bigUint + "}}", "", 0, false},
242 {"ideal nil without type", "{{nil}}", "", 0, false},
244 // Fields of structs.
245 {".X", "-{{.X}}-", "-x-", tVal, true},
246 {".U.V", "-{{.U.V}}-", "-v-", tVal, true},
247 {".unexported", "{{.unexported}}", "", tVal, false},
249 // Fields on maps.
250 {"map .one", "{{.MSI.one}}", "1", tVal, true},
251 {"map .two", "{{.MSI.two}}", "2", tVal, true},
252 {"map .NO", "{{.MSI.NO}}", "<no value>", tVal, true},
253 {"map .one interface", "{{.MXI.one}}", "1", tVal, true},
254 {"map .WRONG args", "{{.MSI.one 1}}", "", tVal, false},
255 {"map .WRONG type", "{{.MII.one}}", "", tVal, false},
257 // Dots of all kinds to test basic evaluation.
258 {"dot int", "<{{.}}>", "<13>", 13, true},
259 {"dot uint", "<{{.}}>", "<14>", uint(14), true},
260 {"dot float", "<{{.}}>", "<15.1>", 15.1, true},
261 {"dot bool", "<{{.}}>", "<true>", true, true},
262 {"dot complex", "<{{.}}>", "<(16.2-17i)>", 16.2 - 17i, true},
263 {"dot string", "<{{.}}>", "<hello>", "hello", true},
264 {"dot slice", "<{{.}}>", "<[-1 -2 -3]>", []int{-1, -2, -3}, true},
265 {"dot map", "<{{.}}>", "<map[two:22]>", map[string]int{"two": 22}, true},
266 {"dot struct", "<{{.}}>", "<{7 seven}>", struct {
267 a int
268 b string
269 }{7, "seven"}, true},
271 // Variables.
272 {"$ int", "{{$}}", "123", 123, true},
273 {"$.I", "{{$.I}}", "17", tVal, true},
274 {"$.U.V", "{{$.U.V}}", "v", tVal, true},
275 {"declare in action", "{{$x := $.U.V}}{{$x}}", "v", tVal, true},
277 // Type with String method.
278 {"V{6666}.String()", "-{{.V0}}-", "-<6666>-", tVal, true},
279 {"&V{7777}.String()", "-{{.V1}}-", "-<7777>-", tVal, true},
280 {"(*V)(nil).String()", "-{{.V2}}-", "-nilV-", tVal, true},
282 // Type with Error method.
283 {"W{888}.Error()", "-{{.W0}}-", "-[888]-", tVal, true},
284 {"&W{999}.Error()", "-{{.W1}}-", "-[999]-", tVal, true},
285 {"(*W)(nil).Error()", "-{{.W2}}-", "-nilW-", tVal, true},
287 // Pointers.
288 {"*int", "{{.PI}}", "23", tVal, true},
289 {"*string", "{{.PS}}", "a string", tVal, true},
290 {"*[]int", "{{.PSI}}", "[21 22 23]", tVal, true},
291 {"*[]int[1]", "{{index .PSI 1}}", "22", tVal, true},
292 {"NIL", "{{.NIL}}", "<nil>", tVal, true},
294 // Empty interfaces holding values.
295 {"empty nil", "{{.Empty0}}", "<no value>", tVal, true},
296 {"empty with int", "{{.Empty1}}", "3", tVal, true},
297 {"empty with string", "{{.Empty2}}", "empty2", tVal, true},
298 {"empty with slice", "{{.Empty3}}", "[7 8]", tVal, true},
299 {"empty with struct", "{{.Empty4}}", "{UinEmpty}", tVal, true},
300 {"empty with struct, field", "{{.Empty4.V}}", "UinEmpty", tVal, true},
302 // Method calls.
303 {".Method0", "-{{.Method0}}-", "-M0-", tVal, true},
304 {".Method1(1234)", "-{{.Method1 1234}}-", "-1234-", tVal, true},
305 {".Method1(.I)", "-{{.Method1 .I}}-", "-17-", tVal, true},
306 {".Method2(3, .X)", "-{{.Method2 3 .X}}-", "-Method2: 3 x-", tVal, true},
307 {".Method2(.U16, `str`)", "-{{.Method2 .U16 `str`}}-", "-Method2: 16 str-", tVal, true},
308 {".Method2(.U16, $x)", "{{if $x := .X}}-{{.Method2 .U16 $x}}{{end}}-", "-Method2: 16 x-", tVal, true},
309 {".Method3(nil constant)", "-{{.Method3 nil}}-", "-Method3: <nil>-", tVal, true},
310 {".Method3(nil value)", "-{{.Method3 .MXI.unset}}-", "-Method3: <nil>-", tVal, true},
311 {"method on var", "{{if $x := .}}-{{$x.Method2 .U16 $x.X}}{{end}}-", "-Method2: 16 x-", tVal, true},
312 {"method on chained var",
313 "{{range .MSIone}}{{if $.U.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}",
314 "true", tVal, true},
315 {"chained method",
316 "{{range .MSIone}}{{if $.GetU.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}",
317 "true", tVal, true},
318 {"chained method on variable",
319 "{{with $x := .}}{{with .SI}}{{$.GetU.TrueFalse $.True}}{{end}}{{end}}",
320 "true", tVal, true},
321 {".NilOKFunc not nil", "{{call .NilOKFunc .PI}}", "false", tVal, true},
322 {".NilOKFunc nil", "{{call .NilOKFunc nil}}", "true", tVal, true},
324 // Function call builtin.
325 {".BinaryFunc", "{{call .BinaryFunc `1` `2`}}", "[1=2]", tVal, true},
326 {".VariadicFunc0", "{{call .VariadicFunc}}", "<>", tVal, true},
327 {".VariadicFunc2", "{{call .VariadicFunc `he` `llo`}}", "<he+llo>", tVal, true},
328 {".VariadicFuncInt", "{{call .VariadicFuncInt 33 `he` `llo`}}", "33=<he+llo>", tVal, true},
329 {"if .BinaryFunc call", "{{ if .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{end}}", "[1=2]", tVal, true},
330 {"if not .BinaryFunc call", "{{ if not .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{else}}No{{end}}", "No", tVal, true},
331 {"Interface Call", `{{stringer .S}}`, "foozle", map[string]interface{}{"S": bytes.NewBufferString("foozle")}, true},
332 {".ErrFunc", "{{call .ErrFunc}}", "bla", tVal, true},
334 // Erroneous function calls (check args).
335 {".BinaryFuncTooFew", "{{call .BinaryFunc `1`}}", "", tVal, false},
336 {".BinaryFuncTooMany", "{{call .BinaryFunc `1` `2` `3`}}", "", tVal, false},
337 {".BinaryFuncBad0", "{{call .BinaryFunc 1 3}}", "", tVal, false},
338 {".BinaryFuncBad1", "{{call .BinaryFunc `1` 3}}", "", tVal, false},
339 {".VariadicFuncBad0", "{{call .VariadicFunc 3}}", "", tVal, false},
340 {".VariadicFuncIntBad0", "{{call .VariadicFuncInt}}", "", tVal, false},
341 {".VariadicFuncIntBad`", "{{call .VariadicFuncInt `x`}}", "", tVal, false},
342 {".VariadicFuncNilBad", "{{call .VariadicFunc nil}}", "", tVal, false},
344 // Pipelines.
345 {"pipeline", "-{{.Method0 | .Method2 .U16}}-", "-Method2: 16 M0-", tVal, true},
346 {"pipeline func", "-{{call .VariadicFunc `llo` | call .VariadicFunc `he` }}-", "-<he+<llo>>-", tVal, true},
348 // Parenthesized expressions
349 {"parens in pipeline", "{{printf `%d %d %d` (1) (2 | add 3) (add 4 (add 5 6))}}", "1 5 15", tVal, true},
351 // Parenthesized expressions with field accesses
352 {"parens: $ in paren", "{{($).X}}", "x", tVal, true},
353 {"parens: $.GetU in paren", "{{($.GetU).V}}", "v", tVal, true},
354 {"parens: $ in paren in pipe", "{{($ | echo).X}}", "x", tVal, true},
355 {"parens: spaces and args", `{{(makemap "up" "down" "left" "right").left}}`, "right", tVal, true},
357 // If.
358 {"if true", "{{if true}}TRUE{{end}}", "TRUE", tVal, true},
359 {"if false", "{{if false}}TRUE{{else}}FALSE{{end}}", "FALSE", tVal, true},
360 {"if nil", "{{if nil}}TRUE{{end}}", "", tVal, false},
361 {"if 1", "{{if 1}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
362 {"if 0", "{{if 0}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
363 {"if 1.5", "{{if 1.5}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
364 {"if 0.0", "{{if .FloatZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
365 {"if 1.5i", "{{if 1.5i}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
366 {"if 0.0i", "{{if .ComplexZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
367 {"if emptystring", "{{if ``}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
368 {"if string", "{{if `notempty`}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
369 {"if emptyslice", "{{if .SIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
370 {"if slice", "{{if .SI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
371 {"if emptymap", "{{if .MSIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
372 {"if map", "{{if .MSI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
373 {"if map unset", "{{if .MXI.none}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
374 {"if map not unset", "{{if not .MXI.none}}ZERO{{else}}NON-ZERO{{end}}", "ZERO", tVal, true},
375 {"if $x with $y int", "{{if $x := true}}{{with $y := .I}}{{$x}},{{$y}}{{end}}{{end}}", "true,17", tVal, true},
376 {"if $x with $x int", "{{if $x := true}}{{with $x := .I}}{{$x}},{{end}}{{$x}}{{end}}", "17,true", tVal, true},
377 {"if else if", "{{if false}}FALSE{{else if true}}TRUE{{end}}", "TRUE", tVal, true},
378 {"if else chain", "{{if eq 1 3}}1{{else if eq 2 3}}2{{else if eq 3 3}}3{{end}}", "3", tVal, true},
380 // Print etc.
381 {"print", `{{print "hello, print"}}`, "hello, print", tVal, true},
382 {"print 123", `{{print 1 2 3}}`, "1 2 3", tVal, true},
383 {"print nil", `{{print nil}}`, "<nil>", tVal, true},
384 {"println", `{{println 1 2 3}}`, "1 2 3\n", tVal, true},
385 {"printf int", `{{printf "%04x" 127}}`, "007f", tVal, true},
386 {"printf float", `{{printf "%g" 3.5}}`, "3.5", tVal, true},
387 {"printf complex", `{{printf "%g" 1+7i}}`, "(1+7i)", tVal, true},
388 {"printf string", `{{printf "%s" "hello"}}`, "hello", tVal, true},
389 {"printf function", `{{printf "%#q" zeroArgs}}`, "`zeroArgs`", tVal, true},
390 {"printf field", `{{printf "%s" .U.V}}`, "v", tVal, true},
391 {"printf method", `{{printf "%s" .Method0}}`, "M0", tVal, true},
392 {"printf dot", `{{with .I}}{{printf "%d" .}}{{end}}`, "17", tVal, true},
393 {"printf var", `{{with $x := .I}}{{printf "%d" $x}}{{end}}`, "17", tVal, true},
394 {"printf lots", `{{printf "%d %s %g %s" 127 "hello" 7-3i .Method0}}`, "127 hello (7-3i) M0", tVal, true},
396 // HTML.
397 {"html", `{{html "<script>alert(\"XSS\");</script>"}}`,
398 "&lt;script&gt;alert(&#34;XSS&#34;);&lt;/script&gt;", nil, true},
399 {"html pipeline", `{{printf "<script>alert(\"XSS\");</script>" | html}}`,
400 "&lt;script&gt;alert(&#34;XSS&#34;);&lt;/script&gt;", nil, true},
401 {"html", `{{html .PS}}`, "a string", tVal, true},
403 // JavaScript.
404 {"js", `{{js .}}`, `It\'d be nice.`, `It'd be nice.`, true},
406 // URL query.
407 {"urlquery", `{{"http://www.example.org/"|urlquery}}`, "http%3A%2F%2Fwww.example.org%2F", nil, true},
409 // Booleans
410 {"not", "{{not true}} {{not false}}", "false true", nil, true},
411 {"and", "{{and false 0}} {{and 1 0}} {{and 0 true}} {{and 1 1}}", "false 0 0 1", nil, true},
412 {"or", "{{or 0 0}} {{or 1 0}} {{or 0 true}} {{or 1 1}}", "0 1 true 1", nil, true},
413 {"boolean if", "{{if and true 1 `hi`}}TRUE{{else}}FALSE{{end}}", "TRUE", tVal, true},
414 {"boolean if not", "{{if and true 1 `hi` | not}}TRUE{{else}}FALSE{{end}}", "FALSE", nil, true},
416 // Indexing.
417 {"slice[0]", "{{index .SI 0}}", "3", tVal, true},
418 {"slice[1]", "{{index .SI 1}}", "4", tVal, true},
419 {"slice[HUGE]", "{{index .SI 10}}", "", tVal, false},
420 {"slice[WRONG]", "{{index .SI `hello`}}", "", tVal, false},
421 {"map[one]", "{{index .MSI `one`}}", "1", tVal, true},
422 {"map[two]", "{{index .MSI `two`}}", "2", tVal, true},
423 {"map[NO]", "{{index .MSI `XXX`}}", "0", tVal, true},
424 {"map[nil]", "{{index .MSI nil}}", "0", tVal, true},
425 {"map[WRONG]", "{{index .MSI 10}}", "", tVal, false},
426 {"double index", "{{index .SMSI 1 `eleven`}}", "11", tVal, true},
428 // Len.
429 {"slice", "{{len .SI}}", "3", tVal, true},
430 {"map", "{{len .MSI }}", "3", tVal, true},
431 {"len of int", "{{len 3}}", "", tVal, false},
432 {"len of nothing", "{{len .Empty0}}", "", tVal, false},
434 // With.
435 {"with true", "{{with true}}{{.}}{{end}}", "true", tVal, true},
436 {"with false", "{{with false}}{{.}}{{else}}FALSE{{end}}", "FALSE", tVal, true},
437 {"with 1", "{{with 1}}{{.}}{{else}}ZERO{{end}}", "1", tVal, true},
438 {"with 0", "{{with 0}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
439 {"with 1.5", "{{with 1.5}}{{.}}{{else}}ZERO{{end}}", "1.5", tVal, true},
440 {"with 0.0", "{{with .FloatZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
441 {"with 1.5i", "{{with 1.5i}}{{.}}{{else}}ZERO{{end}}", "(0+1.5i)", tVal, true},
442 {"with 0.0i", "{{with .ComplexZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
443 {"with emptystring", "{{with ``}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
444 {"with string", "{{with `notempty`}}{{.}}{{else}}EMPTY{{end}}", "notempty", tVal, true},
445 {"with emptyslice", "{{with .SIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
446 {"with slice", "{{with .SI}}{{.}}{{else}}EMPTY{{end}}", "[3 4 5]", tVal, true},
447 {"with emptymap", "{{with .MSIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
448 {"with map", "{{with .MSIone}}{{.}}{{else}}EMPTY{{end}}", "map[one:1]", tVal, true},
449 {"with empty interface, struct field", "{{with .Empty4}}{{.V}}{{end}}", "UinEmpty", tVal, true},
450 {"with $x int", "{{with $x := .I}}{{$x}}{{end}}", "17", tVal, true},
451 {"with $x struct.U.V", "{{with $x := $}}{{$x.U.V}}{{end}}", "v", tVal, true},
452 {"with variable and action", "{{with $x := $}}{{$y := $.U.V}}{{$y}}{{end}}", "v", tVal, true},
454 // Range.
455 {"range []int", "{{range .SI}}-{{.}}-{{end}}", "-3--4--5-", tVal, true},
456 {"range empty no else", "{{range .SIEmpty}}-{{.}}-{{end}}", "", tVal, true},
457 {"range []int else", "{{range .SI}}-{{.}}-{{else}}EMPTY{{end}}", "-3--4--5-", tVal, true},
458 {"range empty else", "{{range .SIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
459 {"range []bool", "{{range .SB}}-{{.}}-{{end}}", "-true--false-", tVal, true},
460 {"range []int method", "{{range .SI | .MAdd .I}}-{{.}}-{{end}}", "-20--21--22-", tVal, true},
461 {"range map", "{{range .MSI}}-{{.}}-{{end}}", "-1--3--2-", tVal, true},
462 {"range empty map no else", "{{range .MSIEmpty}}-{{.}}-{{end}}", "", tVal, true},
463 {"range map else", "{{range .MSI}}-{{.}}-{{else}}EMPTY{{end}}", "-1--3--2-", tVal, true},
464 {"range empty map else", "{{range .MSIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
465 {"range empty interface", "{{range .Empty3}}-{{.}}-{{else}}EMPTY{{end}}", "-7--8-", tVal, true},
466 {"range empty nil", "{{range .Empty0}}-{{.}}-{{end}}", "", tVal, true},
467 {"range $x SI", "{{range $x := .SI}}<{{$x}}>{{end}}", "<3><4><5>", tVal, true},
468 {"range $x $y SI", "{{range $x, $y := .SI}}<{{$x}}={{$y}}>{{end}}", "<0=3><1=4><2=5>", tVal, true},
469 {"range $x MSIone", "{{range $x := .MSIone}}<{{$x}}>{{end}}", "<1>", tVal, true},
470 {"range $x $y MSIone", "{{range $x, $y := .MSIone}}<{{$x}}={{$y}}>{{end}}", "<one=1>", tVal, true},
471 {"range $x PSI", "{{range $x := .PSI}}<{{$x}}>{{end}}", "<21><22><23>", tVal, true},
472 {"declare in range", "{{range $x := .PSI}}<{{$foo:=$x}}{{$x}}>{{end}}", "<21><22><23>", tVal, true},
473 {"range count", `{{range $i, $x := count 5}}[{{$i}}]{{$x}}{{end}}`, "[0]a[1]b[2]c[3]d[4]e", tVal, true},
474 {"range nil count", `{{range $i, $x := count 0}}{{else}}empty{{end}}`, "empty", tVal, true},
476 // Cute examples.
477 {"or as if true", `{{or .SI "slice is empty"}}`, "[3 4 5]", tVal, true},
478 {"or as if false", `{{or .SIEmpty "slice is empty"}}`, "slice is empty", tVal, true},
480 // Error handling.
481 {"error method, error", "{{.MyError true}}", "", tVal, false},
482 {"error method, no error", "{{.MyError false}}", "false", tVal, true},
484 // Fixed bugs.
485 // Must separate dot and receiver; otherwise args are evaluated with dot set to variable.
486 {"bug0", "{{range .MSIone}}{{if $.Method1 .}}X{{end}}{{end}}", "X", tVal, true},
487 // Do not loop endlessly in indirect for non-empty interfaces.
488 // The bug appears with *interface only; looped forever.
489 {"bug1", "{{.Method0}}", "M0", &iVal, true},
490 // Was taking address of interface field, so method set was empty.
491 {"bug2", "{{$.NonEmptyInterface.Method0}}", "M0", tVal, true},
492 // Struct values were not legal in with - mere oversight.
493 {"bug3", "{{with $}}{{.Method0}}{{end}}", "M0", tVal, true},
494 // Nil interface values in if.
495 {"bug4", "{{if .Empty0}}non-nil{{else}}nil{{end}}", "nil", tVal, true},
496 // Stringer.
497 {"bug5", "{{.Str}}", "foozle", tVal, true},
498 {"bug5a", "{{.Err}}", "erroozle", tVal, true},
499 // Args need to be indirected and dereferenced sometimes.
500 {"bug6a", "{{vfunc .V0 .V1}}", "vfunc", tVal, true},
501 {"bug6b", "{{vfunc .V0 .V0}}", "vfunc", tVal, true},
502 {"bug6c", "{{vfunc .V1 .V0}}", "vfunc", tVal, true},
503 {"bug6d", "{{vfunc .V1 .V1}}", "vfunc", tVal, true},
504 // Legal parse but illegal execution: non-function should have no arguments.
505 {"bug7a", "{{3 2}}", "", tVal, false},
506 {"bug7b", "{{$x := 1}}{{$x 2}}", "", tVal, false},
507 {"bug7c", "{{$x := 1}}{{3 | $x}}", "", tVal, false},
508 // Pipelined arg was not being type-checked.
509 {"bug8a", "{{3|oneArg}}", "", tVal, false},
510 {"bug8b", "{{4|dddArg 3}}", "", tVal, false},
511 // A bug was introduced that broke map lookups for lower-case names.
512 {"bug9", "{{.cause}}", "neglect", map[string]string{"cause": "neglect"}, true},
513 // Field chain starting with function did not work.
514 {"bug10", "{{mapOfThree.three}}-{{(mapOfThree).three}}", "3-3", 0, true},
515 // Dereferencing nil pointer while evaluating function arguments should not panic. Issue 7333.
516 {"bug11", "{{valueString .PS}}", "", T{}, false},
519 func zeroArgs() string {
520 return "zeroArgs"
523 func oneArg(a string) string {
524 return "oneArg=" + a
527 func dddArg(a int, b ...string) string {
528 return fmt.Sprintln(a, b)
531 // count returns a channel that will deliver n sequential 1-letter strings starting at "a"
532 func count(n int) chan string {
533 if n == 0 {
534 return nil
536 c := make(chan string)
537 go func() {
538 for i := 0; i < n; i++ {
539 c <- "abcdefghijklmnop"[i : i+1]
541 close(c)
543 return c
546 // vfunc takes a *V and a V
547 func vfunc(V, *V) string {
548 return "vfunc"
551 // valueString takes a string, not a pointer.
552 func valueString(v string) string {
553 return "value is ignored"
556 func add(args ...int) int {
557 sum := 0
558 for _, x := range args {
559 sum += x
561 return sum
564 func echo(arg interface{}) interface{} {
565 return arg
568 func makemap(arg ...string) map[string]string {
569 if len(arg)%2 != 0 {
570 panic("bad makemap")
572 m := make(map[string]string)
573 for i := 0; i < len(arg); i += 2 {
574 m[arg[i]] = arg[i+1]
576 return m
579 func stringer(s fmt.Stringer) string {
580 return s.String()
583 func mapOfThree() interface{} {
584 return map[string]int{"three": 3}
587 func testExecute(execTests []execTest, template *Template, t *testing.T) {
588 b := new(bytes.Buffer)
589 funcs := FuncMap{
590 "add": add,
591 "count": count,
592 "dddArg": dddArg,
593 "echo": echo,
594 "makemap": makemap,
595 "mapOfThree": mapOfThree,
596 "oneArg": oneArg,
597 "stringer": stringer,
598 "typeOf": typeOf,
599 "valueString": valueString,
600 "vfunc": vfunc,
601 "zeroArgs": zeroArgs,
603 for _, test := range execTests {
604 var tmpl *Template
605 var err error
606 if template == nil {
607 tmpl, err = New(test.name).Funcs(funcs).Parse(test.input)
608 } else {
609 tmpl, err = template.New(test.name).Funcs(funcs).Parse(test.input)
611 if err != nil {
612 t.Errorf("%s: parse error: %s", test.name, err)
613 continue
615 b.Reset()
616 err = tmpl.Execute(b, test.data)
617 switch {
618 case !test.ok && err == nil:
619 t.Errorf("%s: expected error; got none", test.name)
620 continue
621 case test.ok && err != nil:
622 t.Errorf("%s: unexpected execute error: %s", test.name, err)
623 continue
624 case !test.ok && err != nil:
625 // expected error, got one
626 if *debug {
627 fmt.Printf("%s: %s\n\t%s\n", test.name, test.input, err)
630 result := b.String()
631 if result != test.output {
632 t.Errorf("%s: expected\n\t%q\ngot\n\t%q", test.name, test.output, result)
637 func TestExecute(t *testing.T) {
638 testExecute(execTests, nil, t)
641 var delimPairs = []string{
642 "", "", // default
643 "{{", "}}", // same as default
644 "<<", ">>", // distinct
645 "|", "|", // same
646 "(日)", "(本)", // peculiar
649 func TestDelims(t *testing.T) {
650 const hello = "Hello, world"
651 var value = struct{ Str string }{hello}
652 for i := 0; i < len(delimPairs); i += 2 {
653 text := ".Str"
654 left := delimPairs[i+0]
655 trueLeft := left
656 right := delimPairs[i+1]
657 trueRight := right
658 if left == "" { // default case
659 trueLeft = "{{"
661 if right == "" { // default case
662 trueRight = "}}"
664 text = trueLeft + text + trueRight
665 // Now add a comment
666 text += trueLeft + "/*comment*/" + trueRight
667 // Now add an action containing a string.
668 text += trueLeft + `"` + trueLeft + `"` + trueRight
669 // At this point text looks like `{{.Str}}{{/*comment*/}}{{"{{"}}`.
670 tmpl, err := New("delims").Delims(left, right).Parse(text)
671 if err != nil {
672 t.Fatalf("delim %q text %q parse err %s", left, text, err)
674 var b = new(bytes.Buffer)
675 err = tmpl.Execute(b, value)
676 if err != nil {
677 t.Fatalf("delim %q exec err %s", left, err)
679 if b.String() != hello+trueLeft {
680 t.Errorf("expected %q got %q", hello+trueLeft, b.String())
685 // Check that an error from a method flows back to the top.
686 func TestExecuteError(t *testing.T) {
687 b := new(bytes.Buffer)
688 tmpl := New("error")
689 _, err := tmpl.Parse("{{.MyError true}}")
690 if err != nil {
691 t.Fatalf("parse error: %s", err)
693 err = tmpl.Execute(b, tVal)
694 if err == nil {
695 t.Errorf("expected error; got none")
696 } else if !strings.Contains(err.Error(), myError.Error()) {
697 if *debug {
698 fmt.Printf("test execute error: %s\n", err)
700 t.Errorf("expected myError; got %s", err)
704 const execErrorText = `line 1
705 line 2
706 line 3
707 {{template "one" .}}
708 {{define "one"}}{{template "two" .}}{{end}}
709 {{define "two"}}{{template "three" .}}{{end}}
710 {{define "three"}}{{index "hi" $}}{{end}}`
712 // Check that an error from a nested template contains all the relevant information.
713 func TestExecError(t *testing.T) {
714 tmpl, err := New("top").Parse(execErrorText)
715 if err != nil {
716 t.Fatal("parse error:", err)
718 var b bytes.Buffer
719 err = tmpl.Execute(&b, 5) // 5 is out of range indexing "hi"
720 if err == nil {
721 t.Fatal("expected error")
723 const want = `template: top:7:20: executing "three" at <index "hi" $>: error calling index: index out of range: 5`
724 got := err.Error()
725 if got != want {
726 t.Errorf("expected\n%q\ngot\n%q", want, got)
730 func TestJSEscaping(t *testing.T) {
731 testCases := []struct {
732 in, exp string
734 {`a`, `a`},
735 {`'foo`, `\'foo`},
736 {`Go "jump" \`, `Go \"jump\" \\`},
737 {`Yukihiro says "今日は世界"`, `Yukihiro says \"今日は世界\"`},
738 {"unprintable \uFDFF", `unprintable \uFDFF`},
739 {`<html>`, `\x3Chtml\x3E`},
741 for _, tc := range testCases {
742 s := JSEscapeString(tc.in)
743 if s != tc.exp {
744 t.Errorf("JS escaping [%s] got [%s] want [%s]", tc.in, s, tc.exp)
749 // A nice example: walk a binary tree.
751 type Tree struct {
752 Val int
753 Left, Right *Tree
756 // Use different delimiters to test Set.Delims.
757 const treeTemplate = `
758 (define "tree")
760 (.Val)
761 (with .Left)
762 (template "tree" .)
763 (end)
764 (with .Right)
765 (template "tree" .)
766 (end)
768 (end)
771 func TestTree(t *testing.T) {
772 var tree = &Tree{
774 &Tree{
775 2, &Tree{
777 &Tree{
778 4, nil, nil,
780 nil,
782 &Tree{
784 &Tree{
785 6, nil, nil,
787 nil,
790 &Tree{
792 &Tree{
794 &Tree{
795 9, nil, nil,
797 nil,
799 &Tree{
801 &Tree{
802 11, nil, nil,
804 nil,
808 tmpl, err := New("root").Delims("(", ")").Parse(treeTemplate)
809 if err != nil {
810 t.Fatal("parse error:", err)
812 var b bytes.Buffer
813 stripSpace := func(r rune) rune {
814 if r == '\t' || r == '\n' {
815 return -1
817 return r
819 const expect = "[1[2[3[4]][5[6]]][7[8[9]][10[11]]]]"
820 // First by looking up the template.
821 err = tmpl.Lookup("tree").Execute(&b, tree)
822 if err != nil {
823 t.Fatal("exec error:", err)
825 result := strings.Map(stripSpace, b.String())
826 if result != expect {
827 t.Errorf("expected %q got %q", expect, result)
829 // Then direct to execution.
830 b.Reset()
831 err = tmpl.ExecuteTemplate(&b, "tree", tree)
832 if err != nil {
833 t.Fatal("exec error:", err)
835 result = strings.Map(stripSpace, b.String())
836 if result != expect {
837 t.Errorf("expected %q got %q", expect, result)
841 func TestExecuteOnNewTemplate(t *testing.T) {
842 // This is issue 3872.
843 _ = New("Name").Templates()
846 const testTemplates = `{{define "one"}}one{{end}}{{define "two"}}two{{end}}`
848 func TestMessageForExecuteEmpty(t *testing.T) {
849 // Test a truly empty template.
850 tmpl := New("empty")
851 var b bytes.Buffer
852 err := tmpl.Execute(&b, 0)
853 if err == nil {
854 t.Fatal("expected initial error")
856 got := err.Error()
857 want := `template: empty: "empty" is an incomplete or empty template`
858 if got != want {
859 t.Errorf("expected error %s got %s", want, got)
861 // Add a non-empty template to check that the error is helpful.
862 tests, err := New("").Parse(testTemplates)
863 if err != nil {
864 t.Fatal(err)
866 tmpl.AddParseTree("secondary", tests.Tree)
867 err = tmpl.Execute(&b, 0)
868 if err == nil {
869 t.Fatal("expected second error")
871 got = err.Error()
872 want = `template: empty: "empty" is an incomplete or empty template; defined templates are: "secondary"`
873 if got != want {
874 t.Errorf("expected error %s got %s", want, got)
876 // Make sure we can execute the secondary.
877 err = tmpl.ExecuteTemplate(&b, "secondary", 0)
878 if err != nil {
879 t.Fatal(err)
883 type cmpTest struct {
884 expr string
885 truth string
886 ok bool
889 var cmpTests = []cmpTest{
890 {"eq true true", "true", true},
891 {"eq true false", "false", true},
892 {"eq 1+2i 1+2i", "true", true},
893 {"eq 1+2i 1+3i", "false", true},
894 {"eq 1.5 1.5", "true", true},
895 {"eq 1.5 2.5", "false", true},
896 {"eq 1 1", "true", true},
897 {"eq 1 2", "false", true},
898 {"eq `xy` `xy`", "true", true},
899 {"eq `xy` `xyz`", "false", true},
900 {"eq .Xuint .Xuint", "true", true},
901 {"eq .Xuint .Yuint", "false", true},
902 {"eq 3 4 5 6 3", "true", true},
903 {"eq 3 4 5 6 7", "false", true},
904 {"ne true true", "false", true},
905 {"ne true false", "true", true},
906 {"ne 1+2i 1+2i", "false", true},
907 {"ne 1+2i 1+3i", "true", true},
908 {"ne 1.5 1.5", "false", true},
909 {"ne 1.5 2.5", "true", true},
910 {"ne 1 1", "false", true},
911 {"ne 1 2", "true", true},
912 {"ne `xy` `xy`", "false", true},
913 {"ne `xy` `xyz`", "true", true},
914 {"ne .Xuint .Xuint", "false", true},
915 {"ne .Xuint .Yuint", "true", true},
916 {"lt 1.5 1.5", "false", true},
917 {"lt 1.5 2.5", "true", true},
918 {"lt 1 1", "false", true},
919 {"lt 1 2", "true", true},
920 {"lt `xy` `xy`", "false", true},
921 {"lt `xy` `xyz`", "true", true},
922 {"lt .Xuint .Xuint", "false", true},
923 {"lt .Xuint .Yuint", "true", true},
924 {"le 1.5 1.5", "true", true},
925 {"le 1.5 2.5", "true", true},
926 {"le 2.5 1.5", "false", true},
927 {"le 1 1", "true", true},
928 {"le 1 2", "true", true},
929 {"le 2 1", "false", true},
930 {"le `xy` `xy`", "true", true},
931 {"le `xy` `xyz`", "true", true},
932 {"le `xyz` `xy`", "false", true},
933 {"le .Xuint .Xuint", "true", true},
934 {"le .Xuint .Yuint", "true", true},
935 {"le .Yuint .Xuint", "false", true},
936 {"gt 1.5 1.5", "false", true},
937 {"gt 1.5 2.5", "false", true},
938 {"gt 1 1", "false", true},
939 {"gt 2 1", "true", true},
940 {"gt 1 2", "false", true},
941 {"gt `xy` `xy`", "false", true},
942 {"gt `xy` `xyz`", "false", true},
943 {"gt .Xuint .Xuint", "false", true},
944 {"gt .Xuint .Yuint", "false", true},
945 {"gt .Yuint .Xuint", "true", true},
946 {"ge 1.5 1.5", "true", true},
947 {"ge 1.5 2.5", "false", true},
948 {"ge 2.5 1.5", "true", true},
949 {"ge 1 1", "true", true},
950 {"ge 1 2", "false", true},
951 {"ge 2 1", "true", true},
952 {"ge `xy` `xy`", "true", true},
953 {"ge `xy` `xyz`", "false", true},
954 {"ge `xyz` `xy`", "true", true},
955 {"ge .Xuint .Xuint", "true", true},
956 {"ge .Xuint .Yuint", "false", true},
957 {"ge .Yuint .Xuint", "true", true},
958 // Errors
959 {"eq `xy` 1", "", false}, // Different types.
960 {"lt true true", "", false}, // Unordered types.
961 {"lt 1+0i 1+0i", "", false}, // Unordered types.
964 func TestComparison(t *testing.T) {
965 b := new(bytes.Buffer)
966 var cmpStruct = struct {
967 Xuint, Yuint uint
968 }{3, 4}
969 for _, test := range cmpTests {
970 text := fmt.Sprintf("{{if %s}}true{{else}}false{{end}}", test.expr)
971 tmpl, err := New("empty").Parse(text)
972 if err != nil {
973 t.Fatal(err)
975 b.Reset()
976 err = tmpl.Execute(b, &cmpStruct)
977 if test.ok && err != nil {
978 t.Errorf("%s errored incorrectly: %s", test.expr, err)
979 continue
981 if !test.ok && err == nil {
982 t.Errorf("%s did not error", test.expr)
983 continue
985 if b.String() != test.truth {
986 t.Errorf("%s: want %s; got %s", test.expr, test.truth, b.String())