Home | History | Annotate | Download | only in template
      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 	"io/ioutil"
     13 	"reflect"
     14 	"strings"
     15 	"testing"
     16 )
     17 
     18 var debug = flag.Bool("debug", false, "show the errors produced by the tests")
     19 
     20 // T has lots of interesting pieces to use to test execution.
     21 type T struct {
     22 	// Basics
     23 	True        bool
     24 	I           int
     25 	U16         uint16
     26 	X           string
     27 	FloatZero   float64
     28 	ComplexZero complex128
     29 	// Nested structs.
     30 	U *U
     31 	// Struct with String method.
     32 	V0     V
     33 	V1, V2 *V
     34 	// Struct with Error method.
     35 	W0     W
     36 	W1, W2 *W
     37 	// Slices
     38 	SI      []int
     39 	SIEmpty []int
     40 	SB      []bool
     41 	// Maps
     42 	MSI      map[string]int
     43 	MSIone   map[string]int // one element, for deterministic output
     44 	MSIEmpty map[string]int
     45 	MXI      map[interface{}]int
     46 	MII      map[int]int
     47 	MI32S    map[int32]string
     48 	MI64S    map[int64]string
     49 	MUI32S   map[uint32]string
     50 	MUI64S   map[uint64]string
     51 	MI8S     map[int8]string
     52 	MUI8S    map[uint8]string
     53 	SMSI     []map[string]int
     54 	// Empty interfaces; used to see if we can dig inside one.
     55 	Empty0 interface{} // nil
     56 	Empty1 interface{}
     57 	Empty2 interface{}
     58 	Empty3 interface{}
     59 	Empty4 interface{}
     60 	// Non-empty interfaces.
     61 	NonEmptyInterface    I
     62 	NonEmptyInterfacePtS *I
     63 	// Stringer.
     64 	Str fmt.Stringer
     65 	Err error
     66 	// Pointers
     67 	PI  *int
     68 	PS  *string
     69 	PSI *[]int
     70 	NIL *int
     71 	// Function (not method)
     72 	BinaryFunc      func(string, string) string
     73 	VariadicFunc    func(...string) string
     74 	VariadicFuncInt func(int, ...string) string
     75 	NilOKFunc       func(*int) bool
     76 	ErrFunc         func() (string, error)
     77 	// Template to test evaluation of templates.
     78 	Tmpl *Template
     79 	// Unexported field; cannot be accessed by template.
     80 	unexported int
     81 }
     82 
     83 type S []string
     84 
     85 func (S) Method0() string {
     86 	return "M0"
     87 }
     88 
     89 type U struct {
     90 	V string
     91 }
     92 
     93 type V struct {
     94 	j int
     95 }
     96 
     97 func (v *V) String() string {
     98 	if v == nil {
     99 		return "nilV"
    100 	}
    101 	return fmt.Sprintf("<%d>", v.j)
    102 }
    103 
    104 type W struct {
    105 	k int
    106 }
    107 
    108 func (w *W) Error() string {
    109 	if w == nil {
    110 		return "nilW"
    111 	}
    112 	return fmt.Sprintf("[%d]", w.k)
    113 }
    114 
    115 var siVal = I(S{"a", "b"})
    116 
    117 var tVal = &T{
    118 	True:   true,
    119 	I:      17,
    120 	U16:    16,
    121 	X:      "x",
    122 	U:      &U{"v"},
    123 	V0:     V{6666},
    124 	V1:     &V{7777}, // leave V2 as nil
    125 	W0:     W{888},
    126 	W1:     &W{999}, // leave W2 as nil
    127 	SI:     []int{3, 4, 5},
    128 	SB:     []bool{true, false},
    129 	MSI:    map[string]int{"one": 1, "two": 2, "three": 3},
    130 	MSIone: map[string]int{"one": 1},
    131 	MXI:    map[interface{}]int{"one": 1},
    132 	MII:    map[int]int{1: 1},
    133 	MI32S:  map[int32]string{1: "one", 2: "two"},
    134 	MI64S:  map[int64]string{2: "i642", 3: "i643"},
    135 	MUI32S: map[uint32]string{2: "u322", 3: "u323"},
    136 	MUI64S: map[uint64]string{2: "ui642", 3: "ui643"},
    137 	MI8S:   map[int8]string{2: "i82", 3: "i83"},
    138 	MUI8S:  map[uint8]string{2: "u82", 3: "u83"},
    139 	SMSI: []map[string]int{
    140 		{"one": 1, "two": 2},
    141 		{"eleven": 11, "twelve": 12},
    142 	},
    143 	Empty1:               3,
    144 	Empty2:               "empty2",
    145 	Empty3:               []int{7, 8},
    146 	Empty4:               &U{"UinEmpty"},
    147 	NonEmptyInterface:    &T{X: "x"},
    148 	NonEmptyInterfacePtS: &siVal,
    149 	Str:                  bytes.NewBuffer([]byte("foozle")),
    150 	Err:                  errors.New("erroozle"),
    151 	PI:                   newInt(23),
    152 	PS:                   newString("a string"),
    153 	PSI:                  newIntSlice(21, 22, 23),
    154 	BinaryFunc:           func(a, b string) string { return fmt.Sprintf("[%s=%s]", a, b) },
    155 	VariadicFunc:         func(s ...string) string { return fmt.Sprint("<", strings.Join(s, "+"), ">") },
    156 	VariadicFuncInt:      func(a int, s ...string) string { return fmt.Sprint(a, "=<", strings.Join(s, "+"), ">") },
    157 	NilOKFunc:            func(s *int) bool { return s == nil },
    158 	ErrFunc:              func() (string, error) { return "bla", nil },
    159 	Tmpl:                 Must(New("x").Parse("test template")), // "x" is the value of .X
    160 }
    161 
    162 var tSliceOfNil = []*T{nil}
    163 
    164 // A non-empty interface.
    165 type I interface {
    166 	Method0() string
    167 }
    168 
    169 var iVal I = tVal
    170 
    171 // Helpers for creation.
    172 func newInt(n int) *int {
    173 	return &n
    174 }
    175 
    176 func newString(s string) *string {
    177 	return &s
    178 }
    179 
    180 func newIntSlice(n ...int) *[]int {
    181 	p := new([]int)
    182 	*p = make([]int, len(n))
    183 	copy(*p, n)
    184 	return p
    185 }
    186 
    187 // Simple methods with and without arguments.
    188 func (t *T) Method0() string {
    189 	return "M0"
    190 }
    191 
    192 func (t *T) Method1(a int) int {
    193 	return a
    194 }
    195 
    196 func (t *T) Method2(a uint16, b string) string {
    197 	return fmt.Sprintf("Method2: %d %s", a, b)
    198 }
    199 
    200 func (t *T) Method3(v interface{}) string {
    201 	return fmt.Sprintf("Method3: %v", v)
    202 }
    203 
    204 func (t *T) Copy() *T {
    205 	n := new(T)
    206 	*n = *t
    207 	return n
    208 }
    209 
    210 func (t *T) MAdd(a int, b []int) []int {
    211 	v := make([]int, len(b))
    212 	for i, x := range b {
    213 		v[i] = x + a
    214 	}
    215 	return v
    216 }
    217 
    218 var myError = errors.New("my error")
    219 
    220 // MyError returns a value and an error according to its argument.
    221 func (t *T) MyError(error bool) (bool, error) {
    222 	if error {
    223 		return true, myError
    224 	}
    225 	return false, nil
    226 }
    227 
    228 // A few methods to test chaining.
    229 func (t *T) GetU() *U {
    230 	return t.U
    231 }
    232 
    233 func (u *U) TrueFalse(b bool) string {
    234 	if b {
    235 		return "true"
    236 	}
    237 	return ""
    238 }
    239 
    240 func typeOf(arg interface{}) string {
    241 	return fmt.Sprintf("%T", arg)
    242 }
    243 
    244 type execTest struct {
    245 	name   string
    246 	input  string
    247 	output string
    248 	data   interface{}
    249 	ok     bool
    250 }
    251 
    252 // bigInt and bigUint are hex string representing numbers either side
    253 // of the max int boundary.
    254 // We do it this way so the test doesn't depend on ints being 32 bits.
    255 var (
    256 	bigInt  = fmt.Sprintf("0x%x", int(1<<uint(reflect.TypeOf(0).Bits()-1)-1))
    257 	bigUint = fmt.Sprintf("0x%x", uint(1<<uint(reflect.TypeOf(0).Bits()-1)))
    258 )
    259 
    260 var execTests = []execTest{
    261 	// Trivial cases.
    262 	{"empty", "", "", nil, true},
    263 	{"text", "some text", "some text", nil, true},
    264 	{"nil action", "{{nil}}", "", nil, false},
    265 
    266 	// Ideal constants.
    267 	{"ideal int", "{{typeOf 3}}", "int", 0, true},
    268 	{"ideal float", "{{typeOf 1.0}}", "float64", 0, true},
    269 	{"ideal exp float", "{{typeOf 1e1}}", "float64", 0, true},
    270 	{"ideal complex", "{{typeOf 1i}}", "complex128", 0, true},
    271 	{"ideal int", "{{typeOf " + bigInt + "}}", "int", 0, true},
    272 	{"ideal too big", "{{typeOf " + bigUint + "}}", "", 0, false},
    273 	{"ideal nil without type", "{{nil}}", "", 0, false},
    274 
    275 	// Fields of structs.
    276 	{".X", "-{{.X}}-", "-x-", tVal, true},
    277 	{".U.V", "-{{.U.V}}-", "-v-", tVal, true},
    278 	{".unexported", "{{.unexported}}", "", tVal, false},
    279 
    280 	// Fields on maps.
    281 	{"map .one", "{{.MSI.one}}", "1", tVal, true},
    282 	{"map .two", "{{.MSI.two}}", "2", tVal, true},
    283 	{"map .NO", "{{.MSI.NO}}", "<no value>", tVal, true},
    284 	{"map .one interface", "{{.MXI.one}}", "1", tVal, true},
    285 	{"map .WRONG args", "{{.MSI.one 1}}", "", tVal, false},
    286 	{"map .WRONG type", "{{.MII.one}}", "", tVal, false},
    287 
    288 	// Dots of all kinds to test basic evaluation.
    289 	{"dot int", "<{{.}}>", "<13>", 13, true},
    290 	{"dot uint", "<{{.}}>", "<14>", uint(14), true},
    291 	{"dot float", "<{{.}}>", "<15.1>", 15.1, true},
    292 	{"dot bool", "<{{.}}>", "<true>", true, true},
    293 	{"dot complex", "<{{.}}>", "<(16.2-17i)>", 16.2 - 17i, true},
    294 	{"dot string", "<{{.}}>", "<hello>", "hello", true},
    295 	{"dot slice", "<{{.}}>", "<[-1 -2 -3]>", []int{-1, -2, -3}, true},
    296 	{"dot map", "<{{.}}>", "<map[two:22]>", map[string]int{"two": 22}, true},
    297 	{"dot struct", "<{{.}}>", "<{7 seven}>", struct {
    298 		a int
    299 		b string
    300 	}{7, "seven"}, true},
    301 
    302 	// Variables.
    303 	{"$ int", "{{$}}", "123", 123, true},
    304 	{"$.I", "{{$.I}}", "17", tVal, true},
    305 	{"$.U.V", "{{$.U.V}}", "v", tVal, true},
    306 	{"declare in action", "{{$x := $.U.V}}{{$x}}", "v", tVal, true},
    307 
    308 	// Type with String method.
    309 	{"V{6666}.String()", "-{{.V0}}-", "-<6666>-", tVal, true},
    310 	{"&V{7777}.String()", "-{{.V1}}-", "-<7777>-", tVal, true},
    311 	{"(*V)(nil).String()", "-{{.V2}}-", "-nilV-", tVal, true},
    312 
    313 	// Type with Error method.
    314 	{"W{888}.Error()", "-{{.W0}}-", "-[888]-", tVal, true},
    315 	{"&W{999}.Error()", "-{{.W1}}-", "-[999]-", tVal, true},
    316 	{"(*W)(nil).Error()", "-{{.W2}}-", "-nilW-", tVal, true},
    317 
    318 	// Pointers.
    319 	{"*int", "{{.PI}}", "23", tVal, true},
    320 	{"*string", "{{.PS}}", "a string", tVal, true},
    321 	{"*[]int", "{{.PSI}}", "[21 22 23]", tVal, true},
    322 	{"*[]int[1]", "{{index .PSI 1}}", "22", tVal, true},
    323 	{"NIL", "{{.NIL}}", "<nil>", tVal, true},
    324 
    325 	// Empty interfaces holding values.
    326 	{"empty nil", "{{.Empty0}}", "<no value>", tVal, true},
    327 	{"empty with int", "{{.Empty1}}", "3", tVal, true},
    328 	{"empty with string", "{{.Empty2}}", "empty2", tVal, true},
    329 	{"empty with slice", "{{.Empty3}}", "[7 8]", tVal, true},
    330 	{"empty with struct", "{{.Empty4}}", "{UinEmpty}", tVal, true},
    331 	{"empty with struct, field", "{{.Empty4.V}}", "UinEmpty", tVal, true},
    332 
    333 	// Method calls.
    334 	{".Method0", "-{{.Method0}}-", "-M0-", tVal, true},
    335 	{".Method1(1234)", "-{{.Method1 1234}}-", "-1234-", tVal, true},
    336 	{".Method1(.I)", "-{{.Method1 .I}}-", "-17-", tVal, true},
    337 	{".Method2(3, .X)", "-{{.Method2 3 .X}}-", "-Method2: 3 x-", tVal, true},
    338 	{".Method2(.U16, `str`)", "-{{.Method2 .U16 `str`}}-", "-Method2: 16 str-", tVal, true},
    339 	{".Method2(.U16, $x)", "{{if $x := .X}}-{{.Method2 .U16 $x}}{{end}}-", "-Method2: 16 x-", tVal, true},
    340 	{".Method3(nil constant)", "-{{.Method3 nil}}-", "-Method3: <nil>-", tVal, true},
    341 	{".Method3(nil value)", "-{{.Method3 .MXI.unset}}-", "-Method3: <nil>-", tVal, true},
    342 	{"method on var", "{{if $x := .}}-{{$x.Method2 .U16 $x.X}}{{end}}-", "-Method2: 16 x-", tVal, true},
    343 	{"method on chained var",
    344 		"{{range .MSIone}}{{if $.U.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}",
    345 		"true", tVal, true},
    346 	{"chained method",
    347 		"{{range .MSIone}}{{if $.GetU.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}",
    348 		"true", tVal, true},
    349 	{"chained method on variable",
    350 		"{{with $x := .}}{{with .SI}}{{$.GetU.TrueFalse $.True}}{{end}}{{end}}",
    351 		"true", tVal, true},
    352 	{".NilOKFunc not nil", "{{call .NilOKFunc .PI}}", "false", tVal, true},
    353 	{".NilOKFunc nil", "{{call .NilOKFunc nil}}", "true", tVal, true},
    354 	{"method on nil value from slice", "-{{range .}}{{.Method1 1234}}{{end}}-", "-1234-", tSliceOfNil, true},
    355 
    356 	// Function call builtin.
    357 	{".BinaryFunc", "{{call .BinaryFunc `1` `2`}}", "[1=2]", tVal, true},
    358 	{".VariadicFunc0", "{{call .VariadicFunc}}", "<>", tVal, true},
    359 	{".VariadicFunc2", "{{call .VariadicFunc `he` `llo`}}", "<he+llo>", tVal, true},
    360 	{".VariadicFuncInt", "{{call .VariadicFuncInt 33 `he` `llo`}}", "33=<he+llo>", tVal, true},
    361 	{"if .BinaryFunc call", "{{ if .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{end}}", "[1=2]", tVal, true},
    362 	{"if not .BinaryFunc call", "{{ if not .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{else}}No{{end}}", "No", tVal, true},
    363 	{"Interface Call", `{{stringer .S}}`, "foozle", map[string]interface{}{"S": bytes.NewBufferString("foozle")}, true},
    364 	{".ErrFunc", "{{call .ErrFunc}}", "bla", tVal, true},
    365 	{"call nil", "{{call nil}}", "", tVal, false},
    366 
    367 	// Erroneous function calls (check args).
    368 	{".BinaryFuncTooFew", "{{call .BinaryFunc `1`}}", "", tVal, false},
    369 	{".BinaryFuncTooMany", "{{call .BinaryFunc `1` `2` `3`}}", "", tVal, false},
    370 	{".BinaryFuncBad0", "{{call .BinaryFunc 1 3}}", "", tVal, false},
    371 	{".BinaryFuncBad1", "{{call .BinaryFunc `1` 3}}", "", tVal, false},
    372 	{".VariadicFuncBad0", "{{call .VariadicFunc 3}}", "", tVal, false},
    373 	{".VariadicFuncIntBad0", "{{call .VariadicFuncInt}}", "", tVal, false},
    374 	{".VariadicFuncIntBad`", "{{call .VariadicFuncInt `x`}}", "", tVal, false},
    375 	{".VariadicFuncNilBad", "{{call .VariadicFunc nil}}", "", tVal, false},
    376 
    377 	// Pipelines.
    378 	{"pipeline", "-{{.Method0 | .Method2 .U16}}-", "-Method2: 16 M0-", tVal, true},
    379 	{"pipeline func", "-{{call .VariadicFunc `llo` | call .VariadicFunc `he` }}-", "-<he+<llo>>-", tVal, true},
    380 
    381 	// Parenthesized expressions
    382 	{"parens in pipeline", "{{printf `%d %d %d` (1) (2 | add 3) (add 4 (add 5 6))}}", "1 5 15", tVal, true},
    383 
    384 	// Parenthesized expressions with field accesses
    385 	{"parens: $ in paren", "{{($).X}}", "x", tVal, true},
    386 	{"parens: $.GetU in paren", "{{($.GetU).V}}", "v", tVal, true},
    387 	{"parens: $ in paren in pipe", "{{($ | echo).X}}", "x", tVal, true},
    388 	{"parens: spaces and args", `{{(makemap "up" "down" "left" "right").left}}`, "right", tVal, true},
    389 
    390 	// If.
    391 	{"if true", "{{if true}}TRUE{{end}}", "TRUE", tVal, true},
    392 	{"if false", "{{if false}}TRUE{{else}}FALSE{{end}}", "FALSE", tVal, true},
    393 	{"if nil", "{{if nil}}TRUE{{end}}", "", tVal, false},
    394 	{"if 1", "{{if 1}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
    395 	{"if 0", "{{if 0}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
    396 	{"if 1.5", "{{if 1.5}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
    397 	{"if 0.0", "{{if .FloatZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
    398 	{"if 1.5i", "{{if 1.5i}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
    399 	{"if 0.0i", "{{if .ComplexZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
    400 	{"if emptystring", "{{if ``}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
    401 	{"if string", "{{if `notempty`}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
    402 	{"if emptyslice", "{{if .SIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
    403 	{"if slice", "{{if .SI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
    404 	{"if emptymap", "{{if .MSIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
    405 	{"if map", "{{if .MSI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
    406 	{"if map unset", "{{if .MXI.none}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
    407 	{"if map not unset", "{{if not .MXI.none}}ZERO{{else}}NON-ZERO{{end}}", "ZERO", tVal, true},
    408 	{"if $x with $y int", "{{if $x := true}}{{with $y := .I}}{{$x}},{{$y}}{{end}}{{end}}", "true,17", tVal, true},
    409 	{"if $x with $x int", "{{if $x := true}}{{with $x := .I}}{{$x}},{{end}}{{$x}}{{end}}", "17,true", tVal, true},
    410 	{"if else if", "{{if false}}FALSE{{else if true}}TRUE{{end}}", "TRUE", tVal, true},
    411 	{"if else chain", "{{if eq 1 3}}1{{else if eq 2 3}}2{{else if eq 3 3}}3{{end}}", "3", tVal, true},
    412 
    413 	// Print etc.
    414 	{"print", `{{print "hello, print"}}`, "hello, print", tVal, true},
    415 	{"print 123", `{{print 1 2 3}}`, "1 2 3", tVal, true},
    416 	{"print nil", `{{print nil}}`, "<nil>", tVal, true},
    417 	{"println", `{{println 1 2 3}}`, "1 2 3\n", tVal, true},
    418 	{"printf int", `{{printf "%04x" 127}}`, "007f", tVal, true},
    419 	{"printf float", `{{printf "%g" 3.5}}`, "3.5", tVal, true},
    420 	{"printf complex", `{{printf "%g" 1+7i}}`, "(1+7i)", tVal, true},
    421 	{"printf string", `{{printf "%s" "hello"}}`, "hello", tVal, true},
    422 	{"printf function", `{{printf "%#q" zeroArgs}}`, "`zeroArgs`", tVal, true},
    423 	{"printf field", `{{printf "%s" .U.V}}`, "v", tVal, true},
    424 	{"printf method", `{{printf "%s" .Method0}}`, "M0", tVal, true},
    425 	{"printf dot", `{{with .I}}{{printf "%d" .}}{{end}}`, "17", tVal, true},
    426 	{"printf var", `{{with $x := .I}}{{printf "%d" $x}}{{end}}`, "17", tVal, true},
    427 	{"printf lots", `{{printf "%d %s %g %s" 127 "hello" 7-3i .Method0}}`, "127 hello (7-3i) M0", tVal, true},
    428 
    429 	// HTML.
    430 	{"html", `{{html "<script>alert(\"XSS\");</script>"}}`,
    431 		"&lt;script&gt;alert(&#34;XSS&#34;);&lt;/script&gt;", nil, true},
    432 	{"html pipeline", `{{printf "<script>alert(\"XSS\");</script>" | html}}`,
    433 		"&lt;script&gt;alert(&#34;XSS&#34;);&lt;/script&gt;", nil, true},
    434 	{"html", `{{html .PS}}`, "a string", tVal, true},
    435 
    436 	// JavaScript.
    437 	{"js", `{{js .}}`, `It\'d be nice.`, `It'd be nice.`, true},
    438 
    439 	// URL query.
    440 	{"urlquery", `{{"http://www.example.org/"|urlquery}}`, "http%3A%2F%2Fwww.example.org%2F", nil, true},
    441 
    442 	// Booleans
    443 	{"not", "{{not true}} {{not false}}", "false true", nil, true},
    444 	{"and", "{{and false 0}} {{and 1 0}} {{and 0 true}} {{and 1 1}}", "false 0 0 1", nil, true},
    445 	{"or", "{{or 0 0}} {{or 1 0}} {{or 0 true}} {{or 1 1}}", "0 1 true 1", nil, true},
    446 	{"boolean if", "{{if and true 1 `hi`}}TRUE{{else}}FALSE{{end}}", "TRUE", tVal, true},
    447 	{"boolean if not", "{{if and true 1 `hi` | not}}TRUE{{else}}FALSE{{end}}", "FALSE", nil, true},
    448 
    449 	// Indexing.
    450 	{"slice[0]", "{{index .SI 0}}", "3", tVal, true},
    451 	{"slice[1]", "{{index .SI 1}}", "4", tVal, true},
    452 	{"slice[HUGE]", "{{index .SI 10}}", "", tVal, false},
    453 	{"slice[WRONG]", "{{index .SI `hello`}}", "", tVal, false},
    454 	{"slice[nil]", "{{index .SI nil}}", "", tVal, false},
    455 	{"map[one]", "{{index .MSI `one`}}", "1", tVal, true},
    456 	{"map[two]", "{{index .MSI `two`}}", "2", tVal, true},
    457 	{"map[NO]", "{{index .MSI `XXX`}}", "0", tVal, true},
    458 	{"map[nil]", "{{index .MSI nil}}", "", tVal, false},
    459 	{"map[``]", "{{index .MSI ``}}", "0", tVal, true},
    460 	{"map[WRONG]", "{{index .MSI 10}}", "", tVal, false},
    461 	{"double index", "{{index .SMSI 1 `eleven`}}", "11", tVal, true},
    462 	{"nil[1]", "{{index nil 1}}", "", tVal, false},
    463 	{"map MI64S", "{{index .MI64S 2}}", "i642", tVal, true},
    464 	{"map MI32S", "{{index .MI32S 2}}", "two", tVal, true},
    465 	{"map MUI64S", "{{index .MUI64S 3}}", "ui643", tVal, true},
    466 	{"map MI8S", "{{index .MI8S 3}}", "i83", tVal, true},
    467 	{"map MUI8S", "{{index .MUI8S 2}}", "u82", tVal, true},
    468 
    469 	// Len.
    470 	{"slice", "{{len .SI}}", "3", tVal, true},
    471 	{"map", "{{len .MSI }}", "3", tVal, true},
    472 	{"len of int", "{{len 3}}", "", tVal, false},
    473 	{"len of nothing", "{{len .Empty0}}", "", tVal, false},
    474 
    475 	// With.
    476 	{"with true", "{{with true}}{{.}}{{end}}", "true", tVal, true},
    477 	{"with false", "{{with false}}{{.}}{{else}}FALSE{{end}}", "FALSE", tVal, true},
    478 	{"with 1", "{{with 1}}{{.}}{{else}}ZERO{{end}}", "1", tVal, true},
    479 	{"with 0", "{{with 0}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
    480 	{"with 1.5", "{{with 1.5}}{{.}}{{else}}ZERO{{end}}", "1.5", tVal, true},
    481 	{"with 0.0", "{{with .FloatZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
    482 	{"with 1.5i", "{{with 1.5i}}{{.}}{{else}}ZERO{{end}}", "(0+1.5i)", tVal, true},
    483 	{"with 0.0i", "{{with .ComplexZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
    484 	{"with emptystring", "{{with ``}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
    485 	{"with string", "{{with `notempty`}}{{.}}{{else}}EMPTY{{end}}", "notempty", tVal, true},
    486 	{"with emptyslice", "{{with .SIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
    487 	{"with slice", "{{with .SI}}{{.}}{{else}}EMPTY{{end}}", "[3 4 5]", tVal, true},
    488 	{"with emptymap", "{{with .MSIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
    489 	{"with map", "{{with .MSIone}}{{.}}{{else}}EMPTY{{end}}", "map[one:1]", tVal, true},
    490 	{"with empty interface, struct field", "{{with .Empty4}}{{.V}}{{end}}", "UinEmpty", tVal, true},
    491 	{"with $x int", "{{with $x := .I}}{{$x}}{{end}}", "17", tVal, true},
    492 	{"with $x struct.U.V", "{{with $x := $}}{{$x.U.V}}{{end}}", "v", tVal, true},
    493 	{"with variable and action", "{{with $x := $}}{{$y := $.U.V}}{{$y}}{{end}}", "v", tVal, true},
    494 
    495 	// Range.
    496 	{"range []int", "{{range .SI}}-{{.}}-{{end}}", "-3--4--5-", tVal, true},
    497 	{"range empty no else", "{{range .SIEmpty}}-{{.}}-{{end}}", "", tVal, true},
    498 	{"range []int else", "{{range .SI}}-{{.}}-{{else}}EMPTY{{end}}", "-3--4--5-", tVal, true},
    499 	{"range empty else", "{{range .SIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
    500 	{"range []bool", "{{range .SB}}-{{.}}-{{end}}", "-true--false-", tVal, true},
    501 	{"range []int method", "{{range .SI | .MAdd .I}}-{{.}}-{{end}}", "-20--21--22-", tVal, true},
    502 	{"range map", "{{range .MSI}}-{{.}}-{{end}}", "-1--3--2-", tVal, true},
    503 	{"range empty map no else", "{{range .MSIEmpty}}-{{.}}-{{end}}", "", tVal, true},
    504 	{"range map else", "{{range .MSI}}-{{.}}-{{else}}EMPTY{{end}}", "-1--3--2-", tVal, true},
    505 	{"range empty map else", "{{range .MSIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
    506 	{"range empty interface", "{{range .Empty3}}-{{.}}-{{else}}EMPTY{{end}}", "-7--8-", tVal, true},
    507 	{"range empty nil", "{{range .Empty0}}-{{.}}-{{end}}", "", tVal, true},
    508 	{"range $x SI", "{{range $x := .SI}}<{{$x}}>{{end}}", "<3><4><5>", tVal, true},
    509 	{"range $x $y SI", "{{range $x, $y := .SI}}<{{$x}}={{$y}}>{{end}}", "<0=3><1=4><2=5>", tVal, true},
    510 	{"range $x MSIone", "{{range $x := .MSIone}}<{{$x}}>{{end}}", "<1>", tVal, true},
    511 	{"range $x $y MSIone", "{{range $x, $y := .MSIone}}<{{$x}}={{$y}}>{{end}}", "<one=1>", tVal, true},
    512 	{"range $x PSI", "{{range $x := .PSI}}<{{$x}}>{{end}}", "<21><22><23>", tVal, true},
    513 	{"declare in range", "{{range $x := .PSI}}<{{$foo:=$x}}{{$x}}>{{end}}", "<21><22><23>", tVal, true},
    514 	{"range count", `{{range $i, $x := count 5}}[{{$i}}]{{$x}}{{end}}`, "[0]a[1]b[2]c[3]d[4]e", tVal, true},
    515 	{"range nil count", `{{range $i, $x := count 0}}{{else}}empty{{end}}`, "empty", tVal, true},
    516 
    517 	// Cute examples.
    518 	{"or as if true", `{{or .SI "slice is empty"}}`, "[3 4 5]", tVal, true},
    519 	{"or as if false", `{{or .SIEmpty "slice is empty"}}`, "slice is empty", tVal, true},
    520 
    521 	// Error handling.
    522 	{"error method, error", "{{.MyError true}}", "", tVal, false},
    523 	{"error method, no error", "{{.MyError false}}", "false", tVal, true},
    524 
    525 	// Fixed bugs.
    526 	// Must separate dot and receiver; otherwise args are evaluated with dot set to variable.
    527 	{"bug0", "{{range .MSIone}}{{if $.Method1 .}}X{{end}}{{end}}", "X", tVal, true},
    528 	// Do not loop endlessly in indirect for non-empty interfaces.
    529 	// The bug appears with *interface only; looped forever.
    530 	{"bug1", "{{.Method0}}", "M0", &iVal, true},
    531 	// Was taking address of interface field, so method set was empty.
    532 	{"bug2", "{{$.NonEmptyInterface.Method0}}", "M0", tVal, true},
    533 	// Struct values were not legal in with - mere oversight.
    534 	{"bug3", "{{with $}}{{.Method0}}{{end}}", "M0", tVal, true},
    535 	// Nil interface values in if.
    536 	{"bug4", "{{if .Empty0}}non-nil{{else}}nil{{end}}", "nil", tVal, true},
    537 	// Stringer.
    538 	{"bug5", "{{.Str}}", "foozle", tVal, true},
    539 	{"bug5a", "{{.Err}}", "erroozle", tVal, true},
    540 	// Args need to be indirected and dereferenced sometimes.
    541 	{"bug6a", "{{vfunc .V0 .V1}}", "vfunc", tVal, true},
    542 	{"bug6b", "{{vfunc .V0 .V0}}", "vfunc", tVal, true},
    543 	{"bug6c", "{{vfunc .V1 .V0}}", "vfunc", tVal, true},
    544 	{"bug6d", "{{vfunc .V1 .V1}}", "vfunc", tVal, true},
    545 	// Legal parse but illegal execution: non-function should have no arguments.
    546 	{"bug7a", "{{3 2}}", "", tVal, false},
    547 	{"bug7b", "{{$x := 1}}{{$x 2}}", "", tVal, false},
    548 	{"bug7c", "{{$x := 1}}{{3 | $x}}", "", tVal, false},
    549 	// Pipelined arg was not being type-checked.
    550 	{"bug8a", "{{3|oneArg}}", "", tVal, false},
    551 	{"bug8b", "{{4|dddArg 3}}", "", tVal, false},
    552 	// A bug was introduced that broke map lookups for lower-case names.
    553 	{"bug9", "{{.cause}}", "neglect", map[string]string{"cause": "neglect"}, true},
    554 	// Field chain starting with function did not work.
    555 	{"bug10", "{{mapOfThree.three}}-{{(mapOfThree).three}}", "3-3", 0, true},
    556 	// Dereferencing nil pointer while evaluating function arguments should not panic. Issue 7333.
    557 	{"bug11", "{{valueString .PS}}", "", T{}, false},
    558 	// 0xef gave constant type float64. Issue 8622.
    559 	{"bug12xe", "{{printf `%T` 0xef}}", "int", T{}, true},
    560 	{"bug12xE", "{{printf `%T` 0xEE}}", "int", T{}, true},
    561 	{"bug12Xe", "{{printf `%T` 0Xef}}", "int", T{}, true},
    562 	{"bug12XE", "{{printf `%T` 0XEE}}", "int", T{}, true},
    563 	// Chained nodes did not work as arguments. Issue 8473.
    564 	{"bug13", "{{print (.Copy).I}}", "17", tVal, true},
    565 	// Didn't protect against nil or literal values in field chains.
    566 	{"bug14a", "{{(nil).True}}", "", tVal, false},
    567 	{"bug14b", "{{$x := nil}}{{$x.anything}}", "", tVal, false},
    568 	{"bug14c", `{{$x := (1.0)}}{{$y := ("hello")}}{{$x.anything}}{{$y.true}}`, "", tVal, false},
    569 	// Didn't call validateType on function results. Issue 10800.
    570 	{"bug15", "{{valueString returnInt}}", "", tVal, false},
    571 	// Variadic function corner cases. Issue 10946.
    572 	{"bug16a", "{{true|printf}}", "", tVal, false},
    573 	{"bug16b", "{{1|printf}}", "", tVal, false},
    574 	{"bug16c", "{{1.1|printf}}", "", tVal, false},
    575 	{"bug16d", "{{'x'|printf}}", "", tVal, false},
    576 	{"bug16e", "{{0i|printf}}", "", tVal, false},
    577 	{"bug16f", "{{true|twoArgs \"xxx\"}}", "", tVal, false},
    578 	{"bug16g", "{{\"aaa\" |twoArgs \"bbb\"}}", "twoArgs=bbbaaa", tVal, true},
    579 	{"bug16h", "{{1|oneArg}}", "", tVal, false},
    580 	{"bug16i", "{{\"aaa\"|oneArg}}", "oneArg=aaa", tVal, true},
    581 	{"bug16j", "{{1+2i|printf \"%v\"}}", "(1+2i)", tVal, true},
    582 	{"bug16k", "{{\"aaa\"|printf }}", "aaa", tVal, true},
    583 	{"bug17a", "{{.NonEmptyInterface.X}}", "x", tVal, true},
    584 	{"bug17b", "-{{.NonEmptyInterface.Method1 1234}}-", "-1234-", tVal, true},
    585 	{"bug17c", "{{len .NonEmptyInterfacePtS}}", "2", tVal, true},
    586 	{"bug17d", "{{index .NonEmptyInterfacePtS 0}}", "a", tVal, true},
    587 	{"bug17e", "{{range .NonEmptyInterfacePtS}}-{{.}}-{{end}}", "-a--b-", tVal, true},
    588 }
    589 
    590 func zeroArgs() string {
    591 	return "zeroArgs"
    592 }
    593 
    594 func oneArg(a string) string {
    595 	return "oneArg=" + a
    596 }
    597 
    598 func twoArgs(a, b string) string {
    599 	return "twoArgs=" + a + b
    600 }
    601 
    602 func dddArg(a int, b ...string) string {
    603 	return fmt.Sprintln(a, b)
    604 }
    605 
    606 // count returns a channel that will deliver n sequential 1-letter strings starting at "a"
    607 func count(n int) chan string {
    608 	if n == 0 {
    609 		return nil
    610 	}
    611 	c := make(chan string)
    612 	go func() {
    613 		for i := 0; i < n; i++ {
    614 			c <- "abcdefghijklmnop"[i : i+1]
    615 		}
    616 		close(c)
    617 	}()
    618 	return c
    619 }
    620 
    621 // vfunc takes a *V and a V
    622 func vfunc(V, *V) string {
    623 	return "vfunc"
    624 }
    625 
    626 // valueString takes a string, not a pointer.
    627 func valueString(v string) string {
    628 	return "value is ignored"
    629 }
    630 
    631 // returnInt returns an int
    632 func returnInt() int {
    633 	return 7
    634 }
    635 
    636 func add(args ...int) int {
    637 	sum := 0
    638 	for _, x := range args {
    639 		sum += x
    640 	}
    641 	return sum
    642 }
    643 
    644 func echo(arg interface{}) interface{} {
    645 	return arg
    646 }
    647 
    648 func makemap(arg ...string) map[string]string {
    649 	if len(arg)%2 != 0 {
    650 		panic("bad makemap")
    651 	}
    652 	m := make(map[string]string)
    653 	for i := 0; i < len(arg); i += 2 {
    654 		m[arg[i]] = arg[i+1]
    655 	}
    656 	return m
    657 }
    658 
    659 func stringer(s fmt.Stringer) string {
    660 	return s.String()
    661 }
    662 
    663 func mapOfThree() interface{} {
    664 	return map[string]int{"three": 3}
    665 }
    666 
    667 func testExecute(execTests []execTest, template *Template, t *testing.T) {
    668 	b := new(bytes.Buffer)
    669 	funcs := FuncMap{
    670 		"add":         add,
    671 		"count":       count,
    672 		"dddArg":      dddArg,
    673 		"echo":        echo,
    674 		"makemap":     makemap,
    675 		"mapOfThree":  mapOfThree,
    676 		"oneArg":      oneArg,
    677 		"returnInt":   returnInt,
    678 		"stringer":    stringer,
    679 		"twoArgs":     twoArgs,
    680 		"typeOf":      typeOf,
    681 		"valueString": valueString,
    682 		"vfunc":       vfunc,
    683 		"zeroArgs":    zeroArgs,
    684 	}
    685 	for _, test := range execTests {
    686 		var tmpl *Template
    687 		var err error
    688 		if template == nil {
    689 			tmpl, err = New(test.name).Funcs(funcs).Parse(test.input)
    690 		} else {
    691 			tmpl, err = template.New(test.name).Funcs(funcs).Parse(test.input)
    692 		}
    693 		if err != nil {
    694 			t.Errorf("%s: parse error: %s", test.name, err)
    695 			continue
    696 		}
    697 		b.Reset()
    698 		err = tmpl.Execute(b, test.data)
    699 		switch {
    700 		case !test.ok && err == nil:
    701 			t.Errorf("%s: expected error; got none", test.name)
    702 			continue
    703 		case test.ok && err != nil:
    704 			t.Errorf("%s: unexpected execute error: %s", test.name, err)
    705 			continue
    706 		case !test.ok && err != nil:
    707 			// expected error, got one
    708 			if *debug {
    709 				fmt.Printf("%s: %s\n\t%s\n", test.name, test.input, err)
    710 			}
    711 		}
    712 		result := b.String()
    713 		if result != test.output {
    714 			t.Errorf("%s: expected\n\t%q\ngot\n\t%q", test.name, test.output, result)
    715 		}
    716 	}
    717 }
    718 
    719 func TestExecute(t *testing.T) {
    720 	testExecute(execTests, nil, t)
    721 }
    722 
    723 var delimPairs = []string{
    724 	"", "", // default
    725 	"{{", "}}", // same as default
    726 	"<<", ">>", // distinct
    727 	"|", "|", // same
    728 	"()", "()", // peculiar
    729 }
    730 
    731 func TestDelims(t *testing.T) {
    732 	const hello = "Hello, world"
    733 	var value = struct{ Str string }{hello}
    734 	for i := 0; i < len(delimPairs); i += 2 {
    735 		text := ".Str"
    736 		left := delimPairs[i+0]
    737 		trueLeft := left
    738 		right := delimPairs[i+1]
    739 		trueRight := right
    740 		if left == "" { // default case
    741 			trueLeft = "{{"
    742 		}
    743 		if right == "" { // default case
    744 			trueRight = "}}"
    745 		}
    746 		text = trueLeft + text + trueRight
    747 		// Now add a comment
    748 		text += trueLeft + "/*comment*/" + trueRight
    749 		// Now add  an action containing a string.
    750 		text += trueLeft + `"` + trueLeft + `"` + trueRight
    751 		// At this point text looks like `{{.Str}}{{/*comment*/}}{{"{{"}}`.
    752 		tmpl, err := New("delims").Delims(left, right).Parse(text)
    753 		if err != nil {
    754 			t.Fatalf("delim %q text %q parse err %s", left, text, err)
    755 		}
    756 		var b = new(bytes.Buffer)
    757 		err = tmpl.Execute(b, value)
    758 		if err != nil {
    759 			t.Fatalf("delim %q exec err %s", left, err)
    760 		}
    761 		if b.String() != hello+trueLeft {
    762 			t.Errorf("expected %q got %q", hello+trueLeft, b.String())
    763 		}
    764 	}
    765 }
    766 
    767 // Check that an error from a method flows back to the top.
    768 func TestExecuteError(t *testing.T) {
    769 	b := new(bytes.Buffer)
    770 	tmpl := New("error")
    771 	_, err := tmpl.Parse("{{.MyError true}}")
    772 	if err != nil {
    773 		t.Fatalf("parse error: %s", err)
    774 	}
    775 	err = tmpl.Execute(b, tVal)
    776 	if err == nil {
    777 		t.Errorf("expected error; got none")
    778 	} else if !strings.Contains(err.Error(), myError.Error()) {
    779 		if *debug {
    780 			fmt.Printf("test execute error: %s\n", err)
    781 		}
    782 		t.Errorf("expected myError; got %s", err)
    783 	}
    784 }
    785 
    786 const execErrorText = `line 1
    787 line 2
    788 line 3
    789 {{template "one" .}}
    790 {{define "one"}}{{template "two" .}}{{end}}
    791 {{define "two"}}{{template "three" .}}{{end}}
    792 {{define "three"}}{{index "hi" $}}{{end}}`
    793 
    794 // Check that an error from a nested template contains all the relevant information.
    795 func TestExecError(t *testing.T) {
    796 	tmpl, err := New("top").Parse(execErrorText)
    797 	if err != nil {
    798 		t.Fatal("parse error:", err)
    799 	}
    800 	var b bytes.Buffer
    801 	err = tmpl.Execute(&b, 5) // 5 is out of range indexing "hi"
    802 	if err == nil {
    803 		t.Fatal("expected error")
    804 	}
    805 	const want = `template: top:7:20: executing "three" at <index "hi" $>: error calling index: index out of range: 5`
    806 	got := err.Error()
    807 	if got != want {
    808 		t.Errorf("expected\n%q\ngot\n%q", want, got)
    809 	}
    810 }
    811 
    812 func TestJSEscaping(t *testing.T) {
    813 	testCases := []struct {
    814 		in, exp string
    815 	}{
    816 		{`a`, `a`},
    817 		{`'foo`, `\'foo`},
    818 		{`Go "jump" \`, `Go \"jump\" \\`},
    819 		{`Yukihiro says ""`, `Yukihiro says \"\"`},
    820 		{"unprintable \uFDFF", `unprintable \uFDFF`},
    821 		{`<html>`, `\x3Chtml\x3E`},
    822 	}
    823 	for _, tc := range testCases {
    824 		s := JSEscapeString(tc.in)
    825 		if s != tc.exp {
    826 			t.Errorf("JS escaping [%s] got [%s] want [%s]", tc.in, s, tc.exp)
    827 		}
    828 	}
    829 }
    830 
    831 // A nice example: walk a binary tree.
    832 
    833 type Tree struct {
    834 	Val         int
    835 	Left, Right *Tree
    836 }
    837 
    838 // Use different delimiters to test Set.Delims.
    839 // Also test the trimming of leading and trailing spaces.
    840 const treeTemplate = `
    841 	(- define "tree" -)
    842 	[
    843 		(- .Val -)
    844 		(- with .Left -)
    845 			(template "tree" . -)
    846 		(- end -)
    847 		(- with .Right -)
    848 			(- template "tree" . -)
    849 		(- end -)
    850 	]
    851 	(- end -)
    852 `
    853 
    854 func TestTree(t *testing.T) {
    855 	var tree = &Tree{
    856 		1,
    857 		&Tree{
    858 			2, &Tree{
    859 				3,
    860 				&Tree{
    861 					4, nil, nil,
    862 				},
    863 				nil,
    864 			},
    865 			&Tree{
    866 				5,
    867 				&Tree{
    868 					6, nil, nil,
    869 				},
    870 				nil,
    871 			},
    872 		},
    873 		&Tree{
    874 			7,
    875 			&Tree{
    876 				8,
    877 				&Tree{
    878 					9, nil, nil,
    879 				},
    880 				nil,
    881 			},
    882 			&Tree{
    883 				10,
    884 				&Tree{
    885 					11, nil, nil,
    886 				},
    887 				nil,
    888 			},
    889 		},
    890 	}
    891 	tmpl, err := New("root").Delims("(", ")").Parse(treeTemplate)
    892 	if err != nil {
    893 		t.Fatal("parse error:", err)
    894 	}
    895 	var b bytes.Buffer
    896 	const expect = "[1[2[3[4]][5[6]]][7[8[9]][10[11]]]]"
    897 	// First by looking up the template.
    898 	err = tmpl.Lookup("tree").Execute(&b, tree)
    899 	if err != nil {
    900 		t.Fatal("exec error:", err)
    901 	}
    902 	result := b.String()
    903 	if result != expect {
    904 		t.Errorf("expected %q got %q", expect, result)
    905 	}
    906 	// Then direct to execution.
    907 	b.Reset()
    908 	err = tmpl.ExecuteTemplate(&b, "tree", tree)
    909 	if err != nil {
    910 		t.Fatal("exec error:", err)
    911 	}
    912 	result = b.String()
    913 	if result != expect {
    914 		t.Errorf("expected %q got %q", expect, result)
    915 	}
    916 }
    917 
    918 func TestExecuteOnNewTemplate(t *testing.T) {
    919 	// This is issue 3872.
    920 	New("Name").Templates()
    921 	// This is issue 11379.
    922 	new(Template).Templates()
    923 	new(Template).Parse("")
    924 	new(Template).New("abc").Parse("")
    925 	new(Template).Execute(nil, nil)                // returns an error (but does not crash)
    926 	new(Template).ExecuteTemplate(nil, "XXX", nil) // returns an error (but does not crash)
    927 }
    928 
    929 const testTemplates = `{{define "one"}}one{{end}}{{define "two"}}two{{end}}`
    930 
    931 func TestMessageForExecuteEmpty(t *testing.T) {
    932 	// Test a truly empty template.
    933 	tmpl := New("empty")
    934 	var b bytes.Buffer
    935 	err := tmpl.Execute(&b, 0)
    936 	if err == nil {
    937 		t.Fatal("expected initial error")
    938 	}
    939 	got := err.Error()
    940 	want := `template: empty: "empty" is an incomplete or empty template`
    941 	if got != want {
    942 		t.Errorf("expected error %s got %s", want, got)
    943 	}
    944 	// Add a non-empty template to check that the error is helpful.
    945 	tests, err := New("").Parse(testTemplates)
    946 	if err != nil {
    947 		t.Fatal(err)
    948 	}
    949 	tmpl.AddParseTree("secondary", tests.Tree)
    950 	err = tmpl.Execute(&b, 0)
    951 	if err == nil {
    952 		t.Fatal("expected second error")
    953 	}
    954 	got = err.Error()
    955 	want = `template: empty: "empty" is an incomplete or empty template`
    956 	if got != want {
    957 		t.Errorf("expected error %s got %s", want, got)
    958 	}
    959 	// Make sure we can execute the secondary.
    960 	err = tmpl.ExecuteTemplate(&b, "secondary", 0)
    961 	if err != nil {
    962 		t.Fatal(err)
    963 	}
    964 }
    965 
    966 func TestFinalForPrintf(t *testing.T) {
    967 	tmpl, err := New("").Parse(`{{"x" | printf}}`)
    968 	if err != nil {
    969 		t.Fatal(err)
    970 	}
    971 	var b bytes.Buffer
    972 	err = tmpl.Execute(&b, 0)
    973 	if err != nil {
    974 		t.Fatal(err)
    975 	}
    976 }
    977 
    978 type cmpTest struct {
    979 	expr  string
    980 	truth string
    981 	ok    bool
    982 }
    983 
    984 var cmpTests = []cmpTest{
    985 	{"eq true true", "true", true},
    986 	{"eq true false", "false", true},
    987 	{"eq 1+2i 1+2i", "true", true},
    988 	{"eq 1+2i 1+3i", "false", true},
    989 	{"eq 1.5 1.5", "true", true},
    990 	{"eq 1.5 2.5", "false", true},
    991 	{"eq 1 1", "true", true},
    992 	{"eq 1 2", "false", true},
    993 	{"eq `xy` `xy`", "true", true},
    994 	{"eq `xy` `xyz`", "false", true},
    995 	{"eq .Uthree .Uthree", "true", true},
    996 	{"eq .Uthree .Ufour", "false", true},
    997 	{"eq 3 4 5 6 3", "true", true},
    998 	{"eq 3 4 5 6 7", "false", true},
    999 	{"ne true true", "false", true},
   1000 	{"ne true false", "true", true},
   1001 	{"ne 1+2i 1+2i", "false", true},
   1002 	{"ne 1+2i 1+3i", "true", true},
   1003 	{"ne 1.5 1.5", "false", true},
   1004 	{"ne 1.5 2.5", "true", true},
   1005 	{"ne 1 1", "false", true},
   1006 	{"ne 1 2", "true", true},
   1007 	{"ne `xy` `xy`", "false", true},
   1008 	{"ne `xy` `xyz`", "true", true},
   1009 	{"ne .Uthree .Uthree", "false", true},
   1010 	{"ne .Uthree .Ufour", "true", true},
   1011 	{"lt 1.5 1.5", "false", true},
   1012 	{"lt 1.5 2.5", "true", true},
   1013 	{"lt 1 1", "false", true},
   1014 	{"lt 1 2", "true", true},
   1015 	{"lt `xy` `xy`", "false", true},
   1016 	{"lt `xy` `xyz`", "true", true},
   1017 	{"lt .Uthree .Uthree", "false", true},
   1018 	{"lt .Uthree .Ufour", "true", true},
   1019 	{"le 1.5 1.5", "true", true},
   1020 	{"le 1.5 2.5", "true", true},
   1021 	{"le 2.5 1.5", "false", true},
   1022 	{"le 1 1", "true", true},
   1023 	{"le 1 2", "true", true},
   1024 	{"le 2 1", "false", true},
   1025 	{"le `xy` `xy`", "true", true},
   1026 	{"le `xy` `xyz`", "true", true},
   1027 	{"le `xyz` `xy`", "false", true},
   1028 	{"le .Uthree .Uthree", "true", true},
   1029 	{"le .Uthree .Ufour", "true", true},
   1030 	{"le .Ufour .Uthree", "false", true},
   1031 	{"gt 1.5 1.5", "false", true},
   1032 	{"gt 1.5 2.5", "false", true},
   1033 	{"gt 1 1", "false", true},
   1034 	{"gt 2 1", "true", true},
   1035 	{"gt 1 2", "false", true},
   1036 	{"gt `xy` `xy`", "false", true},
   1037 	{"gt `xy` `xyz`", "false", true},
   1038 	{"gt .Uthree .Uthree", "false", true},
   1039 	{"gt .Uthree .Ufour", "false", true},
   1040 	{"gt .Ufour .Uthree", "true", true},
   1041 	{"ge 1.5 1.5", "true", true},
   1042 	{"ge 1.5 2.5", "false", true},
   1043 	{"ge 2.5 1.5", "true", true},
   1044 	{"ge 1 1", "true", true},
   1045 	{"ge 1 2", "false", true},
   1046 	{"ge 2 1", "true", true},
   1047 	{"ge `xy` `xy`", "true", true},
   1048 	{"ge `xy` `xyz`", "false", true},
   1049 	{"ge `xyz` `xy`", "true", true},
   1050 	{"ge .Uthree .Uthree", "true", true},
   1051 	{"ge .Uthree .Ufour", "false", true},
   1052 	{"ge .Ufour .Uthree", "true", true},
   1053 	// Mixing signed and unsigned integers.
   1054 	{"eq .Uthree .Three", "true", true},
   1055 	{"eq .Three .Uthree", "true", true},
   1056 	{"le .Uthree .Three", "true", true},
   1057 	{"le .Three .Uthree", "true", true},
   1058 	{"ge .Uthree .Three", "true", true},
   1059 	{"ge .Three .Uthree", "true", true},
   1060 	{"lt .Uthree .Three", "false", true},
   1061 	{"lt .Three .Uthree", "false", true},
   1062 	{"gt .Uthree .Three", "false", true},
   1063 	{"gt .Three .Uthree", "false", true},
   1064 	{"eq .Ufour .Three", "false", true},
   1065 	{"lt .Ufour .Three", "false", true},
   1066 	{"gt .Ufour .Three", "true", true},
   1067 	{"eq .NegOne .Uthree", "false", true},
   1068 	{"eq .Uthree .NegOne", "false", true},
   1069 	{"ne .NegOne .Uthree", "true", true},
   1070 	{"ne .Uthree .NegOne", "true", true},
   1071 	{"lt .NegOne .Uthree", "true", true},
   1072 	{"lt .Uthree .NegOne", "false", true},
   1073 	{"le .NegOne .Uthree", "true", true},
   1074 	{"le .Uthree .NegOne", "false", true},
   1075 	{"gt .NegOne .Uthree", "false", true},
   1076 	{"gt .Uthree .NegOne", "true", true},
   1077 	{"ge .NegOne .Uthree", "false", true},
   1078 	{"ge .Uthree .NegOne", "true", true},
   1079 	{"eq (index `x` 0) 'x'", "true", true}, // The example that triggered this rule.
   1080 	{"eq (index `x` 0) 'y'", "false", true},
   1081 	// Errors
   1082 	{"eq `xy` 1", "", false},    // Different types.
   1083 	{"eq 2 2.0", "", false},     // Different types.
   1084 	{"lt true true", "", false}, // Unordered types.
   1085 	{"lt 1+0i 1+0i", "", false}, // Unordered types.
   1086 }
   1087 
   1088 func TestComparison(t *testing.T) {
   1089 	b := new(bytes.Buffer)
   1090 	var cmpStruct = struct {
   1091 		Uthree, Ufour uint
   1092 		NegOne, Three int
   1093 	}{3, 4, -1, 3}
   1094 	for _, test := range cmpTests {
   1095 		text := fmt.Sprintf("{{if %s}}true{{else}}false{{end}}", test.expr)
   1096 		tmpl, err := New("empty").Parse(text)
   1097 		if err != nil {
   1098 			t.Fatalf("%q: %s", test.expr, err)
   1099 		}
   1100 		b.Reset()
   1101 		err = tmpl.Execute(b, &cmpStruct)
   1102 		if test.ok && err != nil {
   1103 			t.Errorf("%s errored incorrectly: %s", test.expr, err)
   1104 			continue
   1105 		}
   1106 		if !test.ok && err == nil {
   1107 			t.Errorf("%s did not error", test.expr)
   1108 			continue
   1109 		}
   1110 		if b.String() != test.truth {
   1111 			t.Errorf("%s: want %s; got %s", test.expr, test.truth, b.String())
   1112 		}
   1113 	}
   1114 }
   1115 
   1116 func TestMissingMapKey(t *testing.T) {
   1117 	data := map[string]int{
   1118 		"x": 99,
   1119 	}
   1120 	tmpl, err := New("t1").Parse("{{.x}} {{.y}}")
   1121 	if err != nil {
   1122 		t.Fatal(err)
   1123 	}
   1124 	var b bytes.Buffer
   1125 	// By default, just get "<no value>"
   1126 	err = tmpl.Execute(&b, data)
   1127 	if err != nil {
   1128 		t.Fatal(err)
   1129 	}
   1130 	want := "99 <no value>"
   1131 	got := b.String()
   1132 	if got != want {
   1133 		t.Errorf("got %q; expected %q", got, want)
   1134 	}
   1135 	// Same if we set the option explicitly to the default.
   1136 	tmpl.Option("missingkey=default")
   1137 	b.Reset()
   1138 	err = tmpl.Execute(&b, data)
   1139 	if err != nil {
   1140 		t.Fatal("default:", err)
   1141 	}
   1142 	want = "99 <no value>"
   1143 	got = b.String()
   1144 	if got != want {
   1145 		t.Errorf("got %q; expected %q", got, want)
   1146 	}
   1147 	// Next we ask for a zero value
   1148 	tmpl.Option("missingkey=zero")
   1149 	b.Reset()
   1150 	err = tmpl.Execute(&b, data)
   1151 	if err != nil {
   1152 		t.Fatal("zero:", err)
   1153 	}
   1154 	want = "99 0"
   1155 	got = b.String()
   1156 	if got != want {
   1157 		t.Errorf("got %q; expected %q", got, want)
   1158 	}
   1159 	// Now we ask for an error.
   1160 	tmpl.Option("missingkey=error")
   1161 	err = tmpl.Execute(&b, data)
   1162 	if err == nil {
   1163 		t.Errorf("expected error; got none")
   1164 	}
   1165 	// same Option, but now a nil interface: ask for an error
   1166 	err = tmpl.Execute(&b, nil)
   1167 	t.Log(err)
   1168 	if err == nil {
   1169 		t.Errorf("expected error for nil-interface; got none")
   1170 	}
   1171 }
   1172 
   1173 // Test that the error message for multiline unterminated string
   1174 // refers to the line number of the opening quote.
   1175 func TestUnterminatedStringError(t *testing.T) {
   1176 	_, err := New("X").Parse("hello\n\n{{`unterminated\n\n\n\n}}\n some more\n\n")
   1177 	if err == nil {
   1178 		t.Fatal("expected error")
   1179 	}
   1180 	str := err.Error()
   1181 	if !strings.Contains(str, "X:3: unexpected unterminated raw quoted string") {
   1182 		t.Fatalf("unexpected error: %s", str)
   1183 	}
   1184 }
   1185 
   1186 const alwaysErrorText = "always be failing"
   1187 
   1188 var alwaysError = errors.New(alwaysErrorText)
   1189 
   1190 type ErrorWriter int
   1191 
   1192 func (e ErrorWriter) Write(p []byte) (int, error) {
   1193 	return 0, alwaysError
   1194 }
   1195 
   1196 func TestExecuteGivesExecError(t *testing.T) {
   1197 	// First, a non-execution error shouldn't be an ExecError.
   1198 	tmpl, err := New("X").Parse("hello")
   1199 	if err != nil {
   1200 		t.Fatal(err)
   1201 	}
   1202 	err = tmpl.Execute(ErrorWriter(0), 0)
   1203 	if err == nil {
   1204 		t.Fatal("expected error; got none")
   1205 	}
   1206 	if err.Error() != alwaysErrorText {
   1207 		t.Errorf("expected %q error; got %q", alwaysErrorText, err)
   1208 	}
   1209 	// This one should be an ExecError.
   1210 	tmpl, err = New("X").Parse("hello, {{.X.Y}}")
   1211 	if err != nil {
   1212 		t.Fatal(err)
   1213 	}
   1214 	err = tmpl.Execute(ioutil.Discard, 0)
   1215 	if err == nil {
   1216 		t.Fatal("expected error; got none")
   1217 	}
   1218 	eerr, ok := err.(ExecError)
   1219 	if !ok {
   1220 		t.Fatalf("did not expect ExecError %s", eerr)
   1221 	}
   1222 	expect := "field X in type int"
   1223 	if !strings.Contains(err.Error(), expect) {
   1224 		t.Errorf("expected %q; got %q", expect, err)
   1225 	}
   1226 }
   1227 
   1228 func funcNameTestFunc() int {
   1229 	return 0
   1230 }
   1231 
   1232 func TestGoodFuncNames(t *testing.T) {
   1233 	names := []string{
   1234 		"_",
   1235 		"a",
   1236 		"a1",
   1237 		"a1",
   1238 		"",
   1239 	}
   1240 	for _, name := range names {
   1241 		tmpl := New("X").Funcs(
   1242 			FuncMap{
   1243 				name: funcNameTestFunc,
   1244 			},
   1245 		)
   1246 		if tmpl == nil {
   1247 			t.Fatalf("nil result for %q", name)
   1248 		}
   1249 	}
   1250 }
   1251 
   1252 func TestBadFuncNames(t *testing.T) {
   1253 	names := []string{
   1254 		"",
   1255 		"2",
   1256 		"a-b",
   1257 	}
   1258 	for _, name := range names {
   1259 		testBadFuncName(name, t)
   1260 	}
   1261 }
   1262 
   1263 func testBadFuncName(name string, t *testing.T) {
   1264 	defer func() {
   1265 		recover()
   1266 	}()
   1267 	New("X").Funcs(
   1268 		FuncMap{
   1269 			name: funcNameTestFunc,
   1270 		},
   1271 	)
   1272 	// If we get here, the name did not cause a panic, which is how Funcs
   1273 	// reports an error.
   1274 	t.Errorf("%q succeeded incorrectly as function name", name)
   1275 }
   1276 
   1277 func TestBlock(t *testing.T) {
   1278 	const (
   1279 		input   = `a({{block "inner" .}}bar({{.}})baz{{end}})b`
   1280 		want    = `a(bar(hello)baz)b`
   1281 		overlay = `{{define "inner"}}foo({{.}})bar{{end}}`
   1282 		want2   = `a(foo(goodbye)bar)b`
   1283 	)
   1284 	tmpl, err := New("outer").Parse(input)
   1285 	if err != nil {
   1286 		t.Fatal(err)
   1287 	}
   1288 	tmpl2, err := Must(tmpl.Clone()).Parse(overlay)
   1289 	if err != nil {
   1290 		t.Fatal(err)
   1291 	}
   1292 
   1293 	var buf bytes.Buffer
   1294 	if err := tmpl.Execute(&buf, "hello"); err != nil {
   1295 		t.Fatal(err)
   1296 	}
   1297 	if got := buf.String(); got != want {
   1298 		t.Errorf("got %q, want %q", got, want)
   1299 	}
   1300 
   1301 	buf.Reset()
   1302 	if err := tmpl2.Execute(&buf, "goodbye"); err != nil {
   1303 		t.Fatal(err)
   1304 	}
   1305 	if got := buf.String(); got != want2 {
   1306 		t.Errorf("got %q, want %q", got, want2)
   1307 	}
   1308 }
   1309 
   1310 // Check that calling an invalid field on nil pointer prints
   1311 // a field error instead of a distracting nil pointer error.
   1312 // https://golang.org/issue/15125
   1313 func TestMissingFieldOnNil(t *testing.T) {
   1314 	tmpl := Must(New("tmpl").Parse("{{.MissingField}}"))
   1315 	var d *T
   1316 	err := tmpl.Execute(ioutil.Discard, d)
   1317 	got := "<nil>"
   1318 	if err != nil {
   1319 		got = err.Error()
   1320 	}
   1321 	want := "can't evaluate field MissingField in type *template.T"
   1322 	if !strings.HasSuffix(got, want) {
   1323 		t.Errorf("got error %q, want %q", got, want)
   1324 	}
   1325 }
   1326 
   1327 func TestMaxExecDepth(t *testing.T) {
   1328 	tmpl := Must(New("tmpl").Parse(`{{template "tmpl" .}}`))
   1329 	err := tmpl.Execute(ioutil.Discard, nil)
   1330 	got := "<nil>"
   1331 	if err != nil {
   1332 		got = err.Error()
   1333 	}
   1334 	const want = "exceeded maximum template depth"
   1335 	if !strings.Contains(got, want) {
   1336 		t.Errorf("got error %q; want %q", got, want)
   1337 	}
   1338 }
   1339 
   1340 func TestAddrOfIndex(t *testing.T) {
   1341 	// golang.org/issue/14916.
   1342 	// Before index worked on reflect.Values, the .String could not be
   1343 	// found on the (incorrectly unaddressable) V value,
   1344 	// in contrast to range, which worked fine.
   1345 	// Also testing that passing a reflect.Value to tmpl.Execute works.
   1346 	texts := []string{
   1347 		`{{range .}}{{.String}}{{end}}`,
   1348 		`{{with index . 0}}{{.String}}{{end}}`,
   1349 	}
   1350 	for _, text := range texts {
   1351 		tmpl := Must(New("tmpl").Parse(text))
   1352 		var buf bytes.Buffer
   1353 		err := tmpl.Execute(&buf, reflect.ValueOf([]V{{1}}))
   1354 		if err != nil {
   1355 			t.Fatalf("%s: Execute: %v", text, err)
   1356 		}
   1357 		if buf.String() != "<1>" {
   1358 			t.Fatalf("%s: template output = %q, want %q", text, &buf, "<1>")
   1359 		}
   1360 	}
   1361 }
   1362 
   1363 func TestInterfaceValues(t *testing.T) {
   1364 	// golang.org/issue/17714.
   1365 	// Before index worked on reflect.Values, interface values
   1366 	// were always implicitly promoted to the underlying value,
   1367 	// except that nil interfaces were promoted to the zero reflect.Value.
   1368 	// Eliminating a round trip to interface{} and back to reflect.Value
   1369 	// eliminated this promotion, breaking these cases.
   1370 	tests := []struct {
   1371 		text string
   1372 		out  string
   1373 	}{
   1374 		{`{{index .Nil 1}}`, "ERROR: index of untyped nil"},
   1375 		{`{{index .Slice 2}}`, "2"},
   1376 		{`{{index .Slice .Two}}`, "2"},
   1377 		{`{{call .Nil 1}}`, "ERROR: call of nil"},
   1378 		{`{{call .PlusOne 1}}`, "2"},
   1379 		{`{{call .PlusOne .One}}`, "2"},
   1380 		{`{{and (index .Slice 0) true}}`, "0"},
   1381 		{`{{and .Zero true}}`, "0"},
   1382 		{`{{and (index .Slice 1) false}}`, "false"},
   1383 		{`{{and .One false}}`, "false"},
   1384 		{`{{or (index .Slice 0) false}}`, "false"},
   1385 		{`{{or .Zero false}}`, "false"},
   1386 		{`{{or (index .Slice 1) true}}`, "1"},
   1387 		{`{{or .One true}}`, "1"},
   1388 		{`{{not (index .Slice 0)}}`, "true"},
   1389 		{`{{not .Zero}}`, "true"},
   1390 		{`{{not (index .Slice 1)}}`, "false"},
   1391 		{`{{not .One}}`, "false"},
   1392 		{`{{eq (index .Slice 0) .Zero}}`, "true"},
   1393 		{`{{eq (index .Slice 1) .One}}`, "true"},
   1394 		{`{{ne (index .Slice 0) .Zero}}`, "false"},
   1395 		{`{{ne (index .Slice 1) .One}}`, "false"},
   1396 		{`{{ge (index .Slice 0) .One}}`, "false"},
   1397 		{`{{ge (index .Slice 1) .Zero}}`, "true"},
   1398 		{`{{gt (index .Slice 0) .One}}`, "false"},
   1399 		{`{{gt (index .Slice 1) .Zero}}`, "true"},
   1400 		{`{{le (index .Slice 0) .One}}`, "true"},
   1401 		{`{{le (index .Slice 1) .Zero}}`, "false"},
   1402 		{`{{lt (index .Slice 0) .One}}`, "true"},
   1403 		{`{{lt (index .Slice 1) .Zero}}`, "false"},
   1404 	}
   1405 
   1406 	for _, tt := range tests {
   1407 		tmpl := Must(New("tmpl").Parse(tt.text))
   1408 		var buf bytes.Buffer
   1409 		err := tmpl.Execute(&buf, map[string]interface{}{
   1410 			"PlusOne": func(n int) int {
   1411 				return n + 1
   1412 			},
   1413 			"Slice": []int{0, 1, 2, 3},
   1414 			"One":   1,
   1415 			"Two":   2,
   1416 			"Nil":   nil,
   1417 			"Zero":  0,
   1418 		})
   1419 		if strings.HasPrefix(tt.out, "ERROR:") {
   1420 			e := strings.TrimSpace(strings.TrimPrefix(tt.out, "ERROR:"))
   1421 			if err == nil || !strings.Contains(err.Error(), e) {
   1422 				t.Errorf("%s: Execute: %v, want error %q", tt.text, err, e)
   1423 			}
   1424 			continue
   1425 		}
   1426 		if err != nil {
   1427 			t.Errorf("%s: Execute: %v", tt.text, err)
   1428 			continue
   1429 		}
   1430 		if buf.String() != tt.out {
   1431 			t.Errorf("%s: template output = %q, want %q", tt.text, &buf, tt.out)
   1432 		}
   1433 	}
   1434 }
   1435