Debian Codegraph @

tpl/internal/go_templates/texttemplate/parse/parse_test.go

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