github.com/tcnksm/go@v0.0.0-20141208075154-439b32936367/src/text/template/exec_test.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package template 6 7 import ( 8 "bytes" 9 "errors" 10 "flag" 11 "fmt" 12 "reflect" 13 "strings" 14 "testing" 15 ) 16 17 var debug = flag.Bool("debug", false, "show the errors produced by the tests") 18 19 // T has lots of interesting pieces to use to test execution. 20 type T struct { 21 // Basics 22 True bool 23 I int 24 U16 uint16 25 X string 26 FloatZero float64 27 ComplexZero complex128 28 // Nested structs. 29 U *U 30 // Struct with String method. 31 V0 V 32 V1, V2 *V 33 // Struct with Error method. 34 W0 W 35 W1, W2 *W 36 // Slices 37 SI []int 38 SIEmpty []int 39 SB []bool 40 // Maps 41 MSI map[string]int 42 MSIone map[string]int // one element, for deterministic output 43 MSIEmpty map[string]int 44 MXI map[interface{}]int 45 MII map[int]int 46 SMSI []map[string]int 47 // Empty interfaces; used to see if we can dig inside one. 48 Empty0 interface{} // nil 49 Empty1 interface{} 50 Empty2 interface{} 51 Empty3 interface{} 52 Empty4 interface{} 53 // Non-empty interface. 54 NonEmptyInterface I 55 // Stringer. 56 Str fmt.Stringer 57 Err error 58 // Pointers 59 PI *int 60 PS *string 61 PSI *[]int 62 NIL *int 63 // Function (not method) 64 BinaryFunc func(string, string) string 65 VariadicFunc func(...string) string 66 VariadicFuncInt func(int, ...string) string 67 NilOKFunc func(*int) bool 68 ErrFunc func() (string, error) 69 // Template to test evaluation of templates. 70 Tmpl *Template 71 // Unexported field; cannot be accessed by template. 72 unexported int 73 } 74 75 type U struct { 76 V string 77 } 78 79 type V struct { 80 j int 81 } 82 83 func (v *V) String() string { 84 if v == nil { 85 return "nilV" 86 } 87 return fmt.Sprintf("<%d>", v.j) 88 } 89 90 type W struct { 91 k int 92 } 93 94 func (w *W) Error() string { 95 if w == nil { 96 return "nilW" 97 } 98 return fmt.Sprintf("[%d]", w.k) 99 } 100 101 var tVal = &T{ 102 True: true, 103 I: 17, 104 U16: 16, 105 X: "x", 106 U: &U{"v"}, 107 V0: V{6666}, 108 V1: &V{7777}, // leave V2 as nil 109 W0: W{888}, 110 W1: &W{999}, // leave W2 as nil 111 SI: []int{3, 4, 5}, 112 SB: []bool{true, false}, 113 MSI: map[string]int{"one": 1, "two": 2, "three": 3}, 114 MSIone: map[string]int{"one": 1}, 115 MXI: map[interface{}]int{"one": 1}, 116 MII: map[int]int{1: 1}, 117 SMSI: []map[string]int{ 118 {"one": 1, "two": 2}, 119 {"eleven": 11, "twelve": 12}, 120 }, 121 Empty1: 3, 122 Empty2: "empty2", 123 Empty3: []int{7, 8}, 124 Empty4: &U{"UinEmpty"}, 125 NonEmptyInterface: new(T), 126 Str: bytes.NewBuffer([]byte("foozle")), 127 Err: errors.New("erroozle"), 128 PI: newInt(23), 129 PS: newString("a string"), 130 PSI: newIntSlice(21, 22, 23), 131 BinaryFunc: func(a, b string) string { return fmt.Sprintf("[%s=%s]", a, b) }, 132 VariadicFunc: func(s ...string) string { return fmt.Sprint("<", strings.Join(s, "+"), ">") }, 133 VariadicFuncInt: func(a int, s ...string) string { return fmt.Sprint(a, "=<", strings.Join(s, "+"), ">") }, 134 NilOKFunc: func(s *int) bool { return s == nil }, 135 ErrFunc: func() (string, error) { return "bla", nil }, 136 Tmpl: Must(New("x").Parse("test template")), // "x" is the value of .X 137 } 138 139 // A non-empty interface. 140 type I interface { 141 Method0() string 142 } 143 144 var iVal I = tVal 145 146 // Helpers for creation. 147 func newInt(n int) *int { 148 return &n 149 } 150 151 func newString(s string) *string { 152 return &s 153 } 154 155 func newIntSlice(n ...int) *[]int { 156 p := new([]int) 157 *p = make([]int, len(n)) 158 copy(*p, n) 159 return p 160 } 161 162 // Simple methods with and without arguments. 163 func (t *T) Method0() string { 164 return "M0" 165 } 166 167 func (t *T) Method1(a int) int { 168 return a 169 } 170 171 func (t *T) Method2(a uint16, b string) string { 172 return fmt.Sprintf("Method2: %d %s", a, b) 173 } 174 175 func (t *T) Method3(v interface{}) string { 176 return fmt.Sprintf("Method3: %v", v) 177 } 178 179 func (t *T) Copy() *T { 180 n := new(T) 181 *n = *t 182 return n 183 } 184 185 func (t *T) MAdd(a int, b []int) []int { 186 v := make([]int, len(b)) 187 for i, x := range b { 188 v[i] = x + a 189 } 190 return v 191 } 192 193 var myError = errors.New("my error") 194 195 // MyError returns a value and an error according to its argument. 196 func (t *T) MyError(error bool) (bool, error) { 197 if error { 198 return true, myError 199 } 200 return false, nil 201 } 202 203 // A few methods to test chaining. 204 func (t *T) GetU() *U { 205 return t.U 206 } 207 208 func (u *U) TrueFalse(b bool) string { 209 if b { 210 return "true" 211 } 212 return "" 213 } 214 215 func typeOf(arg interface{}) string { 216 return fmt.Sprintf("%T", arg) 217 } 218 219 type execTest struct { 220 name string 221 input string 222 output string 223 data interface{} 224 ok bool 225 } 226 227 // bigInt and bigUint are hex string representing numbers either side 228 // of the max int boundary. 229 // We do it this way so the test doesn't depend on ints being 32 bits. 230 var ( 231 bigInt = fmt.Sprintf("0x%x", int(1<<uint(reflect.TypeOf(0).Bits()-1)-1)) 232 bigUint = fmt.Sprintf("0x%x", uint(1<<uint(reflect.TypeOf(0).Bits()-1))) 233 ) 234 235 var execTests = []execTest{ 236 // Trivial cases. 237 {"empty", "", "", nil, true}, 238 {"text", "some text", "some text", nil, true}, 239 {"nil action", "{{nil}}", "", nil, false}, 240 241 // Ideal constants. 242 {"ideal int", "{{typeOf 3}}", "int", 0, true}, 243 {"ideal float", "{{typeOf 1.0}}", "float64", 0, true}, 244 {"ideal exp float", "{{typeOf 1e1}}", "float64", 0, true}, 245 {"ideal complex", "{{typeOf 1i}}", "complex128", 0, true}, 246 {"ideal int", "{{typeOf " + bigInt + "}}", "int", 0, true}, 247 {"ideal too big", "{{typeOf " + bigUint + "}}", "", 0, false}, 248 {"ideal nil without type", "{{nil}}", "", 0, false}, 249 250 // Fields of structs. 251 {".X", "-{{.X}}-", "-x-", tVal, true}, 252 {".U.V", "-{{.U.V}}-", "-v-", tVal, true}, 253 {".unexported", "{{.unexported}}", "", tVal, false}, 254 255 // Fields on maps. 256 {"map .one", "{{.MSI.one}}", "1", tVal, true}, 257 {"map .two", "{{.MSI.two}}", "2", tVal, true}, 258 {"map .NO", "{{.MSI.NO}}", "<no value>", tVal, true}, 259 {"map .one interface", "{{.MXI.one}}", "1", tVal, true}, 260 {"map .WRONG args", "{{.MSI.one 1}}", "", tVal, false}, 261 {"map .WRONG type", "{{.MII.one}}", "", tVal, false}, 262 263 // Dots of all kinds to test basic evaluation. 264 {"dot int", "<{{.}}>", "<13>", 13, true}, 265 {"dot uint", "<{{.}}>", "<14>", uint(14), true}, 266 {"dot float", "<{{.}}>", "<15.1>", 15.1, true}, 267 {"dot bool", "<{{.}}>", "<true>", true, true}, 268 {"dot complex", "<{{.}}>", "<(16.2-17i)>", 16.2 - 17i, true}, 269 {"dot string", "<{{.}}>", "<hello>", "hello", true}, 270 {"dot slice", "<{{.}}>", "<[-1 -2 -3]>", []int{-1, -2, -3}, true}, 271 {"dot map", "<{{.}}>", "<map[two:22]>", map[string]int{"two": 22}, true}, 272 {"dot struct", "<{{.}}>", "<{7 seven}>", struct { 273 a int 274 b string 275 }{7, "seven"}, true}, 276 277 // Variables. 278 {"$ int", "{{$}}", "123", 123, true}, 279 {"$.I", "{{$.I}}", "17", tVal, true}, 280 {"$.U.V", "{{$.U.V}}", "v", tVal, true}, 281 {"declare in action", "{{$x := $.U.V}}{{$x}}", "v", tVal, true}, 282 283 // Type with String method. 284 {"V{6666}.String()", "-{{.V0}}-", "-<6666>-", tVal, true}, 285 {"&V{7777}.String()", "-{{.V1}}-", "-<7777>-", tVal, true}, 286 {"(*V)(nil).String()", "-{{.V2}}-", "-nilV-", tVal, true}, 287 288 // Type with Error method. 289 {"W{888}.Error()", "-{{.W0}}-", "-[888]-", tVal, true}, 290 {"&W{999}.Error()", "-{{.W1}}-", "-[999]-", tVal, true}, 291 {"(*W)(nil).Error()", "-{{.W2}}-", "-nilW-", tVal, true}, 292 293 // Pointers. 294 {"*int", "{{.PI}}", "23", tVal, true}, 295 {"*string", "{{.PS}}", "a string", tVal, true}, 296 {"*[]int", "{{.PSI}}", "[21 22 23]", tVal, true}, 297 {"*[]int[1]", "{{index .PSI 1}}", "22", tVal, true}, 298 {"NIL", "{{.NIL}}", "<nil>", tVal, true}, 299 300 // Empty interfaces holding values. 301 {"empty nil", "{{.Empty0}}", "<no value>", tVal, true}, 302 {"empty with int", "{{.Empty1}}", "3", tVal, true}, 303 {"empty with string", "{{.Empty2}}", "empty2", tVal, true}, 304 {"empty with slice", "{{.Empty3}}", "[7 8]", tVal, true}, 305 {"empty with struct", "{{.Empty4}}", "{UinEmpty}", tVal, true}, 306 {"empty with struct, field", "{{.Empty4.V}}", "UinEmpty", tVal, true}, 307 308 // Method calls. 309 {".Method0", "-{{.Method0}}-", "-M0-", tVal, true}, 310 {".Method1(1234)", "-{{.Method1 1234}}-", "-1234-", tVal, true}, 311 {".Method1(.I)", "-{{.Method1 .I}}-", "-17-", tVal, true}, 312 {".Method2(3, .X)", "-{{.Method2 3 .X}}-", "-Method2: 3 x-", tVal, true}, 313 {".Method2(.U16, `str`)", "-{{.Method2 .U16 `str`}}-", "-Method2: 16 str-", tVal, true}, 314 {".Method2(.U16, $x)", "{{if $x := .X}}-{{.Method2 .U16 $x}}{{end}}-", "-Method2: 16 x-", tVal, true}, 315 {".Method3(nil constant)", "-{{.Method3 nil}}-", "-Method3: <nil>-", tVal, true}, 316 {".Method3(nil value)", "-{{.Method3 .MXI.unset}}-", "-Method3: <nil>-", tVal, true}, 317 {"method on var", "{{if $x := .}}-{{$x.Method2 .U16 $x.X}}{{end}}-", "-Method2: 16 x-", tVal, true}, 318 {"method on chained var", 319 "{{range .MSIone}}{{if $.U.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}", 320 "true", tVal, true}, 321 {"chained method", 322 "{{range .MSIone}}{{if $.GetU.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}", 323 "true", tVal, true}, 324 {"chained method on variable", 325 "{{with $x := .}}{{with .SI}}{{$.GetU.TrueFalse $.True}}{{end}}{{end}}", 326 "true", tVal, true}, 327 {".NilOKFunc not nil", "{{call .NilOKFunc .PI}}", "false", tVal, true}, 328 {".NilOKFunc nil", "{{call .NilOKFunc nil}}", "true", tVal, true}, 329 330 // Function call builtin. 331 {".BinaryFunc", "{{call .BinaryFunc `1` `2`}}", "[1=2]", tVal, true}, 332 {".VariadicFunc0", "{{call .VariadicFunc}}", "<>", tVal, true}, 333 {".VariadicFunc2", "{{call .VariadicFunc `he` `llo`}}", "<he+llo>", tVal, true}, 334 {".VariadicFuncInt", "{{call .VariadicFuncInt 33 `he` `llo`}}", "33=<he+llo>", tVal, true}, 335 {"if .BinaryFunc call", "{{ if .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{end}}", "[1=2]", tVal, true}, 336 {"if not .BinaryFunc call", "{{ if not .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{else}}No{{end}}", "No", tVal, true}, 337 {"Interface Call", `{{stringer .S}}`, "foozle", map[string]interface{}{"S": bytes.NewBufferString("foozle")}, true}, 338 {".ErrFunc", "{{call .ErrFunc}}", "bla", tVal, true}, 339 340 // Erroneous function calls (check args). 341 {".BinaryFuncTooFew", "{{call .BinaryFunc `1`}}", "", tVal, false}, 342 {".BinaryFuncTooMany", "{{call .BinaryFunc `1` `2` `3`}}", "", tVal, false}, 343 {".BinaryFuncBad0", "{{call .BinaryFunc 1 3}}", "", tVal, false}, 344 {".BinaryFuncBad1", "{{call .BinaryFunc `1` 3}}", "", tVal, false}, 345 {".VariadicFuncBad0", "{{call .VariadicFunc 3}}", "", tVal, false}, 346 {".VariadicFuncIntBad0", "{{call .VariadicFuncInt}}", "", tVal, false}, 347 {".VariadicFuncIntBad`", "{{call .VariadicFuncInt `x`}}", "", tVal, false}, 348 {".VariadicFuncNilBad", "{{call .VariadicFunc nil}}", "", tVal, false}, 349 350 // Pipelines. 351 {"pipeline", "-{{.Method0 | .Method2 .U16}}-", "-Method2: 16 M0-", tVal, true}, 352 {"pipeline func", "-{{call .VariadicFunc `llo` | call .VariadicFunc `he` }}-", "-<he+<llo>>-", tVal, true}, 353 354 // Parenthesized expressions 355 {"parens in pipeline", "{{printf `%d %d %d` (1) (2 | add 3) (add 4 (add 5 6))}}", "1 5 15", tVal, true}, 356 357 // Parenthesized expressions with field accesses 358 {"parens: $ in paren", "{{($).X}}", "x", tVal, true}, 359 {"parens: $.GetU in paren", "{{($.GetU).V}}", "v", tVal, true}, 360 {"parens: $ in paren in pipe", "{{($ | echo).X}}", "x", tVal, true}, 361 {"parens: spaces and args", `{{(makemap "up" "down" "left" "right").left}}`, "right", tVal, true}, 362 363 // If. 364 {"if true", "{{if true}}TRUE{{end}}", "TRUE", tVal, true}, 365 {"if false", "{{if false}}TRUE{{else}}FALSE{{end}}", "FALSE", tVal, true}, 366 {"if nil", "{{if nil}}TRUE{{end}}", "", tVal, false}, 367 {"if 1", "{{if 1}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true}, 368 {"if 0", "{{if 0}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true}, 369 {"if 1.5", "{{if 1.5}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true}, 370 {"if 0.0", "{{if .FloatZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true}, 371 {"if 1.5i", "{{if 1.5i}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true}, 372 {"if 0.0i", "{{if .ComplexZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true}, 373 {"if emptystring", "{{if ``}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true}, 374 {"if string", "{{if `notempty`}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true}, 375 {"if emptyslice", "{{if .SIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true}, 376 {"if slice", "{{if .SI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true}, 377 {"if emptymap", "{{if .MSIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true}, 378 {"if map", "{{if .MSI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true}, 379 {"if map unset", "{{if .MXI.none}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true}, 380 {"if map not unset", "{{if not .MXI.none}}ZERO{{else}}NON-ZERO{{end}}", "ZERO", tVal, true}, 381 {"if $x with $y int", "{{if $x := true}}{{with $y := .I}}{{$x}},{{$y}}{{end}}{{end}}", "true,17", tVal, true}, 382 {"if $x with $x int", "{{if $x := true}}{{with $x := .I}}{{$x}},{{end}}{{$x}}{{end}}", "17,true", tVal, true}, 383 {"if else if", "{{if false}}FALSE{{else if true}}TRUE{{end}}", "TRUE", tVal, true}, 384 {"if else chain", "{{if eq 1 3}}1{{else if eq 2 3}}2{{else if eq 3 3}}3{{end}}", "3", tVal, true}, 385 386 // Print etc. 387 {"print", `{{print "hello, print"}}`, "hello, print", tVal, true}, 388 {"print 123", `{{print 1 2 3}}`, "1 2 3", tVal, true}, 389 {"print nil", `{{print nil}}`, "<nil>", tVal, true}, 390 {"println", `{{println 1 2 3}}`, "1 2 3\n", tVal, true}, 391 {"printf int", `{{printf "%04x" 127}}`, "007f", tVal, true}, 392 {"printf float", `{{printf "%g" 3.5}}`, "3.5", tVal, true}, 393 {"printf complex", `{{printf "%g" 1+7i}}`, "(1+7i)", tVal, true}, 394 {"printf string", `{{printf "%s" "hello"}}`, "hello", tVal, true}, 395 {"printf function", `{{printf "%#q" zeroArgs}}`, "`zeroArgs`", tVal, true}, 396 {"printf field", `{{printf "%s" .U.V}}`, "v", tVal, true}, 397 {"printf method", `{{printf "%s" .Method0}}`, "M0", tVal, true}, 398 {"printf dot", `{{with .I}}{{printf "%d" .}}{{end}}`, "17", tVal, true}, 399 {"printf var", `{{with $x := .I}}{{printf "%d" $x}}{{end}}`, "17", tVal, true}, 400 {"printf lots", `{{printf "%d %s %g %s" 127 "hello" 7-3i .Method0}}`, "127 hello (7-3i) M0", tVal, true}, 401 402 // HTML. 403 {"html", `{{html "<script>alert(\"XSS\");</script>"}}`, 404 "<script>alert("XSS");</script>", nil, true}, 405 {"html pipeline", `{{printf "<script>alert(\"XSS\");</script>" | html}}`, 406 "<script>alert("XSS");</script>", nil, true}, 407 {"html", `{{html .PS}}`, "a string", tVal, true}, 408 409 // JavaScript. 410 {"js", `{{js .}}`, `It\'d be nice.`, `It'd be nice.`, true}, 411 412 // URL query. 413 {"urlquery", `{{"http://www.example.org/"|urlquery}}`, "http%3A%2F%2Fwww.example.org%2F", nil, true}, 414 415 // Booleans 416 {"not", "{{not true}} {{not false}}", "false true", nil, true}, 417 {"and", "{{and false 0}} {{and 1 0}} {{and 0 true}} {{and 1 1}}", "false 0 0 1", nil, true}, 418 {"or", "{{or 0 0}} {{or 1 0}} {{or 0 true}} {{or 1 1}}", "0 1 true 1", nil, true}, 419 {"boolean if", "{{if and true 1 `hi`}}TRUE{{else}}FALSE{{end}}", "TRUE", tVal, true}, 420 {"boolean if not", "{{if and true 1 `hi` | not}}TRUE{{else}}FALSE{{end}}", "FALSE", nil, true}, 421 422 // Indexing. 423 {"slice[0]", "{{index .SI 0}}", "3", tVal, true}, 424 {"slice[1]", "{{index .SI 1}}", "4", tVal, true}, 425 {"slice[HUGE]", "{{index .SI 10}}", "", tVal, false}, 426 {"slice[WRONG]", "{{index .SI `hello`}}", "", tVal, false}, 427 {"map[one]", "{{index .MSI `one`}}", "1", tVal, true}, 428 {"map[two]", "{{index .MSI `two`}}", "2", tVal, true}, 429 {"map[NO]", "{{index .MSI `XXX`}}", "0", tVal, true}, 430 {"map[nil]", "{{index .MSI nil}}", "0", tVal, true}, 431 {"map[WRONG]", "{{index .MSI 10}}", "", tVal, false}, 432 {"double index", "{{index .SMSI 1 `eleven`}}", "11", tVal, true}, 433 434 // Len. 435 {"slice", "{{len .SI}}", "3", tVal, true}, 436 {"map", "{{len .MSI }}", "3", tVal, true}, 437 {"len of int", "{{len 3}}", "", tVal, false}, 438 {"len of nothing", "{{len .Empty0}}", "", tVal, false}, 439 440 // With. 441 {"with true", "{{with true}}{{.}}{{end}}", "true", tVal, true}, 442 {"with false", "{{with false}}{{.}}{{else}}FALSE{{end}}", "FALSE", tVal, true}, 443 {"with 1", "{{with 1}}{{.}}{{else}}ZERO{{end}}", "1", tVal, true}, 444 {"with 0", "{{with 0}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true}, 445 {"with 1.5", "{{with 1.5}}{{.}}{{else}}ZERO{{end}}", "1.5", tVal, true}, 446 {"with 0.0", "{{with .FloatZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true}, 447 {"with 1.5i", "{{with 1.5i}}{{.}}{{else}}ZERO{{end}}", "(0+1.5i)", tVal, true}, 448 {"with 0.0i", "{{with .ComplexZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true}, 449 {"with emptystring", "{{with ``}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true}, 450 {"with string", "{{with `notempty`}}{{.}}{{else}}EMPTY{{end}}", "notempty", tVal, true}, 451 {"with emptyslice", "{{with .SIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true}, 452 {"with slice", "{{with .SI}}{{.}}{{else}}EMPTY{{end}}", "[3 4 5]", tVal, true}, 453 {"with emptymap", "{{with .MSIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true}, 454 {"with map", "{{with .MSIone}}{{.}}{{else}}EMPTY{{end}}", "map[one:1]", tVal, true}, 455 {"with empty interface, struct field", "{{with .Empty4}}{{.V}}{{end}}", "UinEmpty", tVal, true}, 456 {"with $x int", "{{with $x := .I}}{{$x}}{{end}}", "17", tVal, true}, 457 {"with $x struct.U.V", "{{with $x := $}}{{$x.U.V}}{{end}}", "v", tVal, true}, 458 {"with variable and action", "{{with $x := $}}{{$y := $.U.V}}{{$y}}{{end}}", "v", tVal, true}, 459 460 // Range. 461 {"range []int", "{{range .SI}}-{{.}}-{{end}}", "-3--4--5-", tVal, true}, 462 {"range empty no else", "{{range .SIEmpty}}-{{.}}-{{end}}", "", tVal, true}, 463 {"range []int else", "{{range .SI}}-{{.}}-{{else}}EMPTY{{end}}", "-3--4--5-", tVal, true}, 464 {"range empty else", "{{range .SIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true}, 465 {"range []bool", "{{range .SB}}-{{.}}-{{end}}", "-true--false-", tVal, true}, 466 {"range []int method", "{{range .SI | .MAdd .I}}-{{.}}-{{end}}", "-20--21--22-", tVal, true}, 467 {"range map", "{{range .MSI}}-{{.}}-{{end}}", "-1--3--2-", tVal, true}, 468 {"range empty map no else", "{{range .MSIEmpty}}-{{.}}-{{end}}", "", tVal, true}, 469 {"range map else", "{{range .MSI}}-{{.}}-{{else}}EMPTY{{end}}", "-1--3--2-", tVal, true}, 470 {"range empty map else", "{{range .MSIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true}, 471 {"range empty interface", "{{range .Empty3}}-{{.}}-{{else}}EMPTY{{end}}", "-7--8-", tVal, true}, 472 {"range empty nil", "{{range .Empty0}}-{{.}}-{{end}}", "", tVal, true}, 473 {"range $x SI", "{{range $x := .SI}}<{{$x}}>{{end}}", "<3><4><5>", tVal, true}, 474 {"range $x $y SI", "{{range $x, $y := .SI}}<{{$x}}={{$y}}>{{end}}", "<0=3><1=4><2=5>", tVal, true}, 475 {"range $x MSIone", "{{range $x := .MSIone}}<{{$x}}>{{end}}", "<1>", tVal, true}, 476 {"range $x $y MSIone", "{{range $x, $y := .MSIone}}<{{$x}}={{$y}}>{{end}}", "<one=1>", tVal, true}, 477 {"range $x PSI", "{{range $x := .PSI}}<{{$x}}>{{end}}", "<21><22><23>", tVal, true}, 478 {"declare in range", "{{range $x := .PSI}}<{{$foo:=$x}}{{$x}}>{{end}}", "<21><22><23>", tVal, true}, 479 {"range count", `{{range $i, $x := count 5}}[{{$i}}]{{$x}}{{end}}`, "[0]a[1]b[2]c[3]d[4]e", tVal, true}, 480 {"range nil count", `{{range $i, $x := count 0}}{{else}}empty{{end}}`, "empty", tVal, true}, 481 482 // Cute examples. 483 {"or as if true", `{{or .SI "slice is empty"}}`, "[3 4 5]", tVal, true}, 484 {"or as if false", `{{or .SIEmpty "slice is empty"}}`, "slice is empty", tVal, true}, 485 486 // Error handling. 487 {"error method, error", "{{.MyError true}}", "", tVal, false}, 488 {"error method, no error", "{{.MyError false}}", "false", tVal, true}, 489 490 // Fixed bugs. 491 // Must separate dot and receiver; otherwise args are evaluated with dot set to variable. 492 {"bug0", "{{range .MSIone}}{{if $.Method1 .}}X{{end}}{{end}}", "X", tVal, true}, 493 // Do not loop endlessly in indirect for non-empty interfaces. 494 // The bug appears with *interface only; looped forever. 495 {"bug1", "{{.Method0}}", "M0", &iVal, true}, 496 // Was taking address of interface field, so method set was empty. 497 {"bug2", "{{$.NonEmptyInterface.Method0}}", "M0", tVal, true}, 498 // Struct values were not legal in with - mere oversight. 499 {"bug3", "{{with $}}{{.Method0}}{{end}}", "M0", tVal, true}, 500 // Nil interface values in if. 501 {"bug4", "{{if .Empty0}}non-nil{{else}}nil{{end}}", "nil", tVal, true}, 502 // Stringer. 503 {"bug5", "{{.Str}}", "foozle", tVal, true}, 504 {"bug5a", "{{.Err}}", "erroozle", tVal, true}, 505 // Args need to be indirected and dereferenced sometimes. 506 {"bug6a", "{{vfunc .V0 .V1}}", "vfunc", tVal, true}, 507 {"bug6b", "{{vfunc .V0 .V0}}", "vfunc", tVal, true}, 508 {"bug6c", "{{vfunc .V1 .V0}}", "vfunc", tVal, true}, 509 {"bug6d", "{{vfunc .V1 .V1}}", "vfunc", tVal, true}, 510 // Legal parse but illegal execution: non-function should have no arguments. 511 {"bug7a", "{{3 2}}", "", tVal, false}, 512 {"bug7b", "{{$x := 1}}{{$x 2}}", "", tVal, false}, 513 {"bug7c", "{{$x := 1}}{{3 | $x}}", "", tVal, false}, 514 // Pipelined arg was not being type-checked. 515 {"bug8a", "{{3|oneArg}}", "", tVal, false}, 516 {"bug8b", "{{4|dddArg 3}}", "", tVal, false}, 517 // A bug was introduced that broke map lookups for lower-case names. 518 {"bug9", "{{.cause}}", "neglect", map[string]string{"cause": "neglect"}, true}, 519 // Field chain starting with function did not work. 520 {"bug10", "{{mapOfThree.three}}-{{(mapOfThree).three}}", "3-3", 0, true}, 521 // Dereferencing nil pointer while evaluating function arguments should not panic. Issue 7333. 522 {"bug11", "{{valueString .PS}}", "", T{}, false}, 523 // 0xef gave constant type float64. Issue 8622. 524 {"bug12xe", "{{printf `%T` 0xef}}", "int", T{}, true}, 525 {"bug12xE", "{{printf `%T` 0xEE}}", "int", T{}, true}, 526 {"bug12Xe", "{{printf `%T` 0Xef}}", "int", T{}, true}, 527 {"bug12XE", "{{printf `%T` 0XEE}}", "int", T{}, true}, 528 // Chained nodes did not work as arguments. Issue 8473. 529 {"bug13", "{{print (.Copy).I}}", "17", tVal, true}, 530 } 531 532 func zeroArgs() string { 533 return "zeroArgs" 534 } 535 536 func oneArg(a string) string { 537 return "oneArg=" + a 538 } 539 540 func dddArg(a int, b ...string) string { 541 return fmt.Sprintln(a, b) 542 } 543 544 // count returns a channel that will deliver n sequential 1-letter strings starting at "a" 545 func count(n int) chan string { 546 if n == 0 { 547 return nil 548 } 549 c := make(chan string) 550 go func() { 551 for i := 0; i < n; i++ { 552 c <- "abcdefghijklmnop"[i : i+1] 553 } 554 close(c) 555 }() 556 return c 557 } 558 559 // vfunc takes a *V and a V 560 func vfunc(V, *V) string { 561 return "vfunc" 562 } 563 564 // valueString takes a string, not a pointer. 565 func valueString(v string) string { 566 return "value is ignored" 567 } 568 569 func add(args ...int) int { 570 sum := 0 571 for _, x := range args { 572 sum += x 573 } 574 return sum 575 } 576 577 func echo(arg interface{}) interface{} { 578 return arg 579 } 580 581 func makemap(arg ...string) map[string]string { 582 if len(arg)%2 != 0 { 583 panic("bad makemap") 584 } 585 m := make(map[string]string) 586 for i := 0; i < len(arg); i += 2 { 587 m[arg[i]] = arg[i+1] 588 } 589 return m 590 } 591 592 func stringer(s fmt.Stringer) string { 593 return s.String() 594 } 595 596 func mapOfThree() interface{} { 597 return map[string]int{"three": 3} 598 } 599 600 func testExecute(execTests []execTest, template *Template, t *testing.T) { 601 b := new(bytes.Buffer) 602 funcs := FuncMap{ 603 "add": add, 604 "count": count, 605 "dddArg": dddArg, 606 "echo": echo, 607 "makemap": makemap, 608 "mapOfThree": mapOfThree, 609 "oneArg": oneArg, 610 "stringer": stringer, 611 "typeOf": typeOf, 612 "valueString": valueString, 613 "vfunc": vfunc, 614 "zeroArgs": zeroArgs, 615 } 616 for _, test := range execTests { 617 var tmpl *Template 618 var err error 619 if template == nil { 620 tmpl, err = New(test.name).Funcs(funcs).Parse(test.input) 621 } else { 622 tmpl, err = template.New(test.name).Funcs(funcs).Parse(test.input) 623 } 624 if err != nil { 625 t.Errorf("%s: parse error: %s", test.name, err) 626 continue 627 } 628 b.Reset() 629 err = tmpl.Execute(b, test.data) 630 switch { 631 case !test.ok && err == nil: 632 t.Errorf("%s: expected error; got none", test.name) 633 continue 634 case test.ok && err != nil: 635 t.Errorf("%s: unexpected execute error: %s", test.name, err) 636 continue 637 case !test.ok && err != nil: 638 // expected error, got one 639 if *debug { 640 fmt.Printf("%s: %s\n\t%s\n", test.name, test.input, err) 641 } 642 } 643 result := b.String() 644 if result != test.output { 645 t.Errorf("%s: expected\n\t%q\ngot\n\t%q", test.name, test.output, result) 646 } 647 } 648 } 649 650 func TestExecute(t *testing.T) { 651 testExecute(execTests, nil, t) 652 } 653 654 var delimPairs = []string{ 655 "", "", // default 656 "{{", "}}", // same as default 657 "<<", ">>", // distinct 658 "|", "|", // same 659 "(日)", "(本)", // peculiar 660 } 661 662 func TestDelims(t *testing.T) { 663 const hello = "Hello, world" 664 var value = struct{ Str string }{hello} 665 for i := 0; i < len(delimPairs); i += 2 { 666 text := ".Str" 667 left := delimPairs[i+0] 668 trueLeft := left 669 right := delimPairs[i+1] 670 trueRight := right 671 if left == "" { // default case 672 trueLeft = "{{" 673 } 674 if right == "" { // default case 675 trueRight = "}}" 676 } 677 text = trueLeft + text + trueRight 678 // Now add a comment 679 text += trueLeft + "/*comment*/" + trueRight 680 // Now add an action containing a string. 681 text += trueLeft + `"` + trueLeft + `"` + trueRight 682 // At this point text looks like `{{.Str}}{{/*comment*/}}{{"{{"}}`. 683 tmpl, err := New("delims").Delims(left, right).Parse(text) 684 if err != nil { 685 t.Fatalf("delim %q text %q parse err %s", left, text, err) 686 } 687 var b = new(bytes.Buffer) 688 err = tmpl.Execute(b, value) 689 if err != nil { 690 t.Fatalf("delim %q exec err %s", left, err) 691 } 692 if b.String() != hello+trueLeft { 693 t.Errorf("expected %q got %q", hello+trueLeft, b.String()) 694 } 695 } 696 } 697 698 // Check that an error from a method flows back to the top. 699 func TestExecuteError(t *testing.T) { 700 b := new(bytes.Buffer) 701 tmpl := New("error") 702 _, err := tmpl.Parse("{{.MyError true}}") 703 if err != nil { 704 t.Fatalf("parse error: %s", err) 705 } 706 err = tmpl.Execute(b, tVal) 707 if err == nil { 708 t.Errorf("expected error; got none") 709 } else if !strings.Contains(err.Error(), myError.Error()) { 710 if *debug { 711 fmt.Printf("test execute error: %s\n", err) 712 } 713 t.Errorf("expected myError; got %s", err) 714 } 715 } 716 717 const execErrorText = `line 1 718 line 2 719 line 3 720 {{template "one" .}} 721 {{define "one"}}{{template "two" .}}{{end}} 722 {{define "two"}}{{template "three" .}}{{end}} 723 {{define "three"}}{{index "hi" $}}{{end}}` 724 725 // Check that an error from a nested template contains all the relevant information. 726 func TestExecError(t *testing.T) { 727 tmpl, err := New("top").Parse(execErrorText) 728 if err != nil { 729 t.Fatal("parse error:", err) 730 } 731 var b bytes.Buffer 732 err = tmpl.Execute(&b, 5) // 5 is out of range indexing "hi" 733 if err == nil { 734 t.Fatal("expected error") 735 } 736 const want = `template: top:7:20: executing "three" at <index "hi" $>: error calling index: index out of range: 5` 737 got := err.Error() 738 if got != want { 739 t.Errorf("expected\n%q\ngot\n%q", want, got) 740 } 741 } 742 743 func TestJSEscaping(t *testing.T) { 744 testCases := []struct { 745 in, exp string 746 }{ 747 {`a`, `a`}, 748 {`'foo`, `\'foo`}, 749 {`Go "jump" \`, `Go \"jump\" \\`}, 750 {`Yukihiro says "今日は世界"`, `Yukihiro says \"今日は世界\"`}, 751 {"unprintable \uFDFF", `unprintable \uFDFF`}, 752 {`<html>`, `\x3Chtml\x3E`}, 753 } 754 for _, tc := range testCases { 755 s := JSEscapeString(tc.in) 756 if s != tc.exp { 757 t.Errorf("JS escaping [%s] got [%s] want [%s]", tc.in, s, tc.exp) 758 } 759 } 760 } 761 762 // A nice example: walk a binary tree. 763 764 type Tree struct { 765 Val int 766 Left, Right *Tree 767 } 768 769 // Use different delimiters to test Set.Delims. 770 const treeTemplate = ` 771 (define "tree") 772 [ 773 (.Val) 774 (with .Left) 775 (template "tree" .) 776 (end) 777 (with .Right) 778 (template "tree" .) 779 (end) 780 ] 781 (end) 782 ` 783 784 func TestTree(t *testing.T) { 785 var tree = &Tree{ 786 1, 787 &Tree{ 788 2, &Tree{ 789 3, 790 &Tree{ 791 4, nil, nil, 792 }, 793 nil, 794 }, 795 &Tree{ 796 5, 797 &Tree{ 798 6, nil, nil, 799 }, 800 nil, 801 }, 802 }, 803 &Tree{ 804 7, 805 &Tree{ 806 8, 807 &Tree{ 808 9, nil, nil, 809 }, 810 nil, 811 }, 812 &Tree{ 813 10, 814 &Tree{ 815 11, nil, nil, 816 }, 817 nil, 818 }, 819 }, 820 } 821 tmpl, err := New("root").Delims("(", ")").Parse(treeTemplate) 822 if err != nil { 823 t.Fatal("parse error:", err) 824 } 825 var b bytes.Buffer 826 stripSpace := func(r rune) rune { 827 if r == '\t' || r == '\n' { 828 return -1 829 } 830 return r 831 } 832 const expect = "[1[2[3[4]][5[6]]][7[8[9]][10[11]]]]" 833 // First by looking up the template. 834 err = tmpl.Lookup("tree").Execute(&b, tree) 835 if err != nil { 836 t.Fatal("exec error:", err) 837 } 838 result := strings.Map(stripSpace, b.String()) 839 if result != expect { 840 t.Errorf("expected %q got %q", expect, result) 841 } 842 // Then direct to execution. 843 b.Reset() 844 err = tmpl.ExecuteTemplate(&b, "tree", tree) 845 if err != nil { 846 t.Fatal("exec error:", err) 847 } 848 result = strings.Map(stripSpace, b.String()) 849 if result != expect { 850 t.Errorf("expected %q got %q", expect, result) 851 } 852 } 853 854 func TestExecuteOnNewTemplate(t *testing.T) { 855 // This is issue 3872. 856 _ = New("Name").Templates() 857 } 858 859 const testTemplates = `{{define "one"}}one{{end}}{{define "two"}}two{{end}}` 860 861 func TestMessageForExecuteEmpty(t *testing.T) { 862 // Test a truly empty template. 863 tmpl := New("empty") 864 var b bytes.Buffer 865 err := tmpl.Execute(&b, 0) 866 if err == nil { 867 t.Fatal("expected initial error") 868 } 869 got := err.Error() 870 want := `template: empty: "empty" is an incomplete or empty template` 871 if got != want { 872 t.Errorf("expected error %s got %s", want, got) 873 } 874 // Add a non-empty template to check that the error is helpful. 875 tests, err := New("").Parse(testTemplates) 876 if err != nil { 877 t.Fatal(err) 878 } 879 tmpl.AddParseTree("secondary", tests.Tree) 880 err = tmpl.Execute(&b, 0) 881 if err == nil { 882 t.Fatal("expected second error") 883 } 884 got = err.Error() 885 want = `template: empty: "empty" is an incomplete or empty template; defined templates are: "secondary"` 886 if got != want { 887 t.Errorf("expected error %s got %s", want, got) 888 } 889 // Make sure we can execute the secondary. 890 err = tmpl.ExecuteTemplate(&b, "secondary", 0) 891 if err != nil { 892 t.Fatal(err) 893 } 894 } 895 896 func TestFinalForPrintf(t *testing.T) { 897 tmpl, err := New("").Parse(`{{"x" | printf}}`) 898 if err != nil { 899 t.Fatal(err) 900 } 901 var b bytes.Buffer 902 err = tmpl.Execute(&b, 0) 903 if err != nil { 904 t.Fatal(err) 905 } 906 } 907 908 type cmpTest struct { 909 expr string 910 truth string 911 ok bool 912 } 913 914 var cmpTests = []cmpTest{ 915 {"eq true true", "true", true}, 916 {"eq true false", "false", true}, 917 {"eq 1+2i 1+2i", "true", true}, 918 {"eq 1+2i 1+3i", "false", true}, 919 {"eq 1.5 1.5", "true", true}, 920 {"eq 1.5 2.5", "false", true}, 921 {"eq 1 1", "true", true}, 922 {"eq 1 2", "false", true}, 923 {"eq `xy` `xy`", "true", true}, 924 {"eq `xy` `xyz`", "false", true}, 925 {"eq .Uthree .Uthree", "true", true}, 926 {"eq .Uthree .Ufour", "false", true}, 927 {"eq 3 4 5 6 3", "true", true}, 928 {"eq 3 4 5 6 7", "false", true}, 929 {"ne true true", "false", true}, 930 {"ne true false", "true", true}, 931 {"ne 1+2i 1+2i", "false", true}, 932 {"ne 1+2i 1+3i", "true", true}, 933 {"ne 1.5 1.5", "false", true}, 934 {"ne 1.5 2.5", "true", true}, 935 {"ne 1 1", "false", true}, 936 {"ne 1 2", "true", true}, 937 {"ne `xy` `xy`", "false", true}, 938 {"ne `xy` `xyz`", "true", true}, 939 {"ne .Uthree .Uthree", "false", true}, 940 {"ne .Uthree .Ufour", "true", true}, 941 {"lt 1.5 1.5", "false", true}, 942 {"lt 1.5 2.5", "true", true}, 943 {"lt 1 1", "false", true}, 944 {"lt 1 2", "true", true}, 945 {"lt `xy` `xy`", "false", true}, 946 {"lt `xy` `xyz`", "true", true}, 947 {"lt .Uthree .Uthree", "false", true}, 948 {"lt .Uthree .Ufour", "true", true}, 949 {"le 1.5 1.5", "true", true}, 950 {"le 1.5 2.5", "true", true}, 951 {"le 2.5 1.5", "false", true}, 952 {"le 1 1", "true", true}, 953 {"le 1 2", "true", true}, 954 {"le 2 1", "false", true}, 955 {"le `xy` `xy`", "true", true}, 956 {"le `xy` `xyz`", "true", true}, 957 {"le `xyz` `xy`", "false", true}, 958 {"le .Uthree .Uthree", "true", true}, 959 {"le .Uthree .Ufour", "true", true}, 960 {"le .Ufour .Uthree", "false", true}, 961 {"gt 1.5 1.5", "false", true}, 962 {"gt 1.5 2.5", "false", true}, 963 {"gt 1 1", "false", true}, 964 {"gt 2 1", "true", true}, 965 {"gt 1 2", "false", true}, 966 {"gt `xy` `xy`", "false", true}, 967 {"gt `xy` `xyz`", "false", true}, 968 {"gt .Uthree .Uthree", "false", true}, 969 {"gt .Uthree .Ufour", "false", true}, 970 {"gt .Ufour .Uthree", "true", true}, 971 {"ge 1.5 1.5", "true", true}, 972 {"ge 1.5 2.5", "false", true}, 973 {"ge 2.5 1.5", "true", true}, 974 {"ge 1 1", "true", true}, 975 {"ge 1 2", "false", true}, 976 {"ge 2 1", "true", true}, 977 {"ge `xy` `xy`", "true", true}, 978 {"ge `xy` `xyz`", "false", true}, 979 {"ge `xyz` `xy`", "true", true}, 980 {"ge .Uthree .Uthree", "true", true}, 981 {"ge .Uthree .Ufour", "false", true}, 982 {"ge .Ufour .Uthree", "true", true}, 983 // Mixing signed and unsigned integers. 984 {"eq .Uthree .Three", "true", true}, 985 {"eq .Three .Uthree", "true", true}, 986 {"le .Uthree .Three", "true", true}, 987 {"le .Three .Uthree", "true", true}, 988 {"ge .Uthree .Three", "true", true}, 989 {"ge .Three .Uthree", "true", true}, 990 {"lt .Uthree .Three", "false", true}, 991 {"lt .Three .Uthree", "false", true}, 992 {"gt .Uthree .Three", "false", true}, 993 {"gt .Three .Uthree", "false", true}, 994 {"eq .Ufour .Three", "false", true}, 995 {"lt .Ufour .Three", "false", true}, 996 {"gt .Ufour .Three", "true", true}, 997 {"eq .NegOne .Uthree", "false", true}, 998 {"eq .Uthree .NegOne", "false", true}, 999 {"ne .NegOne .Uthree", "true", true}, 1000 {"ne .Uthree .NegOne", "true", true}, 1001 {"lt .NegOne .Uthree", "true", true}, 1002 {"lt .Uthree .NegOne", "false", true}, 1003 {"le .NegOne .Uthree", "true", true}, 1004 {"le .Uthree .NegOne", "false", true}, 1005 {"gt .NegOne .Uthree", "false", true}, 1006 {"gt .Uthree .NegOne", "true", true}, 1007 {"ge .NegOne .Uthree", "false", true}, 1008 {"ge .Uthree .NegOne", "true", true}, 1009 {"eq (index `x` 0) 'x'", "true", true}, // The example that triggered this rule. 1010 {"eq (index `x` 0) 'y'", "false", true}, 1011 // Errors 1012 {"eq `xy` 1", "", false}, // Different types. 1013 {"eq 2 2.0", "", false}, // Different types. 1014 {"lt true true", "", false}, // Unordered types. 1015 {"lt 1+0i 1+0i", "", false}, // Unordered types. 1016 } 1017 1018 func TestComparison(t *testing.T) { 1019 b := new(bytes.Buffer) 1020 var cmpStruct = struct { 1021 Uthree, Ufour uint 1022 NegOne, Three int 1023 }{3, 4, -1, 3} 1024 for _, test := range cmpTests { 1025 text := fmt.Sprintf("{{if %s}}true{{else}}false{{end}}", test.expr) 1026 tmpl, err := New("empty").Parse(text) 1027 if err != nil { 1028 t.Fatalf("%q: %s", test.expr, err) 1029 } 1030 b.Reset() 1031 err = tmpl.Execute(b, &cmpStruct) 1032 if test.ok && err != nil { 1033 t.Errorf("%s errored incorrectly: %s", test.expr, err) 1034 continue 1035 } 1036 if !test.ok && err == nil { 1037 t.Errorf("%s did not error", test.expr) 1038 continue 1039 } 1040 if b.String() != test.truth { 1041 t.Errorf("%s: want %s; got %s", test.expr, test.truth, b.String()) 1042 } 1043 } 1044 }