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