blob: 8f6c67bbaa6b6092ca7d1804b7faf374a444b7a4 [file] [log] [blame]
Rob Pike81592c22011-06-28 23:04:08 +10001// 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
5package template
6
7import (
8 "bytes"
Russ Coxe73680a2011-11-04 07:33:55 -04009 "errors"
Rob Pikec66917d2011-08-09 15:42:53 +100010 "flag"
Rob Pike81592c22011-06-28 23:04:08 +100011 "fmt"
Rob Pike7c477412011-07-12 13:15:26 +100012 "reflect"
Rob Pike81592c22011-06-28 23:04:08 +100013 "strings"
14 "testing"
15)
16
Rob Pikec66917d2011-08-09 15:42:53 +100017var debug = flag.Bool("debug", false, "show the errors produced by the tests")
18
Rob Pike81592c22011-06-28 23:04:08 +100019// T has lots of interesting pieces to use to test execution.
20type T struct {
21 // Basics
Rob Pikec3344d62011-07-14 07:52:07 +100022 True bool
Rob Pike13f88972011-07-04 15:15:47 +100023 I int
24 U16 uint16
25 X string
26 FloatZero float64
27 ComplexZero float64
Rob Pike81592c22011-06-28 23:04:08 +100028 // Nested structs.
29 U *U
Rob Pike6ca968c2011-08-11 14:36:51 +100030 // Struct with String method.
31 V0 V
32 V1, V2 *V
David Symonds39fcca62011-11-04 23:45:38 +110033 // Struct with Error method.
34 W0 W
35 W1, W2 *W
Rob Pike81592c22011-06-28 23:04:08 +100036 // Slices
Rob Pike13f88972011-07-04 15:15:47 +100037 SI []int
38 SIEmpty []int
39 SB []bool
Rob Pike81592c22011-06-28 23:04:08 +100040 // Maps
41 MSI map[string]int
Rob Pike13f88972011-07-04 15:15:47 +100042 MSIone map[string]int // one element, for deterministic output
Rob Pike81592c22011-06-28 23:04:08 +100043 MSIEmpty map[string]int
Gustavo Niemeyere3df71f2011-08-15 00:56:01 -030044 MXI map[interface{}]int
45 MII map[int]int
Rob Pike6732bd32011-07-06 22:27:06 +100046 SMSI []map[string]int
Rob Pike238274e2011-07-07 14:51:35 +100047 // 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{}
Rob Pike1adda462011-08-09 17:07:29 +100053 // Non-empty interface.
54 NonEmptyInterface I
David Symondsfe59d862011-08-12 13:29:56 +100055 // Stringer.
56 Str fmt.Stringer
Russ Coxe73680a2011-11-04 07:33:55 -040057 Err error
Rob Pike238274e2011-07-07 14:51:35 +100058 // Pointers
59 PI *int
60 PSI *[]int
61 NIL *int
Rob Pikeaca80712012-02-15 16:05:34 +110062 // Function (not method)
Rob Pikef1d3ff12012-03-03 23:14:20 +110063 BinaryFunc func(string, string) string
64 VariadicFunc func(...string) string
65 VariadicFuncInt func(int, ...string) string
Rob Pike3987b912011-07-10 07:32:01 +100066 // Template to test evaluation of templates.
67 Tmpl *Template
Rob Pikea8098cb2012-04-23 15:39:02 +100068 // Unexported field; cannot be accessed by template.
69 unexported int
Rob Pike238274e2011-07-07 14:51:35 +100070}
71
Rob Pikea8529812011-07-08 15:22:05 +100072type U struct {
73 V string
74}
75
Rob Pike6ca968c2011-08-11 14:36:51 +100076type V struct {
77 j int
78}
79
80func (v *V) String() string {
81 if v == nil {
82 return "nilV"
83 }
84 return fmt.Sprintf("<%d>", v.j)
85}
86
David Symonds39fcca62011-11-04 23:45:38 +110087type W struct {
88 k int
89}
90
91func (w *W) Error() string {
92 if w == nil {
93 return "nilW"
94 }
95 return fmt.Sprintf("[%d]", w.k)
96}
97
Rob Pike238274e2011-07-07 14:51:35 +100098var tVal = &T{
Rob Pikec3344d62011-07-14 07:52:07 +100099 True: true,
Rob Pike238274e2011-07-07 14:51:35 +1000100 I: 17,
101 U16: 16,
102 X: "x",
103 U: &U{"v"},
Rob Pike6ca968c2011-08-11 14:36:51 +1000104 V0: V{6666},
105 V1: &V{7777}, // leave V2 as nil
David Symonds39fcca62011-11-04 23:45:38 +1100106 W0: W{888},
107 W1: &W{999}, // leave W2 as nil
Rob Pike238274e2011-07-07 14:51:35 +1000108 SI: []int{3, 4, 5},
109 SB: []bool{true, false},
110 MSI: map[string]int{"one": 1, "two": 2, "three": 3},
111 MSIone: map[string]int{"one": 1},
Gustavo Niemeyere3df71f2011-08-15 00:56:01 -0300112 MXI: map[interface{}]int{"one": 1},
113 MII: map[int]int{1: 1},
Rob Pike238274e2011-07-07 14:51:35 +1000114 SMSI: []map[string]int{
115 {"one": 1, "two": 2},
116 {"eleven": 11, "twelve": 12},
117 },
Rob Pike1adda462011-08-09 17:07:29 +1000118 Empty1: 3,
119 Empty2: "empty2",
120 Empty3: []int{7, 8},
121 Empty4: &U{"UinEmpty"},
122 NonEmptyInterface: new(T),
Russ Cox853c8462011-10-27 21:17:47 -0700123 Str: bytes.NewBuffer([]byte("foozle")),
Russ Coxe73680a2011-11-04 07:33:55 -0400124 Err: errors.New("erroozle"),
Rob Pike1adda462011-08-09 17:07:29 +1000125 PI: newInt(23),
126 PSI: newIntSlice(21, 22, 23),
Rob Pikef1d3ff12012-03-03 23:14:20 +1100127 BinaryFunc: func(a, b string) string { return fmt.Sprintf("[%s=%s]", a, b) },
128 VariadicFunc: func(s ...string) string { return fmt.Sprint("<", strings.Join(s, "+"), ">") },
129 VariadicFuncInt: func(a int, s ...string) string { return fmt.Sprint(a, "=<", strings.Join(s, "+"), ">") },
Rob Pike1adda462011-08-09 17:07:29 +1000130 Tmpl: Must(New("x").Parse("test template")), // "x" is the value of .X
Rob Pike238274e2011-07-07 14:51:35 +1000131}
132
Robert Griesemer7162f392011-07-30 17:11:52 -0700133// A non-empty interface.
134type I interface {
135 Method0() string
136}
137
138var iVal I = tVal
139
Rob Pike238274e2011-07-07 14:51:35 +1000140// Helpers for creation.
141func newInt(n int) *int {
142 p := new(int)
143 *p = n
144 return p
145}
146
147func newIntSlice(n ...int) *[]int {
148 p := new([]int)
149 *p = make([]int, len(n))
150 copy(*p, n)
151 return p
Rob Pike81592c22011-06-28 23:04:08 +1000152}
153
154// Simple methods with and without arguments.
155func (t *T) Method0() string {
Rob Pikea8529812011-07-08 15:22:05 +1000156 return "M0"
Rob Pike81592c22011-06-28 23:04:08 +1000157}
158
159func (t *T) Method1(a int) int {
160 return a
161}
162
163func (t *T) Method2(a uint16, b string) string {
164 return fmt.Sprintf("Method2: %d %s", a, b)
165}
166
Gustavo Niemeyer12f473f2011-12-18 22:14:11 -0200167func (t *T) Method3(v interface{}) string {
168 return fmt.Sprintf("Method3: %v", v)
169}
170
Rob Pike81592c22011-06-28 23:04:08 +1000171func (t *T) MAdd(a int, b []int) []int {
172 v := make([]int, len(b))
173 for i, x := range b {
174 v[i] = x + a
175 }
176 return v
177}
178
Rob Pike47424d92012-02-14 07:11:39 +1100179var myError = errors.New("my error")
180
181// MyError returns a value and an error according to its argument.
182func (t *T) MyError(error bool) (bool, error) {
Rob Pikec756a192011-06-29 15:02:04 +1000183 if error {
Rob Pike47424d92012-02-14 07:11:39 +1100184 return true, myError
Rob Pike81592c22011-06-28 23:04:08 +1000185 }
Rob Pikec756a192011-06-29 15:02:04 +1000186 return false, nil
Rob Pike81592c22011-06-28 23:04:08 +1000187}
188
Rob Pikec3344d62011-07-14 07:52:07 +1000189// A few methods to test chaining.
190func (t *T) GetU() *U {
191 return t.U
192}
193
194func (u *U) TrueFalse(b bool) string {
195 if b {
196 return "true"
197 }
198 return ""
199}
200
Rob Pike7c477412011-07-12 13:15:26 +1000201func typeOf(arg interface{}) string {
202 return fmt.Sprintf("%T", arg)
203}
204
Rob Pike81592c22011-06-28 23:04:08 +1000205type execTest struct {
206 name string
207 input string
208 output string
209 data interface{}
210 ok bool
211}
212
Rob Pike7c477412011-07-12 13:15:26 +1000213// bigInt and bigUint are hex string representing numbers either side
214// of the max int boundary.
215// We do it this way so the test doesn't depend on ints being 32 bits.
216var (
217 bigInt = fmt.Sprintf("0x%x", int(1<<uint(reflect.TypeOf(0).Bits()-1)-1))
218 bigUint = fmt.Sprintf("0x%x", uint(1<<uint(reflect.TypeOf(0).Bits()-1)))
219)
220
Rob Pike81592c22011-06-28 23:04:08 +1000221var execTests = []execTest{
Rob Pike13f88972011-07-04 15:15:47 +1000222 // Trivial cases.
Rob Pike81592c22011-06-28 23:04:08 +1000223 {"empty", "", "", nil, true},
224 {"text", "some text", "some text", nil, true},
Rob Pike238274e2011-07-07 14:51:35 +1000225
Rob Pike7c477412011-07-12 13:15:26 +1000226 // Ideal constants.
227 {"ideal int", "{{typeOf 3}}", "int", 0, true},
228 {"ideal float", "{{typeOf 1.0}}", "float64", 0, true},
229 {"ideal exp float", "{{typeOf 1e1}}", "float64", 0, true},
230 {"ideal complex", "{{typeOf 1i}}", "complex128", 0, true},
231 {"ideal int", "{{typeOf " + bigInt + "}}", "int", 0, true},
232 {"ideal too big", "{{typeOf " + bigUint + "}}", "", 0, false},
233
Rob Pike13f88972011-07-04 15:15:47 +1000234 // Fields of structs.
Rob Pike81592c22011-06-28 23:04:08 +1000235 {".X", "-{{.X}}-", "-x-", tVal, true},
236 {".U.V", "-{{.U.V}}-", "-v-", tVal, true},
Rob Pikea8098cb2012-04-23 15:39:02 +1000237 {".unexported", "{{.unexported}}", "", tVal, false},
Rob Pike238274e2011-07-07 14:51:35 +1000238
Gustavo Niemeyere3df71f2011-08-15 00:56:01 -0300239 // Fields on maps.
240 {"map .one", "{{.MSI.one}}", "1", tVal, true},
241 {"map .two", "{{.MSI.two}}", "2", tVal, true},
242 {"map .NO", "{{.MSI.NO}}", "<no value>", tVal, true},
243 {"map .one interface", "{{.MXI.one}}", "1", tVal, true},
244 {"map .WRONG args", "{{.MSI.one 1}}", "", tVal, false},
245 {"map .WRONG type", "{{.MII.one}}", "", tVal, false},
246
Rob Pike13f88972011-07-04 15:15:47 +1000247 // Dots of all kinds to test basic evaluation.
248 {"dot int", "<{{.}}>", "<13>", 13, true},
249 {"dot uint", "<{{.}}>", "<14>", uint(14), true},
250 {"dot float", "<{{.}}>", "<15.1>", 15.1, true},
251 {"dot bool", "<{{.}}>", "<true>", true, true},
252 {"dot complex", "<{{.}}>", "<(16.2-17i)>", 16.2 - 17i, true},
253 {"dot string", "<{{.}}>", "<hello>", "hello", true},
254 {"dot slice", "<{{.}}>", "<[-1 -2 -3]>", []int{-1, -2, -3}, true},
Russ Cox9a7dd712011-10-17 14:51:45 -0400255 {"dot map", "<{{.}}>", "<map[two:22]>", map[string]int{"two": 22}, true},
Rob Pike13f88972011-07-04 15:15:47 +1000256 {"dot struct", "<{{.}}>", "<{7 seven}>", struct {
257 a int
258 b string
259 }{7, "seven"}, true},
Rob Pike238274e2011-07-07 14:51:35 +1000260
Rob Pike58baf642011-07-09 12:05:39 +1000261 // Variables.
262 {"$ int", "{{$}}", "123", 123, true},
Rob Pike7b79b3b2011-07-11 15:23:38 +1000263 {"$.I", "{{$.I}}", "17", tVal, true},
264 {"$.U.V", "{{$.U.V}}", "v", tVal, true},
Rob Pike3e79c952011-07-22 10:51:40 +1000265 {"declare in action", "{{$x := $.U.V}}{{$x}}", "v", tVal, true},
Rob Pike58baf642011-07-09 12:05:39 +1000266
Rob Pike6ca968c2011-08-11 14:36:51 +1000267 // Type with String method.
268 {"V{6666}.String()", "-{{.V0}}-", "-<6666>-", tVal, true},
269 {"&V{7777}.String()", "-{{.V1}}-", "-<7777>-", tVal, true},
270 {"(*V)(nil).String()", "-{{.V2}}-", "-nilV-", tVal, true},
271
David Symonds39fcca62011-11-04 23:45:38 +1100272 // Type with Error method.
273 {"W{888}.Error()", "-{{.W0}}-", "-[888]-", tVal, true},
274 {"&W{999}.Error()", "-{{.W1}}-", "-[999]-", tVal, true},
275 {"(*W)(nil).Error()", "-{{.W2}}-", "-nilW-", tVal, true},
276
Rob Pike238274e2011-07-07 14:51:35 +1000277 // Pointers.
278 {"*int", "{{.PI}}", "23", tVal, true},
279 {"*[]int", "{{.PSI}}", "[21 22 23]", tVal, true},
280 {"*[]int[1]", "{{index .PSI 1}}", "22", tVal, true},
281 {"NIL", "{{.NIL}}", "<nil>", tVal, true},
282
Rob Piked3d08e12011-07-08 18:25:46 +1000283 // Empty interfaces holding values.
Rob Pike238274e2011-07-07 14:51:35 +1000284 {"empty nil", "{{.Empty0}}", "<no value>", tVal, true},
285 {"empty with int", "{{.Empty1}}", "3", tVal, true},
286 {"empty with string", "{{.Empty2}}", "empty2", tVal, true},
287 {"empty with slice", "{{.Empty3}}", "[7 8]", tVal, true},
Rob Pike9a5bb282011-07-18 17:34:42 +1000288 {"empty with struct", "{{.Empty4}}", "{UinEmpty}", tVal, true},
289 {"empty with struct, field", "{{.Empty4.V}}", "UinEmpty", tVal, true},
Rob Pike238274e2011-07-07 14:51:35 +1000290
Rob Pike13f88972011-07-04 15:15:47 +1000291 // Method calls.
Rob Pikea8529812011-07-08 15:22:05 +1000292 {".Method0", "-{{.Method0}}-", "-M0-", tVal, true},
Rob Pike81592c22011-06-28 23:04:08 +1000293 {".Method1(1234)", "-{{.Method1 1234}}-", "-1234-", tVal, true},
294 {".Method1(.I)", "-{{.Method1 .I}}-", "-17-", tVal, true},
295 {".Method2(3, .X)", "-{{.Method2 3 .X}}-", "-Method2: 3 x-", tVal, true},
296 {".Method2(.U16, `str`)", "-{{.Method2 .U16 `str`}}-", "-Method2: 16 str-", tVal, true},
Rob Pikee86d7272011-07-09 17:11:35 +1000297 {".Method2(.U16, $x)", "{{if $x := .X}}-{{.Method2 .U16 $x}}{{end}}-", "-Method2: 16 x-", tVal, true},
Gustavo Niemeyer12f473f2011-12-18 22:14:11 -0200298 {".Method3(nil)", "-{{.Method3 .MXI.unset}}-", "-Method3: <nil>-", tVal, true},
Rob Pike7b79b3b2011-07-11 15:23:38 +1000299 {"method on var", "{{if $x := .}}-{{$x.Method2 .U16 $x.X}}{{end}}-", "-Method2: 16 x-", tVal, true},
Rob Pikec3344d62011-07-14 07:52:07 +1000300 {"method on chained var",
301 "{{range .MSIone}}{{if $.U.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}",
302 "true", tVal, true},
303 {"chained method",
304 "{{range .MSIone}}{{if $.GetU.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}",
305 "true", tVal, true},
306 {"chained method on variable",
307 "{{with $x := .}}{{with .SI}}{{$.GetU.TrueFalse $.True}}{{end}}{{end}}",
308 "true", tVal, true},
Rob Pike238274e2011-07-07 14:51:35 +1000309
Rob Pikef1d3ff12012-03-03 23:14:20 +1100310 // Function call builtin.
311 {".BinaryFunc", "{{call .BinaryFunc `1` `2`}}", "[1=2]", tVal, true},
312 {".VariadicFunc0", "{{call .VariadicFunc}}", "<>", tVal, true},
313 {".VariadicFunc2", "{{call .VariadicFunc `he` `llo`}}", "<he+llo>", tVal, true},
314 {".VariadicFuncInt", "{{call .VariadicFuncInt 33 `he` `llo`}}", "33=<he+llo>", tVal, true},
315 {"if .BinaryFunc call", "{{ if .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{end}}", "[1=2]", tVal, true},
316 {"if not .BinaryFunc call", "{{ if not .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{else}}No{{end}}", "No", tVal, true},
317
318 // Erroneous function calls (check args).
319 {".BinaryFuncTooFew", "{{call .BinaryFunc `1`}}", "", tVal, false},
320 {".BinaryFuncTooMany", "{{call .BinaryFunc `1` `2` `3`}}", "", tVal, false},
321 {".BinaryFuncBad0", "{{call .BinaryFunc 1 3}}", "", tVal, false},
322 {".BinaryFuncBad1", "{{call .BinaryFunc `1` 3}}", "", tVal, false},
323 {".VariadicFuncBad0", "{{call .VariadicFunc 3}}", "", tVal, false},
Rob Pike227a04d2012-03-04 08:06:26 +1100324 {".VariadicFuncIntBad0", "{{call .VariadicFuncInt}}", "", tVal, false},
325 {".VariadicFuncIntBad`", "{{call .VariadicFuncInt `x`}}", "", tVal, false},
Rob Pikeaca80712012-02-15 16:05:34 +1100326
Rob Pike13f88972011-07-04 15:15:47 +1000327 // Pipelines.
Rob Pikea8529812011-07-08 15:22:05 +1000328 {"pipeline", "-{{.Method0 | .Method2 .U16}}-", "-Method2: 16 M0-", tVal, true},
Rob Pikef1d3ff12012-03-03 23:14:20 +1100329 {"pipeline func", "-{{call .VariadicFunc `llo` | call .VariadicFunc `he` }}-", "-<he+<llo>>-", tVal, true},
Rob Pike238274e2011-07-07 14:51:35 +1000330
Rob Pike13f88972011-07-04 15:15:47 +1000331 // If.
332 {"if true", "{{if true}}TRUE{{end}}", "TRUE", tVal, true},
333 {"if false", "{{if false}}TRUE{{else}}FALSE{{end}}", "FALSE", tVal, true},
334 {"if 1", "{{if 1}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
335 {"if 0", "{{if 0}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
336 {"if 1.5", "{{if 1.5}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
337 {"if 0.0", "{{if .FloatZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
338 {"if 1.5i", "{{if 1.5i}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
339 {"if 0.0i", "{{if .ComplexZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
340 {"if emptystring", "{{if ``}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
341 {"if string", "{{if `notempty`}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
342 {"if emptyslice", "{{if .SIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
343 {"if slice", "{{if .SI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
344 {"if emptymap", "{{if .MSIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
345 {"if map", "{{if .MSI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
Gustavo Niemeyer12f473f2011-12-18 22:14:11 -0200346 {"if map unset", "{{if .MXI.none}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
347 {"if map not unset", "{{if not .MXI.none}}ZERO{{else}}NON-ZERO{{end}}", "ZERO", tVal, true},
Rob Pikefc1f0bd2011-07-14 13:15:55 +1000348 {"if $x with $y int", "{{if $x := true}}{{with $y := .I}}{{$x}},{{$y}}{{end}}{{end}}", "true,17", tVal, true},
349 {"if $x with $x int", "{{if $x := true}}{{with $x := .I}}{{$x}},{{end}}{{$x}}{{end}}", "17,true", tVal, true},
Rob Pike238274e2011-07-07 14:51:35 +1000350
Rob Pikeabae8472011-07-11 09:19:18 +1000351 // Print etc.
352 {"print", `{{print "hello, print"}}`, "hello, print", tVal, true},
353 {"print", `{{print 1 2 3}}`, "1 2 3", tVal, true},
354 {"println", `{{println 1 2 3}}`, "1 2 3\n", tVal, true},
Rob Pikeb177c972011-07-05 14:23:51 +1000355 {"printf int", `{{printf "%04x" 127}}`, "007f", tVal, true},
356 {"printf float", `{{printf "%g" 3.5}}`, "3.5", tVal, true},
357 {"printf complex", `{{printf "%g" 1+7i}}`, "(1+7i)", tVal, true},
358 {"printf string", `{{printf "%s" "hello"}}`, "hello", tVal, true},
Rob Piked3d08e12011-07-08 18:25:46 +1000359 {"printf function", `{{printf "%#q" zeroArgs}}`, "`zeroArgs`", tVal, true},
Rob Pikeb177c972011-07-05 14:23:51 +1000360 {"printf field", `{{printf "%s" .U.V}}`, "v", tVal, true},
Rob Pikea8529812011-07-08 15:22:05 +1000361 {"printf method", `{{printf "%s" .Method0}}`, "M0", tVal, true},
Rob Pikee86d7272011-07-09 17:11:35 +1000362 {"printf dot", `{{with .I}}{{printf "%d" .}}{{end}}`, "17", tVal, true},
363 {"printf var", `{{with $x := .I}}{{printf "%d" $x}}{{end}}`, "17", tVal, true},
Rob Pikea8529812011-07-08 15:22:05 +1000364 {"printf lots", `{{printf "%d %s %g %s" 127 "hello" 7-3i .Method0}}`, "127 hello (7-3i) M0", tVal, true},
Rob Pike238274e2011-07-07 14:51:35 +1000365
Rob Pikeeea54432011-07-05 17:05:15 +1000366 // HTML.
Rob Pikecc9fed72011-07-05 15:58:54 +1000367 {"html", `{{html "<script>alert(\"XSS\");</script>"}}`,
Rob Pikeeea54432011-07-05 17:05:15 +1000368 "&lt;script&gt;alert(&#34;XSS&#34;);&lt;/script&gt;", nil, true},
Rob Pikecc9fed72011-07-05 15:58:54 +1000369 {"html pipeline", `{{printf "<script>alert(\"XSS\");</script>" | html}}`,
Rob Pikeeea54432011-07-05 17:05:15 +1000370 "&lt;script&gt;alert(&#34;XSS&#34;);&lt;/script&gt;", nil, true},
Rob Pike238274e2011-07-07 14:51:35 +1000371
372 // JavaScript.
David Symonds33705dd2011-07-06 16:51:49 +1000373 {"js", `{{js .}}`, `It\'d be nice.`, `It'd be nice.`, true},
Rob Pike238274e2011-07-07 14:51:35 +1000374
David Symonds5e48e642011-08-13 14:00:16 +1000375 // URL query.
376 {"urlquery", `{{"http://www.example.org/"|urlquery}}`, "http%3A%2F%2Fwww.example.org%2F", nil, true},
David Symondsa09ba8b2011-08-08 16:29:57 +1000377
Rob Pikeeea54432011-07-05 17:05:15 +1000378 // Booleans
379 {"not", "{{not true}} {{not false}}", "false true", nil, true},
Rob Pike469e3332011-07-14 07:59:04 +1000380 {"and", "{{and false 0}} {{and 1 0}} {{and 0 true}} {{and 1 1}}", "false 0 0 1", nil, true},
381 {"or", "{{or 0 0}} {{or 1 0}} {{or 0 true}} {{or 1 1}}", "0 1 true 1", nil, true},
Rob Pikeeea54432011-07-05 17:05:15 +1000382 {"boolean if", "{{if and true 1 `hi`}}TRUE{{else}}FALSE{{end}}", "TRUE", tVal, true},
383 {"boolean if not", "{{if and true 1 `hi` | not}}TRUE{{else}}FALSE{{end}}", "FALSE", nil, true},
Rob Pike238274e2011-07-07 14:51:35 +1000384
Rob Pike6732bd32011-07-06 22:27:06 +1000385 // Indexing.
386 {"slice[0]", "{{index .SI 0}}", "3", tVal, true},
387 {"slice[1]", "{{index .SI 1}}", "4", tVal, true},
388 {"slice[HUGE]", "{{index .SI 10}}", "", tVal, false},
389 {"slice[WRONG]", "{{index .SI `hello`}}", "", tVal, false},
390 {"map[one]", "{{index .MSI `one`}}", "1", tVal, true},
391 {"map[two]", "{{index .MSI `two`}}", "2", tVal, true},
Roger Peppe6ed27d42011-08-01 09:03:35 -0700392 {"map[NO]", "{{index .MSI `XXX`}}", "", tVal, true},
Rob Pike6732bd32011-07-06 22:27:06 +1000393 {"map[WRONG]", "{{index .MSI 10}}", "", tVal, false},
394 {"double index", "{{index .SMSI 1 `eleven`}}", "11", tVal, true},
Rob Pike238274e2011-07-07 14:51:35 +1000395
Rob Pikeb1d1da42011-08-12 11:47:44 +1000396 // Len.
397 {"slice", "{{len .SI}}", "3", tVal, true},
398 {"map", "{{len .MSI }}", "3", tVal, true},
399 {"len of int", "{{len 3}}", "", tVal, false},
400 {"len of nothing", "{{len .Empty0}}", "", tVal, false},
401
Rob Pike13f88972011-07-04 15:15:47 +1000402 // With.
403 {"with true", "{{with true}}{{.}}{{end}}", "true", tVal, true},
404 {"with false", "{{with false}}{{.}}{{else}}FALSE{{end}}", "FALSE", tVal, true},
405 {"with 1", "{{with 1}}{{.}}{{else}}ZERO{{end}}", "1", tVal, true},
406 {"with 0", "{{with 0}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
407 {"with 1.5", "{{with 1.5}}{{.}}{{else}}ZERO{{end}}", "1.5", tVal, true},
408 {"with 0.0", "{{with .FloatZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
409 {"with 1.5i", "{{with 1.5i}}{{.}}{{else}}ZERO{{end}}", "(0+1.5i)", tVal, true},
410 {"with 0.0i", "{{with .ComplexZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
411 {"with emptystring", "{{with ``}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
412 {"with string", "{{with `notempty`}}{{.}}{{else}}EMPTY{{end}}", "notempty", tVal, true},
413 {"with emptyslice", "{{with .SIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
414 {"with slice", "{{with .SI}}{{.}}{{else}}EMPTY{{end}}", "[3 4 5]", tVal, true},
415 {"with emptymap", "{{with .MSIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
416 {"with map", "{{with .MSIone}}{{.}}{{else}}EMPTY{{end}}", "map[one:1]", tVal, true},
Rob Pike9a5bb282011-07-18 17:34:42 +1000417 {"with empty interface, struct field", "{{with .Empty4}}{{.V}}{{end}}", "UinEmpty", tVal, true},
Rob Pikefc1f0bd2011-07-14 13:15:55 +1000418 {"with $x int", "{{with $x := .I}}{{$x}}{{end}}", "17", tVal, true},
Rob Pikec7057012011-07-17 13:31:59 +1000419 {"with $x struct.U.V", "{{with $x := $}}{{$x.U.V}}{{end}}", "v", tVal, true},
Rob Pike3e79c952011-07-22 10:51:40 +1000420 {"with variable and action", "{{with $x := $}}{{$y := $.U.V}}{{$y}}{{end}}", "v", tVal, true},
Rob Pike238274e2011-07-07 14:51:35 +1000421
Rob Pike13f88972011-07-04 15:15:47 +1000422 // Range.
Rob Pike81592c22011-06-28 23:04:08 +1000423 {"range []int", "{{range .SI}}-{{.}}-{{end}}", "-3--4--5-", tVal, true},
Rob Pike13f88972011-07-04 15:15:47 +1000424 {"range empty no else", "{{range .SIEmpty}}-{{.}}-{{end}}", "", tVal, true},
Rob Pike81592c22011-06-28 23:04:08 +1000425 {"range []int else", "{{range .SI}}-{{.}}-{{else}}EMPTY{{end}}", "-3--4--5-", tVal, true},
Rob Pike13f88972011-07-04 15:15:47 +1000426 {"range empty else", "{{range .SIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
Rob Pikec756a192011-06-29 15:02:04 +1000427 {"range []bool", "{{range .SB}}-{{.}}-{{end}}", "-true--false-", tVal, true},
Rob Pike81592c22011-06-28 23:04:08 +1000428 {"range []int method", "{{range .SI | .MAdd .I}}-{{.}}-{{end}}", "-20--21--22-", tVal, true},
Rob Pikea5950df2012-01-13 14:09:13 -0800429 {"range map", "{{range .MSI}}-{{.}}-{{end}}", "-1--3--2-", tVal, true},
Rob Pike81592c22011-06-28 23:04:08 +1000430 {"range empty map no else", "{{range .MSIEmpty}}-{{.}}-{{end}}", "", tVal, true},
Rob Pikea5950df2012-01-13 14:09:13 -0800431 {"range map else", "{{range .MSI}}-{{.}}-{{else}}EMPTY{{end}}", "-1--3--2-", tVal, true},
Rob Pike81592c22011-06-28 23:04:08 +1000432 {"range empty map else", "{{range .MSIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
Rob Pike238274e2011-07-07 14:51:35 +1000433 {"range empty interface", "{{range .Empty3}}-{{.}}-{{else}}EMPTY{{end}}", "-7--8-", tVal, true},
Gustavo Niemeyere3f3a542011-08-15 00:22:28 -0300434 {"range empty nil", "{{range .Empty0}}-{{.}}-{{end}}", "", tVal, true},
Rob Pikefc1f0bd2011-07-14 13:15:55 +1000435 {"range $x SI", "{{range $x := .SI}}<{{$x}}>{{end}}", "<3><4><5>", tVal, true},
436 {"range $x $y SI", "{{range $x, $y := .SI}}<{{$x}}={{$y}}>{{end}}", "<0=3><1=4><2=5>", tVal, true},
437 {"range $x MSIone", "{{range $x := .MSIone}}<{{$x}}>{{end}}", "<1>", tVal, true},
438 {"range $x $y MSIone", "{{range $x, $y := .MSIone}}<{{$x}}={{$y}}>{{end}}", "<one=1>", tVal, true},
439 {"range $x PSI", "{{range $x := .PSI}}<{{$x}}>{{end}}", "<21><22><23>", tVal, true},
Rob Pike3e79c952011-07-22 10:51:40 +1000440 {"declare in range", "{{range $x := .PSI}}<{{$foo:=$x}}{{$x}}>{{end}}", "<21><22><23>", tVal, true},
Rob Pike361c5ac2011-08-29 15:56:52 +1000441 {"range count", `{{range $i, $x := count 5}}[{{$i}}]{{$x}}{{end}}`, "[0]a[1]b[2]c[3]d[4]e", tVal, true},
442 {"range nil count", `{{range $i, $x := count 0}}{{else}}empty{{end}}`, "empty", tVal, true},
Rob Pike238274e2011-07-07 14:51:35 +1000443
Rob Pike469e3332011-07-14 07:59:04 +1000444 // Cute examples.
445 {"or as if true", `{{or .SI "slice is empty"}}`, "[3 4 5]", tVal, true},
446 {"or as if false", `{{or .SIEmpty "slice is empty"}}`, "slice is empty", tVal, true},
447
Rob Pike13f88972011-07-04 15:15:47 +1000448 // Error handling.
Rob Pike47424d92012-02-14 07:11:39 +1100449 {"error method, error", "{{.MyError true}}", "", tVal, false},
450 {"error method, no error", "{{.MyError false}}", "false", tVal, true},
Rob Piked366c362011-07-11 18:06:24 +1000451
452 // Fixed bugs.
453 // Must separate dot and receiver; otherwise args are evaluated with dot set to variable.
Rob Pikec3344d62011-07-14 07:52:07 +1000454 {"bug0", "{{range .MSIone}}{{if $.Method1 .}}X{{end}}{{end}}", "X", tVal, true},
Robert Griesemer7162f392011-07-30 17:11:52 -0700455 // Do not loop endlessly in indirect for non-empty interfaces.
Rob Pike1adda462011-08-09 17:07:29 +1000456 // The bug appears with *interface only; looped forever.
457 {"bug1", "{{.Method0}}", "M0", &iVal, true},
458 // Was taking address of interface field, so method set was empty.
459 {"bug2", "{{$.NonEmptyInterface.Method0}}", "M0", tVal, true},
460 // Struct values were not legal in with - mere oversight.
Rob Pike39fa2a52011-08-11 08:27:16 +1000461 {"bug3", "{{with $}}{{.Method0}}{{end}}", "M0", tVal, true},
462 // Nil interface values in if.
463 {"bug4", "{{if .Empty0}}non-nil{{else}}nil{{end}}", "nil", tVal, true},
David Symondsfe59d862011-08-12 13:29:56 +1000464 // Stringer.
465 {"bug5", "{{.Str}}", "foozle", tVal, true},
Russ Coxe73680a2011-11-04 07:33:55 -0400466 {"bug5a", "{{.Err}}", "erroozle", tVal, true},
Rob Piked45e808c2011-09-06 15:34:38 -0700467 // Args need to be indirected and dereferenced sometimes.
468 {"bug6a", "{{vfunc .V0 .V1}}", "vfunc", tVal, true},
469 {"bug6b", "{{vfunc .V0 .V0}}", "vfunc", tVal, true},
470 {"bug6c", "{{vfunc .V1 .V0}}", "vfunc", tVal, true},
471 {"bug6d", "{{vfunc .V1 .V1}}", "vfunc", tVal, true},
Rob Piked6ad6f02012-03-14 10:46:21 +1100472 // Legal parse but illegal execution: non-function should have no arguments.
473 {"bug7a", "{{3 2}}", "", tVal, false},
474 {"bug7b", "{{$x := 1}}{{$x 2}}", "", tVal, false},
475 {"bug7c", "{{$x := 1}}{{3 | $x}}", "", tVal, false},
Rob Pike065db4e2012-04-03 11:44:52 +1000476 // Pipelined arg was not being type-checked.
477 {"bug8a", "{{3|oneArg}}", "", tVal, false},
478 {"bug8b", "{{4|dddArg 3}}", "", tVal, false},
Rob Pikea8098cb2012-04-23 15:39:02 +1000479 // A bug was introduced that broke map lookups for lower-case names.
480 {"bug9", "{{.cause}}", "neglect", map[string]string{"cause": "neglect"}, true},
Rob Pike81592c22011-06-28 23:04:08 +1000481}
482
Rob Piked3d08e12011-07-08 18:25:46 +1000483func zeroArgs() string {
484 return "zeroArgs"
485}
486
487func oneArg(a string) string {
488 return "oneArg=" + a
Rob Pikeb177c972011-07-05 14:23:51 +1000489}
490
Rob Pike065db4e2012-04-03 11:44:52 +1000491func dddArg(a int, b ...string) string {
492 return fmt.Sprintln(a, b)
493}
494
Rob Pike361c5ac2011-08-29 15:56:52 +1000495// count returns a channel that will deliver n sequential 1-letter strings starting at "a"
496func count(n int) chan string {
497 if n == 0 {
498 return nil
499 }
500 c := make(chan string)
501 go func() {
502 for i := 0; i < n; i++ {
503 c <- "abcdefghijklmnop"[i : i+1]
504 }
505 close(c)
506 }()
507 return c
508}
509
Rob Piked45e808c2011-09-06 15:34:38 -0700510// vfunc takes a *V and a V
511func vfunc(V, *V) string {
512 return "vfunc"
513}
514
Rob Pikef56db6f2011-11-23 20:17:22 -0800515func testExecute(execTests []execTest, template *Template, t *testing.T) {
Rob Pike81592c22011-06-28 23:04:08 +1000516 b := new(bytes.Buffer)
Rob Pike361c5ac2011-08-29 15:56:52 +1000517 funcs := FuncMap{
518 "count": count,
Rob Pike065db4e2012-04-03 11:44:52 +1000519 "dddArg": dddArg,
Rob Pike361c5ac2011-08-29 15:56:52 +1000520 "oneArg": oneArg,
521 "typeOf": typeOf,
Rob Piked45e808c2011-09-06 15:34:38 -0700522 "vfunc": vfunc,
Rob Pike361c5ac2011-08-29 15:56:52 +1000523 "zeroArgs": zeroArgs,
524 }
Rob Pike81592c22011-06-28 23:04:08 +1000525 for _, test := range execTests {
Rob Pikef56db6f2011-11-23 20:17:22 -0800526 var tmpl *Template
527 var err error
528 if template == nil {
529 tmpl, err = New(test.name).Funcs(funcs).Parse(test.input)
530 } else {
531 tmpl, err = template.New(test.name).Funcs(funcs).Parse(test.input)
Rob Pike25d29872011-11-17 22:53:23 -0800532 }
Rob Pike81592c22011-06-28 23:04:08 +1000533 if err != nil {
534 t.Errorf("%s: parse error: %s", test.name, err)
535 continue
536 }
537 b.Reset()
Rob Pike0f7a1952011-07-21 14:22:01 +1000538 err = tmpl.Execute(b, test.data)
Rob Pike81592c22011-06-28 23:04:08 +1000539 switch {
540 case !test.ok && err == nil:
541 t.Errorf("%s: expected error; got none", test.name)
542 continue
543 case test.ok && err != nil:
544 t.Errorf("%s: unexpected execute error: %s", test.name, err)
545 continue
546 case !test.ok && err != nil:
Rob Pike6732bd32011-07-06 22:27:06 +1000547 // expected error, got one
548 if *debug {
549 fmt.Printf("%s: %s\n\t%s\n", test.name, test.input, err)
550 }
Rob Pike81592c22011-06-28 23:04:08 +1000551 }
552 result := b.String()
553 if result != test.output {
554 t.Errorf("%s: expected\n\t%q\ngot\n\t%q", test.name, test.output, result)
555 }
556 }
557}
558
Rob Pike13f88972011-07-04 15:15:47 +1000559func TestExecute(t *testing.T) {
560 testExecute(execTests, nil, t)
561}
562
Rob Pikedcf53182011-10-06 13:30:50 -0700563var delimPairs = []string{
564 "", "", // default
565 "{{", "}}", // same as default
566 "<<", ">>", // distinct
567 "|", "|", // same
568 "(日)", "(本)", // peculiar
569}
570
571func TestDelims(t *testing.T) {
572 const hello = "Hello, world"
573 var value = struct{ Str string }{hello}
574 for i := 0; i < len(delimPairs); i += 2 {
575 text := ".Str"
576 left := delimPairs[i+0]
Rob Pikeb3dd3272011-10-06 15:21:56 -0700577 trueLeft := left
Rob Pikedcf53182011-10-06 13:30:50 -0700578 right := delimPairs[i+1]
Rob Pikeb3dd3272011-10-06 15:21:56 -0700579 trueRight := right
Rob Pikedcf53182011-10-06 13:30:50 -0700580 if left == "" { // default case
Rob Pikeb3dd3272011-10-06 15:21:56 -0700581 trueLeft = "{{"
Rob Pikedcf53182011-10-06 13:30:50 -0700582 }
583 if right == "" { // default case
Rob Pikeb3dd3272011-10-06 15:21:56 -0700584 trueRight = "}}"
Rob Pikedcf53182011-10-06 13:30:50 -0700585 }
Rob Pikeb3dd3272011-10-06 15:21:56 -0700586 text = trueLeft + text + trueRight
587 // Now add a comment
588 text += trueLeft + "/*comment*/" + trueRight
589 // Now add an action containing a string.
590 text += trueLeft + `"` + trueLeft + `"` + trueRight
591 // At this point text looks like `{{.Str}}{{/*comment*/}}{{"{{"}}`.
Rob Pikedcf53182011-10-06 13:30:50 -0700592 tmpl, err := New("delims").Delims(left, right).Parse(text)
593 if err != nil {
594 t.Fatalf("delim %q text %q parse err %s", left, text, err)
595 }
596 var b = new(bytes.Buffer)
597 err = tmpl.Execute(b, value)
598 if err != nil {
599 t.Fatalf("delim %q exec err %s", left, err)
600 }
Rob Pikeb3dd3272011-10-06 15:21:56 -0700601 if b.String() != hello+trueLeft {
Robert Henckec5018242011-10-13 13:34:01 +1100602 t.Errorf("expected %q got %q", hello+trueLeft, b.String())
Rob Pikedcf53182011-10-06 13:30:50 -0700603 }
604 }
605}
606
Rob Pike81592c22011-06-28 23:04:08 +1000607// Check that an error from a method flows back to the top.
608func TestExecuteError(t *testing.T) {
609 b := new(bytes.Buffer)
610 tmpl := New("error")
Rob Pike47424d92012-02-14 07:11:39 +1100611 _, err := tmpl.Parse("{{.MyError true}}")
Rob Pike81592c22011-06-28 23:04:08 +1000612 if err != nil {
613 t.Fatalf("parse error: %s", err)
614 }
615 err = tmpl.Execute(b, tVal)
616 if err == nil {
617 t.Errorf("expected error; got none")
Rob Pike47424d92012-02-14 07:11:39 +1100618 } else if !strings.Contains(err.Error(), myError.Error()) {
Rob Pikedfffc7a2011-07-14 11:32:06 +1000619 if *debug {
620 fmt.Printf("test execute error: %s\n", err)
621 }
Rob Pike47424d92012-02-14 07:11:39 +1100622 t.Errorf("expected myError; got %s", err)
Rob Pike81592c22011-06-28 23:04:08 +1000623 }
624}
David Symonds33705dd2011-07-06 16:51:49 +1000625
626func TestJSEscaping(t *testing.T) {
627 testCases := []struct {
628 in, exp string
629 }{
630 {`a`, `a`},
631 {`'foo`, `\'foo`},
632 {`Go "jump" \`, `Go \"jump\" \\`},
633 {`Yukihiro says "今日は世界"`, `Yukihiro says \"今日は世界\"`},
634 {"unprintable \uFDFF", `unprintable \uFDFF`},
David Symondsa16ad6f2011-07-14 12:02:58 +1000635 {`<html>`, `\x3Chtml\x3E`},
David Symonds33705dd2011-07-06 16:51:49 +1000636 }
637 for _, tc := range testCases {
638 s := JSEscapeString(tc.in)
639 if s != tc.exp {
640 t.Errorf("JS escaping [%s] got [%s] want [%s]", tc.in, s, tc.exp)
641 }
642 }
643}
Rob Pike02039b62011-07-08 16:49:06 +1000644
645// A nice example: walk a binary tree.
646
647type Tree struct {
648 Val int
649 Left, Right *Tree
650}
651
Rob Pikedcf53182011-10-06 13:30:50 -0700652// Use different delimiters to test Set.Delims.
Rob Pike02039b62011-07-08 16:49:06 +1000653const treeTemplate = `
Rob Pikedcf53182011-10-06 13:30:50 -0700654 (define "tree")
Rob Pike02039b62011-07-08 16:49:06 +1000655 [
Rob Pikedcf53182011-10-06 13:30:50 -0700656 (.Val)
657 (with .Left)
658 (template "tree" .)
659 (end)
660 (with .Right)
661 (template "tree" .)
662 (end)
Rob Pike02039b62011-07-08 16:49:06 +1000663 ]
Rob Pikedcf53182011-10-06 13:30:50 -0700664 (end)
Rob Pike02039b62011-07-08 16:49:06 +1000665`
666
667func TestTree(t *testing.T) {
668 var tree = &Tree{
669 1,
670 &Tree{
671 2, &Tree{
672 3,
673 &Tree{
674 4, nil, nil,
675 },
676 nil,
677 },
678 &Tree{
679 5,
680 &Tree{
681 6, nil, nil,
682 },
683 nil,
684 },
685 },
686 &Tree{
687 7,
688 &Tree{
689 8,
690 &Tree{
691 9, nil, nil,
692 },
693 nil,
694 },
695 &Tree{
696 10,
697 &Tree{
698 11, nil, nil,
699 },
700 nil,
701 },
702 },
703 }
Rob Pikef56db6f2011-11-23 20:17:22 -0800704 tmpl, err := New("root").Delims("(", ")").Parse(treeTemplate)
Rob Pike02039b62011-07-08 16:49:06 +1000705 if err != nil {
706 t.Fatal("parse error:", err)
707 }
708 var b bytes.Buffer
Russ Coxcfa036a2011-10-25 22:22:42 -0700709 stripSpace := func(r rune) rune {
Rob Pike02039b62011-07-08 16:49:06 +1000710 if r == '\t' || r == '\n' {
711 return -1
712 }
713 return r
714 }
Rob Pike02039b62011-07-08 16:49:06 +1000715 const expect = "[1[2[3[4]][5[6]]][7[8[9]][10[11]]]]"
Rob Pikef56db6f2011-11-23 20:17:22 -0800716 // First by looking up the template.
Rob Pikee9025df2011-11-26 08:32:55 -0800717 err = tmpl.Lookup("tree").Execute(&b, tree)
Rob Pikef56db6f2011-11-23 20:17:22 -0800718 if err != nil {
719 t.Fatal("exec error:", err)
720 }
721 result := strings.Map(stripSpace, b.String())
722 if result != expect {
723 t.Errorf("expected %q got %q", expect, result)
724 }
725 // Then direct to execution.
726 b.Reset()
727 err = tmpl.ExecuteTemplate(&b, "tree", tree)
728 if err != nil {
729 t.Fatal("exec error:", err)
730 }
731 result = strings.Map(stripSpace, b.String())
Rob Pike02039b62011-07-08 16:49:06 +1000732 if result != expect {
733 t.Errorf("expected %q got %q", expect, result)
734 }
735}