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 // Didn't protect against nil or literal values in field chains. 531 {"bug14a", "{{(nil).True}}", "", tVal, false}, 532 {"bug14b", "{{$x := nil}}{{$x.anything}}", "", tVal, false}, 533 {"bug14c", `{{$x := (1.0)}}{{$y := ("hello")}}{{$x.anything}}{{$y.true}}`, "", tVal, false}, 534 // Didn't call validateType on function results. Issue 10800. 535 {"bug15", "{{valueString returnInt}}", "", tVal, false}, 536 // Variadic function corner cases. Issue 10946. 537 {"bug16a", "{{true|printf}}", "", tVal, false}, 538 {"bug16b", "{{1|printf}}", "", tVal, false}, 539 {"bug16c", "{{1.1|printf}}", "", tVal, false}, 540 {"bug16d", "{{'x'|printf}}", "", tVal, false}, 541 {"bug16e", "{{0i|printf}}", "", tVal, false}, 542 {"bug16f", "{{true|twoArgs \"xxx\"}}", "", tVal, false}, 543 {"bug16g", "{{\"aaa\" |twoArgs \"bbb\"}}", "twoArgs=bbbaaa", tVal, true}, 544 {"bug16h", "{{1|oneArg}}", "", tVal, false}, 545 {"bug16i", "{{\"aaa\"|oneArg}}", "oneArg=aaa", tVal, true}, 546 {"bug16j", "{{1+2i|printf \"%v\"}}", "(1+2i)", tVal, true}, 547 {"bug16k", "{{\"aaa\"|printf }}", "aaa", tVal, true}, 548 } 549 550 func zeroArgs() string { 551 return "zeroArgs" 552 } 553 554 func oneArg(a string) string { 555 return "oneArg=" + a 556 } 557 558 func twoArgs(a, b string) string { 559 return "twoArgs=" + a + b 560 } 561 562 func dddArg(a int, b ...string) string { 563 return fmt.Sprintln(a, b) 564 } 565 566 // count returns a channel that will deliver n sequential 1-letter strings starting at "a" 567 func count(n int) chan string { 568 if n == 0 { 569 return nil 570 } 571 c := make(chan string) 572 go func() { 573 for i := 0; i < n; i++ { 574 c <- "abcdefghijklmnop"[i : i+1] 575 } 576 close(c) 577 }() 578 return c 579 } 580 581 // vfunc takes a *V and a V 582 func vfunc(V, *V) string { 583 return "vfunc" 584 } 585 586 // valueString takes a string, not a pointer. 587 func valueString(v string) string { 588 return "value is ignored" 589 } 590 591 // returnInt returns an int 592 func returnInt() int { 593 return 7 594 } 595 596 func add(args ...int) int { 597 sum := 0 598 for _, x := range args { 599 sum += x 600 } 601 return sum 602 } 603 604 func echo(arg interface{}) interface{} { 605 return arg 606 } 607 608 func makemap(arg ...string) map[string]string { 609 if len(arg)%2 != 0 { 610 panic("bad makemap") 611 } 612 m := make(map[string]string) 613 for i := 0; i < len(arg); i += 2 { 614 m[arg[i]] = arg[i+1] 615 } 616 return m 617 } 618 619 func stringer(s fmt.Stringer) string { 620 return s.String() 621 } 622 623 func mapOfThree() interface{} { 624 return map[string]int{"three": 3} 625 } 626 627 func testExecute(execTests []execTest, template *Template, t *testing.T) { 628 b := new(bytes.Buffer) 629 funcs := FuncMap{ 630 "add": add, 631 "count": count, 632 "dddArg": dddArg, 633 "echo": echo, 634 "makemap": makemap, 635 "mapOfThree": mapOfThree, 636 "oneArg": oneArg, 637 "returnInt": returnInt, 638 "stringer": stringer, 639 "twoArgs": twoArgs, 640 "typeOf": typeOf, 641 "valueString": valueString, 642 "vfunc": vfunc, 643 "zeroArgs": zeroArgs, 644 } 645 for _, test := range execTests { 646 var tmpl *Template 647 var err error 648 if template == nil { 649 tmpl, err = New(test.name).Funcs(funcs).Parse(test.input) 650 } else { 651 tmpl, err = template.New(test.name).Funcs(funcs).Parse(test.input) 652 } 653 if err != nil { 654 t.Errorf("%s: parse error: %s", test.name, err) 655 continue 656 } 657 b.Reset() 658 err = tmpl.Execute(b, test.data) 659 switch { 660 case !test.ok && err == nil: 661 t.Errorf("%s: expected error; got none", test.name) 662 continue 663 case test.ok && err != nil: 664 t.Errorf("%s: unexpected execute error: %s", test.name, err) 665 continue 666 case !test.ok && err != nil: 667 // expected error, got one 668 if *debug { 669 fmt.Printf("%s: %s\n\t%s\n", test.name, test.input, err) 670 } 671 } 672 result := b.String() 673 if result != test.output { 674 t.Errorf("%s: expected\n\t%q\ngot\n\t%q", test.name, test.output, result) 675 } 676 } 677 } 678 679 func TestExecute(t *testing.T) { 680 testExecute(execTests, nil, t) 681 } 682 683 var delimPairs = []string{ 684 "", "", // default 685 "{{", "}}", // same as default 686 "<<", ">>", // distinct 687 "|", "|", // same 688 "()", "()", // peculiar 689 } 690 691 func TestDelims(t *testing.T) { 692 const hello = "Hello, world" 693 var value = struct{ Str string }{hello} 694 for i := 0; i < len(delimPairs); i += 2 { 695 text := ".Str" 696 left := delimPairs[i+0] 697 trueLeft := left 698 right := delimPairs[i+1] 699 trueRight := right 700 if left == "" { // default case 701 trueLeft = "{{" 702 } 703 if right == "" { // default case 704 trueRight = "}}" 705 } 706 text = trueLeft + text + trueRight 707 // Now add a comment 708 text += trueLeft + "/*comment*/" + trueRight 709 // Now add an action containing a string. 710 text += trueLeft + `"` + trueLeft + `"` + trueRight 711 // At this point text looks like `{{.Str}}{{/*comment*/}}{{"{{"}}`. 712 tmpl, err := New("delims").Delims(left, right).Parse(text) 713 if err != nil { 714 t.Fatalf("delim %q text %q parse err %s", left, text, err) 715 } 716 var b = new(bytes.Buffer) 717 err = tmpl.Execute(b, value) 718 if err != nil { 719 t.Fatalf("delim %q exec err %s", left, err) 720 } 721 if b.String() != hello+trueLeft { 722 t.Errorf("expected %q got %q", hello+trueLeft, b.String()) 723 } 724 } 725 } 726 727 // Check that an error from a method flows back to the top. 728 func TestExecuteError(t *testing.T) { 729 b := new(bytes.Buffer) 730 tmpl := New("error") 731 _, err := tmpl.Parse("{{.MyError true}}") 732 if err != nil { 733 t.Fatalf("parse error: %s", err) 734 } 735 err = tmpl.Execute(b, tVal) 736 if err == nil { 737 t.Errorf("expected error; got none") 738 } else if !strings.Contains(err.Error(), myError.Error()) { 739 if *debug { 740 fmt.Printf("test execute error: %s\n", err) 741 } 742 t.Errorf("expected myError; got %s", err) 743 } 744 } 745 746 const execErrorText = `line 1 747 line 2 748 line 3 749 {{template "one" .}} 750 {{define "one"}}{{template "two" .}}{{end}} 751 {{define "two"}}{{template "three" .}}{{end}} 752 {{define "three"}}{{index "hi" $}}{{end}}` 753 754 // Check that an error from a nested template contains all the relevant information. 755 func TestExecError(t *testing.T) { 756 tmpl, err := New("top").Parse(execErrorText) 757 if err != nil { 758 t.Fatal("parse error:", err) 759 } 760 var b bytes.Buffer 761 err = tmpl.Execute(&b, 5) // 5 is out of range indexing "hi" 762 if err == nil { 763 t.Fatal("expected error") 764 } 765 const want = `template: top:7:20: executing "three" at <index "hi" $>: error calling index: index out of range: 5` 766 got := err.Error() 767 if got != want { 768 t.Errorf("expected\n%q\ngot\n%q", want, got) 769 } 770 } 771 772 func TestJSEscaping(t *testing.T) { 773 testCases := []struct { 774 in, exp string 775 }{ 776 {`a`, `a`}, 777 {`'foo`, `\'foo`}, 778 {`Go "jump" \`, `Go \"jump\" \\`}, 779 {`Yukihiro says ""`, `Yukihiro says \"\"`}, 780 {"unprintable \uFDFF", `unprintable \uFDFF`}, 781 {`<html>`, `\x3Chtml\x3E`}, 782 } 783 for _, tc := range testCases { 784 s := JSEscapeString(tc.in) 785 if s != tc.exp { 786 t.Errorf("JS escaping [%s] got [%s] want [%s]", tc.in, s, tc.exp) 787 } 788 } 789 } 790 791 // A nice example: walk a binary tree. 792 793 type Tree struct { 794 Val int 795 Left, Right *Tree 796 } 797 798 // Use different delimiters to test Set.Delims. 799 const treeTemplate = ` 800 (define "tree") 801 [ 802 (.Val) 803 (with .Left) 804 (template "tree" .) 805 (end) 806 (with .Right) 807 (template "tree" .) 808 (end) 809 ] 810 (end) 811 ` 812 813 func TestTree(t *testing.T) { 814 var tree = &Tree{ 815 1, 816 &Tree{ 817 2, &Tree{ 818 3, 819 &Tree{ 820 4, nil, nil, 821 }, 822 nil, 823 }, 824 &Tree{ 825 5, 826 &Tree{ 827 6, nil, nil, 828 }, 829 nil, 830 }, 831 }, 832 &Tree{ 833 7, 834 &Tree{ 835 8, 836 &Tree{ 837 9, nil, nil, 838 }, 839 nil, 840 }, 841 &Tree{ 842 10, 843 &Tree{ 844 11, nil, nil, 845 }, 846 nil, 847 }, 848 }, 849 } 850 tmpl, err := New("root").Delims("(", ")").Parse(treeTemplate) 851 if err != nil { 852 t.Fatal("parse error:", err) 853 } 854 var b bytes.Buffer 855 stripSpace := func(r rune) rune { 856 if r == '\t' || r == '\n' { 857 return -1 858 } 859 return r 860 } 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 := strings.Map(stripSpace, 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 = strings.Map(stripSpace, 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