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