Source file src/text/template/exec_test.go

Documentation: text/template

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package template
     6  
     7  import (
     8  	"bytes"
     9  	"errors"
    10  	"flag"
    11  	"fmt"
    12  	"io/ioutil"
    13  	"reflect"
    14  	"strings"
    15  	"testing"
    16  )
    17  
    18  var debug = flag.Bool("debug", false, "show the errors produced by the tests")
    19  
    20  // T has lots of interesting pieces to use to test execution.
    21  type T struct {
    22  	// Basics
    23  	True        bool
    24  	I           int
    25  	U16         uint16
    26  	X, 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  	// Issue 31810: Parenthesized first element of pipeline with arguments.
   356  	// See also TestIssue31810.
   357  	{"unparenthesized non-function", "{{1 2}}", "", nil, false},
   358  	{"parenthesized non-function", "{{(1) 2}}", "", nil, false},
   359  	{"parenthesized non-function with no args", "{{(1)}}", "1", nil, true}, // This is fine.
   360  
   361  	// Method calls.
   362  	{".Method0", "-{{.Method0}}-", "-M0-", tVal, true},
   363  	{".Method1(1234)", "-{{.Method1 1234}}-", "-1234-", tVal, true},
   364  	{".Method1(.I)", "-{{.Method1 .I}}-", "-17-", tVal, true},
   365  	{".Method2(3, .X)", "-{{.Method2 3 .X}}-", "-Method2: 3 x-", tVal, true},
   366  	{".Method2(.U16, `str`)", "-{{.Method2 .U16 `str`}}-", "-Method2: 16 str-", tVal, true},
   367  	{".Method2(.U16, $x)", "{{if $x := .X}}-{{.Method2 .U16 $x}}{{end}}-", "-Method2: 16 x-", tVal, true},
   368  	{".Method3(nil constant)", "-{{.Method3 nil}}-", "-Method3: <nil>-", tVal, true},
   369  	{".Method3(nil value)", "-{{.Method3 .MXI.unset}}-", "-Method3: <nil>-", tVal, true},
   370  	{"method on var", "{{if $x := .}}-{{$x.Method2 .U16 $x.X}}{{end}}-", "-Method2: 16 x-", tVal, true},
   371  	{"method on chained var",
   372  		"{{range .MSIone}}{{if $.U.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}",
   373  		"true", tVal, true},
   374  	{"chained method",
   375  		"{{range .MSIone}}{{if $.GetU.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}",
   376  		"true", tVal, true},
   377  	{"chained method on variable",
   378  		"{{with $x := .}}{{with .SI}}{{$.GetU.TrueFalse $.True}}{{end}}{{end}}",
   379  		"true", tVal, true},
   380  	{".NilOKFunc not nil", "{{call .NilOKFunc .PI}}", "false", tVal, true},
   381  	{".NilOKFunc nil", "{{call .NilOKFunc nil}}", "true", tVal, true},
   382  	{"method on nil value from slice", "-{{range .}}{{.Method1 1234}}{{end}}-", "-1234-", tSliceOfNil, true},
   383  	{"method on typed nil interface value", "{{.NonEmptyInterfaceTypedNil.Method0}}", "M0", tVal, true},
   384  
   385  	// Function call builtin.
   386  	{".BinaryFunc", "{{call .BinaryFunc `1` `2`}}", "[1=2]", tVal, true},
   387  	{".VariadicFunc0", "{{call .VariadicFunc}}", "<>", tVal, true},
   388  	{".VariadicFunc2", "{{call .VariadicFunc `he` `llo`}}", "<he+llo>", tVal, true},
   389  	{".VariadicFuncInt", "{{call .VariadicFuncInt 33 `he` `llo`}}", "33=<he+llo>", tVal, true},
   390  	{"if .BinaryFunc call", "{{ if .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{end}}", "[1=2]", tVal, true},
   391  	{"if not .BinaryFunc call", "{{ if not .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{else}}No{{end}}", "No", tVal, true},
   392  	{"Interface Call", `{{stringer .S}}`, "foozle", map[string]interface{}{"S": bytes.NewBufferString("foozle")}, true},
   393  	{".ErrFunc", "{{call .ErrFunc}}", "bla", tVal, true},
   394  	{"call nil", "{{call nil}}", "", tVal, false},
   395  
   396  	// Erroneous function calls (check args).
   397  	{".BinaryFuncTooFew", "{{call .BinaryFunc `1`}}", "", tVal, false},
   398  	{".BinaryFuncTooMany", "{{call .BinaryFunc `1` `2` `3`}}", "", tVal, false},
   399  	{".BinaryFuncBad0", "{{call .BinaryFunc 1 3}}", "", tVal, false},
   400  	{".BinaryFuncBad1", "{{call .BinaryFunc `1` 3}}", "", tVal, false},
   401  	{".VariadicFuncBad0", "{{call .VariadicFunc 3}}", "", tVal, false},
   402  	{".VariadicFuncIntBad0", "{{call .VariadicFuncInt}}", "", tVal, false},
   403  	{".VariadicFuncIntBad`", "{{call .VariadicFuncInt `x`}}", "", tVal, false},
   404  	{".VariadicFuncNilBad", "{{call .VariadicFunc nil}}", "", tVal, false},
   405  
   406  	// Pipelines.
   407  	{"pipeline", "-{{.Method0 | .Method2 .U16}}-", "-Method2: 16 M0-", tVal, true},
   408  	{"pipeline func", "-{{call .VariadicFunc `llo` | call .VariadicFunc `he` }}-", "-<he+<llo>>-", tVal, true},
   409  
   410  	// Nil values aren't missing arguments.
   411  	{"nil pipeline", "{{ .Empty0 | call .NilOKFunc }}", "true", tVal, true},
   412  	{"nil call arg", "{{ call .NilOKFunc .Empty0 }}", "true", tVal, true},
   413  	{"bad nil pipeline", "{{ .Empty0 | .VariadicFunc }}", "", tVal, false},
   414  
   415  	// Parenthesized expressions
   416  	{"parens in pipeline", "{{printf `%d %d %d` (1) (2 | add 3) (add 4 (add 5 6))}}", "1 5 15", tVal, true},
   417  
   418  	// Parenthesized expressions with field accesses
   419  	{"parens: $ in paren", "{{($).X}}", "x", tVal, true},
   420  	{"parens: $.GetU in paren", "{{($.GetU).V}}", "v", tVal, true},
   421  	{"parens: $ in paren in pipe", "{{($ | echo).X}}", "x", tVal, true},
   422  	{"parens: spaces and args", `{{(makemap "up" "down" "left" "right").left}}`, "right", tVal, true},
   423  
   424  	// If.
   425  	{"if true", "{{if true}}TRUE{{end}}", "TRUE", tVal, true},
   426  	{"if false", "{{if false}}TRUE{{else}}FALSE{{end}}", "FALSE", tVal, true},
   427  	{"if nil", "{{if nil}}TRUE{{end}}", "", tVal, false},
   428  	{"if on typed nil interface value", "{{if .NonEmptyInterfaceTypedNil}}TRUE{{ end }}", "", tVal, true},
   429  	{"if 1", "{{if 1}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
   430  	{"if 0", "{{if 0}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
   431  	{"if 1.5", "{{if 1.5}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
   432  	{"if 0.0", "{{if .FloatZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
   433  	{"if 1.5i", "{{if 1.5i}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
   434  	{"if 0.0i", "{{if .ComplexZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
   435  	{"if emptystring", "{{if ``}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
   436  	{"if string", "{{if `notempty`}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
   437  	{"if emptyslice", "{{if .SIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
   438  	{"if slice", "{{if .SI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
   439  	{"if emptymap", "{{if .MSIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
   440  	{"if map", "{{if .MSI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
   441  	{"if map unset", "{{if .MXI.none}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
   442  	{"if map not unset", "{{if not .MXI.none}}ZERO{{else}}NON-ZERO{{end}}", "ZERO", tVal, true},
   443  	{"if $x with $y int", "{{if $x := true}}{{with $y := .I}}{{$x}},{{$y}}{{end}}{{end}}", "true,17", tVal, true},
   444  	{"if $x with $x int", "{{if $x := true}}{{with $x := .I}}{{$x}},{{end}}{{$x}}{{end}}", "17,true", tVal, true},
   445  	{"if else if", "{{if false}}FALSE{{else if true}}TRUE{{end}}", "TRUE", tVal, true},
   446  	{"if else chain", "{{if eq 1 3}}1{{else if eq 2 3}}2{{else if eq 3 3}}3{{end}}", "3", tVal, true},
   447  
   448  	// Print etc.
   449  	{"print", `{{print "hello, print"}}`, "hello, print", tVal, true},
   450  	{"print 123", `{{print 1 2 3}}`, "1 2 3", tVal, true},
   451  	{"print nil", `{{print nil}}`, "<nil>", tVal, true},
   452  	{"println", `{{println 1 2 3}}`, "1 2 3\n", tVal, true},
   453  	{"printf int", `{{printf "%04x" 127}}`, "007f", tVal, true},
   454  	{"printf float", `{{printf "%g" 3.5}}`, "3.5", tVal, true},
   455  	{"printf complex", `{{printf "%g" 1+7i}}`, "(1+7i)", tVal, true},
   456  	{"printf string", `{{printf "%s" "hello"}}`, "hello", tVal, true},
   457  	{"printf function", `{{printf "%#q" zeroArgs}}`, "`zeroArgs`", tVal, true},
   458  	{"printf field", `{{printf "%s" .U.V}}`, "v", tVal, true},
   459  	{"printf method", `{{printf "%s" .Method0}}`, "M0", tVal, true},
   460  	{"printf dot", `{{with .I}}{{printf "%d" .}}{{end}}`, "17", tVal, true},
   461  	{"printf var", `{{with $x := .I}}{{printf "%d" $x}}{{end}}`, "17", tVal, true},
   462  	{"printf lots", `{{printf "%d %s %g %s" 127 "hello" 7-3i .Method0}}`, "127 hello (7-3i) M0", tVal, true},
   463  
   464  	// HTML.
   465  	{"html", `{{html "<script>alert(\"XSS\");</script>"}}`,
   466  		"&lt;script&gt;alert(&#34;XSS&#34;);&lt;/script&gt;", nil, true},
   467  	{"html pipeline", `{{printf "<script>alert(\"XSS\");</script>" | html}}`,
   468  		"&lt;script&gt;alert(&#34;XSS&#34;);&lt;/script&gt;", nil, true},
   469  	{"html", `{{html .PS}}`, "a string", tVal, true},
   470  	{"html typed nil", `{{html .NIL}}`, "&lt;nil&gt;", tVal, true},
   471  	{"html untyped nil", `{{html .Empty0}}`, "&lt;no value&gt;", tVal, true},
   472  
   473  	// JavaScript.
   474  	{"js", `{{js .}}`, `It\'d be nice.`, `It'd be nice.`, true},
   475  
   476  	// URL query.
   477  	{"urlquery", `{{"http://www.example.org/"|urlquery}}`, "http%3A%2F%2Fwww.example.org%2F", nil, true},
   478  
   479  	// Booleans
   480  	{"not", "{{not true}} {{not false}}", "false true", nil, true},
   481  	{"and", "{{and false 0}} {{and 1 0}} {{and 0 true}} {{and 1 1}}", "false 0 0 1", nil, true},
   482  	{"or", "{{or 0 0}} {{or 1 0}} {{or 0 true}} {{or 1 1}}", "0 1 true 1", nil, true},
   483  	{"boolean if", "{{if and true 1 `hi`}}TRUE{{else}}FALSE{{end}}", "TRUE", tVal, true},
   484  	{"boolean if not", "{{if and true 1 `hi` | not}}TRUE{{else}}FALSE{{end}}", "FALSE", nil, true},
   485  
   486  	// Indexing.
   487  	{"slice[0]", "{{index .SI 0}}", "3", tVal, true},
   488  	{"slice[1]", "{{index .SI 1}}", "4", tVal, true},
   489  	{"slice[HUGE]", "{{index .SI 10}}", "", tVal, false},
   490  	{"slice[WRONG]", "{{index .SI `hello`}}", "", tVal, false},
   491  	{"slice[nil]", "{{index .SI nil}}", "", tVal, false},
   492  	{"map[one]", "{{index .MSI `one`}}", "1", tVal, true},
   493  	{"map[two]", "{{index .MSI `two`}}", "2", tVal, true},
   494  	{"map[NO]", "{{index .MSI `XXX`}}", "0", tVal, true},
   495  	{"map[nil]", "{{index .MSI nil}}", "", tVal, false},
   496  	{"map[``]", "{{index .MSI ``}}", "0", tVal, true},
   497  	{"map[WRONG]", "{{index .MSI 10}}", "", tVal, false},
   498  	{"double index", "{{index .SMSI 1 `eleven`}}", "11", tVal, true},
   499  	{"nil[1]", "{{index nil 1}}", "", tVal, false},
   500  	{"map MI64S", "{{index .MI64S 2}}", "i642", tVal, true},
   501  	{"map MI32S", "{{index .MI32S 2}}", "two", tVal, true},
   502  	{"map MUI64S", "{{index .MUI64S 3}}", "ui643", tVal, true},
   503  	{"map MI8S", "{{index .MI8S 3}}", "i83", tVal, true},
   504  	{"map MUI8S", "{{index .MUI8S 2}}", "u82", tVal, true},
   505  	{"index of an interface field", "{{index .Empty3 0}}", "7", tVal, true},
   506  
   507  	// Slicing.
   508  	{"slice[:]", "{{slice .SI}}", "[3 4 5]", tVal, true},
   509  	{"slice[1:]", "{{slice .SI 1}}", "[4 5]", tVal, true},
   510  	{"slice[1:2]", "{{slice .SI 1 2}}", "[4]", tVal, true},
   511  	{"slice[-1:]", "{{slice .SI -1}}", "", tVal, false},
   512  	{"slice[1:-2]", "{{slice .SI 1 -2}}", "", tVal, false},
   513  	{"slice[1:2:-1]", "{{slice .SI 1 2 -1}}", "", tVal, false},
   514  	{"slice[2:1]", "{{slice .SI 2 1}}", "", tVal, false},
   515  	{"slice[2:2:1]", "{{slice .SI 2 2 1}}", "", tVal, false},
   516  	{"out of range", "{{slice .SI 4 5}}", "", tVal, false},
   517  	{"out of range", "{{slice .SI 2 2 5}}", "", tVal, false},
   518  	{"len(s) < indexes < cap(s)", "{{slice .SICap 6 10}}", "[0 0 0 0]", tVal, true},
   519  	{"len(s) < indexes < cap(s)", "{{slice .SICap 6 10 10}}", "[0 0 0 0]", tVal, true},
   520  	{"indexes > cap(s)", "{{slice .SICap 10 11}}", "", tVal, false},
   521  	{"indexes > cap(s)", "{{slice .SICap 6 10 11}}", "", tVal, false},
   522  	{"array[:]", "{{slice .AI}}", "[3 4 5]", tVal, true},
   523  	{"array[1:]", "{{slice .AI 1}}", "[4 5]", tVal, true},
   524  	{"array[1:2]", "{{slice .AI 1 2}}", "[4]", tVal, true},
   525  	{"string[:]", "{{slice .S}}", "xyz", tVal, true},
   526  	{"string[0:1]", "{{slice .S 0 1}}", "x", tVal, true},
   527  	{"string[1:]", "{{slice .S 1}}", "yz", tVal, true},
   528  	{"string[1:2]", "{{slice .S 1 2}}", "y", tVal, true},
   529  	{"out of range", "{{slice .S 1 5}}", "", tVal, false},
   530  	{"3-index slice of string", "{{slice .S 1 2 2}}", "", tVal, false},
   531  	{"slice of an interface field", "{{slice .Empty3 0 1}}", "[7]", tVal, true},
   532  
   533  	// Len.
   534  	{"slice", "{{len .SI}}", "3", tVal, true},
   535  	{"map", "{{len .MSI }}", "3", tVal, true},
   536  	{"len of int", "{{len 3}}", "", tVal, false},
   537  	{"len of nothing", "{{len .Empty0}}", "", tVal, false},
   538  	{"len of an interface field", "{{len .Empty3}}", "2", tVal, true},
   539  
   540  	// With.
   541  	{"with true", "{{with true}}{{.}}{{end}}", "true", tVal, true},
   542  	{"with false", "{{with false}}{{.}}{{else}}FALSE{{end}}", "FALSE", tVal, true},
   543  	{"with 1", "{{with 1}}{{.}}{{else}}ZERO{{end}}", "1", tVal, true},
   544  	{"with 0", "{{with 0}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
   545  	{"with 1.5", "{{with 1.5}}{{.}}{{else}}ZERO{{end}}", "1.5", tVal, true},
   546  	{"with 0.0", "{{with .FloatZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
   547  	{"with 1.5i", "{{with 1.5i}}{{.}}{{else}}ZERO{{end}}", "(0+1.5i)", tVal, true},
   548  	{"with 0.0i", "{{with .ComplexZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
   549  	{"with emptystring", "{{with ``}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
   550  	{"with string", "{{with `notempty`}}{{.}}{{else}}EMPTY{{end}}", "notempty", tVal, true},
   551  	{"with emptyslice", "{{with .SIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
   552  	{"with slice", "{{with .SI}}{{.}}{{else}}EMPTY{{end}}", "[3 4 5]", tVal, true},
   553  	{"with emptymap", "{{with .MSIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
   554  	{"with map", "{{with .MSIone}}{{.}}{{else}}EMPTY{{end}}", "map[one:1]", tVal, true},
   555  	{"with empty interface, struct field", "{{with .Empty4}}{{.V}}{{end}}", "UinEmpty", tVal, true},
   556  	{"with $x int", "{{with $x := .I}}{{$x}}{{end}}", "17", tVal, true},
   557  	{"with $x struct.U.V", "{{with $x := $}}{{$x.U.V}}{{end}}", "v", tVal, true},
   558  	{"with variable and action", "{{with $x := $}}{{$y := $.U.V}}{{$y}}{{end}}", "v", tVal, true},
   559  	{"with on typed nil interface value", "{{with .NonEmptyInterfaceTypedNil}}TRUE{{ end }}", "", tVal, true},
   560  
   561  	// Range.
   562  	{"range []int", "{{range .SI}}-{{.}}-{{end}}", "-3--4--5-", tVal, true},
   563  	{"range empty no else", "{{range .SIEmpty}}-{{.}}-{{end}}", "", tVal, true},
   564  	{"range []int else", "{{range .SI}}-{{.}}-{{else}}EMPTY{{end}}", "-3--4--5-", tVal, true},
   565  	{"range empty else", "{{range .SIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
   566  	{"range []bool", "{{range .SB}}-{{.}}-{{end}}", "-true--false-", tVal, true},
   567  	{"range []int method", "{{range .SI | .MAdd .I}}-{{.}}-{{end}}", "-20--21--22-", tVal, true},
   568  	{"range map", "{{range .MSI}}-{{.}}-{{end}}", "-1--3--2-", tVal, true},
   569  	{"range empty map no else", "{{range .MSIEmpty}}-{{.}}-{{end}}", "", tVal, true},
   570  	{"range map else", "{{range .MSI}}-{{.}}-{{else}}EMPTY{{end}}", "-1--3--2-", tVal, true},
   571  	{"range empty map else", "{{range .MSIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
   572  	{"range empty interface", "{{range .Empty3}}-{{.}}-{{else}}EMPTY{{end}}", "-7--8-", tVal, true},
   573  	{"range empty nil", "{{range .Empty0}}-{{.}}-{{end}}", "", tVal, true},
   574  	{"range $x SI", "{{range $x := .SI}}<{{$x}}>{{end}}", "<3><4><5>", tVal, true},
   575  	{"range $x $y SI", "{{range $x, $y := .SI}}<{{$x}}={{$y}}>{{end}}", "<0=3><1=4><2=5>", tVal, true},
   576  	{"range $x MSIone", "{{range $x := .MSIone}}<{{$x}}>{{end}}", "<1>", tVal, true},
   577  	{"range $x $y MSIone", "{{range $x, $y := .MSIone}}<{{$x}}={{$y}}>{{end}}", "<one=1>", tVal, true},
   578  	{"range $x PSI", "{{range $x := .PSI}}<{{$x}}>{{end}}", "<21><22><23>", tVal, true},
   579  	{"declare in range", "{{range $x := .PSI}}<{{$foo:=$x}}{{$x}}>{{end}}", "<21><22><23>", tVal, true},
   580  	{"range count", `{{range $i, $x := count 5}}[{{$i}}]{{$x}}{{end}}`, "[0]a[1]b[2]c[3]d[4]e", tVal, true},
   581  	{"range nil count", `{{range $i, $x := count 0}}{{else}}empty{{end}}`, "empty", tVal, true},
   582  
   583  	// Cute examples.
   584  	{"or as if true", `{{or .SI "slice is empty"}}`, "[3 4 5]", tVal, true},
   585  	{"or as if false", `{{or .SIEmpty "slice is empty"}}`, "slice is empty", tVal, true},
   586  
   587  	// Error handling.
   588  	{"error method, error", "{{.MyError true}}", "", tVal, false},
   589  	{"error method, no error", "{{.MyError false}}", "false", tVal, true},
   590  
   591  	// Numbers
   592  	{"decimal", "{{print 1234}}", "1234", tVal, true},
   593  	{"decimal _", "{{print 12_34}}", "1234", tVal, true},
   594  	{"binary", "{{print 0b101}}", "5", tVal, true},
   595  	{"binary _", "{{print 0b_1_0_1}}", "5", tVal, true},
   596  	{"BINARY", "{{print 0B101}}", "5", tVal, true},
   597  	{"octal0", "{{print 0377}}", "255", tVal, true},
   598  	{"octal", "{{print 0o377}}", "255", tVal, true},
   599  	{"octal _", "{{print 0o_3_7_7}}", "255", tVal, true},
   600  	{"OCTAL", "{{print 0O377}}", "255", tVal, true},
   601  	{"hex", "{{print 0x123}}", "291", tVal, true},
   602  	{"hex _", "{{print 0x1_23}}", "291", tVal, true},
   603  	{"HEX", "{{print 0X123ABC}}", "1194684", tVal, true},
   604  	{"float", "{{print 123.4}}", "123.4", tVal, true},
   605  	{"float _", "{{print 0_0_1_2_3.4}}", "123.4", tVal, true},
   606  	{"hex float", "{{print +0x1.ep+2}}", "7.5", tVal, true},
   607  	{"hex float _", "{{print +0x_1.e_0p+0_2}}", "7.5", tVal, true},
   608  	{"HEX float", "{{print +0X1.EP+2}}", "7.5", tVal, true},
   609  	{"print multi", "{{print 1_2_3_4 7.5_00_00_00}}", "1234 7.5", tVal, true},
   610  	{"print multi2", "{{print 1234 0x0_1.e_0p+02}}", "1234 7.5", tVal, true},
   611  
   612  	// Fixed bugs.
   613  	// Must separate dot and receiver; otherwise args are evaluated with dot set to variable.
   614  	{"bug0", "{{range .MSIone}}{{if $.Method1 .}}X{{end}}{{end}}", "X", tVal, true},
   615  	// Do not loop endlessly in indirect for non-empty interfaces.
   616  	// The bug appears with *interface only; looped forever.
   617  	{"bug1", "{{.Method0}}", "M0", &iVal, true},
   618  	// Was taking address of interface field, so method set was empty.
   619  	{"bug2", "{{$.NonEmptyInterface.Method0}}", "M0", tVal, true},
   620  	// Struct values were not legal in with - mere oversight.
   621  	{"bug3", "{{with $}}{{.Method0}}{{end}}", "M0", tVal, true},
   622  	// Nil interface values in if.
   623  	{"bug4", "{{if .Empty0}}non-nil{{else}}nil{{end}}", "nil", tVal, true},
   624  	// Stringer.
   625  	{"bug5", "{{.Str}}", "foozle", tVal, true},
   626  	{"bug5a", "{{.Err}}", "erroozle", tVal, true},
   627  	// Args need to be indirected and dereferenced sometimes.
   628  	{"bug6a", "{{vfunc .V0 .V1}}", "vfunc", tVal, true},
   629  	{"bug6b", "{{vfunc .V0 .V0}}", "vfunc", tVal, true},
   630  	{"bug6c", "{{vfunc .V1 .V0}}", "vfunc", tVal, true},
   631  	{"bug6d", "{{vfunc .V1 .V1}}", "vfunc", tVal, true},
   632  	// Legal parse but illegal execution: non-function should have no arguments.
   633  	{"bug7a", "{{3 2}}", "", tVal, false},
   634  	{"bug7b", "{{$x := 1}}{{$x 2}}", "", tVal, false},
   635  	{"bug7c", "{{$x := 1}}{{3 | $x}}", "", tVal, false},
   636  	// Pipelined arg was not being type-checked.
   637  	{"bug8a", "{{3|oneArg}}", "", tVal, false},
   638  	{"bug8b", "{{4|dddArg 3}}", "", tVal, false},
   639  	// A bug was introduced that broke map lookups for lower-case names.
   640  	{"bug9", "{{.cause}}", "neglect", map[string]string{"cause": "neglect"}, true},
   641  	// Field chain starting with function did not work.
   642  	{"bug10", "{{mapOfThree.three}}-{{(mapOfThree).three}}", "3-3", 0, true},
   643  	// Dereferencing nil pointer while evaluating function arguments should not panic. Issue 7333.
   644  	{"bug11", "{{valueString .PS}}", "", T{}, false},
   645  	// 0xef gave constant type float64. Issue 8622.
   646  	{"bug12xe", "{{printf `%T` 0xef}}", "int", T{}, true},
   647  	{"bug12xE", "{{printf `%T` 0xEE}}", "int", T{}, true},
   648  	{"bug12Xe", "{{printf `%T` 0Xef}}", "int", T{}, true},
   649  	{"bug12XE", "{{printf `%T` 0XEE}}", "int", T{}, true},
   650  	// Chained nodes did not work as arguments. Issue 8473.
   651  	{"bug13", "{{print (.Copy).I}}", "17", tVal, true},
   652  	// Didn't protect against nil or literal values in field chains.
   653  	{"bug14a", "{{(nil).True}}", "", tVal, false},
   654  	{"bug14b", "{{$x := nil}}{{$x.anything}}", "", tVal, false},
   655  	{"bug14c", `{{$x := (1.0)}}{{$y := ("hello")}}{{$x.anything}}{{$y.true}}`, "", tVal, false},
   656  	// Didn't call validateType on function results. Issue 10800.
   657  	{"bug15", "{{valueString returnInt}}", "", tVal, false},
   658  	// Variadic function corner cases. Issue 10946.
   659  	{"bug16a", "{{true|printf}}", "", tVal, false},
   660  	{"bug16b", "{{1|printf}}", "", tVal, false},
   661  	{"bug16c", "{{1.1|printf}}", "", tVal, false},
   662  	{"bug16d", "{{'x'|printf}}", "", tVal, false},
   663  	{"bug16e", "{{0i|printf}}", "", tVal, false},
   664  	{"bug16f", "{{true|twoArgs \"xxx\"}}", "", tVal, false},
   665  	{"bug16g", "{{\"aaa\" |twoArgs \"bbb\"}}", "twoArgs=bbbaaa", tVal, true},
   666  	{"bug16h", "{{1|oneArg}}", "", tVal, false},
   667  	{"bug16i", "{{\"aaa\"|oneArg}}", "oneArg=aaa", tVal, true},
   668  	{"bug16j", "{{1+2i|printf \"%v\"}}", "(1+2i)", tVal, true},
   669  	{"bug16k", "{{\"aaa\"|printf }}", "aaa", tVal, true},
   670  	{"bug17a", "{{.NonEmptyInterface.X}}", "x", tVal, true},
   671  	{"bug17b", "-{{.NonEmptyInterface.Method1 1234}}-", "-1234-", tVal, true},
   672  	{"bug17c", "{{len .NonEmptyInterfacePtS}}", "2", tVal, true},
   673  	{"bug17d", "{{index .NonEmptyInterfacePtS 0}}", "a", tVal, true},
   674  	{"bug17e", "{{range .NonEmptyInterfacePtS}}-{{.}}-{{end}}", "-a--b-", tVal, true},
   675  
   676  	// More variadic function corner cases. Some runes would get evaluated
   677  	// as constant floats instead of ints. Issue 34483.
   678  	{"bug18a", "{{eq . '.'}}", "true", '.', true},
   679  	{"bug18b", "{{eq . 'e'}}", "true", 'e', true},
   680  	{"bug18c", "{{eq . 'P'}}", "true", 'P', true},
   681  }
   682  
   683  func zeroArgs() string {
   684  	return "zeroArgs"
   685  }
   686  
   687  func oneArg(a string) string {
   688  	return "oneArg=" + a
   689  }
   690  
   691  func twoArgs(a, b string) string {
   692  	return "twoArgs=" + a + b
   693  }
   694  
   695  func dddArg(a int, b ...string) string {
   696  	return fmt.Sprintln(a, b)
   697  }
   698  
   699  // count returns a channel that will deliver n sequential 1-letter strings starting at "a"
   700  func count(n int) chan string {
   701  	if n == 0 {
   702  		return nil
   703  	}
   704  	c := make(chan string)
   705  	go func() {
   706  		for i := 0; i < n; i++ {
   707  			c <- "abcdefghijklmnop"[i : i+1]
   708  		}
   709  		close(c)
   710  	}()
   711  	return c
   712  }
   713  
   714  // vfunc takes a *V and a V
   715  func vfunc(V, *V) string {
   716  	return "vfunc"
   717  }
   718  
   719  // valueString takes a string, not a pointer.
   720  func valueString(v string) string {
   721  	return "value is ignored"
   722  }
   723  
   724  // returnInt returns an int
   725  func returnInt() int {
   726  	return 7
   727  }
   728  
   729  func add(args ...int) int {
   730  	sum := 0
   731  	for _, x := range args {
   732  		sum += x
   733  	}
   734  	return sum
   735  }
   736  
   737  func echo(arg interface{}) interface{} {
   738  	return arg
   739  }
   740  
   741  func makemap(arg ...string) map[string]string {
   742  	if len(arg)%2 != 0 {
   743  		panic("bad makemap")
   744  	}
   745  	m := make(map[string]string)
   746  	for i := 0; i < len(arg); i += 2 {
   747  		m[arg[i]] = arg[i+1]
   748  	}
   749  	return m
   750  }
   751  
   752  func stringer(s fmt.Stringer) string {
   753  	return s.String()
   754  }
   755  
   756  func mapOfThree() interface{} {
   757  	return map[string]int{"three": 3}
   758  }
   759  
   760  func testExecute(execTests []execTest, template *Template, t *testing.T) {
   761  	b := new(bytes.Buffer)
   762  	funcs := FuncMap{
   763  		"add":         add,
   764  		"count":       count,
   765  		"dddArg":      dddArg,
   766  		"echo":        echo,
   767  		"makemap":     makemap,
   768  		"mapOfThree":  mapOfThree,
   769  		"oneArg":      oneArg,
   770  		"returnInt":   returnInt,
   771  		"stringer":    stringer,
   772  		"twoArgs":     twoArgs,
   773  		"typeOf":      typeOf,
   774  		"valueString": valueString,
   775  		"vfunc":       vfunc,
   776  		"zeroArgs":    zeroArgs,
   777  	}
   778  	for _, test := range execTests {
   779  		var tmpl *Template
   780  		var err error
   781  		if template == nil {
   782  			tmpl, err = New(test.name).Funcs(funcs).Parse(test.input)
   783  		} else {
   784  			tmpl, err = template.New(test.name).Funcs(funcs).Parse(test.input)
   785  		}
   786  		if err != nil {
   787  			t.Errorf("%s: parse error: %s", test.name, err)
   788  			continue
   789  		}
   790  		b.Reset()
   791  		err = tmpl.Execute(b, test.data)
   792  		switch {
   793  		case !test.ok && err == nil:
   794  			t.Errorf("%s: expected error; got none", test.name)
   795  			continue
   796  		case test.ok && err != nil:
   797  			t.Errorf("%s: unexpected execute error: %s", test.name, err)
   798  			continue
   799  		case !test.ok && err != nil:
   800  			// expected error, got one
   801  			if *debug {
   802  				fmt.Printf("%s: %s\n\t%s\n", test.name, test.input, err)
   803  			}
   804  		}
   805  		result := b.String()
   806  		if result != test.output {
   807  			t.Errorf("%s: expected\n\t%q\ngot\n\t%q", test.name, test.output, result)
   808  		}
   809  	}
   810  }
   811  
   812  func TestExecute(t *testing.T) {
   813  	testExecute(execTests, nil, t)
   814  }
   815  
   816  var delimPairs = []string{
   817  	"", "", // default
   818  	"{{", "}}", // same as default
   819  	"<<", ">>", // distinct
   820  	"|", "|", // same
   821  	"(日)", "(本)", // peculiar
   822  }
   823  
   824  func TestDelims(t *testing.T) {
   825  	const hello = "Hello, world"
   826  	var value = struct{ Str string }{hello}
   827  	for i := 0; i < len(delimPairs); i += 2 {
   828  		text := ".Str"
   829  		left := delimPairs[i+0]
   830  		trueLeft := left
   831  		right := delimPairs[i+1]
   832  		trueRight := right
   833  		if left == "" { // default case
   834  			trueLeft = "{{"
   835  		}
   836  		if right == "" { // default case
   837  			trueRight = "}}"
   838  		}
   839  		text = trueLeft + text + trueRight
   840  		// Now add a comment
   841  		text += trueLeft + "/*comment*/" + trueRight
   842  		// Now add  an action containing a string.
   843  		text += trueLeft + `"` + trueLeft + `"` + trueRight
   844  		// At this point text looks like `{{.Str}}{{/*comment*/}}{{"{{"}}`.
   845  		tmpl, err := New("delims").Delims(left, right).Parse(text)
   846  		if err != nil {
   847  			t.Fatalf("delim %q text %q parse err %s", left, text, err)
   848  		}
   849  		var b = new(bytes.Buffer)
   850  		err = tmpl.Execute(b, value)
   851  		if err != nil {
   852  			t.Fatalf("delim %q exec err %s", left, err)
   853  		}
   854  		if b.String() != hello+trueLeft {
   855  			t.Errorf("expected %q got %q", hello+trueLeft, b.String())
   856  		}
   857  	}
   858  }
   859  
   860  // Check that an error from a method flows back to the top.
   861  func TestExecuteError(t *testing.T) {
   862  	b := new(bytes.Buffer)
   863  	tmpl := New("error")
   864  	_, err := tmpl.Parse("{{.MyError true}}")
   865  	if err != nil {
   866  		t.Fatalf("parse error: %s", err)
   867  	}
   868  	err = tmpl.Execute(b, tVal)
   869  	if err == nil {
   870  		t.Errorf("expected error; got none")
   871  	} else if !strings.Contains(err.Error(), myError.Error()) {
   872  		if *debug {
   873  			fmt.Printf("test execute error: %s\n", err)
   874  		}
   875  		t.Errorf("expected myError; got %s", err)
   876  	}
   877  }
   878  
   879  const execErrorText = `line 1
   880  line 2
   881  line 3
   882  {{template "one" .}}
   883  {{define "one"}}{{template "two" .}}{{end}}
   884  {{define "two"}}{{template "three" .}}{{end}}
   885  {{define "three"}}{{index "hi" $}}{{end}}`
   886  
   887  // Check that an error from a nested template contains all the relevant information.
   888  func TestExecError(t *testing.T) {
   889  	tmpl, err := New("top").Parse(execErrorText)
   890  	if err != nil {
   891  		t.Fatal("parse error:", err)
   892  	}
   893  	var b bytes.Buffer
   894  	err = tmpl.Execute(&b, 5) // 5 is out of range indexing "hi"
   895  	if err == nil {
   896  		t.Fatal("expected error")
   897  	}
   898  	const want = `template: top:7:20: executing "three" at <index "hi" $>: error calling index: index out of range: 5`
   899  	got := err.Error()
   900  	if got != want {
   901  		t.Errorf("expected\n%q\ngot\n%q", want, got)
   902  	}
   903  }
   904  
   905  func TestJSEscaping(t *testing.T) {
   906  	testCases := []struct {
   907  		in, exp string
   908  	}{
   909  		{`a`, `a`},
   910  		{`'foo`, `\'foo`},
   911  		{`Go "jump" \`, `Go \"jump\" \\`},
   912  		{`Yukihiro says "今日は世界"`, `Yukihiro says \"今日は世界\"`},
   913  		{"unprintable \uFDFF", `unprintable \uFDFF`},
   914  		{`<html>`, `\x3Chtml\x3E`},
   915  		{`no = in attributes`, `no \x3D in attributes`},
   916  		{`&#x27; does not become HTML entity`, `\x26#x27; does not become HTML entity`},
   917  	}
   918  	for _, tc := range testCases {
   919  		s := JSEscapeString(tc.in)
   920  		if s != tc.exp {
   921  			t.Errorf("JS escaping [%s] got [%s] want [%s]", tc.in, s, tc.exp)
   922  		}
   923  	}
   924  }
   925  
   926  // A nice example: walk a binary tree.
   927  
   928  type Tree struct {
   929  	Val         int
   930  	Left, Right *Tree
   931  }
   932  
   933  // Use different delimiters to test Set.Delims.
   934  // Also test the trimming of leading and trailing spaces.
   935  const treeTemplate = `
   936  	(- define "tree" -)
   937  	[
   938  		(- .Val -)
   939  		(- with .Left -)
   940  			(template "tree" . -)
   941  		(- end -)
   942  		(- with .Right -)
   943  			(- template "tree" . -)
   944  		(- end -)
   945  	]
   946  	(- end -)
   947  `
   948  
   949  func TestTree(t *testing.T) {
   950  	var tree = &Tree{
   951  		1,
   952  		&Tree{
   953  			2, &Tree{
   954  				3,
   955  				&Tree{
   956  					4, nil, nil,
   957  				},
   958  				nil,
   959  			},
   960  			&Tree{
   961  				5,
   962  				&Tree{
   963  					6, nil, nil,
   964  				},
   965  				nil,
   966  			},
   967  		},
   968  		&Tree{
   969  			7,
   970  			&Tree{
   971  				8,
   972  				&Tree{
   973  					9, nil, nil,
   974  				},
   975  				nil,
   976  			},
   977  			&Tree{
   978  				10,
   979  				&Tree{
   980  					11, nil, nil,
   981  				},
   982  				nil,
   983  			},
   984  		},
   985  	}
   986  	tmpl, err := New("root").Delims("(", ")").Parse(treeTemplate)
   987  	if err != nil {
   988  		t.Fatal("parse error:", err)
   989  	}
   990  	var b bytes.Buffer
   991  	const expect = "[1[2[3[4]][5[6]]][7[8[9]][10[11]]]]"
   992  	// First by looking up the template.
   993  	err = tmpl.Lookup("tree").Execute(&b, tree)
   994  	if err != nil {
   995  		t.Fatal("exec error:", err)
   996  	}
   997  	result := b.String()
   998  	if result != expect {
   999  		t.Errorf("expected %q got %q", expect, result)
  1000  	}
  1001  	// Then direct to execution.
  1002  	b.Reset()
  1003  	err = tmpl.ExecuteTemplate(&b, "tree", tree)
  1004  	if err != nil {
  1005  		t.Fatal("exec error:", err)
  1006  	}
  1007  	result = b.String()
  1008  	if result != expect {
  1009  		t.Errorf("expected %q got %q", expect, result)
  1010  	}
  1011  }
  1012  
  1013  func TestExecuteOnNewTemplate(t *testing.T) {
  1014  	// This is issue 3872.
  1015  	New("Name").Templates()
  1016  	// This is issue 11379.
  1017  	new(Template).Templates()
  1018  	new(Template).Parse("")
  1019  	new(Template).New("abc").Parse("")
  1020  	new(Template).Execute(nil, nil)                // returns an error (but does not crash)
  1021  	new(Template).ExecuteTemplate(nil, "XXX", nil) // returns an error (but does not crash)
  1022  }
  1023  
  1024  const testTemplates = `{{define "one"}}one{{end}}{{define "two"}}two{{end}}`
  1025  
  1026  func TestMessageForExecuteEmpty(t *testing.T) {
  1027  	// Test a truly empty template.
  1028  	tmpl := New("empty")
  1029  	var b bytes.Buffer
  1030  	err := tmpl.Execute(&b, 0)
  1031  	if err == nil {
  1032  		t.Fatal("expected initial error")
  1033  	}
  1034  	got := err.Error()
  1035  	want := `template: empty: "empty" is an incomplete or empty template`
  1036  	if got != want {
  1037  		t.Errorf("expected error %s got %s", want, got)
  1038  	}
  1039  	// Add a non-empty template to check that the error is helpful.
  1040  	tests, err := New("").Parse(testTemplates)
  1041  	if err != nil {
  1042  		t.Fatal(err)
  1043  	}
  1044  	tmpl.AddParseTree("secondary", tests.Tree)
  1045  	err = tmpl.Execute(&b, 0)
  1046  	if err == nil {
  1047  		t.Fatal("expected second error")
  1048  	}
  1049  	got = err.Error()
  1050  	want = `template: empty: "empty" is an incomplete or empty template`
  1051  	if got != want {
  1052  		t.Errorf("expected error %s got %s", want, got)
  1053  	}
  1054  	// Make sure we can execute the secondary.
  1055  	err = tmpl.ExecuteTemplate(&b, "secondary", 0)
  1056  	if err != nil {
  1057  		t.Fatal(err)
  1058  	}
  1059  }
  1060  
  1061  func TestFinalForPrintf(t *testing.T) {
  1062  	tmpl, err := New("").Parse(`{{"x" | printf}}`)
  1063  	if err != nil {
  1064  		t.Fatal(err)
  1065  	}
  1066  	var b bytes.Buffer
  1067  	err = tmpl.Execute(&b, 0)
  1068  	if err != nil {
  1069  		t.Fatal(err)
  1070  	}
  1071  }
  1072  
  1073  type cmpTest struct {
  1074  	expr  string
  1075  	truth string
  1076  	ok    bool
  1077  }
  1078  
  1079  var cmpTests = []cmpTest{
  1080  	{"eq true true", "true", true},
  1081  	{"eq true false", "false", true},
  1082  	{"eq 1+2i 1+2i", "true", true},
  1083  	{"eq 1+2i 1+3i", "false", true},
  1084  	{"eq 1.5 1.5", "true", true},
  1085  	{"eq 1.5 2.5", "false", true},
  1086  	{"eq 1 1", "true", true},
  1087  	{"eq 1 2", "false", true},
  1088  	{"eq `xy` `xy`", "true", true},
  1089  	{"eq `xy` `xyz`", "false", true},
  1090  	{"eq .Uthree .Uthree", "true", true},
  1091  	{"eq .Uthree .Ufour", "false", true},
  1092  	{"eq 3 4 5 6 3", "true", true},
  1093  	{"eq 3 4 5 6 7", "false", true},
  1094  	{"ne true true", "false", true},
  1095  	{"ne true false", "true", true},
  1096  	{"ne 1+2i 1+2i", "false", true},
  1097  	{"ne 1+2i 1+3i", "true", true},
  1098  	{"ne 1.5 1.5", "false", true},
  1099  	{"ne 1.5 2.5", "true", true},
  1100  	{"ne 1 1", "false", true},
  1101  	{"ne 1 2", "true", true},
  1102  	{"ne `xy` `xy`", "false", true},
  1103  	{"ne `xy` `xyz`", "true", true},
  1104  	{"ne .Uthree .Uthree", "false", true},
  1105  	{"ne .Uthree .Ufour", "true", true},
  1106  	{"lt 1.5 1.5", "false", true},
  1107  	{"lt 1.5 2.5", "true", true},
  1108  	{"lt 1 1", "false", true},
  1109  	{"lt 1 2", "true", true},
  1110  	{"lt `xy` `xy`", "false", true},
  1111  	{"lt `xy` `xyz`", "true", true},
  1112  	{"lt .Uthree .Uthree", "false", true},
  1113  	{"lt .Uthree .Ufour", "true", true},
  1114  	{"le 1.5 1.5", "true", true},
  1115  	{"le 1.5 2.5", "true", true},
  1116  	{"le 2.5 1.5", "false", true},
  1117  	{"le 1 1", "true", true},
  1118  	{"le 1 2", "true", true},
  1119  	{"le 2 1", "false", true},
  1120  	{"le `xy` `xy`", "true", true},
  1121  	{"le `xy` `xyz`", "true", true},
  1122  	{"le `xyz` `xy`", "false", true},
  1123  	{"le .Uthree .Uthree", "true", true},
  1124  	{"le .Uthree .Ufour", "true", true},
  1125  	{"le .Ufour .Uthree", "false", true},
  1126  	{"gt 1.5 1.5", "false", true},
  1127  	{"gt 1.5 2.5", "false", true},
  1128  	{"gt 1 1", "false", true},
  1129  	{"gt 2 1", "true", true},
  1130  	{"gt 1 2", "false", true},
  1131  	{"gt `xy` `xy`", "false", true},
  1132  	{"gt `xy` `xyz`", "false", true},
  1133  	{"gt .Uthree .Uthree", "false", true},
  1134  	{"gt .Uthree .Ufour", "false", true},
  1135  	{"gt .Ufour .Uthree", "true", true},
  1136  	{"ge 1.5 1.5", "true", true},
  1137  	{"ge 1.5 2.5", "false", true},
  1138  	{"ge 2.5 1.5", "true", true},
  1139  	{"ge 1 1", "true", true},
  1140  	{"ge 1 2", "false", true},
  1141  	{"ge 2 1", "true", true},
  1142  	{"ge `xy` `xy`", "true", true},
  1143  	{"ge `xy` `xyz`", "false", true},
  1144  	{"ge `xyz` `xy`", "true", true},
  1145  	{"ge .Uthree .Uthree", "true", true},
  1146  	{"ge .Uthree .Ufour", "false", true},
  1147  	{"ge .Ufour .Uthree", "true", true},
  1148  	// Mixing signed and unsigned integers.
  1149  	{"eq .Uthree .Three", "true", true},
  1150  	{"eq .Three .Uthree", "true", true},
  1151  	{"le .Uthree .Three", "true", true},
  1152  	{"le .Three .Uthree", "true", true},
  1153  	{"ge .Uthree .Three", "true", true},
  1154  	{"ge .Three .Uthree", "true", true},
  1155  	{"lt .Uthree .Three", "false", true},
  1156  	{"lt .Three .Uthree", "false", true},
  1157  	{"gt .Uthree .Three", "false", true},
  1158  	{"gt .Three .Uthree", "false", true},
  1159  	{"eq .Ufour .Three", "false", true},
  1160  	{"lt .Ufour .Three", "false", true},
  1161  	{"gt .Ufour .Three", "true", true},
  1162  	{"eq .NegOne .Uthree", "false", true},
  1163  	{"eq .Uthree .NegOne", "false", true},
  1164  	{"ne .NegOne .Uthree", "true", true},
  1165  	{"ne .Uthree .NegOne", "true", true},
  1166  	{"lt .NegOne .Uthree", "true", true},
  1167  	{"lt .Uthree .NegOne", "false", true},
  1168  	{"le .NegOne .Uthree", "true", true},
  1169  	{"le .Uthree .NegOne", "false", true},
  1170  	{"gt .NegOne .Uthree", "false", true},
  1171  	{"gt .Uthree .NegOne", "true", true},
  1172  	{"ge .NegOne .Uthree", "false", true},
  1173  	{"ge .Uthree .NegOne", "true", true},
  1174  	{"eq (index `x` 0) 'x'", "true", true}, // The example that triggered this rule.
  1175  	{"eq (index `x` 0) 'y'", "false", true},
  1176  	{"eq .V1 .V2", "true", true},
  1177  	{"eq .Ptr .Ptr", "true", true},
  1178  	{"eq .Ptr .NilPtr", "false", true},
  1179  	{"eq .NilPtr .NilPtr", "true", true},
  1180  	{"eq .Iface1 .Iface1", "true", true},
  1181  	{"eq .Iface1 .Iface2", "false", true},
  1182  	{"eq .Iface2 .Iface2", "true", true},
  1183  	// Errors
  1184  	{"eq `xy` 1", "", false},       // Different types.
  1185  	{"eq 2 2.0", "", false},        // Different types.
  1186  	{"lt true true", "", false},    // Unordered types.
  1187  	{"lt 1+0i 1+0i", "", false},    // Unordered types.
  1188  	{"eq .Ptr 1", "", false},       // Incompatible types.
  1189  	{"eq .Ptr .NegOne", "", false}, // Incompatible types.
  1190  	{"eq .Map .Map", "", false},    // Uncomparable types.
  1191  	{"eq .Map .V1", "", false},     // Uncomparable types.
  1192  }
  1193  
  1194  func TestComparison(t *testing.T) {
  1195  	b := new(bytes.Buffer)
  1196  	var cmpStruct = struct {
  1197  		Uthree, Ufour  uint
  1198  		NegOne, Three  int
  1199  		Ptr, NilPtr    *int
  1200  		Map            map[int]int
  1201  		V1, V2         V
  1202  		Iface1, Iface2 fmt.Stringer
  1203  	}{
  1204  		Uthree: 3,
  1205  		Ufour:  4,
  1206  		NegOne: -1,
  1207  		Three:  3,
  1208  		Ptr:    new(int),
  1209  		Iface1: b,
  1210  	}
  1211  	for _, test := range cmpTests {
  1212  		text := fmt.Sprintf("{{if %s}}true{{else}}false{{end}}", test.expr)
  1213  		tmpl, err := New("empty").Parse(text)
  1214  		if err != nil {
  1215  			t.Fatalf("%q: %s", test.expr, err)
  1216  		}
  1217  		b.Reset()
  1218  		err = tmpl.Execute(b, &cmpStruct)
  1219  		if test.ok && err != nil {
  1220  			t.Errorf("%s errored incorrectly: %s", test.expr, err)
  1221  			continue
  1222  		}
  1223  		if !test.ok && err == nil {
  1224  			t.Errorf("%s did not error", test.expr)
  1225  			continue
  1226  		}
  1227  		if b.String() != test.truth {
  1228  			t.Errorf("%s: want %s; got %s", test.expr, test.truth, b.String())
  1229  		}
  1230  	}
  1231  }
  1232  
  1233  func TestMissingMapKey(t *testing.T) {
  1234  	data := map[string]int{
  1235  		"x": 99,
  1236  	}
  1237  	tmpl, err := New("t1").Parse("{{.x}} {{.y}}")
  1238  	if err != nil {
  1239  		t.Fatal(err)
  1240  	}
  1241  	var b bytes.Buffer
  1242  	// By default, just get "<no value>"
  1243  	err = tmpl.Execute(&b, data)
  1244  	if err != nil {
  1245  		t.Fatal(err)
  1246  	}
  1247  	want := "99 <no value>"
  1248  	got := b.String()
  1249  	if got != want {
  1250  		t.Errorf("got %q; expected %q", got, want)
  1251  	}
  1252  	// Same if we set the option explicitly to the default.
  1253  	tmpl.Option("missingkey=default")
  1254  	b.Reset()
  1255  	err = tmpl.Execute(&b, data)
  1256  	if err != nil {
  1257  		t.Fatal("default:", err)
  1258  	}
  1259  	want = "99 <no value>"
  1260  	got = b.String()
  1261  	if got != want {
  1262  		t.Errorf("got %q; expected %q", got, want)
  1263  	}
  1264  	// Next we ask for a zero value
  1265  	tmpl.Option("missingkey=zero")
  1266  	b.Reset()
  1267  	err = tmpl.Execute(&b, data)
  1268  	if err != nil {
  1269  		t.Fatal("zero:", err)
  1270  	}
  1271  	want = "99 0"
  1272  	got = b.String()
  1273  	if got != want {
  1274  		t.Errorf("got %q; expected %q", got, want)
  1275  	}
  1276  	// Now we ask for an error.
  1277  	tmpl.Option("missingkey=error")
  1278  	err = tmpl.Execute(&b, data)
  1279  	if err == nil {
  1280  		t.Errorf("expected error; got none")
  1281  	}
  1282  	// same Option, but now a nil interface: ask for an error
  1283  	err = tmpl.Execute(&b, nil)
  1284  	t.Log(err)
  1285  	if err == nil {
  1286  		t.Errorf("expected error for nil-interface; got none")
  1287  	}
  1288  }
  1289  
  1290  // Test that the error message for multiline unterminated string
  1291  // refers to the line number of the opening quote.
  1292  func TestUnterminatedStringError(t *testing.T) {
  1293  	_, err := New("X").Parse("hello\n\n{{`unterminated\n\n\n\n}}\n some more\n\n")
  1294  	if err == nil {
  1295  		t.Fatal("expected error")
  1296  	}
  1297  	str := err.Error()
  1298  	if !strings.Contains(str, "X:3: unexpected unterminated raw quoted string") {
  1299  		t.Fatalf("unexpected error: %s", str)
  1300  	}
  1301  }
  1302  
  1303  const alwaysErrorText = "always be failing"
  1304  
  1305  var alwaysError = errors.New(alwaysErrorText)
  1306  
  1307  type ErrorWriter int
  1308  
  1309  func (e ErrorWriter) Write(p []byte) (int, error) {
  1310  	return 0, alwaysError
  1311  }
  1312  
  1313  func TestExecuteGivesExecError(t *testing.T) {
  1314  	// First, a non-execution error shouldn't be an ExecError.
  1315  	tmpl, err := New("X").Parse("hello")
  1316  	if err != nil {
  1317  		t.Fatal(err)
  1318  	}
  1319  	err = tmpl.Execute(ErrorWriter(0), 0)
  1320  	if err == nil {
  1321  		t.Fatal("expected error; got none")
  1322  	}
  1323  	if err.Error() != alwaysErrorText {
  1324  		t.Errorf("expected %q error; got %q", alwaysErrorText, err)
  1325  	}
  1326  	// This one should be an ExecError.
  1327  	tmpl, err = New("X").Parse("hello, {{.X.Y}}")
  1328  	if err != nil {
  1329  		t.Fatal(err)
  1330  	}
  1331  	err = tmpl.Execute(ioutil.Discard, 0)
  1332  	if err == nil {
  1333  		t.Fatal("expected error; got none")
  1334  	}
  1335  	eerr, ok := err.(ExecError)
  1336  	if !ok {
  1337  		t.Fatalf("did not expect ExecError %s", eerr)
  1338  	}
  1339  	expect := "field X in type int"
  1340  	if !strings.Contains(err.Error(), expect) {
  1341  		t.Errorf("expected %q; got %q", expect, err)
  1342  	}
  1343  }
  1344  
  1345  func funcNameTestFunc() int {
  1346  	return 0
  1347  }
  1348  
  1349  func TestGoodFuncNames(t *testing.T) {
  1350  	names := []string{
  1351  		"_",
  1352  		"a",
  1353  		"a1",
  1354  		"a1",
  1355  		"Ӵ",
  1356  	}
  1357  	for _, name := range names {
  1358  		tmpl := New("X").Funcs(
  1359  			FuncMap{
  1360  				name: funcNameTestFunc,
  1361  			},
  1362  		)
  1363  		if tmpl == nil {
  1364  			t.Fatalf("nil result for %q", name)
  1365  		}
  1366  	}
  1367  }
  1368  
  1369  func TestBadFuncNames(t *testing.T) {
  1370  	names := []string{
  1371  		"",
  1372  		"2",
  1373  		"a-b",
  1374  	}
  1375  	for _, name := range names {
  1376  		testBadFuncName(name, t)
  1377  	}
  1378  }
  1379  
  1380  func testBadFuncName(name string, t *testing.T) {
  1381  	t.Helper()
  1382  	defer func() {
  1383  		recover()
  1384  	}()
  1385  	New("X").Funcs(
  1386  		FuncMap{
  1387  			name: funcNameTestFunc,
  1388  		},
  1389  	)
  1390  	// If we get here, the name did not cause a panic, which is how Funcs
  1391  	// reports an error.
  1392  	t.Errorf("%q succeeded incorrectly as function name", name)
  1393  }
  1394  
  1395  func TestBlock(t *testing.T) {
  1396  	const (
  1397  		input   = `a({{block "inner" .}}bar({{.}})baz{{end}})b`
  1398  		want    = `a(bar(hello)baz)b`
  1399  		overlay = `{{define "inner"}}foo({{.}})bar{{end}}`
  1400  		want2   = `a(foo(goodbye)bar)b`
  1401  	)
  1402  	tmpl, err := New("outer").Parse(input)
  1403  	if err != nil {
  1404  		t.Fatal(err)
  1405  	}
  1406  	tmpl2, err := Must(tmpl.Clone()).Parse(overlay)
  1407  	if err != nil {
  1408  		t.Fatal(err)
  1409  	}
  1410  
  1411  	var buf bytes.Buffer
  1412  	if err := tmpl.Execute(&buf, "hello"); err != nil {
  1413  		t.Fatal(err)
  1414  	}
  1415  	if got := buf.String(); got != want {
  1416  		t.Errorf("got %q, want %q", got, want)
  1417  	}
  1418  
  1419  	buf.Reset()
  1420  	if err := tmpl2.Execute(&buf, "goodbye"); err != nil {
  1421  		t.Fatal(err)
  1422  	}
  1423  	if got := buf.String(); got != want2 {
  1424  		t.Errorf("got %q, want %q", got, want2)
  1425  	}
  1426  }
  1427  
  1428  func TestEvalFieldErrors(t *testing.T) {
  1429  	tests := []struct {
  1430  		name, src string
  1431  		value     interface{}
  1432  		want      string
  1433  	}{
  1434  		{
  1435  			// Check that calling an invalid field on nil pointer
  1436  			// prints a field error instead of a distracting nil
  1437  			// pointer error. https://golang.org/issue/15125
  1438  			"MissingFieldOnNil",
  1439  			"{{.MissingField}}",
  1440  			(*T)(nil),
  1441  			"can't evaluate field MissingField in type *template.T",
  1442  		},
  1443  		{
  1444  			"MissingFieldOnNonNil",
  1445  			"{{.MissingField}}",
  1446  			&T{},
  1447  			"can't evaluate field MissingField in type *template.T",
  1448  		},
  1449  		{
  1450  			"ExistingFieldOnNil",
  1451  			"{{.X}}",
  1452  			(*T)(nil),
  1453  			"nil pointer evaluating *template.T.X",
  1454  		},
  1455  		{
  1456  			"MissingKeyOnNilMap",
  1457  			"{{.MissingKey}}",
  1458  			(*map[string]string)(nil),
  1459  			"nil pointer evaluating *map[string]string.MissingKey",
  1460  		},
  1461  		{
  1462  			"MissingKeyOnNilMapPtr",
  1463  			"{{.MissingKey}}",
  1464  			(*map[string]string)(nil),
  1465  			"nil pointer evaluating *map[string]string.MissingKey",
  1466  		},
  1467  		{
  1468  			"MissingKeyOnMapPtrToNil",
  1469  			"{{.MissingKey}}",
  1470  			&map[string]string{},
  1471  			"<nil>",
  1472  		},
  1473  	}
  1474  	for _, tc := range tests {
  1475  		t.Run(tc.name, func(t *testing.T) {
  1476  			tmpl := Must(New("tmpl").Parse(tc.src))
  1477  			err := tmpl.Execute(ioutil.Discard, tc.value)
  1478  			got := "<nil>"
  1479  			if err != nil {
  1480  				got = err.Error()
  1481  			}
  1482  			if !strings.HasSuffix(got, tc.want) {
  1483  				t.Fatalf("got error %q, want %q", got, tc.want)
  1484  			}
  1485  		})
  1486  	}
  1487  }
  1488  
  1489  func TestMaxExecDepth(t *testing.T) {
  1490  	if testing.Short() {
  1491  		t.Skip("skipping in -short mode")
  1492  	}
  1493  	tmpl := Must(New("tmpl").Parse(`{{template "tmpl" .}}`))
  1494  	err := tmpl.Execute(ioutil.Discard, nil)
  1495  	got := "<nil>"
  1496  	if err != nil {
  1497  		got = err.Error()
  1498  	}
  1499  	const want = "exceeded maximum template depth"
  1500  	if !strings.Contains(got, want) {
  1501  		t.Errorf("got error %q; want %q", got, want)
  1502  	}
  1503  }
  1504  
  1505  func TestAddrOfIndex(t *testing.T) {
  1506  	// golang.org/issue/14916.
  1507  	// Before index worked on reflect.Values, the .String could not be
  1508  	// found on the (incorrectly unaddressable) V value,
  1509  	// in contrast to range, which worked fine.
  1510  	// Also testing that passing a reflect.Value to tmpl.Execute works.
  1511  	texts := []string{
  1512  		`{{range .}}{{.String}}{{end}}`,
  1513  		`{{with index . 0}}{{.String}}{{end}}`,
  1514  	}
  1515  	for _, text := range texts {
  1516  		tmpl := Must(New("tmpl").Parse(text))
  1517  		var buf bytes.Buffer
  1518  		err := tmpl.Execute(&buf, reflect.ValueOf([]V{{1}}))
  1519  		if err != nil {
  1520  			t.Fatalf("%s: Execute: %v", text, err)
  1521  		}
  1522  		if buf.String() != "<1>" {
  1523  			t.Fatalf("%s: template output = %q, want %q", text, &buf, "<1>")
  1524  		}
  1525  	}
  1526  }
  1527  
  1528  func TestInterfaceValues(t *testing.T) {
  1529  	// golang.org/issue/17714.
  1530  	// Before index worked on reflect.Values, interface values
  1531  	// were always implicitly promoted to the underlying value,
  1532  	// except that nil interfaces were promoted to the zero reflect.Value.
  1533  	// Eliminating a round trip to interface{} and back to reflect.Value
  1534  	// eliminated this promotion, breaking these cases.
  1535  	tests := []struct {
  1536  		text string
  1537  		out  string
  1538  	}{
  1539  		{`{{index .Nil 1}}`, "ERROR: index of untyped nil"},
  1540  		{`{{index .Slice 2}}`, "2"},
  1541  		{`{{index .Slice .Two}}`, "2"},
  1542  		{`{{call .Nil 1}}`, "ERROR: call of nil"},
  1543  		{`{{call .PlusOne 1}}`, "2"},
  1544  		{`{{call .PlusOne .One}}`, "2"},
  1545  		{`{{and (index .Slice 0) true}}`, "0"},
  1546  		{`{{and .Zero true}}`, "0"},
  1547  		{`{{and (index .Slice 1) false}}`, "false"},
  1548  		{`{{and .One false}}`, "false"},
  1549  		{`{{or (index .Slice 0) false}}`, "false"},
  1550  		{`{{or .Zero false}}`, "false"},
  1551  		{`{{or (index .Slice 1) true}}`, "1"},
  1552  		{`{{or .One true}}`, "1"},
  1553  		{`{{not (index .Slice 0)}}`, "true"},
  1554  		{`{{not .Zero}}`, "true"},
  1555  		{`{{not (index .Slice 1)}}`, "false"},
  1556  		{`{{not .One}}`, "false"},
  1557  		{`{{eq (index .Slice 0) .Zero}}`, "true"},
  1558  		{`{{eq (index .Slice 1) .One}}`, "true"},
  1559  		{`{{ne (index .Slice 0) .Zero}}`, "false"},
  1560  		{`{{ne (index .Slice 1) .One}}`, "false"},
  1561  		{`{{ge (index .Slice 0) .One}}`, "false"},
  1562  		{`{{ge (index .Slice 1) .Zero}}`, "true"},
  1563  		{`{{gt (index .Slice 0) .One}}`, "false"},
  1564  		{`{{gt (index .Slice 1) .Zero}}`, "true"},
  1565  		{`{{le (index .Slice 0) .One}}`, "true"},
  1566  		{`{{le (index .Slice 1) .Zero}}`, "false"},
  1567  		{`{{lt (index .Slice 0) .One}}`, "true"},
  1568  		{`{{lt (index .Slice 1) .Zero}}`, "false"},
  1569  	}
  1570  
  1571  	for _, tt := range tests {
  1572  		tmpl := Must(New("tmpl").Parse(tt.text))
  1573  		var buf bytes.Buffer
  1574  		err := tmpl.Execute(&buf, map[string]interface{}{
  1575  			"PlusOne": func(n int) int {
  1576  				return n + 1
  1577  			},
  1578  			"Slice": []int{0, 1, 2, 3},
  1579  			"One":   1,
  1580  			"Two":   2,
  1581  			"Nil":   nil,
  1582  			"Zero":  0,
  1583  		})
  1584  		if strings.HasPrefix(tt.out, "ERROR:") {
  1585  			e := strings.TrimSpace(strings.TrimPrefix(tt.out, "ERROR:"))
  1586  			if err == nil || !strings.Contains(err.Error(), e) {
  1587  				t.Errorf("%s: Execute: %v, want error %q", tt.text, err, e)
  1588  			}
  1589  			continue
  1590  		}
  1591  		if err != nil {
  1592  			t.Errorf("%s: Execute: %v", tt.text, err)
  1593  			continue
  1594  		}
  1595  		if buf.String() != tt.out {
  1596  			t.Errorf("%s: template output = %q, want %q", tt.text, &buf, tt.out)
  1597  		}
  1598  	}
  1599  }
  1600  
  1601  // Check that panics during calls are recovered and returned as errors.
  1602  func TestExecutePanicDuringCall(t *testing.T) {
  1603  	funcs := map[string]interface{}{
  1604  		"doPanic": func() string {
  1605  			panic("custom panic string")
  1606  		},
  1607  	}
  1608  	tests := []struct {
  1609  		name    string
  1610  		input   string
  1611  		data    interface{}
  1612  		wantErr string
  1613  	}{
  1614  		{
  1615  			"direct func call panics",
  1616  			"{{doPanic}}", (*T)(nil),
  1617  			`template: t:1:2: executing "t" at <doPanic>: error calling doPanic: custom panic string`,
  1618  		},
  1619  		{
  1620  			"indirect func call panics",
  1621  			"{{call doPanic}}", (*T)(nil),
  1622  			`template: t:1:7: executing "t" at <doPanic>: error calling doPanic: custom panic string`,
  1623  		},
  1624  		{
  1625  			"direct method call panics",
  1626  			"{{.GetU}}", (*T)(nil),
  1627  			`template: t:1:2: executing "t" at <.GetU>: error calling GetU: runtime error: invalid memory address or nil pointer dereference`,
  1628  		},
  1629  		{
  1630  			"indirect method call panics",
  1631  			"{{call .GetU}}", (*T)(nil),
  1632  			`template: t:1:7: executing "t" at <.GetU>: error calling GetU: runtime error: invalid memory address or nil pointer dereference`,
  1633  		},
  1634  		{
  1635  			"func field call panics",
  1636  			"{{call .PanicFunc}}", tVal,
  1637  			`template: t:1:2: executing "t" at <call .PanicFunc>: error calling call: test panic`,
  1638  		},
  1639  		{
  1640  			"method call on nil interface",
  1641  			"{{.NonEmptyInterfaceNil.Method0}}", tVal,
  1642  			`template: t:1:23: executing "t" at <.NonEmptyInterfaceNil.Method0>: nil pointer evaluating template.I.Method0`,
  1643  		},
  1644  	}
  1645  	for _, tc := range tests {
  1646  		b := new(bytes.Buffer)
  1647  		tmpl, err := New("t").Funcs(funcs).Parse(tc.input)
  1648  		if err != nil {
  1649  			t.Fatalf("parse error: %s", err)
  1650  		}
  1651  		err = tmpl.Execute(b, tc.data)
  1652  		if err == nil {
  1653  			t.Errorf("%s: expected error; got none", tc.name)
  1654  		} else if !strings.Contains(err.Error(), tc.wantErr) {
  1655  			if *debug {
  1656  				fmt.Printf("%s: test execute error: %s\n", tc.name, err)
  1657  			}
  1658  			t.Errorf("%s: expected error:\n%s\ngot:\n%s", tc.name, tc.wantErr, err)
  1659  		}
  1660  	}
  1661  }
  1662  
  1663  // Issue 31810. Check that a parenthesized first argument behaves properly.
  1664  func TestIssue31810(t *testing.T) {
  1665  	// A simple value with no arguments is fine.
  1666  	var b bytes.Buffer
  1667  	const text = "{{ (.)  }}"
  1668  	tmpl, err := New("").Parse(text)
  1669  	if err != nil {
  1670  		t.Error(err)
  1671  	}
  1672  	err = tmpl.Execute(&b, "result")
  1673  	if err != nil {
  1674  		t.Error(err)
  1675  	}
  1676  	if b.String() != "result" {
  1677  		t.Errorf("%s got %q, expected %q", text, b.String(), "result")
  1678  	}
  1679  
  1680  	// Even a plain function fails - need to use call.
  1681  	f := func() string { return "result" }
  1682  	b.Reset()
  1683  	err = tmpl.Execute(&b, f)
  1684  	if err == nil {
  1685  		t.Error("expected error with no call, got none")
  1686  	}
  1687  
  1688  	// Works if the function is explicitly called.
  1689  	const textCall = "{{ (call .)  }}"
  1690  	tmpl, err = New("").Parse(textCall)
  1691  	b.Reset()
  1692  	err = tmpl.Execute(&b, f)
  1693  	if err != nil {
  1694  		t.Error(err)
  1695  	}
  1696  	if b.String() != "result" {
  1697  		t.Errorf("%s got %q, expected %q", textCall, b.String(), "result")
  1698  	}
  1699  }
  1700  

View as plain text