...
Run Format

Source file src/text/template/exec_test.go

Documentation: text/template

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

View as plain text