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