OSDN Git Service

libgo: Update to Go 1.0.3.
[pf3gnuchains/gcc-fork.git] / libgo / go / text / template / exec_test.go
1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package template
6
7 import (
8         "bytes"
9         "errors"
10         "flag"
11         "fmt"
12         "reflect"
13         "strings"
14         "testing"
15 )
16
17 var debug = flag.Bool("debug", false, "show the errors produced by the tests")
18
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 float64
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         PSI *[]int
61         NIL *int
62         // Function (not method)
63         BinaryFunc      func(string, string) string
64         VariadicFunc    func(...string) string
65         VariadicFuncInt func(int, ...string) string
66         // Template to test evaluation of templates.
67         Tmpl *Template
68 }
69
70 type U struct {
71         V string
72 }
73
74 type V struct {
75         j int
76 }
77
78 func (v *V) String() string {
79         if v == nil {
80                 return "nilV"
81         }
82         return fmt.Sprintf("<%d>", v.j)
83 }
84
85 type W struct {
86         k int
87 }
88
89 func (w *W) Error() string {
90         if w == nil {
91                 return "nilW"
92         }
93         return fmt.Sprintf("[%d]", w.k)
94 }
95
96 var tVal = &T{
97         True:   true,
98         I:      17,
99         U16:    16,
100         X:      "x",
101         U:      &U{"v"},
102         V0:     V{6666},
103         V1:     &V{7777}, // leave V2 as nil
104         W0:     W{888},
105         W1:     &W{999}, // leave W2 as nil
106         SI:     []int{3, 4, 5},
107         SB:     []bool{true, false},
108         MSI:    map[string]int{"one": 1, "two": 2, "three": 3},
109         MSIone: map[string]int{"one": 1},
110         MXI:    map[interface{}]int{"one": 1},
111         MII:    map[int]int{1: 1},
112         SMSI: []map[string]int{
113                 {"one": 1, "two": 2},
114                 {"eleven": 11, "twelve": 12},
115         },
116         Empty1:            3,
117         Empty2:            "empty2",
118         Empty3:            []int{7, 8},
119         Empty4:            &U{"UinEmpty"},
120         NonEmptyInterface: new(T),
121         Str:               bytes.NewBuffer([]byte("foozle")),
122         Err:               errors.New("erroozle"),
123         PI:                newInt(23),
124         PSI:               newIntSlice(21, 22, 23),
125         BinaryFunc:        func(a, b string) string { return fmt.Sprintf("[%s=%s]", a, b) },
126         VariadicFunc:      func(s ...string) string { return fmt.Sprint("<", strings.Join(s, "+"), ">") },
127         VariadicFuncInt:   func(a int, s ...string) string { return fmt.Sprint(a, "=<", strings.Join(s, "+"), ">") },
128         Tmpl:              Must(New("x").Parse("test template")), // "x" is the value of .X
129 }
130
131 // A non-empty interface.
132 type I interface {
133         Method0() string
134 }
135
136 var iVal I = tVal
137
138 // Helpers for creation.
139 func newInt(n int) *int {
140         p := new(int)
141         *p = n
142         return p
143 }
144
145 func newIntSlice(n ...int) *[]int {
146         p := new([]int)
147         *p = make([]int, len(n))
148         copy(*p, n)
149         return p
150 }
151
152 // Simple methods with and without arguments.
153 func (t *T) Method0() string {
154         return "M0"
155 }
156
157 func (t *T) Method1(a int) int {
158         return a
159 }
160
161 func (t *T) Method2(a uint16, b string) string {
162         return fmt.Sprintf("Method2: %d %s", a, b)
163 }
164
165 func (t *T) Method3(v interface{}) string {
166         return fmt.Sprintf("Method3: %v", v)
167 }
168
169 func (t *T) MAdd(a int, b []int) []int {
170         v := make([]int, len(b))
171         for i, x := range b {
172                 v[i] = x + a
173         }
174         return v
175 }
176
177 var myError = errors.New("my error")
178
179 // MyError returns a value and an error according to its argument.
180 func (t *T) MyError(error bool) (bool, error) {
181         if error {
182                 return true, myError
183         }
184         return false, nil
185 }
186
187 // A few methods to test chaining.
188 func (t *T) GetU() *U {
189         return t.U
190 }
191
192 func (u *U) TrueFalse(b bool) string {
193         if b {
194                 return "true"
195         }
196         return ""
197 }
198
199 func typeOf(arg interface{}) string {
200         return fmt.Sprintf("%T", arg)
201 }
202
203 type execTest struct {
204         name   string
205         input  string
206         output string
207         data   interface{}
208         ok     bool
209 }
210
211 // bigInt and bigUint are hex string representing numbers either side
212 // of the max int boundary.
213 // We do it this way so the test doesn't depend on ints being 32 bits.
214 var (
215         bigInt  = fmt.Sprintf("0x%x", int(1<<uint(reflect.TypeOf(0).Bits()-1)-1))
216         bigUint = fmt.Sprintf("0x%x", uint(1<<uint(reflect.TypeOf(0).Bits()-1)))
217 )
218
219 var execTests = []execTest{
220         // Trivial cases.
221         {"empty", "", "", nil, true},
222         {"text", "some text", "some text", nil, true},
223
224         // Ideal constants.
225         {"ideal int", "{{typeOf 3}}", "int", 0, true},
226         {"ideal float", "{{typeOf 1.0}}", "float64", 0, true},
227         {"ideal exp float", "{{typeOf 1e1}}", "float64", 0, true},
228         {"ideal complex", "{{typeOf 1i}}", "complex128", 0, true},
229         {"ideal int", "{{typeOf " + bigInt + "}}", "int", 0, true},
230         {"ideal too big", "{{typeOf " + bigUint + "}}", "", 0, false},
231
232         // Fields of structs.
233         {".X", "-{{.X}}-", "-x-", tVal, true},
234         {".U.V", "-{{.U.V}}-", "-v-", tVal, true},
235
236         // Fields on maps.
237         {"map .one", "{{.MSI.one}}", "1", tVal, true},
238         {"map .two", "{{.MSI.two}}", "2", tVal, true},
239         {"map .NO", "{{.MSI.NO}}", "<no value>", tVal, true},
240         {"map .one interface", "{{.MXI.one}}", "1", tVal, true},
241         {"map .WRONG args", "{{.MSI.one 1}}", "", tVal, false},
242         {"map .WRONG type", "{{.MII.one}}", "", tVal, false},
243
244         // Dots of all kinds to test basic evaluation.
245         {"dot int", "<{{.}}>", "<13>", 13, true},
246         {"dot uint", "<{{.}}>", "<14>", uint(14), true},
247         {"dot float", "<{{.}}>", "<15.1>", 15.1, true},
248         {"dot bool", "<{{.}}>", "<true>", true, true},
249         {"dot complex", "<{{.}}>", "<(16.2-17i)>", 16.2 - 17i, true},
250         {"dot string", "<{{.}}>", "<hello>", "hello", true},
251         {"dot slice", "<{{.}}>", "<[-1 -2 -3]>", []int{-1, -2, -3}, true},
252         {"dot map", "<{{.}}>", "<map[two:22]>", map[string]int{"two": 22}, true},
253         {"dot struct", "<{{.}}>", "<{7 seven}>", struct {
254                 a int
255                 b string
256         }{7, "seven"}, true},
257
258         // Variables.
259         {"$ int", "{{$}}", "123", 123, true},
260         {"$.I", "{{$.I}}", "17", tVal, true},
261         {"$.U.V", "{{$.U.V}}", "v", tVal, true},
262         {"declare in action", "{{$x := $.U.V}}{{$x}}", "v", tVal, true},
263
264         // Type with String method.
265         {"V{6666}.String()", "-{{.V0}}-", "-<6666>-", tVal, true},
266         {"&V{7777}.String()", "-{{.V1}}-", "-<7777>-", tVal, true},
267         {"(*V)(nil).String()", "-{{.V2}}-", "-nilV-", tVal, true},
268
269         // Type with Error method.
270         {"W{888}.Error()", "-{{.W0}}-", "-[888]-", tVal, true},
271         {"&W{999}.Error()", "-{{.W1}}-", "-[999]-", tVal, true},
272         {"(*W)(nil).Error()", "-{{.W2}}-", "-nilW-", tVal, true},
273
274         // Pointers.
275         {"*int", "{{.PI}}", "23", tVal, true},
276         {"*[]int", "{{.PSI}}", "[21 22 23]", tVal, true},
277         {"*[]int[1]", "{{index .PSI 1}}", "22", tVal, true},
278         {"NIL", "{{.NIL}}", "<nil>", tVal, true},
279
280         // Empty interfaces holding values.
281         {"empty nil", "{{.Empty0}}", "<no value>", tVal, true},
282         {"empty with int", "{{.Empty1}}", "3", tVal, true},
283         {"empty with string", "{{.Empty2}}", "empty2", tVal, true},
284         {"empty with slice", "{{.Empty3}}", "[7 8]", tVal, true},
285         {"empty with struct", "{{.Empty4}}", "{UinEmpty}", tVal, true},
286         {"empty with struct, field", "{{.Empty4.V}}", "UinEmpty", tVal, true},
287
288         // Method calls.
289         {".Method0", "-{{.Method0}}-", "-M0-", tVal, true},
290         {".Method1(1234)", "-{{.Method1 1234}}-", "-1234-", tVal, true},
291         {".Method1(.I)", "-{{.Method1 .I}}-", "-17-", tVal, true},
292         {".Method2(3, .X)", "-{{.Method2 3 .X}}-", "-Method2: 3 x-", tVal, true},
293         {".Method2(.U16, `str`)", "-{{.Method2 .U16 `str`}}-", "-Method2: 16 str-", tVal, true},
294         {".Method2(.U16, $x)", "{{if $x := .X}}-{{.Method2 .U16 $x}}{{end}}-", "-Method2: 16 x-", tVal, true},
295         {".Method3(nil)", "-{{.Method3 .MXI.unset}}-", "-Method3: <nil>-", tVal, true},
296         {"method on var", "{{if $x := .}}-{{$x.Method2 .U16 $x.X}}{{end}}-", "-Method2: 16 x-", tVal, true},
297         {"method on chained var",
298                 "{{range .MSIone}}{{if $.U.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}",
299                 "true", tVal, true},
300         {"chained method",
301                 "{{range .MSIone}}{{if $.GetU.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}",
302                 "true", tVal, true},
303         {"chained method on variable",
304                 "{{with $x := .}}{{with .SI}}{{$.GetU.TrueFalse $.True}}{{end}}{{end}}",
305                 "true", tVal, true},
306
307         // Function call builtin.
308         {".BinaryFunc", "{{call .BinaryFunc `1` `2`}}", "[1=2]", tVal, true},
309         {".VariadicFunc0", "{{call .VariadicFunc}}", "<>", tVal, true},
310         {".VariadicFunc2", "{{call .VariadicFunc `he` `llo`}}", "<he+llo>", tVal, true},
311         {".VariadicFuncInt", "{{call .VariadicFuncInt 33 `he` `llo`}}", "33=<he+llo>", tVal, true},
312         {"if .BinaryFunc call", "{{ if .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{end}}", "[1=2]", tVal, true},
313         {"if not .BinaryFunc call", "{{ if not .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{else}}No{{end}}", "No", tVal, true},
314         {"Interface Call", `{{stringer .S}}`, "foozle", map[string]interface{}{"S": bytes.NewBufferString("foozle")}, true},
315
316         // Erroneous function calls (check args).
317         {".BinaryFuncTooFew", "{{call .BinaryFunc `1`}}", "", tVal, false},
318         {".BinaryFuncTooMany", "{{call .BinaryFunc `1` `2` `3`}}", "", tVal, false},
319         {".BinaryFuncBad0", "{{call .BinaryFunc 1 3}}", "", tVal, false},
320         {".BinaryFuncBad1", "{{call .BinaryFunc `1` 3}}", "", tVal, false},
321         {".VariadicFuncBad0", "{{call .VariadicFunc 3}}", "", tVal, false},
322         {".VariadicFuncIntBad0", "{{call .VariadicFuncInt}}", "", tVal, false},
323         {".VariadicFuncIntBad`", "{{call .VariadicFuncInt `x`}}", "", tVal, false},
324
325         // Pipelines.
326         {"pipeline", "-{{.Method0 | .Method2 .U16}}-", "-Method2: 16 M0-", tVal, true},
327         {"pipeline func", "-{{call .VariadicFunc `llo` | call .VariadicFunc `he` }}-", "-<he+<llo>>-", tVal, true},
328
329         // If.
330         {"if true", "{{if true}}TRUE{{end}}", "TRUE", tVal, true},
331         {"if false", "{{if false}}TRUE{{else}}FALSE{{end}}", "FALSE", tVal, true},
332         {"if 1", "{{if 1}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
333         {"if 0", "{{if 0}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
334         {"if 1.5", "{{if 1.5}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
335         {"if 0.0", "{{if .FloatZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
336         {"if 1.5i", "{{if 1.5i}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
337         {"if 0.0i", "{{if .ComplexZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
338         {"if emptystring", "{{if ``}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
339         {"if string", "{{if `notempty`}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
340         {"if emptyslice", "{{if .SIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
341         {"if slice", "{{if .SI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
342         {"if emptymap", "{{if .MSIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
343         {"if map", "{{if .MSI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
344         {"if map unset", "{{if .MXI.none}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
345         {"if map not unset", "{{if not .MXI.none}}ZERO{{else}}NON-ZERO{{end}}", "ZERO", tVal, true},
346         {"if $x with $y int", "{{if $x := true}}{{with $y := .I}}{{$x}},{{$y}}{{end}}{{end}}", "true,17", tVal, true},
347         {"if $x with $x int", "{{if $x := true}}{{with $x := .I}}{{$x}},{{end}}{{$x}}{{end}}", "17,true", tVal, true},
348
349         // Print etc.
350         {"print", `{{print "hello, print"}}`, "hello, print", tVal, true},
351         {"print", `{{print 1 2 3}}`, "1 2 3", tVal, true},
352         {"println", `{{println 1 2 3}}`, "1 2 3\n", tVal, true},
353         {"printf int", `{{printf "%04x" 127}}`, "007f", tVal, true},
354         {"printf float", `{{printf "%g" 3.5}}`, "3.5", tVal, true},
355         {"printf complex", `{{printf "%g" 1+7i}}`, "(1+7i)", tVal, true},
356         {"printf string", `{{printf "%s" "hello"}}`, "hello", tVal, true},
357         {"printf function", `{{printf "%#q" zeroArgs}}`, "`zeroArgs`", tVal, true},
358         {"printf field", `{{printf "%s" .U.V}}`, "v", tVal, true},
359         {"printf method", `{{printf "%s" .Method0}}`, "M0", tVal, true},
360         {"printf dot", `{{with .I}}{{printf "%d" .}}{{end}}`, "17", tVal, true},
361         {"printf var", `{{with $x := .I}}{{printf "%d" $x}}{{end}}`, "17", tVal, true},
362         {"printf lots", `{{printf "%d %s %g %s" 127 "hello" 7-3i .Method0}}`, "127 hello (7-3i) M0", tVal, true},
363
364         // HTML.
365         {"html", `{{html "<script>alert(\"XSS\");</script>"}}`,
366                 "&lt;script&gt;alert(&#34;XSS&#34;);&lt;/script&gt;", nil, true},
367         {"html pipeline", `{{printf "<script>alert(\"XSS\");</script>" | html}}`,
368                 "&lt;script&gt;alert(&#34;XSS&#34;);&lt;/script&gt;", nil, true},
369
370         // JavaScript.
371         {"js", `{{js .}}`, `It\'d be nice.`, `It'd be nice.`, true},
372
373         // URL query.
374         {"urlquery", `{{"http://www.example.org/"|urlquery}}`, "http%3A%2F%2Fwww.example.org%2F", nil, true},
375
376         // Booleans
377         {"not", "{{not true}} {{not false}}", "false true", nil, true},
378         {"and", "{{and false 0}} {{and 1 0}} {{and 0 true}} {{and 1 1}}", "false 0 0 1", nil, true},
379         {"or", "{{or 0 0}} {{or 1 0}} {{or 0 true}} {{or 1 1}}", "0 1 true 1", nil, true},
380         {"boolean if", "{{if and true 1 `hi`}}TRUE{{else}}FALSE{{end}}", "TRUE", tVal, true},
381         {"boolean if not", "{{if and true 1 `hi` | not}}TRUE{{else}}FALSE{{end}}", "FALSE", nil, true},
382
383         // Indexing.
384         {"slice[0]", "{{index .SI 0}}", "3", tVal, true},
385         {"slice[1]", "{{index .SI 1}}", "4", tVal, true},
386         {"slice[HUGE]", "{{index .SI 10}}", "", tVal, false},
387         {"slice[WRONG]", "{{index .SI `hello`}}", "", tVal, false},
388         {"map[one]", "{{index .MSI `one`}}", "1", tVal, true},
389         {"map[two]", "{{index .MSI `two`}}", "2", tVal, true},
390         {"map[NO]", "{{index .MSI `XXX`}}", "0", tVal, true},
391         {"map[WRONG]", "{{index .MSI 10}}", "", tVal, false},
392         {"double index", "{{index .SMSI 1 `eleven`}}", "11", tVal, true},
393
394         // Len.
395         {"slice", "{{len .SI}}", "3", tVal, true},
396         {"map", "{{len .MSI }}", "3", tVal, true},
397         {"len of int", "{{len 3}}", "", tVal, false},
398         {"len of nothing", "{{len .Empty0}}", "", tVal, false},
399
400         // With.
401         {"with true", "{{with true}}{{.}}{{end}}", "true", tVal, true},
402         {"with false", "{{with false}}{{.}}{{else}}FALSE{{end}}", "FALSE", tVal, true},
403         {"with 1", "{{with 1}}{{.}}{{else}}ZERO{{end}}", "1", tVal, true},
404         {"with 0", "{{with 0}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
405         {"with 1.5", "{{with 1.5}}{{.}}{{else}}ZERO{{end}}", "1.5", tVal, true},
406         {"with 0.0", "{{with .FloatZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
407         {"with 1.5i", "{{with 1.5i}}{{.}}{{else}}ZERO{{end}}", "(0+1.5i)", tVal, true},
408         {"with 0.0i", "{{with .ComplexZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
409         {"with emptystring", "{{with ``}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
410         {"with string", "{{with `notempty`}}{{.}}{{else}}EMPTY{{end}}", "notempty", tVal, true},
411         {"with emptyslice", "{{with .SIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
412         {"with slice", "{{with .SI}}{{.}}{{else}}EMPTY{{end}}", "[3 4 5]", tVal, true},
413         {"with emptymap", "{{with .MSIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
414         {"with map", "{{with .MSIone}}{{.}}{{else}}EMPTY{{end}}", "map[one:1]", tVal, true},
415         {"with empty interface, struct field", "{{with .Empty4}}{{.V}}{{end}}", "UinEmpty", tVal, true},
416         {"with $x int", "{{with $x := .I}}{{$x}}{{end}}", "17", tVal, true},
417         {"with $x struct.U.V", "{{with $x := $}}{{$x.U.V}}{{end}}", "v", tVal, true},
418         {"with variable and action", "{{with $x := $}}{{$y := $.U.V}}{{$y}}{{end}}", "v", tVal, true},
419
420         // Range.
421         {"range []int", "{{range .SI}}-{{.}}-{{end}}", "-3--4--5-", tVal, true},
422         {"range empty no else", "{{range .SIEmpty}}-{{.}}-{{end}}", "", tVal, true},
423         {"range []int else", "{{range .SI}}-{{.}}-{{else}}EMPTY{{end}}", "-3--4--5-", tVal, true},
424         {"range empty else", "{{range .SIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
425         {"range []bool", "{{range .SB}}-{{.}}-{{end}}", "-true--false-", tVal, true},
426         {"range []int method", "{{range .SI | .MAdd .I}}-{{.}}-{{end}}", "-20--21--22-", tVal, true},
427         {"range map", "{{range .MSI}}-{{.}}-{{end}}", "-1--3--2-", tVal, true},
428         {"range empty map no else", "{{range .MSIEmpty}}-{{.}}-{{end}}", "", tVal, true},
429         {"range map else", "{{range .MSI}}-{{.}}-{{else}}EMPTY{{end}}", "-1--3--2-", tVal, true},
430         {"range empty map else", "{{range .MSIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
431         {"range empty interface", "{{range .Empty3}}-{{.}}-{{else}}EMPTY{{end}}", "-7--8-", tVal, true},
432         {"range empty nil", "{{range .Empty0}}-{{.}}-{{end}}", "", tVal, true},
433         {"range $x SI", "{{range $x := .SI}}<{{$x}}>{{end}}", "<3><4><5>", tVal, true},
434         {"range $x $y SI", "{{range $x, $y := .SI}}<{{$x}}={{$y}}>{{end}}", "<0=3><1=4><2=5>", tVal, true},
435         {"range $x MSIone", "{{range $x := .MSIone}}<{{$x}}>{{end}}", "<1>", tVal, true},
436         {"range $x $y MSIone", "{{range $x, $y := .MSIone}}<{{$x}}={{$y}}>{{end}}", "<one=1>", tVal, true},
437         {"range $x PSI", "{{range $x := .PSI}}<{{$x}}>{{end}}", "<21><22><23>", tVal, true},
438         {"declare in range", "{{range $x := .PSI}}<{{$foo:=$x}}{{$x}}>{{end}}", "<21><22><23>", tVal, true},
439         {"range count", `{{range $i, $x := count 5}}[{{$i}}]{{$x}}{{end}}`, "[0]a[1]b[2]c[3]d[4]e", tVal, true},
440         {"range nil count", `{{range $i, $x := count 0}}{{else}}empty{{end}}`, "empty", tVal, true},
441
442         // Cute examples.
443         {"or as if true", `{{or .SI "slice is empty"}}`, "[3 4 5]", tVal, true},
444         {"or as if false", `{{or .SIEmpty "slice is empty"}}`, "slice is empty", tVal, true},
445
446         // Error handling.
447         {"error method, error", "{{.MyError true}}", "", tVal, false},
448         {"error method, no error", "{{.MyError false}}", "false", tVal, true},
449
450         // Fixed bugs.
451         // Must separate dot and receiver; otherwise args are evaluated with dot set to variable.
452         {"bug0", "{{range .MSIone}}{{if $.Method1 .}}X{{end}}{{end}}", "X", tVal, true},
453         // Do not loop endlessly in indirect for non-empty interfaces.
454         // The bug appears with *interface only; looped forever.
455         {"bug1", "{{.Method0}}", "M0", &iVal, true},
456         // Was taking address of interface field, so method set was empty.
457         {"bug2", "{{$.NonEmptyInterface.Method0}}", "M0", tVal, true},
458         // Struct values were not legal in with - mere oversight.
459         {"bug3", "{{with $}}{{.Method0}}{{end}}", "M0", tVal, true},
460         // Nil interface values in if.
461         {"bug4", "{{if .Empty0}}non-nil{{else}}nil{{end}}", "nil", tVal, true},
462         // Stringer.
463         {"bug5", "{{.Str}}", "foozle", tVal, true},
464         {"bug5a", "{{.Err}}", "erroozle", tVal, true},
465         // Args need to be indirected and dereferenced sometimes.
466         {"bug6a", "{{vfunc .V0 .V1}}", "vfunc", tVal, true},
467         {"bug6b", "{{vfunc .V0 .V0}}", "vfunc", tVal, true},
468         {"bug6c", "{{vfunc .V1 .V0}}", "vfunc", tVal, true},
469         {"bug6d", "{{vfunc .V1 .V1}}", "vfunc", tVal, true},
470         // Legal parse but illegal execution: non-function should have no arguments.
471         {"bug7a", "{{3 2}}", "", tVal, false},
472         {"bug7b", "{{$x := 1}}{{$x 2}}", "", tVal, false},
473         {"bug7c", "{{$x := 1}}{{3 | $x}}", "", tVal, false},
474         // Pipelined arg was not being type-checked.
475         {"bug8a", "{{3|oneArg}}", "", tVal, false},
476         {"bug8b", "{{4|dddArg 3}}", "", tVal, false},
477 }
478
479 func zeroArgs() string {
480         return "zeroArgs"
481 }
482
483 func oneArg(a string) string {
484         return "oneArg=" + a
485 }
486
487 func dddArg(a int, b ...string) string {
488         return fmt.Sprintln(a, b)
489 }
490
491 // count returns a channel that will deliver n sequential 1-letter strings starting at "a"
492 func count(n int) chan string {
493         if n == 0 {
494                 return nil
495         }
496         c := make(chan string)
497         go func() {
498                 for i := 0; i < n; i++ {
499                         c <- "abcdefghijklmnop"[i : i+1]
500                 }
501                 close(c)
502         }()
503         return c
504 }
505
506 // vfunc takes a *V and a V
507 func vfunc(V, *V) string {
508         return "vfunc"
509 }
510
511 func stringer(s fmt.Stringer) string {
512         return s.String()
513 }
514
515 func testExecute(execTests []execTest, template *Template, t *testing.T) {
516         b := new(bytes.Buffer)
517         funcs := FuncMap{
518                 "count":    count,
519                 "dddArg":   dddArg,
520                 "oneArg":   oneArg,
521                 "typeOf":   typeOf,
522                 "vfunc":    vfunc,
523                 "zeroArgs": zeroArgs,
524                 "stringer": stringer,
525         }
526         for _, test := range execTests {
527                 var tmpl *Template
528                 var err error
529                 if template == nil {
530                         tmpl, err = New(test.name).Funcs(funcs).Parse(test.input)
531                 } else {
532                         tmpl, err = template.New(test.name).Funcs(funcs).Parse(test.input)
533                 }
534                 if err != nil {
535                         t.Errorf("%s: parse error: %s", test.name, err)
536                         continue
537                 }
538                 b.Reset()
539                 err = tmpl.Execute(b, test.data)
540                 switch {
541                 case !test.ok && err == nil:
542                         t.Errorf("%s: expected error; got none", test.name)
543                         continue
544                 case test.ok && err != nil:
545                         t.Errorf("%s: unexpected execute error: %s", test.name, err)
546                         continue
547                 case !test.ok && err != nil:
548                         // expected error, got one
549                         if *debug {
550                                 fmt.Printf("%s: %s\n\t%s\n", test.name, test.input, err)
551                         }
552                 }
553                 result := b.String()
554                 if result != test.output {
555                         t.Errorf("%s: expected\n\t%q\ngot\n\t%q", test.name, test.output, result)
556                 }
557         }
558 }
559
560 func TestExecute(t *testing.T) {
561         testExecute(execTests, nil, t)
562 }
563
564 var delimPairs = []string{
565         "", "", // default
566         "{{", "}}", // same as default
567         "<<", ">>", // distinct
568         "|", "|", // same
569         "(日)", "(本)", // peculiar
570 }
571
572 func TestDelims(t *testing.T) {
573         const hello = "Hello, world"
574         var value = struct{ Str string }{hello}
575         for i := 0; i < len(delimPairs); i += 2 {
576                 text := ".Str"
577                 left := delimPairs[i+0]
578                 trueLeft := left
579                 right := delimPairs[i+1]
580                 trueRight := right
581                 if left == "" { // default case
582                         trueLeft = "{{"
583                 }
584                 if right == "" { // default case
585                         trueRight = "}}"
586                 }
587                 text = trueLeft + text + trueRight
588                 // Now add a comment
589                 text += trueLeft + "/*comment*/" + trueRight
590                 // Now add  an action containing a string.
591                 text += trueLeft + `"` + trueLeft + `"` + trueRight
592                 // At this point text looks like `{{.Str}}{{/*comment*/}}{{"{{"}}`.
593                 tmpl, err := New("delims").Delims(left, right).Parse(text)
594                 if err != nil {
595                         t.Fatalf("delim %q text %q parse err %s", left, text, err)
596                 }
597                 var b = new(bytes.Buffer)
598                 err = tmpl.Execute(b, value)
599                 if err != nil {
600                         t.Fatalf("delim %q exec err %s", left, err)
601                 }
602                 if b.String() != hello+trueLeft {
603                         t.Errorf("expected %q got %q", hello+trueLeft, b.String())
604                 }
605         }
606 }
607
608 // Check that an error from a method flows back to the top.
609 func TestExecuteError(t *testing.T) {
610         b := new(bytes.Buffer)
611         tmpl := New("error")
612         _, err := tmpl.Parse("{{.MyError true}}")
613         if err != nil {
614                 t.Fatalf("parse error: %s", err)
615         }
616         err = tmpl.Execute(b, tVal)
617         if err == nil {
618                 t.Errorf("expected error; got none")
619         } else if !strings.Contains(err.Error(), myError.Error()) {
620                 if *debug {
621                         fmt.Printf("test execute error: %s\n", err)
622                 }
623                 t.Errorf("expected myError; got %s", err)
624         }
625 }
626
627 func TestJSEscaping(t *testing.T) {
628         testCases := []struct {
629                 in, exp string
630         }{
631                 {`a`, `a`},
632                 {`'foo`, `\'foo`},
633                 {`Go "jump" \`, `Go \"jump\" \\`},
634                 {`Yukihiro says "今日は世界"`, `Yukihiro says \"今日は世界\"`},
635                 {"unprintable \uFDFF", `unprintable \uFDFF`},
636                 {`<html>`, `\x3Chtml\x3E`},
637         }
638         for _, tc := range testCases {
639                 s := JSEscapeString(tc.in)
640                 if s != tc.exp {
641                         t.Errorf("JS escaping [%s] got [%s] want [%s]", tc.in, s, tc.exp)
642                 }
643         }
644 }
645
646 // A nice example: walk a binary tree.
647
648 type Tree struct {
649         Val         int
650         Left, Right *Tree
651 }
652
653 // Use different delimiters to test Set.Delims.
654 const treeTemplate = `
655         (define "tree")
656         [
657                 (.Val)
658                 (with .Left)
659                         (template "tree" .)
660                 (end)
661                 (with .Right)
662                         (template "tree" .)
663                 (end)
664         ]
665         (end)
666 `
667
668 func TestTree(t *testing.T) {
669         var tree = &Tree{
670                 1,
671                 &Tree{
672                         2, &Tree{
673                                 3,
674                                 &Tree{
675                                         4, nil, nil,
676                                 },
677                                 nil,
678                         },
679                         &Tree{
680                                 5,
681                                 &Tree{
682                                         6, nil, nil,
683                                 },
684                                 nil,
685                         },
686                 },
687                 &Tree{
688                         7,
689                         &Tree{
690                                 8,
691                                 &Tree{
692                                         9, nil, nil,
693                                 },
694                                 nil,
695                         },
696                         &Tree{
697                                 10,
698                                 &Tree{
699                                         11, nil, nil,
700                                 },
701                                 nil,
702                         },
703                 },
704         }
705         tmpl, err := New("root").Delims("(", ")").Parse(treeTemplate)
706         if err != nil {
707                 t.Fatal("parse error:", err)
708         }
709         var b bytes.Buffer
710         stripSpace := func(r rune) rune {
711                 if r == '\t' || r == '\n' {
712                         return -1
713                 }
714                 return r
715         }
716         const expect = "[1[2[3[4]][5[6]]][7[8[9]][10[11]]]]"
717         // First by looking up the template.
718         err = tmpl.Lookup("tree").Execute(&b, tree)
719         if err != nil {
720                 t.Fatal("exec error:", err)
721         }
722         result := strings.Map(stripSpace, b.String())
723         if result != expect {
724                 t.Errorf("expected %q got %q", expect, result)
725         }
726         // Then direct to execution.
727         b.Reset()
728         err = tmpl.ExecuteTemplate(&b, "tree", tree)
729         if err != nil {
730                 t.Fatal("exec error:", err)
731         }
732         result = strings.Map(stripSpace, b.String())
733         if result != expect {
734                 t.Errorf("expected %q got %q", expect, result)
735         }
736 }