github.com/geraldss/go/src@v0.0.0-20210511222824-ac7d0ebfc235/text/template/parse/parse_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 parse 6 7 import ( 8 "flag" 9 "fmt" 10 "strings" 11 "testing" 12 ) 13 14 var debug = flag.Bool("debug", false, "show the errors produced by the main tests") 15 16 type numberTest struct { 17 text string 18 isInt bool 19 isUint bool 20 isFloat bool 21 isComplex bool 22 int64 23 uint64 24 float64 25 complex128 26 } 27 28 var numberTests = []numberTest{ 29 // basics 30 {"0", true, true, true, false, 0, 0, 0, 0}, 31 {"-0", true, true, true, false, 0, 0, 0, 0}, // check that -0 is a uint. 32 {"73", true, true, true, false, 73, 73, 73, 0}, 33 {"7_3", true, true, true, false, 73, 73, 73, 0}, 34 {"0b10_010_01", true, true, true, false, 73, 73, 73, 0}, 35 {"0B10_010_01", true, true, true, false, 73, 73, 73, 0}, 36 {"073", true, true, true, false, 073, 073, 073, 0}, 37 {"0o73", true, true, true, false, 073, 073, 073, 0}, 38 {"0O73", true, true, true, false, 073, 073, 073, 0}, 39 {"0x73", true, true, true, false, 0x73, 0x73, 0x73, 0}, 40 {"0X73", true, true, true, false, 0x73, 0x73, 0x73, 0}, 41 {"0x7_3", true, true, true, false, 0x73, 0x73, 0x73, 0}, 42 {"-73", true, false, true, false, -73, 0, -73, 0}, 43 {"+73", true, false, true, false, 73, 0, 73, 0}, 44 {"100", true, true, true, false, 100, 100, 100, 0}, 45 {"1e9", true, true, true, false, 1e9, 1e9, 1e9, 0}, 46 {"-1e9", true, false, true, false, -1e9, 0, -1e9, 0}, 47 {"-1.2", false, false, true, false, 0, 0, -1.2, 0}, 48 {"1e19", false, true, true, false, 0, 1e19, 1e19, 0}, 49 {"1e1_9", false, true, true, false, 0, 1e19, 1e19, 0}, 50 {"1E19", false, true, true, false, 0, 1e19, 1e19, 0}, 51 {"-1e19", false, false, true, false, 0, 0, -1e19, 0}, 52 {"0x_1p4", true, true, true, false, 16, 16, 16, 0}, 53 {"0X_1P4", true, true, true, false, 16, 16, 16, 0}, 54 {"0x_1p-4", false, false, true, false, 0, 0, 1 / 16., 0}, 55 {"4i", false, false, false, true, 0, 0, 0, 4i}, 56 {"-1.2+4.2i", false, false, false, true, 0, 0, 0, -1.2 + 4.2i}, 57 {"073i", false, false, false, true, 0, 0, 0, 73i}, // not octal! 58 // complex with 0 imaginary are float (and maybe integer) 59 {"0i", true, true, true, true, 0, 0, 0, 0}, 60 {"-1.2+0i", false, false, true, true, 0, 0, -1.2, -1.2}, 61 {"-12+0i", true, false, true, true, -12, 0, -12, -12}, 62 {"13+0i", true, true, true, true, 13, 13, 13, 13}, 63 // funny bases 64 {"0123", true, true, true, false, 0123, 0123, 0123, 0}, 65 {"-0x0", true, true, true, false, 0, 0, 0, 0}, 66 {"0xdeadbeef", true, true, true, false, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0}, 67 // character constants 68 {`'a'`, true, true, true, false, 'a', 'a', 'a', 0}, 69 {`'\n'`, true, true, true, false, '\n', '\n', '\n', 0}, 70 {`'\\'`, true, true, true, false, '\\', '\\', '\\', 0}, 71 {`'\''`, true, true, true, false, '\'', '\'', '\'', 0}, 72 {`'\xFF'`, true, true, true, false, 0xFF, 0xFF, 0xFF, 0}, 73 {`'パ'`, true, true, true, false, 0x30d1, 0x30d1, 0x30d1, 0}, 74 {`'\u30d1'`, true, true, true, false, 0x30d1, 0x30d1, 0x30d1, 0}, 75 {`'\U000030d1'`, true, true, true, false, 0x30d1, 0x30d1, 0x30d1, 0}, 76 // some broken syntax 77 {text: "+-2"}, 78 {text: "0x123."}, 79 {text: "1e."}, 80 {text: "0xi."}, 81 {text: "1+2."}, 82 {text: "'x"}, 83 {text: "'xx'"}, 84 {text: "'433937734937734969526500969526500'"}, // Integer too large - issue 10634. 85 // Issue 8622 - 0xe parsed as floating point. Very embarrassing. 86 {"0xef", true, true, true, false, 0xef, 0xef, 0xef, 0}, 87 } 88 89 func TestNumberParse(t *testing.T) { 90 for _, test := range numberTests { 91 // If fmt.Sscan thinks it's complex, it's complex. We can't trust the output 92 // because imaginary comes out as a number. 93 var c complex128 94 typ := itemNumber 95 var tree *Tree 96 if test.text[0] == '\'' { 97 typ = itemCharConstant 98 } else { 99 _, err := fmt.Sscan(test.text, &c) 100 if err == nil { 101 typ = itemComplex 102 } 103 } 104 n, err := tree.newNumber(0, test.text, typ) 105 ok := test.isInt || test.isUint || test.isFloat || test.isComplex 106 if ok && err != nil { 107 t.Errorf("unexpected error for %q: %s", test.text, err) 108 continue 109 } 110 if !ok && err == nil { 111 t.Errorf("expected error for %q", test.text) 112 continue 113 } 114 if !ok { 115 if *debug { 116 fmt.Printf("%s\n\t%s\n", test.text, err) 117 } 118 continue 119 } 120 if n.IsComplex != test.isComplex { 121 t.Errorf("complex incorrect for %q; should be %t", test.text, test.isComplex) 122 } 123 if test.isInt { 124 if !n.IsInt { 125 t.Errorf("expected integer for %q", test.text) 126 } 127 if n.Int64 != test.int64 { 128 t.Errorf("int64 for %q should be %d Is %d", test.text, test.int64, n.Int64) 129 } 130 } else if n.IsInt { 131 t.Errorf("did not expect integer for %q", test.text) 132 } 133 if test.isUint { 134 if !n.IsUint { 135 t.Errorf("expected unsigned integer for %q", test.text) 136 } 137 if n.Uint64 != test.uint64 { 138 t.Errorf("uint64 for %q should be %d Is %d", test.text, test.uint64, n.Uint64) 139 } 140 } else if n.IsUint { 141 t.Errorf("did not expect unsigned integer for %q", test.text) 142 } 143 if test.isFloat { 144 if !n.IsFloat { 145 t.Errorf("expected float for %q", test.text) 146 } 147 if n.Float64 != test.float64 { 148 t.Errorf("float64 for %q should be %g Is %g", test.text, test.float64, n.Float64) 149 } 150 } else if n.IsFloat { 151 t.Errorf("did not expect float for %q", test.text) 152 } 153 if test.isComplex { 154 if !n.IsComplex { 155 t.Errorf("expected complex for %q", test.text) 156 } 157 if n.Complex128 != test.complex128 { 158 t.Errorf("complex128 for %q should be %g Is %g", test.text, test.complex128, n.Complex128) 159 } 160 } else if n.IsComplex { 161 t.Errorf("did not expect complex for %q", test.text) 162 } 163 } 164 } 165 166 type parseTest struct { 167 name string 168 input string 169 ok bool 170 result string // what the user would see in an error message. 171 } 172 173 const ( 174 noError = true 175 hasError = false 176 ) 177 178 var parseTests = []parseTest{ 179 {"empty", "", noError, 180 ``}, 181 {"comment", "{{/*\n\n\n*/}}", noError, 182 ``}, 183 {"spaces", " \t\n", noError, 184 `" \t\n"`}, 185 {"text", "some text", noError, 186 `"some text"`}, 187 {"emptyAction", "{{}}", hasError, 188 `{{}}`}, 189 {"field", "{{.X}}", noError, 190 `{{.X}}`}, 191 {"simple command", "{{printf}}", noError, 192 `{{printf}}`}, 193 {"$ invocation", "{{$}}", noError, 194 "{{$}}"}, 195 {"variable invocation", "{{with $x := 3}}{{$x 23}}{{end}}", noError, 196 "{{with $x := 3}}{{$x 23}}{{end}}"}, 197 {"variable with fields", "{{$.I}}", noError, 198 "{{$.I}}"}, 199 {"multi-word command", "{{printf `%d` 23}}", noError, 200 "{{printf `%d` 23}}"}, 201 {"pipeline", "{{.X|.Y}}", noError, 202 `{{.X | .Y}}`}, 203 {"pipeline with decl", "{{$x := .X|.Y}}", noError, 204 `{{$x := .X | .Y}}`}, 205 {"nested pipeline", "{{.X (.Y .Z) (.A | .B .C) (.E)}}", noError, 206 `{{.X (.Y .Z) (.A | .B .C) (.E)}}`}, 207 {"field applied to parentheses", "{{(.Y .Z).Field}}", noError, 208 `{{(.Y .Z).Field}}`}, 209 {"simple if", "{{if .X}}hello{{end}}", noError, 210 `{{if .X}}"hello"{{end}}`}, 211 {"if with else", "{{if .X}}true{{else}}false{{end}}", noError, 212 `{{if .X}}"true"{{else}}"false"{{end}}`}, 213 {"if with else if", "{{if .X}}true{{else if .Y}}false{{end}}", noError, 214 `{{if .X}}"true"{{else}}{{if .Y}}"false"{{end}}{{end}}`}, 215 {"if else chain", "+{{if .X}}X{{else if .Y}}Y{{else if .Z}}Z{{end}}+", noError, 216 `"+"{{if .X}}"X"{{else}}{{if .Y}}"Y"{{else}}{{if .Z}}"Z"{{end}}{{end}}{{end}}"+"`}, 217 {"simple range", "{{range .X}}hello{{end}}", noError, 218 `{{range .X}}"hello"{{end}}`}, 219 {"chained field range", "{{range .X.Y.Z}}hello{{end}}", noError, 220 `{{range .X.Y.Z}}"hello"{{end}}`}, 221 {"nested range", "{{range .X}}hello{{range .Y}}goodbye{{end}}{{end}}", noError, 222 `{{range .X}}"hello"{{range .Y}}"goodbye"{{end}}{{end}}`}, 223 {"range with else", "{{range .X}}true{{else}}false{{end}}", noError, 224 `{{range .X}}"true"{{else}}"false"{{end}}`}, 225 {"range over pipeline", "{{range .X|.M}}true{{else}}false{{end}}", noError, 226 `{{range .X | .M}}"true"{{else}}"false"{{end}}`}, 227 {"range []int", "{{range .SI}}{{.}}{{end}}", noError, 228 `{{range .SI}}{{.}}{{end}}`}, 229 {"range 1 var", "{{range $x := .SI}}{{.}}{{end}}", noError, 230 `{{range $x := .SI}}{{.}}{{end}}`}, 231 {"range 2 vars", "{{range $x, $y := .SI}}{{.}}{{end}}", noError, 232 `{{range $x, $y := .SI}}{{.}}{{end}}`}, 233 {"constants", "{{range .SI 1 -3.2i true false 'a' nil}}{{end}}", noError, 234 `{{range .SI 1 -3.2i true false 'a' nil}}{{end}}`}, 235 {"template", "{{template `x`}}", noError, 236 `{{template "x"}}`}, 237 {"template with arg", "{{template `x` .Y}}", noError, 238 `{{template "x" .Y}}`}, 239 {"with", "{{with .X}}hello{{end}}", noError, 240 `{{with .X}}"hello"{{end}}`}, 241 {"with with else", "{{with .X}}hello{{else}}goodbye{{end}}", noError, 242 `{{with .X}}"hello"{{else}}"goodbye"{{end}}`}, 243 // Trimming spaces. 244 {"trim left", "x \r\n\t{{- 3}}", noError, `"x"{{3}}`}, 245 {"trim right", "{{3 -}}\n\n\ty", noError, `{{3}}"y"`}, 246 {"trim left and right", "x \r\n\t{{- 3 -}}\n\n\ty", noError, `"x"{{3}}"y"`}, 247 {"trim with extra spaces", "x\n{{- 3 -}}\ny", noError, `"x"{{3}}"y"`}, 248 {"comment trim left", "x \r\n\t{{- /* hi */}}", noError, `"x"`}, 249 {"comment trim right", "{{/* hi */ -}}\n\n\ty", noError, `"y"`}, 250 {"comment trim left and right", "x \r\n\t{{- /* */ -}}\n\n\ty", noError, `"x""y"`}, 251 {"block definition", `{{block "foo" .}}hello{{end}}`, noError, 252 `{{template "foo" .}}`}, 253 254 {"newline in assignment", "{{ $x \n := \n 1 \n }}", noError, "{{$x := 1}}"}, 255 {"newline in empty action", "{{\n}}", hasError, "{{\n}}"}, 256 {"newline in pipeline", "{{\n\"x\"\n|\nprintf\n}}", noError, `{{"x" | printf}}`}, 257 {"newline in comment", "{{/*\nhello\n*/}}", noError, ""}, 258 {"newline in comment", "{{-\n/*\nhello\n*/\n-}}", noError, ""}, 259 260 // Errors. 261 {"unclosed action", "hello{{range", hasError, ""}, 262 {"unmatched end", "{{end}}", hasError, ""}, 263 {"unmatched else", "{{else}}", hasError, ""}, 264 {"unmatched else after if", "{{if .X}}hello{{end}}{{else}}", hasError, ""}, 265 {"multiple else", "{{if .X}}1{{else}}2{{else}}3{{end}}", hasError, ""}, 266 {"missing end", "hello{{range .x}}", hasError, ""}, 267 {"missing end after else", "hello{{range .x}}{{else}}", hasError, ""}, 268 {"undefined function", "hello{{undefined}}", hasError, ""}, 269 {"undefined variable", "{{$x}}", hasError, ""}, 270 {"variable undefined after end", "{{with $x := 4}}{{end}}{{$x}}", hasError, ""}, 271 {"variable undefined in template", "{{template $v}}", hasError, ""}, 272 {"declare with field", "{{with $x.Y := 4}}{{end}}", hasError, ""}, 273 {"template with field ref", "{{template .X}}", hasError, ""}, 274 {"template with var", "{{template $v}}", hasError, ""}, 275 {"invalid punctuation", "{{printf 3, 4}}", hasError, ""}, 276 {"multidecl outside range", "{{with $v, $u := 3}}{{end}}", hasError, ""}, 277 {"too many decls in range", "{{range $u, $v, $w := 3}}{{end}}", hasError, ""}, 278 {"dot applied to parentheses", "{{printf (printf .).}}", hasError, ""}, 279 {"adjacent args", "{{printf 3`x`}}", hasError, ""}, 280 {"adjacent args with .", "{{printf `x`.}}", hasError, ""}, 281 {"extra end after if", "{{if .X}}a{{else if .Y}}b{{end}}{{end}}", hasError, ""}, 282 // Other kinds of assignments and operators aren't available yet. 283 {"bug0a", "{{$x := 0}}{{$x}}", noError, "{{$x := 0}}{{$x}}"}, 284 {"bug0b", "{{$x += 1}}{{$x}}", hasError, ""}, 285 {"bug0c", "{{$x ! 2}}{{$x}}", hasError, ""}, 286 {"bug0d", "{{$x % 3}}{{$x}}", hasError, ""}, 287 // Check the parse fails for := rather than comma. 288 {"bug0e", "{{range $x := $y := 3}}{{end}}", hasError, ""}, 289 // Another bug: variable read must ignore following punctuation. 290 {"bug1a", "{{$x:=.}}{{$x!2}}", hasError, ""}, // ! is just illegal here. 291 {"bug1b", "{{$x:=.}}{{$x+2}}", hasError, ""}, // $x+2 should not parse as ($x) (+2). 292 {"bug1c", "{{$x:=.}}{{$x +2}}", noError, "{{$x := .}}{{$x +2}}"}, // It's OK with a space. 293 // dot following a literal value 294 {"dot after integer", "{{1.E}}", hasError, ""}, 295 {"dot after float", "{{0.1.E}}", hasError, ""}, 296 {"dot after boolean", "{{true.E}}", hasError, ""}, 297 {"dot after char", "{{'a'.any}}", hasError, ""}, 298 {"dot after string", `{{"hello".guys}}`, hasError, ""}, 299 {"dot after dot", "{{..E}}", hasError, ""}, 300 {"dot after nil", "{{nil.E}}", hasError, ""}, 301 // Wrong pipeline 302 {"wrong pipeline dot", "{{12|.}}", hasError, ""}, 303 {"wrong pipeline number", "{{.|12|printf}}", hasError, ""}, 304 {"wrong pipeline string", "{{.|printf|\"error\"}}", hasError, ""}, 305 {"wrong pipeline char", "{{12|printf|'e'}}", hasError, ""}, 306 {"wrong pipeline boolean", "{{.|true}}", hasError, ""}, 307 {"wrong pipeline nil", "{{'c'|nil}}", hasError, ""}, 308 {"empty pipeline", `{{printf "%d" ( ) }}`, hasError, ""}, 309 // Missing pipeline in block 310 {"block definition", `{{block "foo"}}hello{{end}}`, hasError, ""}, 311 } 312 313 var builtins = map[string]interface{}{ 314 "printf": fmt.Sprintf, 315 "contains": strings.Contains, 316 } 317 318 func testParse(doCopy bool, t *testing.T) { 319 textFormat = "%q" 320 defer func() { textFormat = "%s" }() 321 for _, test := range parseTests { 322 tmpl, err := New(test.name).Parse(test.input, "", "", make(map[string]*Tree), builtins) 323 switch { 324 case err == nil && !test.ok: 325 t.Errorf("%q: expected error; got none", test.name) 326 continue 327 case err != nil && test.ok: 328 t.Errorf("%q: unexpected error: %v", test.name, err) 329 continue 330 case err != nil && !test.ok: 331 // expected error, got one 332 if *debug { 333 fmt.Printf("%s: %s\n\t%s\n", test.name, test.input, err) 334 } 335 continue 336 } 337 var result string 338 if doCopy { 339 result = tmpl.Root.Copy().String() 340 } else { 341 result = tmpl.Root.String() 342 } 343 if result != test.result { 344 t.Errorf("%s=(%q): got\n\t%v\nexpected\n\t%v", test.name, test.input, result, test.result) 345 } 346 } 347 } 348 349 func TestParse(t *testing.T) { 350 testParse(false, t) 351 } 352 353 // Same as TestParse, but we copy the node first 354 func TestParseCopy(t *testing.T) { 355 testParse(true, t) 356 } 357 358 func TestParseWithComments(t *testing.T) { 359 textFormat = "%q" 360 defer func() { textFormat = "%s" }() 361 tests := [...]parseTest{ 362 {"comment", "{{/*\n\n\n*/}}", noError, "{{/*\n\n\n*/}}"}, 363 {"comment trim left", "x \r\n\t{{- /* hi */}}", noError, `"x"{{/* hi */}}`}, 364 {"comment trim right", "{{/* hi */ -}}\n\n\ty", noError, `{{/* hi */}}"y"`}, 365 {"comment trim left and right", "x \r\n\t{{- /* */ -}}\n\n\ty", noError, `"x"{{/* */}}"y"`}, 366 } 367 for _, test := range tests { 368 t.Run(test.name, func(t *testing.T) { 369 tr := New(test.name) 370 tr.Mode = ParseComments 371 tmpl, err := tr.Parse(test.input, "", "", make(map[string]*Tree)) 372 if err != nil { 373 t.Errorf("%q: expected error; got none", test.name) 374 } 375 if result := tmpl.Root.String(); result != test.result { 376 t.Errorf("%s=(%q): got\n\t%v\nexpected\n\t%v", test.name, test.input, result, test.result) 377 } 378 }) 379 } 380 } 381 382 type isEmptyTest struct { 383 name string 384 input string 385 empty bool 386 } 387 388 var isEmptyTests = []isEmptyTest{ 389 {"empty", ``, true}, 390 {"nonempty", `hello`, false}, 391 {"spaces only", " \t\n \t\n", true}, 392 {"comment only", "{{/* comment */}}", true}, 393 {"definition", `{{define "x"}}something{{end}}`, true}, 394 {"definitions and space", "{{define `x`}}something{{end}}\n\n{{define `y`}}something{{end}}\n\n", true}, 395 {"definitions and text", "{{define `x`}}something{{end}}\nx\n{{define `y`}}something{{end}}\ny\n", false}, 396 {"definition and action", "{{define `x`}}something{{end}}{{if 3}}foo{{end}}", false}, 397 } 398 399 func TestIsEmpty(t *testing.T) { 400 if !IsEmptyTree(nil) { 401 t.Errorf("nil tree is not empty") 402 } 403 for _, test := range isEmptyTests { 404 tree, err := New("root").Parse(test.input, "", "", make(map[string]*Tree), nil) 405 if err != nil { 406 t.Errorf("%q: unexpected error: %v", test.name, err) 407 continue 408 } 409 if empty := IsEmptyTree(tree.Root); empty != test.empty { 410 t.Errorf("%q: expected %t got %t", test.name, test.empty, empty) 411 } 412 } 413 } 414 415 func TestErrorContextWithTreeCopy(t *testing.T) { 416 tree, err := New("root").Parse("{{if true}}{{end}}", "", "", make(map[string]*Tree), nil) 417 if err != nil { 418 t.Fatalf("unexpected tree parse failure: %v", err) 419 } 420 treeCopy := tree.Copy() 421 wantLocation, wantContext := tree.ErrorContext(tree.Root.Nodes[0]) 422 gotLocation, gotContext := treeCopy.ErrorContext(treeCopy.Root.Nodes[0]) 423 if wantLocation != gotLocation { 424 t.Errorf("wrong error location want %q got %q", wantLocation, gotLocation) 425 } 426 if wantContext != gotContext { 427 t.Errorf("wrong error location want %q got %q", wantContext, gotContext) 428 } 429 } 430 431 // All failures, and the result is a string that must appear in the error message. 432 var errorTests = []parseTest{ 433 // Check line numbers are accurate. 434 {"unclosed1", 435 "line1\n{{", 436 hasError, `unclosed1:2: unclosed action`}, 437 {"unclosed2", 438 "line1\n{{define `x`}}line2\n{{", 439 hasError, `unclosed2:3: unclosed action`}, 440 {"unclosed3", 441 "line1\n{{\"x\"\n\"y\"\n", 442 hasError, `unclosed3:4: unclosed action started at unclosed3:2`}, 443 {"unclosed4", 444 "{{\n\n\n\n\n", 445 hasError, `unclosed4:6: unclosed action started at unclosed4:1`}, 446 {"var1", 447 "line1\n{{\nx\n}}", 448 hasError, `var1:3: function "x" not defined`}, 449 // Specific errors. 450 {"function", 451 "{{foo}}", 452 hasError, `function "foo" not defined`}, 453 {"comment1", 454 "{{/*}}", 455 hasError, `comment1:1: unclosed comment`}, 456 {"comment2", 457 "{{/*\nhello\n}}", 458 hasError, `comment2:1: unclosed comment`}, 459 {"lparen", 460 "{{.X (1 2 3}}", 461 hasError, `unclosed left paren`}, 462 {"rparen", 463 "{{.X 1 2 3 ) }}", 464 hasError, `unexpected ")" in command`}, 465 {"rparen2", 466 "{{(.X 1 2 3", 467 hasError, `unclosed action`}, 468 {"space", 469 "{{`x`3}}", 470 hasError, `in operand`}, 471 {"idchar", 472 "{{a#}}", 473 hasError, `'#'`}, 474 {"charconst", 475 "{{'a}}", 476 hasError, `unterminated character constant`}, 477 {"stringconst", 478 `{{"a}}`, 479 hasError, `unterminated quoted string`}, 480 {"rawstringconst", 481 "{{`a}}", 482 hasError, `unterminated raw quoted string`}, 483 {"number", 484 "{{0xi}}", 485 hasError, `number syntax`}, 486 {"multidefine", 487 "{{define `a`}}a{{end}}{{define `a`}}b{{end}}", 488 hasError, `multiple definition of template`}, 489 {"eof", 490 "{{range .X}}", 491 hasError, `unexpected EOF`}, 492 {"variable", 493 // Declare $x so it's defined, to avoid that error, and then check we don't parse a declaration. 494 "{{$x := 23}}{{with $x.y := 3}}{{$x 23}}{{end}}", 495 hasError, `unexpected ":="`}, 496 {"multidecl", 497 "{{$a,$b,$c := 23}}", 498 hasError, `too many declarations`}, 499 {"undefvar", 500 "{{$a}}", 501 hasError, `undefined variable`}, 502 {"wrongdot", 503 "{{true.any}}", 504 hasError, `unexpected . after term`}, 505 {"wrongpipeline", 506 "{{12|false}}", 507 hasError, `non executable command in pipeline`}, 508 {"emptypipeline", 509 `{{ ( ) }}`, 510 hasError, `missing value for parenthesized pipeline`}, 511 {"multilinerawstring", 512 "{{ $v := `\n` }} {{", 513 hasError, `multilinerawstring:2: unclosed action`}, 514 {"rangeundefvar", 515 "{{range $k}}{{end}}", 516 hasError, `undefined variable`}, 517 {"rangeundefvars", 518 "{{range $k, $v}}{{end}}", 519 hasError, `undefined variable`}, 520 {"rangemissingvalue1", 521 "{{range $k,}}{{end}}", 522 hasError, `missing value for range`}, 523 {"rangemissingvalue2", 524 "{{range $k, $v := }}{{end}}", 525 hasError, `missing value for range`}, 526 {"rangenotvariable1", 527 "{{range $k, .}}{{end}}", 528 hasError, `range can only initialize variables`}, 529 {"rangenotvariable2", 530 "{{range $k, 123 := .}}{{end}}", 531 hasError, `range can only initialize variables`}, 532 } 533 534 func TestErrors(t *testing.T) { 535 for _, test := range errorTests { 536 t.Run(test.name, func(t *testing.T) { 537 _, err := New(test.name).Parse(test.input, "", "", make(map[string]*Tree)) 538 if err == nil { 539 t.Fatalf("expected error %q, got nil", test.result) 540 } 541 if !strings.Contains(err.Error(), test.result) { 542 t.Fatalf("error %q does not contain %q", err, test.result) 543 } 544 }) 545 } 546 } 547 548 func TestBlock(t *testing.T) { 549 const ( 550 input = `a{{block "inner" .}}bar{{.}}baz{{end}}b` 551 outer = `a{{template "inner" .}}b` 552 inner = `bar{{.}}baz` 553 ) 554 treeSet := make(map[string]*Tree) 555 tmpl, err := New("outer").Parse(input, "", "", treeSet, nil) 556 if err != nil { 557 t.Fatal(err) 558 } 559 if g, w := tmpl.Root.String(), outer; g != w { 560 t.Errorf("outer template = %q, want %q", g, w) 561 } 562 inTmpl := treeSet["inner"] 563 if inTmpl == nil { 564 t.Fatal("block did not define template") 565 } 566 if g, w := inTmpl.Root.String(), inner; g != w { 567 t.Errorf("inner template = %q, want %q", g, w) 568 } 569 } 570 571 func TestLineNum(t *testing.T) { 572 const count = 100 573 text := strings.Repeat("{{printf 1234}}\n", count) 574 tree, err := New("bench").Parse(text, "", "", make(map[string]*Tree), builtins) 575 if err != nil { 576 t.Fatal(err) 577 } 578 // Check the line numbers. Each line is an action containing a template, followed by text. 579 // That's two nodes per line. 580 nodes := tree.Root.Nodes 581 for i := 0; i < len(nodes); i += 2 { 582 line := 1 + i/2 583 // Action first. 584 action := nodes[i].(*ActionNode) 585 if action.Line != line { 586 t.Fatalf("line %d: action is line %d", line, action.Line) 587 } 588 pipe := action.Pipe 589 if pipe.Line != line { 590 t.Fatalf("line %d: pipe is line %d", line, pipe.Line) 591 } 592 } 593 } 594 595 func BenchmarkParseLarge(b *testing.B) { 596 text := strings.Repeat("{{1234}}\n", 10000) 597 for i := 0; i < b.N; i++ { 598 _, err := New("bench").Parse(text, "", "", make(map[string]*Tree), builtins) 599 if err != nil { 600 b.Fatal(err) 601 } 602 } 603 } 604 605 var sinkv, sinkl string 606 607 func BenchmarkVariableString(b *testing.B) { 608 v := &VariableNode{ 609 Ident: []string{"$", "A", "BB", "CCC", "THIS_IS_THE_VARIABLE_BEING_PROCESSED"}, 610 } 611 b.ResetTimer() 612 b.ReportAllocs() 613 for i := 0; i < b.N; i++ { 614 sinkv = v.String() 615 } 616 if sinkv == "" { 617 b.Fatal("Benchmark was not run") 618 } 619 } 620 621 func BenchmarkListString(b *testing.B) { 622 text := ` 623 {{(printf .Field1.Field2.Field3).Value}} 624 {{$x := (printf .Field1.Field2.Field3).Value}} 625 {{$y := (printf $x.Field1.Field2.Field3).Value}} 626 {{$z := $y.Field1.Field2.Field3}} 627 {{if contains $y $z}} 628 {{printf "%q" $y}} 629 {{else}} 630 {{printf "%q" $x}} 631 {{end}} 632 {{with $z.Field1 | contains "boring"}} 633 {{printf "%q" . | printf "%s"}} 634 {{else}} 635 {{printf "%d %d %d" 11 11 11}} 636 {{printf "%d %d %s" 22 22 $x.Field1.Field2.Field3 | printf "%s"}} 637 {{printf "%v" (contains $z.Field1.Field2 $y)}} 638 {{end}} 639 ` 640 tree, err := New("bench").Parse(text, "", "", make(map[string]*Tree), builtins) 641 if err != nil { 642 b.Fatal(err) 643 } 644 b.ResetTimer() 645 b.ReportAllocs() 646 for i := 0; i < b.N; i++ { 647 sinkl = tree.Root.String() 648 } 649 if sinkl == "" { 650 b.Fatal("Benchmark was not run") 651 } 652 }