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