github.com/corona10/go@v0.0.0-20180224231303-7a218942be57/src/text/template/exec_test.go (about)

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