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.
17 var debug
= flag
.Bool("debug", false, "show the errors produced by the tests")
19 // T has lots of interesting pieces to use to test execution.
27 ComplexZero complex128
30 // Struct with String method.
33 // Struct with Error method.
42 MSIone
map[string]int // one element, for deterministic output
43 MSIEmpty
map[string]int
44 MXI
map[interface{}]int
47 // Empty interfaces; used to see if we can dig inside one.
48 Empty0
interface{} // nil
53 // Non-empty interface.
63 // Function (not method)
64 BinaryFunc
func(string, string) string
65 VariadicFunc
func(...string) string
66 VariadicFuncInt
func(int, ...string) string
67 NilOKFunc
func(*int) bool
68 ErrFunc
func() (string, error
)
69 // Template to test evaluation of templates.
71 // Unexported field; cannot be accessed by template.
83 func (v
*V
) String() string {
87 return fmt
.Sprintf("<%d>", v
.j
)
94 func (w
*W
) Error() string {
98 return fmt
.Sprintf("[%d]", w
.k
)
108 V1
: &V
{7777}, // leave V2 as nil
110 W1
: &W
{999}, // leave W2 as nil
112 SB
: []bool{true, false},
113 MSI
: map[string]int{"one": 1, "two": 2, "three": 3},
114 MSIone
: map[string]int{"one": 1},
115 MXI
: map[interface{}]int{"one": 1},
116 MII
: map[int]int{1: 1},
117 SMSI
: []map[string]int{
118 {"one": 1, "two": 2},
119 {"eleven": 11, "twelve": 12},
124 Empty4
: &U
{"UinEmpty"},
125 NonEmptyInterface
: new(T
),
126 Str
: bytes
.NewBuffer([]byte("foozle")),
127 Err
: errors
.New("erroozle"),
129 PS
: newString("a string"),
130 PSI
: newIntSlice(21, 22, 23),
131 BinaryFunc
: func(a
, b
string) string { return fmt
.Sprintf("[%s=%s]", a
, b
) },
132 VariadicFunc
: func(s
...string) string { return fmt
.Sprint("<", strings
.Join(s
, "+"), ">") },
133 VariadicFuncInt
: func(a
int, s
...string) string { return fmt
.Sprint(a
, "=<", strings
.Join(s
, "+"), ">") },
134 NilOKFunc
: func(s
*int) bool { return s
== nil },
135 ErrFunc
: func() (string, error
) { return "bla", nil },
136 Tmpl
: Must(New("x").Parse("test template")), // "x" is the value of .X
139 // A non-empty interface.
146 // Helpers for creation.
147 func newInt(n
int) *int {
151 func newString(s
string) *string {
155 func newIntSlice(n
...int) *[]int {
157 *p
= make([]int, len(n
))
162 // Simple methods with and without arguments.
163 func (t
*T
) Method0() string {
167 func (t
*T
) Method1(a
int) int {
171 func (t
*T
) Method2(a
uint16, b
string) string {
172 return fmt
.Sprintf("Method2: %d %s", a
, b
)
175 func (t
*T
) Method3(v
interface{}) string {
176 return fmt
.Sprintf("Method3: %v", v
)
179 func (t
*T
) MAdd(a
int, b
[]int) []int {
180 v
:= make([]int, len(b
))
181 for i
, x
:= range b
{
187 var myError
= errors
.New("my error")
189 // MyError returns a value and an error according to its argument.
190 func (t
*T
) MyError(error
bool) (bool, error
) {
197 // A few methods to test chaining.
198 func (t
*T
) GetU() *U
{
202 func (u
*U
) TrueFalse(b
bool) string {
209 func typeOf(arg
interface{}) string {
210 return fmt
.Sprintf("%T", arg
)
213 type execTest
struct {
221 // bigInt and bigUint are hex string representing numbers either side
222 // of the max int boundary.
223 // We do it this way so the test doesn't depend on ints being 32 bits.
225 bigInt
= fmt
.Sprintf("0x%x", int(1<<uint(reflect
.TypeOf(0).Bits()-1)-1))
226 bigUint
= fmt
.Sprintf("0x%x", uint(1<<uint(reflect
.TypeOf(0).Bits()-1)))
229 var execTests
= []execTest
{
231 {"empty", "", "", nil, true},
232 {"text", "some text", "some text", nil, true},
233 {"nil action", "{{nil}}", "", nil, false},
236 {"ideal int", "{{typeOf 3}}", "int", 0, true},
237 {"ideal float", "{{typeOf 1.0}}", "float64", 0, true},
238 {"ideal exp float", "{{typeOf 1e1}}", "float64", 0, true},
239 {"ideal complex", "{{typeOf 1i}}", "complex128", 0, true},
240 {"ideal int", "{{typeOf " + bigInt
+ "}}", "int", 0, true},
241 {"ideal too big", "{{typeOf " + bigUint
+ "}}", "", 0, false},
242 {"ideal nil without type", "{{nil}}", "", 0, false},
244 // Fields of structs.
245 {".X", "-{{.X}}-", "-x-", tVal
, true},
246 {".U.V", "-{{.U.V}}-", "-v-", tVal
, true},
247 {".unexported", "{{.unexported}}", "", tVal
, false},
250 {"map .one", "{{.MSI.one}}", "1", tVal
, true},
251 {"map .two", "{{.MSI.two}}", "2", tVal
, true},
252 {"map .NO", "{{.MSI.NO}}", "<no value>", tVal
, true},
253 {"map .one interface", "{{.MXI.one}}", "1", tVal
, true},
254 {"map .WRONG args", "{{.MSI.one 1}}", "", tVal
, false},
255 {"map .WRONG type", "{{.MII.one}}", "", tVal
, false},
257 // Dots of all kinds to test basic evaluation.
258 {"dot int", "<{{.}}>", "<13>", 13, true},
259 {"dot uint", "<{{.}}>", "<14>", uint(14), true},
260 {"dot float", "<{{.}}>", "<15.1>", 15.1, true},
261 {"dot bool", "<{{.}}>", "<true>", true, true},
262 {"dot complex", "<{{.}}>", "<(16.2-17i)>", 16.2 - 17i
, true},
263 {"dot string", "<{{.}}>", "<hello>", "hello", true},
264 {"dot slice", "<{{.}}>", "<[-1 -2 -3]>", []int{-1, -2, -3}, true},
265 {"dot map", "<{{.}}>", "<map[two:22]>", map[string]int{"two": 22}, true},
266 {"dot struct", "<{{.}}>", "<{7 seven}>", struct {
269 }{7, "seven"}, true},
272 {"$ int", "{{$}}", "123", 123, true},
273 {"$.I", "{{$.I}}", "17", tVal
, true},
274 {"$.U.V", "{{$.U.V}}", "v", tVal
, true},
275 {"declare in action", "{{$x := $.U.V}}{{$x}}", "v", tVal
, true},
277 // Type with String method.
278 {"V{6666}.String()", "-{{.V0}}-", "-<6666>-", tVal
, true},
279 {"&V{7777}.String()", "-{{.V1}}-", "-<7777>-", tVal
, true},
280 {"(*V)(nil).String()", "-{{.V2}}-", "-nilV-", tVal
, true},
282 // Type with Error method.
283 {"W{888}.Error()", "-{{.W0}}-", "-[888]-", tVal
, true},
284 {"&W{999}.Error()", "-{{.W1}}-", "-[999]-", tVal
, true},
285 {"(*W)(nil).Error()", "-{{.W2}}-", "-nilW-", tVal
, true},
288 {"*int", "{{.PI}}", "23", tVal
, true},
289 {"*string", "{{.PS}}", "a string", tVal
, true},
290 {"*[]int", "{{.PSI}}", "[21 22 23]", tVal
, true},
291 {"*[]int[1]", "{{index .PSI 1}}", "22", tVal
, true},
292 {"NIL", "{{.NIL}}", "<nil>", tVal
, true},
294 // Empty interfaces holding values.
295 {"empty nil", "{{.Empty0}}", "<no value>", tVal
, true},
296 {"empty with int", "{{.Empty1}}", "3", tVal
, true},
297 {"empty with string", "{{.Empty2}}", "empty2", tVal
, true},
298 {"empty with slice", "{{.Empty3}}", "[7 8]", tVal
, true},
299 {"empty with struct", "{{.Empty4}}", "{UinEmpty}", tVal
, true},
300 {"empty with struct, field", "{{.Empty4.V}}", "UinEmpty", tVal
, true},
303 {".Method0", "-{{.Method0}}-", "-M0-", tVal
, true},
304 {".Method1(1234)", "-{{.Method1 1234}}-", "-1234-", tVal
, true},
305 {".Method1(.I)", "-{{.Method1 .I}}-", "-17-", tVal
, true},
306 {".Method2(3, .X)", "-{{.Method2 3 .X}}-", "-Method2: 3 x-", tVal
, true},
307 {".Method2(.U16, `str`)", "-{{.Method2 .U16 `str`}}-", "-Method2: 16 str-", tVal
, true},
308 {".Method2(.U16, $x)", "{{if $x := .X}}-{{.Method2 .U16 $x}}{{end}}-", "-Method2: 16 x-", tVal
, true},
309 {".Method3(nil constant)", "-{{.Method3 nil}}-", "-Method3: <nil>-", tVal
, true},
310 {".Method3(nil value)", "-{{.Method3 .MXI.unset}}-", "-Method3: <nil>-", tVal
, true},
311 {"method on var", "{{if $x := .}}-{{$x.Method2 .U16 $x.X}}{{end}}-", "-Method2: 16 x-", tVal
, true},
312 {"method on chained var",
313 "{{range .MSIone}}{{if $.U.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}",
316 "{{range .MSIone}}{{if $.GetU.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}",
318 {"chained method on variable",
319 "{{with $x := .}}{{with .SI}}{{$.GetU.TrueFalse $.True}}{{end}}{{end}}",
321 {".NilOKFunc not nil", "{{call .NilOKFunc .PI}}", "false", tVal
, true},
322 {".NilOKFunc nil", "{{call .NilOKFunc nil}}", "true", tVal
, true},
324 // Function call builtin.
325 {".BinaryFunc", "{{call .BinaryFunc `1` `2`}}", "[1=2]", tVal
, true},
326 {".VariadicFunc0", "{{call .VariadicFunc}}", "<>", tVal
, true},
327 {".VariadicFunc2", "{{call .VariadicFunc `he` `llo`}}", "<he+llo>", tVal
, true},
328 {".VariadicFuncInt", "{{call .VariadicFuncInt 33 `he` `llo`}}", "33=<he+llo>", tVal
, true},
329 {"if .BinaryFunc call", "{{ if .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{end}}", "[1=2]", tVal
, true},
330 {"if not .BinaryFunc call", "{{ if not .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{else}}No{{end}}", "No", tVal
, true},
331 {"Interface Call", `{{stringer .S}}`, "foozle", map[string]interface{}{"S": bytes
.NewBufferString("foozle")}, true},
332 {".ErrFunc", "{{call .ErrFunc}}", "bla", tVal
, true},
334 // Erroneous function calls (check args).
335 {".BinaryFuncTooFew", "{{call .BinaryFunc `1`}}", "", tVal
, false},
336 {".BinaryFuncTooMany", "{{call .BinaryFunc `1` `2` `3`}}", "", tVal
, false},
337 {".BinaryFuncBad0", "{{call .BinaryFunc 1 3}}", "", tVal
, false},
338 {".BinaryFuncBad1", "{{call .BinaryFunc `1` 3}}", "", tVal
, false},
339 {".VariadicFuncBad0", "{{call .VariadicFunc 3}}", "", tVal
, false},
340 {".VariadicFuncIntBad0", "{{call .VariadicFuncInt}}", "", tVal
, false},
341 {".VariadicFuncIntBad`", "{{call .VariadicFuncInt `x`}}", "", tVal
, false},
342 {".VariadicFuncNilBad", "{{call .VariadicFunc nil}}", "", tVal
, false},
345 {"pipeline", "-{{.Method0 | .Method2 .U16}}-", "-Method2: 16 M0-", tVal
, true},
346 {"pipeline func", "-{{call .VariadicFunc `llo` | call .VariadicFunc `he` }}-", "-<he+<llo>>-", tVal
, true},
348 // Parenthesized expressions
349 {"parens in pipeline", "{{printf `%d %d %d` (1) (2 | add 3) (add 4 (add 5 6))}}", "1 5 15", tVal
, true},
351 // Parenthesized expressions with field accesses
352 {"parens: $ in paren", "{{($).X}}", "x", tVal
, true},
353 {"parens: $.GetU in paren", "{{($.GetU).V}}", "v", tVal
, true},
354 {"parens: $ in paren in pipe", "{{($ | echo).X}}", "x", tVal
, true},
355 {"parens: spaces and args", `{{(makemap "up" "down" "left" "right").left}}`, "right", tVal
, true},
358 {"if true", "{{if true}}TRUE{{end}}", "TRUE", tVal
, true},
359 {"if false", "{{if false}}TRUE{{else}}FALSE{{end}}", "FALSE", tVal
, true},
360 {"if nil", "{{if nil}}TRUE{{end}}", "", tVal
, false},
361 {"if 1", "{{if 1}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal
, true},
362 {"if 0", "{{if 0}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal
, true},
363 {"if 1.5", "{{if 1.5}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal
, true},
364 {"if 0.0", "{{if .FloatZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal
, true},
365 {"if 1.5i", "{{if 1.5i}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal
, true},
366 {"if 0.0i", "{{if .ComplexZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal
, true},
367 {"if emptystring", "{{if ``}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal
, true},
368 {"if string", "{{if `notempty`}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal
, true},
369 {"if emptyslice", "{{if .SIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal
, true},
370 {"if slice", "{{if .SI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal
, true},
371 {"if emptymap", "{{if .MSIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal
, true},
372 {"if map", "{{if .MSI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal
, true},
373 {"if map unset", "{{if .MXI.none}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal
, true},
374 {"if map not unset", "{{if not .MXI.none}}ZERO{{else}}NON-ZERO{{end}}", "ZERO", tVal
, true},
375 {"if $x with $y int", "{{if $x := true}}{{with $y := .I}}{{$x}},{{$y}}{{end}}{{end}}", "true,17", tVal
, true},
376 {"if $x with $x int", "{{if $x := true}}{{with $x := .I}}{{$x}},{{end}}{{$x}}{{end}}", "17,true", tVal
, true},
377 {"if else if", "{{if false}}FALSE{{else if true}}TRUE{{end}}", "TRUE", tVal
, true},
378 {"if else chain", "{{if eq 1 3}}1{{else if eq 2 3}}2{{else if eq 3 3}}3{{end}}", "3", tVal
, true},
381 {"print", `{{print "hello, print"}}`, "hello, print", tVal
, true},
382 {"print 123", `{{print 1 2 3}}`, "1 2 3", tVal
, true},
383 {"print nil", `{{print nil}}`, "<nil>", tVal
, true},
384 {"println", `{{println 1 2 3}}`, "1 2 3\n", tVal
, true},
385 {"printf int", `{{printf "%04x" 127}}`, "007f", tVal
, true},
386 {"printf float", `{{printf "%g" 3.5}}`, "3.5", tVal
, true},
387 {"printf complex", `{{printf "%g" 1+7i}}`, "(1+7i)", tVal
, true},
388 {"printf string", `{{printf "%s" "hello"}}`, "hello", tVal
, true},
389 {"printf function", `{{printf "%#q" zeroArgs}}`, "`zeroArgs`", tVal
, true},
390 {"printf field", `{{printf "%s" .U.V}}`, "v", tVal
, true},
391 {"printf method", `{{printf "%s" .Method0}}`, "M0", tVal
, true},
392 {"printf dot", `{{with .I}}{{printf "%d" .}}{{end}}`, "17", tVal
, true},
393 {"printf var", `{{with $x := .I}}{{printf "%d" $x}}{{end}}`, "17", tVal
, true},
394 {"printf lots", `{{printf "%d %s %g %s" 127 "hello" 7-3i .Method0}}`, "127 hello (7-3i) M0", tVal
, true},
397 {"html", `{{html "<script>alert(\"XSS\");</script>"}}`,
398 "<script>alert("XSS");</script>", nil, true},
399 {"html pipeline", `{{printf "<script>alert(\"XSS\");</script>" | html}}`,
400 "<script>alert("XSS");</script>", nil, true},
401 {"html", `{{html .PS}}`, "a string", tVal
, true},
404 {"js", `{{js .}}`, `It\'d be nice.`, `It'd be nice.`, true},
407 {"urlquery", `{{"http://www.example.org/"|urlquery}}`, "http%3A%2F%2Fwww.example.org%2F", nil, true},
410 {"not", "{{not true}} {{not false}}", "false true", nil, true},
411 {"and", "{{and false 0}} {{and 1 0}} {{and 0 true}} {{and 1 1}}", "false 0 0 1", nil, true},
412 {"or", "{{or 0 0}} {{or 1 0}} {{or 0 true}} {{or 1 1}}", "0 1 true 1", nil, true},
413 {"boolean if", "{{if and true 1 `hi`}}TRUE{{else}}FALSE{{end}}", "TRUE", tVal
, true},
414 {"boolean if not", "{{if and true 1 `hi` | not}}TRUE{{else}}FALSE{{end}}", "FALSE", nil, true},
417 {"slice[0]", "{{index .SI 0}}", "3", tVal
, true},
418 {"slice[1]", "{{index .SI 1}}", "4", tVal
, true},
419 {"slice[HUGE]", "{{index .SI 10}}", "", tVal
, false},
420 {"slice[WRONG]", "{{index .SI `hello`}}", "", tVal
, false},
421 {"map[one]", "{{index .MSI `one`}}", "1", tVal
, true},
422 {"map[two]", "{{index .MSI `two`}}", "2", tVal
, true},
423 {"map[NO]", "{{index .MSI `XXX`}}", "0", tVal
, true},
424 {"map[nil]", "{{index .MSI nil}}", "0", tVal
, true},
425 {"map[WRONG]", "{{index .MSI 10}}", "", tVal
, false},
426 {"double index", "{{index .SMSI 1 `eleven`}}", "11", tVal
, true},
429 {"slice", "{{len .SI}}", "3", tVal
, true},
430 {"map", "{{len .MSI }}", "3", tVal
, true},
431 {"len of int", "{{len 3}}", "", tVal
, false},
432 {"len of nothing", "{{len .Empty0}}", "", tVal
, false},
435 {"with true", "{{with true}}{{.}}{{end}}", "true", tVal
, true},
436 {"with false", "{{with false}}{{.}}{{else}}FALSE{{end}}", "FALSE", tVal
, true},
437 {"with 1", "{{with 1}}{{.}}{{else}}ZERO{{end}}", "1", tVal
, true},
438 {"with 0", "{{with 0}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal
, true},
439 {"with 1.5", "{{with 1.5}}{{.}}{{else}}ZERO{{end}}", "1.5", tVal
, true},
440 {"with 0.0", "{{with .FloatZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal
, true},
441 {"with 1.5i", "{{with 1.5i}}{{.}}{{else}}ZERO{{end}}", "(0+1.5i)", tVal
, true},
442 {"with 0.0i", "{{with .ComplexZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal
, true},
443 {"with emptystring", "{{with ``}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal
, true},
444 {"with string", "{{with `notempty`}}{{.}}{{else}}EMPTY{{end}}", "notempty", tVal
, true},
445 {"with emptyslice", "{{with .SIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal
, true},
446 {"with slice", "{{with .SI}}{{.}}{{else}}EMPTY{{end}}", "[3 4 5]", tVal
, true},
447 {"with emptymap", "{{with .MSIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal
, true},
448 {"with map", "{{with .MSIone}}{{.}}{{else}}EMPTY{{end}}", "map[one:1]", tVal
, true},
449 {"with empty interface, struct field", "{{with .Empty4}}{{.V}}{{end}}", "UinEmpty", tVal
, true},
450 {"with $x int", "{{with $x := .I}}{{$x}}{{end}}", "17", tVal
, true},
451 {"with $x struct.U.V", "{{with $x := $}}{{$x.U.V}}{{end}}", "v", tVal
, true},
452 {"with variable and action", "{{with $x := $}}{{$y := $.U.V}}{{$y}}{{end}}", "v", tVal
, true},
455 {"range []int", "{{range .SI}}-{{.}}-{{end}}", "-3--4--5-", tVal
, true},
456 {"range empty no else", "{{range .SIEmpty}}-{{.}}-{{end}}", "", tVal
, true},
457 {"range []int else", "{{range .SI}}-{{.}}-{{else}}EMPTY{{end}}", "-3--4--5-", tVal
, true},
458 {"range empty else", "{{range .SIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal
, true},
459 {"range []bool", "{{range .SB}}-{{.}}-{{end}}", "-true--false-", tVal
, true},
460 {"range []int method", "{{range .SI | .MAdd .I}}-{{.}}-{{end}}", "-20--21--22-", tVal
, true},
461 {"range map", "{{range .MSI}}-{{.}}-{{end}}", "-1--3--2-", tVal
, true},
462 {"range empty map no else", "{{range .MSIEmpty}}-{{.}}-{{end}}", "", tVal
, true},
463 {"range map else", "{{range .MSI}}-{{.}}-{{else}}EMPTY{{end}}", "-1--3--2-", tVal
, true},
464 {"range empty map else", "{{range .MSIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal
, true},
465 {"range empty interface", "{{range .Empty3}}-{{.}}-{{else}}EMPTY{{end}}", "-7--8-", tVal
, true},
466 {"range empty nil", "{{range .Empty0}}-{{.}}-{{end}}", "", tVal
, true},
467 {"range $x SI", "{{range $x := .SI}}<{{$x}}>{{end}}", "<3><4><5>", tVal
, true},
468 {"range $x $y SI", "{{range $x, $y := .SI}}<{{$x}}={{$y}}>{{end}}", "<0=3><1=4><2=5>", tVal
, true},
469 {"range $x MSIone", "{{range $x := .MSIone}}<{{$x}}>{{end}}", "<1>", tVal
, true},
470 {"range $x $y MSIone", "{{range $x, $y := .MSIone}}<{{$x}}={{$y}}>{{end}}", "<one=1>", tVal
, true},
471 {"range $x PSI", "{{range $x := .PSI}}<{{$x}}>{{end}}", "<21><22><23>", tVal
, true},
472 {"declare in range", "{{range $x := .PSI}}<{{$foo:=$x}}{{$x}}>{{end}}", "<21><22><23>", tVal
, true},
473 {"range count", `{{range $i, $x := count 5}}[{{$i}}]{{$x}}{{end}}`, "[0]a[1]b[2]c[3]d[4]e", tVal
, true},
474 {"range nil count", `{{range $i, $x := count 0}}{{else}}empty{{end}}`, "empty", tVal
, true},
477 {"or as if true", `{{or .SI "slice is empty"}}`, "[3 4 5]", tVal
, true},
478 {"or as if false", `{{or .SIEmpty "slice is empty"}}`, "slice is empty", tVal
, true},
481 {"error method, error", "{{.MyError true}}", "", tVal
, false},
482 {"error method, no error", "{{.MyError false}}", "false", tVal
, true},
485 // Must separate dot and receiver; otherwise args are evaluated with dot set to variable.
486 {"bug0", "{{range .MSIone}}{{if $.Method1 .}}X{{end}}{{end}}", "X", tVal
, true},
487 // Do not loop endlessly in indirect for non-empty interfaces.
488 // The bug appears with *interface only; looped forever.
489 {"bug1", "{{.Method0}}", "M0", &iVal
, true},
490 // Was taking address of interface field, so method set was empty.
491 {"bug2", "{{$.NonEmptyInterface.Method0}}", "M0", tVal
, true},
492 // Struct values were not legal in with - mere oversight.
493 {"bug3", "{{with $}}{{.Method0}}{{end}}", "M0", tVal
, true},
494 // Nil interface values in if.
495 {"bug4", "{{if .Empty0}}non-nil{{else}}nil{{end}}", "nil", tVal
, true},
497 {"bug5", "{{.Str}}", "foozle", tVal
, true},
498 {"bug5a", "{{.Err}}", "erroozle", tVal
, true},
499 // Args need to be indirected and dereferenced sometimes.
500 {"bug6a", "{{vfunc .V0 .V1}}", "vfunc", tVal
, true},
501 {"bug6b", "{{vfunc .V0 .V0}}", "vfunc", tVal
, true},
502 {"bug6c", "{{vfunc .V1 .V0}}", "vfunc", tVal
, true},
503 {"bug6d", "{{vfunc .V1 .V1}}", "vfunc", tVal
, true},
504 // Legal parse but illegal execution: non-function should have no arguments.
505 {"bug7a", "{{3 2}}", "", tVal
, false},
506 {"bug7b", "{{$x := 1}}{{$x 2}}", "", tVal
, false},
507 {"bug7c", "{{$x := 1}}{{3 | $x}}", "", tVal
, false},
508 // Pipelined arg was not being type-checked.
509 {"bug8a", "{{3|oneArg}}", "", tVal
, false},
510 {"bug8b", "{{4|dddArg 3}}", "", tVal
, false},
511 // A bug was introduced that broke map lookups for lower-case names.
512 {"bug9", "{{.cause}}", "neglect", map[string]string{"cause": "neglect"}, true},
513 // Field chain starting with function did not work.
514 {"bug10", "{{mapOfThree.three}}-{{(mapOfThree).three}}", "3-3", 0, true},
515 // Dereferencing nil pointer while evaluating function arguments should not panic. Issue 7333.
516 {"bug11", "{{valueString .PS}}", "", T
{}, false},
519 func zeroArgs() string {
523 func oneArg(a
string) string {
527 func dddArg(a
int, b
...string) string {
528 return fmt
.Sprintln(a
, b
)
531 // count returns a channel that will deliver n sequential 1-letter strings starting at "a"
532 func count(n
int) chan string {
536 c
:= make(chan string)
538 for i
:= 0; i
< n
; i
++ {
539 c
<- "abcdefghijklmnop"[i
: i
+1]
546 // vfunc takes a *V and a V
547 func vfunc(V
, *V
) string {
551 // valueString takes a string, not a pointer.
552 func valueString(v
string) string {
553 return "value is ignored"
556 func add(args
...int) int {
558 for _
, x
:= range args
{
564 func echo(arg
interface{}) interface{} {
568 func makemap(arg
...string) map[string]string {
572 m
:= make(map[string]string)
573 for i
:= 0; i
< len(arg
); i
+= 2 {
579 func stringer(s fmt
.Stringer
) string {
583 func mapOfThree() interface{} {
584 return map[string]int{"three": 3}
587 func testExecute(execTests
[]execTest
, template
*Template
, t
*testing
.T
) {
588 b
:= new(bytes
.Buffer
)
595 "mapOfThree": mapOfThree
,
597 "stringer": stringer
,
599 "valueString": valueString
,
601 "zeroArgs": zeroArgs
,
603 for _
, test
:= range execTests
{
607 tmpl
, err
= New(test
.name
).Funcs(funcs
).Parse(test
.input
)
609 tmpl
, err
= template
.New(test
.name
).Funcs(funcs
).Parse(test
.input
)
612 t
.Errorf("%s: parse error: %s", test
.name
, err
)
616 err
= tmpl
.Execute(b
, test
.data
)
618 case !test
.ok
&& err
== nil:
619 t
.Errorf("%s: expected error; got none", test
.name
)
621 case test
.ok
&& err
!= nil:
622 t
.Errorf("%s: unexpected execute error: %s", test
.name
, err
)
624 case !test
.ok
&& err
!= nil:
625 // expected error, got one
627 fmt
.Printf("%s: %s\n\t%s\n", test
.name
, test
.input
, err
)
631 if result
!= test
.output
{
632 t
.Errorf("%s: expected\n\t%q\ngot\n\t%q", test
.name
, test
.output
, result
)
637 func TestExecute(t
*testing
.T
) {
638 testExecute(execTests
, nil, t
)
641 var delimPairs
= []string{
643 "{{", "}}", // same as default
644 "<<", ">>", // distinct
646 "(日)", "(本)", // peculiar
649 func TestDelims(t
*testing
.T
) {
650 const hello
= "Hello, world"
651 var value
= struct{ Str
string }{hello
}
652 for i
:= 0; i
< len(delimPairs
); i
+= 2 {
654 left
:= delimPairs
[i
+0]
656 right
:= delimPairs
[i
+1]
658 if left
== "" { // default case
661 if right
== "" { // default case
664 text
= trueLeft
+ text
+ trueRight
666 text
+= trueLeft
+ "/*comment*/" + trueRight
667 // Now add an action containing a string.
668 text
+= trueLeft
+ `"` + trueLeft
+ `"` + trueRight
669 // At this point text looks like `{{.Str}}{{/*comment*/}}{{"{{"}}`.
670 tmpl
, err
:= New("delims").Delims(left
, right
).Parse(text
)
672 t
.Fatalf("delim %q text %q parse err %s", left
, text
, err
)
674 var b
= new(bytes
.Buffer
)
675 err
= tmpl
.Execute(b
, value
)
677 t
.Fatalf("delim %q exec err %s", left
, err
)
679 if b
.String() != hello
+trueLeft
{
680 t
.Errorf("expected %q got %q", hello
+trueLeft
, b
.String())
685 // Check that an error from a method flows back to the top.
686 func TestExecuteError(t
*testing
.T
) {
687 b
:= new(bytes
.Buffer
)
689 _
, err
:= tmpl
.Parse("{{.MyError true}}")
691 t
.Fatalf("parse error: %s", err
)
693 err
= tmpl
.Execute(b
, tVal
)
695 t
.Errorf("expected error; got none")
696 } else if !strings
.Contains(err
.Error(), myError
.Error()) {
698 fmt
.Printf("test execute error: %s\n", err
)
700 t
.Errorf("expected myError; got %s", err
)
704 const execErrorText
= `line 1
708 {{define "one"}}{{template "two" .}}{{end}}
709 {{define "two"}}{{template "three" .}}{{end}}
710 {{define "three"}}{{index "hi" $}}{{end}}`
712 // Check that an error from a nested template contains all the relevant information.
713 func TestExecError(t
*testing
.T
) {
714 tmpl
, err
:= New("top").Parse(execErrorText
)
716 t
.Fatal("parse error:", err
)
719 err
= tmpl
.Execute(&b
, 5) // 5 is out of range indexing "hi"
721 t
.Fatal("expected error")
723 const want
= `template: top:7:20: executing "three" at <index "hi" $>: error calling index: index out of range: 5`
726 t
.Errorf("expected\n%q\ngot\n%q", want
, got
)
730 func TestJSEscaping(t
*testing
.T
) {
731 testCases
:= []struct {
736 {`Go "jump" \`, `Go \"jump\" \\`},
737 {`Yukihiro says "今日は世界"`, `Yukihiro says \"今日は世界\"`},
738 {"unprintable \uFDFF", `unprintable \uFDFF`},
739 {`<html>`, `\x3Chtml\x3E`},
741 for _
, tc
:= range testCases
{
742 s
:= JSEscapeString(tc
.in
)
744 t
.Errorf("JS escaping [%s] got [%s] want [%s]", tc
.in
, s
, tc
.exp
)
749 // A nice example: walk a binary tree.
756 // Use different delimiters to test Set.Delims.
757 const treeTemplate
= `
771 func TestTree(t
*testing
.T
) {
808 tmpl
, err
:= New("root").Delims("(", ")").Parse(treeTemplate
)
810 t
.Fatal("parse error:", err
)
813 stripSpace
:= func(r rune
) rune
{
814 if r
== '\t' || r
== '\n' {
819 const expect
= "[1[2[3[4]][5[6]]][7[8[9]][10[11]]]]"
820 // First by looking up the template.
821 err
= tmpl
.Lookup("tree").Execute(&b
, tree
)
823 t
.Fatal("exec error:", err
)
825 result
:= strings
.Map(stripSpace
, b
.String())
826 if result
!= expect
{
827 t
.Errorf("expected %q got %q", expect
, result
)
829 // Then direct to execution.
831 err
= tmpl
.ExecuteTemplate(&b
, "tree", tree
)
833 t
.Fatal("exec error:", err
)
835 result
= strings
.Map(stripSpace
, b
.String())
836 if result
!= expect
{
837 t
.Errorf("expected %q got %q", expect
, result
)
841 func TestExecuteOnNewTemplate(t
*testing
.T
) {
842 // This is issue 3872.
843 _
= New("Name").Templates()
846 const testTemplates
= `{{define "one"}}one{{end}}{{define "two"}}two{{end}}`
848 func TestMessageForExecuteEmpty(t
*testing
.T
) {
849 // Test a truly empty template.
852 err
:= tmpl
.Execute(&b
, 0)
854 t
.Fatal("expected initial error")
857 want
:= `template: empty: "empty" is an incomplete or empty template`
859 t
.Errorf("expected error %s got %s", want
, got
)
861 // Add a non-empty template to check that the error is helpful.
862 tests
, err
:= New("").Parse(testTemplates
)
866 tmpl
.AddParseTree("secondary", tests
.Tree
)
867 err
= tmpl
.Execute(&b
, 0)
869 t
.Fatal("expected second error")
872 want
= `template: empty: "empty" is an incomplete or empty template; defined templates are: "secondary"`
874 t
.Errorf("expected error %s got %s", want
, got
)
876 // Make sure we can execute the secondary.
877 err
= tmpl
.ExecuteTemplate(&b
, "secondary", 0)
883 type cmpTest
struct {
889 var cmpTests
= []cmpTest
{
890 {"eq true true", "true", true},
891 {"eq true false", "false", true},
892 {"eq 1+2i 1+2i", "true", true},
893 {"eq 1+2i 1+3i", "false", true},
894 {"eq 1.5 1.5", "true", true},
895 {"eq 1.5 2.5", "false", true},
896 {"eq 1 1", "true", true},
897 {"eq 1 2", "false", true},
898 {"eq `xy` `xy`", "true", true},
899 {"eq `xy` `xyz`", "false", true},
900 {"eq .Xuint .Xuint", "true", true},
901 {"eq .Xuint .Yuint", "false", true},
902 {"eq 3 4 5 6 3", "true", true},
903 {"eq 3 4 5 6 7", "false", true},
904 {"ne true true", "false", true},
905 {"ne true false", "true", true},
906 {"ne 1+2i 1+2i", "false", true},
907 {"ne 1+2i 1+3i", "true", true},
908 {"ne 1.5 1.5", "false", true},
909 {"ne 1.5 2.5", "true", true},
910 {"ne 1 1", "false", true},
911 {"ne 1 2", "true", true},
912 {"ne `xy` `xy`", "false", true},
913 {"ne `xy` `xyz`", "true", true},
914 {"ne .Xuint .Xuint", "false", true},
915 {"ne .Xuint .Yuint", "true", true},
916 {"lt 1.5 1.5", "false", true},
917 {"lt 1.5 2.5", "true", true},
918 {"lt 1 1", "false", true},
919 {"lt 1 2", "true", true},
920 {"lt `xy` `xy`", "false", true},
921 {"lt `xy` `xyz`", "true", true},
922 {"lt .Xuint .Xuint", "false", true},
923 {"lt .Xuint .Yuint", "true", true},
924 {"le 1.5 1.5", "true", true},
925 {"le 1.5 2.5", "true", true},
926 {"le 2.5 1.5", "false", true},
927 {"le 1 1", "true", true},
928 {"le 1 2", "true", true},
929 {"le 2 1", "false", true},
930 {"le `xy` `xy`", "true", true},
931 {"le `xy` `xyz`", "true", true},
932 {"le `xyz` `xy`", "false", true},
933 {"le .Xuint .Xuint", "true", true},
934 {"le .Xuint .Yuint", "true", true},
935 {"le .Yuint .Xuint", "false", true},
936 {"gt 1.5 1.5", "false", true},
937 {"gt 1.5 2.5", "false", true},
938 {"gt 1 1", "false", true},
939 {"gt 2 1", "true", true},
940 {"gt 1 2", "false", true},
941 {"gt `xy` `xy`", "false", true},
942 {"gt `xy` `xyz`", "false", true},
943 {"gt .Xuint .Xuint", "false", true},
944 {"gt .Xuint .Yuint", "false", true},
945 {"gt .Yuint .Xuint", "true", true},
946 {"ge 1.5 1.5", "true", true},
947 {"ge 1.5 2.5", "false", true},
948 {"ge 2.5 1.5", "true", true},
949 {"ge 1 1", "true", true},
950 {"ge 1 2", "false", true},
951 {"ge 2 1", "true", true},
952 {"ge `xy` `xy`", "true", true},
953 {"ge `xy` `xyz`", "false", true},
954 {"ge `xyz` `xy`", "true", true},
955 {"ge .Xuint .Xuint", "true", true},
956 {"ge .Xuint .Yuint", "false", true},
957 {"ge .Yuint .Xuint", "true", true},
959 {"eq `xy` 1", "", false}, // Different types.
960 {"lt true true", "", false}, // Unordered types.
961 {"lt 1+0i 1+0i", "", false}, // Unordered types.
964 func TestComparison(t
*testing
.T
) {
965 b
:= new(bytes
.Buffer
)
966 var cmpStruct
= struct {
969 for _
, test
:= range cmpTests
{
970 text
:= fmt
.Sprintf("{{if %s}}true{{else}}false{{end}}", test
.expr
)
971 tmpl
, err
:= New("empty").Parse(text
)
976 err
= tmpl
.Execute(b
, &cmpStruct
)
977 if test
.ok
&& err
!= nil {
978 t
.Errorf("%s errored incorrectly: %s", test
.expr
, err
)
981 if !test
.ok
&& err
== nil {
982 t
.Errorf("%s did not error", test
.expr
)
985 if b
.String() != test
.truth
{
986 t
.Errorf("%s: want %s; got %s", test
.expr
, test
.truth
, b
.String())