OSDN Git Service

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