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