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