github.com/kdevb0x/go@v0.0.0-20180115030120-39687051e9e7/src/text/template/exec_test.go (about)

     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  	{"range quick break", `{{range .SI}}{{break}}{{.}}{{end}}`, "", tVal, true},
   517  	{"range break after two", `{{range $i, $x := .SI}}{{if ge $i 2}}{{break}}{{end}}{{.}}{{end}}`, "34", tVal, true},
   518  	{"range continue", `{{range .SI}}{{continue}}{{.}}{{end}}`, "", tVal, true},
   519  	{"range continue condition", `{{range .SI}}{{if eq . 3 }}{{continue}}{{end}}{{.}}{{end}}`, "45", tVal, true},
   520  
   521  	// Cute examples.
   522  	{"or as if true", `{{or .SI "slice is empty"}}`, "[3 4 5]", tVal, true},
   523  	{"or as if false", `{{or .SIEmpty "slice is empty"}}`, "slice is empty", tVal, true},
   524  
   525  	// Error handling.
   526  	{"error method, error", "{{.MyError true}}", "", tVal, false},
   527  	{"error method, no error", "{{.MyError false}}", "false", tVal, true},
   528  
   529  	// Fixed bugs.
   530  	// Must separate dot and receiver; otherwise args are evaluated with dot set to variable.
   531  	{"bug0", "{{range .MSIone}}{{if $.Method1 .}}X{{end}}{{end}}", "X", tVal, true},
   532  	// Do not loop endlessly in indirect for non-empty interfaces.
   533  	// The bug appears with *interface only; looped forever.
   534  	{"bug1", "{{.Method0}}", "M0", &iVal, true},
   535  	// Was taking address of interface field, so method set was empty.
   536  	{"bug2", "{{$.NonEmptyInterface.Method0}}", "M0", tVal, true},
   537  	// Struct values were not legal in with - mere oversight.
   538  	{"bug3", "{{with $}}{{.Method0}}{{end}}", "M0", tVal, true},
   539  	// Nil interface values in if.
   540  	{"bug4", "{{if .Empty0}}non-nil{{else}}nil{{end}}", "nil", tVal, true},
   541  	// Stringer.
   542  	{"bug5", "{{.Str}}", "foozle", tVal, true},
   543  	{"bug5a", "{{.Err}}", "erroozle", tVal, true},
   544  	// Args need to be indirected and dereferenced sometimes.
   545  	{"bug6a", "{{vfunc .V0 .V1}}", "vfunc", tVal, true},
   546  	{"bug6b", "{{vfunc .V0 .V0}}", "vfunc", tVal, true},
   547  	{"bug6c", "{{vfunc .V1 .V0}}", "vfunc", tVal, true},
   548  	{"bug6d", "{{vfunc .V1 .V1}}", "vfunc", tVal, true},
   549  	// Legal parse but illegal execution: non-function should have no arguments.
   550  	{"bug7a", "{{3 2}}", "", tVal, false},
   551  	{"bug7b", "{{$x := 1}}{{$x 2}}", "", tVal, false},
   552  	{"bug7c", "{{$x := 1}}{{3 | $x}}", "", tVal, false},
   553  	// Pipelined arg was not being type-checked.
   554  	{"bug8a", "{{3|oneArg}}", "", tVal, false},
   555  	{"bug8b", "{{4|dddArg 3}}", "", tVal, false},
   556  	// A bug was introduced that broke map lookups for lower-case names.
   557  	{"bug9", "{{.cause}}", "neglect", map[string]string{"cause": "neglect"}, true},
   558  	// Field chain starting with function did not work.
   559  	{"bug10", "{{mapOfThree.three}}-{{(mapOfThree).three}}", "3-3", 0, true},
   560  	// Dereferencing nil pointer while evaluating function arguments should not panic. Issue 7333.
   561  	{"bug11", "{{valueString .PS}}", "", T{}, false},
   562  	// 0xef gave constant type float64. Issue 8622.
   563  	{"bug12xe", "{{printf `%T` 0xef}}", "int", T{}, true},
   564  	{"bug12xE", "{{printf `%T` 0xEE}}", "int", T{}, true},
   565  	{"bug12Xe", "{{printf `%T` 0Xef}}", "int", T{}, true},
   566  	{"bug12XE", "{{printf `%T` 0XEE}}", "int", T{}, true},
   567  	// Chained nodes did not work as arguments. Issue 8473.
   568  	{"bug13", "{{print (.Copy).I}}", "17", tVal, true},
   569  	// Didn't protect against nil or literal values in field chains.
   570  	{"bug14a", "{{(nil).True}}", "", tVal, false},
   571  	{"bug14b", "{{$x := nil}}{{$x.anything}}", "", tVal, false},
   572  	{"bug14c", `{{$x := (1.0)}}{{$y := ("hello")}}{{$x.anything}}{{$y.true}}`, "", tVal, false},
   573  	// Didn't call validateType on function results. Issue 10800.
   574  	{"bug15", "{{valueString returnInt}}", "", tVal, false},
   575  	// Variadic function corner cases. Issue 10946.
   576  	{"bug16a", "{{true|printf}}", "", tVal, false},
   577  	{"bug16b", "{{1|printf}}", "", tVal, false},
   578  	{"bug16c", "{{1.1|printf}}", "", tVal, false},
   579  	{"bug16d", "{{'x'|printf}}", "", tVal, false},
   580  	{"bug16e", "{{0i|printf}}", "", tVal, false},
   581  	{"bug16f", "{{true|twoArgs \"xxx\"}}", "", tVal, false},
   582  	{"bug16g", "{{\"aaa\" |twoArgs \"bbb\"}}", "twoArgs=bbbaaa", tVal, true},
   583  	{"bug16h", "{{1|oneArg}}", "", tVal, false},
   584  	{"bug16i", "{{\"aaa\"|oneArg}}", "oneArg=aaa", tVal, true},
   585  	{"bug16j", "{{1+2i|printf \"%v\"}}", "(1+2i)", tVal, true},
   586  	{"bug16k", "{{\"aaa\"|printf }}", "aaa", tVal, true},
   587  	{"bug17a", "{{.NonEmptyInterface.X}}", "x", tVal, true},
   588  	{"bug17b", "-{{.NonEmptyInterface.Method1 1234}}-", "-1234-", tVal, true},
   589  	{"bug17c", "{{len .NonEmptyInterfacePtS}}", "2", tVal, true},
   590  	{"bug17d", "{{index .NonEmptyInterfacePtS 0}}", "a", tVal, true},
   591  	{"bug17e", "{{range .NonEmptyInterfacePtS}}-{{.}}-{{end}}", "-a--b-", tVal, true},
   592  }
   593  
   594  func zeroArgs() string {
   595  	return "zeroArgs"
   596  }
   597  
   598  func oneArg(a string) string {
   599  	return "oneArg=" + a
   600  }
   601  
   602  func twoArgs(a, b string) string {
   603  	return "twoArgs=" + a + b
   604  }
   605  
   606  func dddArg(a int, b ...string) string {
   607  	return fmt.Sprintln(a, b)
   608  }
   609  
   610  // count returns a channel that will deliver n sequential 1-letter strings starting at "a"
   611  func count(n int) chan string {
   612  	if n == 0 {
   613  		return nil
   614  	}
   615  	c := make(chan string)
   616  	go func() {
   617  		for i := 0; i < n; i++ {
   618  			c <- "abcdefghijklmnop"[i : i+1]
   619  		}
   620  		close(c)
   621  	}()
   622  	return c
   623  }
   624  
   625  // vfunc takes a *V and a V
   626  func vfunc(V, *V) string {
   627  	return "vfunc"
   628  }
   629  
   630  // valueString takes a string, not a pointer.
   631  func valueString(v string) string {
   632  	return "value is ignored"
   633  }
   634  
   635  // returnInt returns an int
   636  func returnInt() int {
   637  	return 7
   638  }
   639  
   640  func add(args ...int) int {
   641  	sum := 0
   642  	for _, x := range args {
   643  		sum += x
   644  	}
   645  	return sum
   646  }
   647  
   648  func echo(arg interface{}) interface{} {
   649  	return arg
   650  }
   651  
   652  func makemap(arg ...string) map[string]string {
   653  	if len(arg)%2 != 0 {
   654  		panic("bad makemap")
   655  	}
   656  	m := make(map[string]string)
   657  	for i := 0; i < len(arg); i += 2 {
   658  		m[arg[i]] = arg[i+1]
   659  	}
   660  	return m
   661  }
   662  
   663  func stringer(s fmt.Stringer) string {
   664  	return s.String()
   665  }
   666  
   667  func mapOfThree() interface{} {
   668  	return map[string]int{"three": 3}
   669  }
   670  
   671  func testExecute(execTests []execTest, template *Template, t *testing.T) {
   672  	b := new(bytes.Buffer)
   673  	funcs := FuncMap{
   674  		"add":         add,
   675  		"count":       count,
   676  		"dddArg":      dddArg,
   677  		"echo":        echo,
   678  		"makemap":     makemap,
   679  		"mapOfThree":  mapOfThree,
   680  		"oneArg":      oneArg,
   681  		"returnInt":   returnInt,
   682  		"stringer":    stringer,
   683  		"twoArgs":     twoArgs,
   684  		"typeOf":      typeOf,
   685  		"valueString": valueString,
   686  		"vfunc":       vfunc,
   687  		"zeroArgs":    zeroArgs,
   688  	}
   689  	for _, test := range execTests {
   690  		var tmpl *Template
   691  		var err error
   692  		if template == nil {
   693  			tmpl, err = New(test.name).Funcs(funcs).Parse(test.input)
   694  		} else {
   695  			tmpl, err = template.New(test.name).Funcs(funcs).Parse(test.input)
   696  		}
   697  		if err != nil {
   698  			t.Errorf("%s: parse error: %s", test.name, err)
   699  			continue
   700  		}
   701  		b.Reset()
   702  		err = tmpl.Execute(b, test.data)
   703  		switch {
   704  		case !test.ok && err == nil:
   705  			t.Errorf("%s: expected error; got none", test.name)
   706  			continue
   707  		case test.ok && err != nil:
   708  			t.Errorf("%s: unexpected execute error: %s", test.name, err)
   709  			continue
   710  		case !test.ok && err != nil:
   711  			// expected error, got one
   712  			if *debug {
   713  				fmt.Printf("%s: %s\n\t%s\n", test.name, test.input, err)
   714  			}
   715  		}
   716  		result := b.String()
   717  		if result != test.output {
   718  			t.Errorf("%s: expected\n\t%q\ngot\n\t%q", test.name, test.output, result)
   719  		}
   720  	}
   721  }
   722  
   723  func TestExecute(t *testing.T) {
   724  	testExecute(execTests, nil, t)
   725  }
   726  
   727  var delimPairs = []string{
   728  	"", "", // default
   729  	"{{", "}}", // same as default
   730  	"<<", ">>", // distinct
   731  	"|", "|", // same
   732  	"(日)", "(本)", // peculiar
   733  }
   734  
   735  func TestDelims(t *testing.T) {
   736  	const hello = "Hello, world"
   737  	var value = struct{ Str string }{hello}
   738  	for i := 0; i < len(delimPairs); i += 2 {
   739  		text := ".Str"
   740  		left := delimPairs[i+0]
   741  		trueLeft := left
   742  		right := delimPairs[i+1]
   743  		trueRight := right
   744  		if left == "" { // default case
   745  			trueLeft = "{{"
   746  		}
   747  		if right == "" { // default case
   748  			trueRight = "}}"
   749  		}
   750  		text = trueLeft + text + trueRight
   751  		// Now add a comment
   752  		text += trueLeft + "/*comment*/" + trueRight
   753  		// Now add  an action containing a string.
   754  		text += trueLeft + `"` + trueLeft + `"` + trueRight
   755  		// At this point text looks like `{{.Str}}{{/*comment*/}}{{"{{"}}`.
   756  		tmpl, err := New("delims").Delims(left, right).Parse(text)
   757  		if err != nil {
   758  			t.Fatalf("delim %q text %q parse err %s", left, text, err)
   759  		}
   760  		var b = new(bytes.Buffer)
   761  		err = tmpl.Execute(b, value)
   762  		if err != nil {
   763  			t.Fatalf("delim %q exec err %s", left, err)
   764  		}
   765  		if b.String() != hello+trueLeft {
   766  			t.Errorf("expected %q got %q", hello+trueLeft, b.String())
   767  		}
   768  	}
   769  }
   770  
   771  // Check that an error from a method flows back to the top.
   772  func TestExecuteError(t *testing.T) {
   773  	b := new(bytes.Buffer)
   774  	tmpl := New("error")
   775  	_, err := tmpl.Parse("{{.MyError true}}")
   776  	if err != nil {
   777  		t.Fatalf("parse error: %s", err)
   778  	}
   779  	err = tmpl.Execute(b, tVal)
   780  	if err == nil {
   781  		t.Errorf("expected error; got none")
   782  	} else if !strings.Contains(err.Error(), myError.Error()) {
   783  		if *debug {
   784  			fmt.Printf("test execute error: %s\n", err)
   785  		}
   786  		t.Errorf("expected myError; got %s", err)
   787  	}
   788  }
   789  
   790  const execErrorText = `line 1
   791  line 2
   792  line 3
   793  {{template "one" .}}
   794  {{define "one"}}{{template "two" .}}{{end}}
   795  {{define "two"}}{{template "three" .}}{{end}}
   796  {{define "three"}}{{index "hi" $}}{{end}}`
   797  
   798  // Check that an error from a nested template contains all the relevant information.
   799  func TestExecError(t *testing.T) {
   800  	tmpl, err := New("top").Parse(execErrorText)
   801  	if err != nil {
   802  		t.Fatal("parse error:", err)
   803  	}
   804  	var b bytes.Buffer
   805  	err = tmpl.Execute(&b, 5) // 5 is out of range indexing "hi"
   806  	if err == nil {
   807  		t.Fatal("expected error")
   808  	}
   809  	const want = `template: top:7:20: executing "three" at <index "hi" $>: error calling index: index out of range: 5`
   810  	got := err.Error()
   811  	if got != want {
   812  		t.Errorf("expected\n%q\ngot\n%q", want, got)
   813  	}
   814  }
   815  
   816  func TestJSEscaping(t *testing.T) {
   817  	testCases := []struct {
   818  		in, exp string
   819  	}{
   820  		{`a`, `a`},
   821  		{`'foo`, `\'foo`},
   822  		{`Go "jump" \`, `Go \"jump\" \\`},
   823  		{`Yukihiro says "今日は世界"`, `Yukihiro says \"今日は世界\"`},
   824  		{"unprintable \uFDFF", `unprintable \uFDFF`},
   825  		{`<html>`, `\x3Chtml\x3E`},
   826  	}
   827  	for _, tc := range testCases {
   828  		s := JSEscapeString(tc.in)
   829  		if s != tc.exp {
   830  			t.Errorf("JS escaping [%s] got [%s] want [%s]", tc.in, s, tc.exp)
   831  		}
   832  	}
   833  }
   834  
   835  // A nice example: walk a binary tree.
   836  
   837  type Tree struct {
   838  	Val         int
   839  	Left, Right *Tree
   840  }
   841  
   842  // Use different delimiters to test Set.Delims.
   843  // Also test the trimming of leading and trailing spaces.
   844  const treeTemplate = `
   845  	(- define "tree" -)
   846  	[
   847  		(- .Val -)
   848  		(- with .Left -)
   849  			(template "tree" . -)
   850  		(- end -)
   851  		(- with .Right -)
   852  			(- template "tree" . -)
   853  		(- end -)
   854  	]
   855  	(- end -)
   856  `
   857  
   858  func TestTree(t *testing.T) {
   859  	var tree = &Tree{
   860  		1,
   861  		&Tree{
   862  			2, &Tree{
   863  				3,
   864  				&Tree{
   865  					4, nil, nil,
   866  				},
   867  				nil,
   868  			},
   869  			&Tree{
   870  				5,
   871  				&Tree{
   872  					6, nil, nil,
   873  				},
   874  				nil,
   875  			},
   876  		},
   877  		&Tree{
   878  			7,
   879  			&Tree{
   880  				8,
   881  				&Tree{
   882  					9, nil, nil,
   883  				},
   884  				nil,
   885  			},
   886  			&Tree{
   887  				10,
   888  				&Tree{
   889  					11, nil, nil,
   890  				},
   891  				nil,
   892  			},
   893  		},
   894  	}
   895  	tmpl, err := New("root").Delims("(", ")").Parse(treeTemplate)
   896  	if err != nil {
   897  		t.Fatal("parse error:", err)
   898  	}
   899  	var b bytes.Buffer
   900  	const expect = "[1[2[3[4]][5[6]]][7[8[9]][10[11]]]]"
   901  	// First by looking up the template.
   902  	err = tmpl.Lookup("tree").Execute(&b, tree)
   903  	if err != nil {
   904  		t.Fatal("exec error:", err)
   905  	}
   906  	result := b.String()
   907  	if result != expect {
   908  		t.Errorf("expected %q got %q", expect, result)
   909  	}
   910  	// Then direct to execution.
   911  	b.Reset()
   912  	err = tmpl.ExecuteTemplate(&b, "tree", tree)
   913  	if err != nil {
   914  		t.Fatal("exec error:", err)
   915  	}
   916  	result = b.String()
   917  	if result != expect {
   918  		t.Errorf("expected %q got %q", expect, result)
   919  	}
   920  }
   921  
   922  func TestExecuteOnNewTemplate(t *testing.T) {
   923  	// This is issue 3872.
   924  	New("Name").Templates()
   925  	// This is issue 11379.
   926  	new(Template).Templates()
   927  	new(Template).Parse("")
   928  	new(Template).New("abc").Parse("")
   929  	new(Template).Execute(nil, nil)                // returns an error (but does not crash)
   930  	new(Template).ExecuteTemplate(nil, "XXX", nil) // returns an error (but does not crash)
   931  }
   932  
   933  const testTemplates = `{{define "one"}}one{{end}}{{define "two"}}two{{end}}`
   934  
   935  func TestMessageForExecuteEmpty(t *testing.T) {
   936  	// Test a truly empty template.
   937  	tmpl := New("empty")
   938  	var b bytes.Buffer
   939  	err := tmpl.Execute(&b, 0)
   940  	if err == nil {
   941  		t.Fatal("expected initial error")
   942  	}
   943  	got := err.Error()
   944  	want := `template: empty: "empty" is an incomplete or empty template`
   945  	if got != want {
   946  		t.Errorf("expected error %s got %s", want, got)
   947  	}
   948  	// Add a non-empty template to check that the error is helpful.
   949  	tests, err := New("").Parse(testTemplates)
   950  	if err != nil {
   951  		t.Fatal(err)
   952  	}
   953  	tmpl.AddParseTree("secondary", tests.Tree)
   954  	err = tmpl.Execute(&b, 0)
   955  	if err == nil {
   956  		t.Fatal("expected second error")
   957  	}
   958  	got = err.Error()
   959  	want = `template: empty: "empty" is an incomplete or empty template`
   960  	if got != want {
   961  		t.Errorf("expected error %s got %s", want, got)
   962  	}
   963  	// Make sure we can execute the secondary.
   964  	err = tmpl.ExecuteTemplate(&b, "secondary", 0)
   965  	if err != nil {
   966  		t.Fatal(err)
   967  	}
   968  }
   969  
   970  func TestFinalForPrintf(t *testing.T) {
   971  	tmpl, err := New("").Parse(`{{"x" | printf}}`)
   972  	if err != nil {
   973  		t.Fatal(err)
   974  	}
   975  	var b bytes.Buffer
   976  	err = tmpl.Execute(&b, 0)
   977  	if err != nil {
   978  		t.Fatal(err)
   979  	}
   980  }
   981  
   982  type cmpTest struct {
   983  	expr  string
   984  	truth string
   985  	ok    bool
   986  }
   987  
   988  var cmpTests = []cmpTest{
   989  	{"eq true true", "true", true},
   990  	{"eq true false", "false", true},
   991  	{"eq 1+2i 1+2i", "true", true},
   992  	{"eq 1+2i 1+3i", "false", true},
   993  	{"eq 1.5 1.5", "true", true},
   994  	{"eq 1.5 2.5", "false", true},
   995  	{"eq 1 1", "true", true},
   996  	{"eq 1 2", "false", true},
   997  	{"eq `xy` `xy`", "true", true},
   998  	{"eq `xy` `xyz`", "false", true},
   999  	{"eq .Uthree .Uthree", "true", true},
  1000  	{"eq .Uthree .Ufour", "false", true},
  1001  	{"eq 3 4 5 6 3", "true", true},
  1002  	{"eq 3 4 5 6 7", "false", true},
  1003  	{"ne true true", "false", true},
  1004  	{"ne true false", "true", true},
  1005  	{"ne 1+2i 1+2i", "false", true},
  1006  	{"ne 1+2i 1+3i", "true", true},
  1007  	{"ne 1.5 1.5", "false", true},
  1008  	{"ne 1.5 2.5", "true", true},
  1009  	{"ne 1 1", "false", true},
  1010  	{"ne 1 2", "true", true},
  1011  	{"ne `xy` `xy`", "false", true},
  1012  	{"ne `xy` `xyz`", "true", true},
  1013  	{"ne .Uthree .Uthree", "false", true},
  1014  	{"ne .Uthree .Ufour", "true", true},
  1015  	{"lt 1.5 1.5", "false", true},
  1016  	{"lt 1.5 2.5", "true", true},
  1017  	{"lt 1 1", "false", true},
  1018  	{"lt 1 2", "true", true},
  1019  	{"lt `xy` `xy`", "false", true},
  1020  	{"lt `xy` `xyz`", "true", true},
  1021  	{"lt .Uthree .Uthree", "false", true},
  1022  	{"lt .Uthree .Ufour", "true", true},
  1023  	{"le 1.5 1.5", "true", true},
  1024  	{"le 1.5 2.5", "true", true},
  1025  	{"le 2.5 1.5", "false", true},
  1026  	{"le 1 1", "true", true},
  1027  	{"le 1 2", "true", true},
  1028  	{"le 2 1", "false", true},
  1029  	{"le `xy` `xy`", "true", true},
  1030  	{"le `xy` `xyz`", "true", true},
  1031  	{"le `xyz` `xy`", "false", true},
  1032  	{"le .Uthree .Uthree", "true", true},
  1033  	{"le .Uthree .Ufour", "true", true},
  1034  	{"le .Ufour .Uthree", "false", true},
  1035  	{"gt 1.5 1.5", "false", true},
  1036  	{"gt 1.5 2.5", "false", true},
  1037  	{"gt 1 1", "false", true},
  1038  	{"gt 2 1", "true", true},
  1039  	{"gt 1 2", "false", true},
  1040  	{"gt `xy` `xy`", "false", true},
  1041  	{"gt `xy` `xyz`", "false", true},
  1042  	{"gt .Uthree .Uthree", "false", true},
  1043  	{"gt .Uthree .Ufour", "false", true},
  1044  	{"gt .Ufour .Uthree", "true", true},
  1045  	{"ge 1.5 1.5", "true", true},
  1046  	{"ge 1.5 2.5", "false", true},
  1047  	{"ge 2.5 1.5", "true", true},
  1048  	{"ge 1 1", "true", true},
  1049  	{"ge 1 2", "false", true},
  1050  	{"ge 2 1", "true", true},
  1051  	{"ge `xy` `xy`", "true", true},
  1052  	{"ge `xy` `xyz`", "false", true},
  1053  	{"ge `xyz` `xy`", "true", true},
  1054  	{"ge .Uthree .Uthree", "true", true},
  1055  	{"ge .Uthree .Ufour", "false", true},
  1056  	{"ge .Ufour .Uthree", "true", true},
  1057  	// Mixing signed and unsigned integers.
  1058  	{"eq .Uthree .Three", "true", true},
  1059  	{"eq .Three .Uthree", "true", true},
  1060  	{"le .Uthree .Three", "true", true},
  1061  	{"le .Three .Uthree", "true", true},
  1062  	{"ge .Uthree .Three", "true", true},
  1063  	{"ge .Three .Uthree", "true", true},
  1064  	{"lt .Uthree .Three", "false", true},
  1065  	{"lt .Three .Uthree", "false", true},
  1066  	{"gt .Uthree .Three", "false", true},
  1067  	{"gt .Three .Uthree", "false", true},
  1068  	{"eq .Ufour .Three", "false", true},
  1069  	{"lt .Ufour .Three", "false", true},
  1070  	{"gt .Ufour .Three", "true", true},
  1071  	{"eq .NegOne .Uthree", "false", true},
  1072  	{"eq .Uthree .NegOne", "false", true},
  1073  	{"ne .NegOne .Uthree", "true", true},
  1074  	{"ne .Uthree .NegOne", "true", true},
  1075  	{"lt .NegOne .Uthree", "true", true},
  1076  	{"lt .Uthree .NegOne", "false", true},
  1077  	{"le .NegOne .Uthree", "true", true},
  1078  	{"le .Uthree .NegOne", "false", true},
  1079  	{"gt .NegOne .Uthree", "false", true},
  1080  	{"gt .Uthree .NegOne", "true", true},
  1081  	{"ge .NegOne .Uthree", "false", true},
  1082  	{"ge .Uthree .NegOne", "true", true},
  1083  	{"eq (index `x` 0) 'x'", "true", true}, // The example that triggered this rule.
  1084  	{"eq (index `x` 0) 'y'", "false", true},
  1085  	// Errors
  1086  	{"eq `xy` 1", "", false},    // Different types.
  1087  	{"eq 2 2.0", "", false},     // Different types.
  1088  	{"lt true true", "", false}, // Unordered types.
  1089  	{"lt 1+0i 1+0i", "", false}, // Unordered types.
  1090  }
  1091  
  1092  func TestComparison(t *testing.T) {
  1093  	b := new(bytes.Buffer)
  1094  	var cmpStruct = struct {
  1095  		Uthree, Ufour uint
  1096  		NegOne, Three int
  1097  	}{3, 4, -1, 3}
  1098  	for _, test := range cmpTests {
  1099  		text := fmt.Sprintf("{{if %s}}true{{else}}false{{end}}", test.expr)
  1100  		tmpl, err := New("empty").Parse(text)
  1101  		if err != nil {
  1102  			t.Fatalf("%q: %s", test.expr, err)
  1103  		}
  1104  		b.Reset()
  1105  		err = tmpl.Execute(b, &cmpStruct)
  1106  		if test.ok && err != nil {
  1107  			t.Errorf("%s errored incorrectly: %s", test.expr, err)
  1108  			continue
  1109  		}
  1110  		if !test.ok && err == nil {
  1111  			t.Errorf("%s did not error", test.expr)
  1112  			continue
  1113  		}
  1114  		if b.String() != test.truth {
  1115  			t.Errorf("%s: want %s; got %s", test.expr, test.truth, b.String())
  1116  		}
  1117  	}
  1118  }
  1119  
  1120  func TestMissingMapKey(t *testing.T) {
  1121  	data := map[string]int{
  1122  		"x": 99,
  1123  	}
  1124  	tmpl, err := New("t1").Parse("{{.x}} {{.y}}")
  1125  	if err != nil {
  1126  		t.Fatal(err)
  1127  	}
  1128  	var b bytes.Buffer
  1129  	// By default, just get "<no value>"
  1130  	err = tmpl.Execute(&b, data)
  1131  	if err != nil {
  1132  		t.Fatal(err)
  1133  	}
  1134  	want := "99 <no value>"
  1135  	got := b.String()
  1136  	if got != want {
  1137  		t.Errorf("got %q; expected %q", got, want)
  1138  	}
  1139  	// Same if we set the option explicitly to the default.
  1140  	tmpl.Option("missingkey=default")
  1141  	b.Reset()
  1142  	err = tmpl.Execute(&b, data)
  1143  	if err != nil {
  1144  		t.Fatal("default:", err)
  1145  	}
  1146  	want = "99 <no value>"
  1147  	got = b.String()
  1148  	if got != want {
  1149  		t.Errorf("got %q; expected %q", got, want)
  1150  	}
  1151  	// Next we ask for a zero value
  1152  	tmpl.Option("missingkey=zero")
  1153  	b.Reset()
  1154  	err = tmpl.Execute(&b, data)
  1155  	if err != nil {
  1156  		t.Fatal("zero:", err)
  1157  	}
  1158  	want = "99 0"
  1159  	got = b.String()
  1160  	if got != want {
  1161  		t.Errorf("got %q; expected %q", got, want)
  1162  	}
  1163  	// Now we ask for an error.
  1164  	tmpl.Option("missingkey=error")
  1165  	err = tmpl.Execute(&b, data)
  1166  	if err == nil {
  1167  		t.Errorf("expected error; got none")
  1168  	}
  1169  	// same Option, but now a nil interface: ask for an error
  1170  	err = tmpl.Execute(&b, nil)
  1171  	t.Log(err)
  1172  	if err == nil {
  1173  		t.Errorf("expected error for nil-interface; got none")
  1174  	}
  1175  }
  1176  
  1177  // Test that the error message for multiline unterminated string
  1178  // refers to the line number of the opening quote.
  1179  func TestUnterminatedStringError(t *testing.T) {
  1180  	_, err := New("X").Parse("hello\n\n{{`unterminated\n\n\n\n}}\n some more\n\n")
  1181  	if err == nil {
  1182  		t.Fatal("expected error")
  1183  	}
  1184  	str := err.Error()
  1185  	if !strings.Contains(str, "X:3: unexpected unterminated raw quoted string") {
  1186  		t.Fatalf("unexpected error: %s", str)
  1187  	}
  1188  }
  1189  
  1190  const alwaysErrorText = "always be failing"
  1191  
  1192  var alwaysError = errors.New(alwaysErrorText)
  1193  
  1194  type ErrorWriter int
  1195  
  1196  func (e ErrorWriter) Write(p []byte) (int, error) {
  1197  	return 0, alwaysError
  1198  }
  1199  
  1200  func TestExecuteGivesExecError(t *testing.T) {
  1201  	// First, a non-execution error shouldn't be an ExecError.
  1202  	tmpl, err := New("X").Parse("hello")
  1203  	if err != nil {
  1204  		t.Fatal(err)
  1205  	}
  1206  	err = tmpl.Execute(ErrorWriter(0), 0)
  1207  	if err == nil {
  1208  		t.Fatal("expected error; got none")
  1209  	}
  1210  	if err.Error() != alwaysErrorText {
  1211  		t.Errorf("expected %q error; got %q", alwaysErrorText, err)
  1212  	}
  1213  	// This one should be an ExecError.
  1214  	tmpl, err = New("X").Parse("hello, {{.X.Y}}")
  1215  	if err != nil {
  1216  		t.Fatal(err)
  1217  	}
  1218  	err = tmpl.Execute(ioutil.Discard, 0)
  1219  	if err == nil {
  1220  		t.Fatal("expected error; got none")
  1221  	}
  1222  	eerr, ok := err.(ExecError)
  1223  	if !ok {
  1224  		t.Fatalf("did not expect ExecError %s", eerr)
  1225  	}
  1226  	expect := "field X in type int"
  1227  	if !strings.Contains(err.Error(), expect) {
  1228  		t.Errorf("expected %q; got %q", expect, err)
  1229  	}
  1230  }
  1231  
  1232  func funcNameTestFunc() int {
  1233  	return 0
  1234  }
  1235  
  1236  func TestGoodFuncNames(t *testing.T) {
  1237  	names := []string{
  1238  		"_",
  1239  		"a",
  1240  		"a1",
  1241  		"a1",
  1242  		"Ӵ",
  1243  	}
  1244  	for _, name := range names {
  1245  		tmpl := New("X").Funcs(
  1246  			FuncMap{
  1247  				name: funcNameTestFunc,
  1248  			},
  1249  		)
  1250  		if tmpl == nil {
  1251  			t.Fatalf("nil result for %q", name)
  1252  		}
  1253  	}
  1254  }
  1255  
  1256  func TestBadFuncNames(t *testing.T) {
  1257  	names := []string{
  1258  		"",
  1259  		"2",
  1260  		"a-b",
  1261  	}
  1262  	for _, name := range names {
  1263  		testBadFuncName(name, t)
  1264  	}
  1265  }
  1266  
  1267  func testBadFuncName(name string, t *testing.T) {
  1268  	defer func() {
  1269  		recover()
  1270  	}()
  1271  	New("X").Funcs(
  1272  		FuncMap{
  1273  			name: funcNameTestFunc,
  1274  		},
  1275  	)
  1276  	// If we get here, the name did not cause a panic, which is how Funcs
  1277  	// reports an error.
  1278  	t.Errorf("%q succeeded incorrectly as function name", name)
  1279  }
  1280  
  1281  func TestBlock(t *testing.T) {
  1282  	const (
  1283  		input   = `a({{block "inner" .}}bar({{.}})baz{{end}})b`
  1284  		want    = `a(bar(hello)baz)b`
  1285  		overlay = `{{define "inner"}}foo({{.}})bar{{end}}`
  1286  		want2   = `a(foo(goodbye)bar)b`
  1287  	)
  1288  	tmpl, err := New("outer").Parse(input)
  1289  	if err != nil {
  1290  		t.Fatal(err)
  1291  	}
  1292  	tmpl2, err := Must(tmpl.Clone()).Parse(overlay)
  1293  	if err != nil {
  1294  		t.Fatal(err)
  1295  	}
  1296  
  1297  	var buf bytes.Buffer
  1298  	if err := tmpl.Execute(&buf, "hello"); err != nil {
  1299  		t.Fatal(err)
  1300  	}
  1301  	if got := buf.String(); got != want {
  1302  		t.Errorf("got %q, want %q", got, want)
  1303  	}
  1304  
  1305  	buf.Reset()
  1306  	if err := tmpl2.Execute(&buf, "goodbye"); err != nil {
  1307  		t.Fatal(err)
  1308  	}
  1309  	if got := buf.String(); got != want2 {
  1310  		t.Errorf("got %q, want %q", got, want2)
  1311  	}
  1312  }
  1313  
  1314  // Check that calling an invalid field on nil pointer prints
  1315  // a field error instead of a distracting nil pointer error.
  1316  // https://golang.org/issue/15125
  1317  func TestMissingFieldOnNil(t *testing.T) {
  1318  	tmpl := Must(New("tmpl").Parse("{{.MissingField}}"))
  1319  	var d *T
  1320  	err := tmpl.Execute(ioutil.Discard, d)
  1321  	got := "<nil>"
  1322  	if err != nil {
  1323  		got = err.Error()
  1324  	}
  1325  	want := "can't evaluate field MissingField in type *template.T"
  1326  	if !strings.HasSuffix(got, want) {
  1327  		t.Errorf("got error %q, want %q", got, want)
  1328  	}
  1329  }
  1330  
  1331  func TestMaxExecDepth(t *testing.T) {
  1332  	tmpl := Must(New("tmpl").Parse(`{{template "tmpl" .}}`))
  1333  	err := tmpl.Execute(ioutil.Discard, nil)
  1334  	got := "<nil>"
  1335  	if err != nil {
  1336  		got = err.Error()
  1337  	}
  1338  	const want = "exceeded maximum template depth"
  1339  	if !strings.Contains(got, want) {
  1340  		t.Errorf("got error %q; want %q", got, want)
  1341  	}
  1342  }
  1343  
  1344  func TestAddrOfIndex(t *testing.T) {
  1345  	// golang.org/issue/14916.
  1346  	// Before index worked on reflect.Values, the .String could not be
  1347  	// found on the (incorrectly unaddressable) V value,
  1348  	// in contrast to range, which worked fine.
  1349  	// Also testing that passing a reflect.Value to tmpl.Execute works.
  1350  	texts := []string{
  1351  		`{{range .}}{{.String}}{{end}}`,
  1352  		`{{with index . 0}}{{.String}}{{end}}`,
  1353  	}
  1354  	for _, text := range texts {
  1355  		tmpl := Must(New("tmpl").Parse(text))
  1356  		var buf bytes.Buffer
  1357  		err := tmpl.Execute(&buf, reflect.ValueOf([]V{{1}}))
  1358  		if err != nil {
  1359  			t.Fatalf("%s: Execute: %v", text, err)
  1360  		}
  1361  		if buf.String() != "<1>" {
  1362  			t.Fatalf("%s: template output = %q, want %q", text, &buf, "<1>")
  1363  		}
  1364  	}
  1365  }
  1366  
  1367  func TestInterfaceValues(t *testing.T) {
  1368  	// golang.org/issue/17714.
  1369  	// Before index worked on reflect.Values, interface values
  1370  	// were always implicitly promoted to the underlying value,
  1371  	// except that nil interfaces were promoted to the zero reflect.Value.
  1372  	// Eliminating a round trip to interface{} and back to reflect.Value
  1373  	// eliminated this promotion, breaking these cases.
  1374  	tests := []struct {
  1375  		text string
  1376  		out  string
  1377  	}{
  1378  		{`{{index .Nil 1}}`, "ERROR: index of untyped nil"},
  1379  		{`{{index .Slice 2}}`, "2"},
  1380  		{`{{index .Slice .Two}}`, "2"},
  1381  		{`{{call .Nil 1}}`, "ERROR: call of nil"},
  1382  		{`{{call .PlusOne 1}}`, "2"},
  1383  		{`{{call .PlusOne .One}}`, "2"},
  1384  		{`{{and (index .Slice 0) true}}`, "0"},
  1385  		{`{{and .Zero true}}`, "0"},
  1386  		{`{{and (index .Slice 1) false}}`, "false"},
  1387  		{`{{and .One false}}`, "false"},
  1388  		{`{{or (index .Slice 0) false}}`, "false"},
  1389  		{`{{or .Zero false}}`, "false"},
  1390  		{`{{or (index .Slice 1) true}}`, "1"},
  1391  		{`{{or .One true}}`, "1"},
  1392  		{`{{not (index .Slice 0)}}`, "true"},
  1393  		{`{{not .Zero}}`, "true"},
  1394  		{`{{not (index .Slice 1)}}`, "false"},
  1395  		{`{{not .One}}`, "false"},
  1396  		{`{{eq (index .Slice 0) .Zero}}`, "true"},
  1397  		{`{{eq (index .Slice 1) .One}}`, "true"},
  1398  		{`{{ne (index .Slice 0) .Zero}}`, "false"},
  1399  		{`{{ne (index .Slice 1) .One}}`, "false"},
  1400  		{`{{ge (index .Slice 0) .One}}`, "false"},
  1401  		{`{{ge (index .Slice 1) .Zero}}`, "true"},
  1402  		{`{{gt (index .Slice 0) .One}}`, "false"},
  1403  		{`{{gt (index .Slice 1) .Zero}}`, "true"},
  1404  		{`{{le (index .Slice 0) .One}}`, "true"},
  1405  		{`{{le (index .Slice 1) .Zero}}`, "false"},
  1406  		{`{{lt (index .Slice 0) .One}}`, "true"},
  1407  		{`{{lt (index .Slice 1) .Zero}}`, "false"},
  1408  	}
  1409  
  1410  	for _, tt := range tests {
  1411  		tmpl := Must(New("tmpl").Parse(tt.text))
  1412  		var buf bytes.Buffer
  1413  		err := tmpl.Execute(&buf, map[string]interface{}{
  1414  			"PlusOne": func(n int) int {
  1415  				return n + 1
  1416  			},
  1417  			"Slice": []int{0, 1, 2, 3},
  1418  			"One":   1,
  1419  			"Two":   2,
  1420  			"Nil":   nil,
  1421  			"Zero":  0,
  1422  		})
  1423  		if strings.HasPrefix(tt.out, "ERROR:") {
  1424  			e := strings.TrimSpace(strings.TrimPrefix(tt.out, "ERROR:"))
  1425  			if err == nil || !strings.Contains(err.Error(), e) {
  1426  				t.Errorf("%s: Execute: %v, want error %q", tt.text, err, e)
  1427  			}
  1428  			continue
  1429  		}
  1430  		if err != nil {
  1431  			t.Errorf("%s: Execute: %v", tt.text, err)
  1432  			continue
  1433  		}
  1434  		if buf.String() != tt.out {
  1435  			t.Errorf("%s: template output = %q, want %q", tt.text, &buf, tt.out)
  1436  		}
  1437  	}
  1438  }