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