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