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