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