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