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