github.com/tcnksm/go@v0.0.0-20141208075154-439b32936367/src/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 {"073", true, true, true, false, 073, 073, 073, 0}, 34 {"0x73", true, true, true, false, 0x73, 0x73, 0x73, 0}, 35 {"-73", true, false, true, false, -73, 0, -73, 0}, 36 {"+73", true, false, true, false, 73, 0, 73, 0}, 37 {"100", true, true, true, false, 100, 100, 100, 0}, 38 {"1e9", true, true, true, false, 1e9, 1e9, 1e9, 0}, 39 {"-1e9", true, false, true, false, -1e9, 0, -1e9, 0}, 40 {"-1.2", false, false, true, false, 0, 0, -1.2, 0}, 41 {"1e19", false, true, true, false, 0, 1e19, 1e19, 0}, 42 {"-1e19", false, false, true, false, 0, 0, -1e19, 0}, 43 {"4i", false, false, false, true, 0, 0, 0, 4i}, 44 {"-1.2+4.2i", false, false, false, true, 0, 0, 0, -1.2 + 4.2i}, 45 {"073i", false, false, false, true, 0, 0, 0, 73i}, // not octal! 46 // complex with 0 imaginary are float (and maybe integer) 47 {"0i", true, true, true, true, 0, 0, 0, 0}, 48 {"-1.2+0i", false, false, true, true, 0, 0, -1.2, -1.2}, 49 {"-12+0i", true, false, true, true, -12, 0, -12, -12}, 50 {"13+0i", true, true, true, true, 13, 13, 13, 13}, 51 // funny bases 52 {"0123", true, true, true, false, 0123, 0123, 0123, 0}, 53 {"-0x0", true, true, true, false, 0, 0, 0, 0}, 54 {"0xdeadbeef", true, true, true, false, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0}, 55 // character constants 56 {`'a'`, true, true, true, false, 'a', 'a', 'a', 0}, 57 {`'\n'`, true, true, true, false, '\n', '\n', '\n', 0}, 58 {`'\\'`, true, true, true, false, '\\', '\\', '\\', 0}, 59 {`'\''`, true, true, true, false, '\'', '\'', '\'', 0}, 60 {`'\xFF'`, true, true, true, false, 0xFF, 0xFF, 0xFF, 0}, 61 {`'パ'`, true, true, true, false, 0x30d1, 0x30d1, 0x30d1, 0}, 62 {`'\u30d1'`, true, true, true, false, 0x30d1, 0x30d1, 0x30d1, 0}, 63 {`'\U000030d1'`, true, true, true, false, 0x30d1, 0x30d1, 0x30d1, 0}, 64 // some broken syntax 65 {text: "+-2"}, 66 {text: "0x123."}, 67 {text: "1e."}, 68 {text: "0xi."}, 69 {text: "1+2."}, 70 {text: "'x"}, 71 {text: "'xx'"}, 72 // Issue 8622 - 0xe parsed as floating point. Very embarrassing. 73 {"0xef", true, true, true, false, 0xef, 0xef, 0xef, 0}, 74 } 75 76 func TestNumberParse(t *testing.T) { 77 for _, test := range numberTests { 78 // If fmt.Sscan thinks it's complex, it's complex. We can't trust the output 79 // because imaginary comes out as a number. 80 var c complex128 81 typ := itemNumber 82 var tree *Tree 83 if test.text[0] == '\'' { 84 typ = itemCharConstant 85 } else { 86 _, err := fmt.Sscan(test.text, &c) 87 if err == nil { 88 typ = itemComplex 89 } 90 } 91 n, err := tree.newNumber(0, test.text, typ) 92 ok := test.isInt || test.isUint || test.isFloat || test.isComplex 93 if ok && err != nil { 94 t.Errorf("unexpected error for %q: %s", test.text, err) 95 continue 96 } 97 if !ok && err == nil { 98 t.Errorf("expected error for %q", test.text) 99 continue 100 } 101 if !ok { 102 if *debug { 103 fmt.Printf("%s\n\t%s\n", test.text, err) 104 } 105 continue 106 } 107 if n.IsComplex != test.isComplex { 108 t.Errorf("complex incorrect for %q; should be %t", test.text, test.isComplex) 109 } 110 if test.isInt { 111 if !n.IsInt { 112 t.Errorf("expected integer for %q", test.text) 113 } 114 if n.Int64 != test.int64 { 115 t.Errorf("int64 for %q should be %d Is %d", test.text, test.int64, n.Int64) 116 } 117 } else if n.IsInt { 118 t.Errorf("did not expect integer for %q", test.text) 119 } 120 if test.isUint { 121 if !n.IsUint { 122 t.Errorf("expected unsigned integer for %q", test.text) 123 } 124 if n.Uint64 != test.uint64 { 125 t.Errorf("uint64 for %q should be %d Is %d", test.text, test.uint64, n.Uint64) 126 } 127 } else if n.IsUint { 128 t.Errorf("did not expect unsigned integer for %q", test.text) 129 } 130 if test.isFloat { 131 if !n.IsFloat { 132 t.Errorf("expected float for %q", test.text) 133 } 134 if n.Float64 != test.float64 { 135 t.Errorf("float64 for %q should be %g Is %g", test.text, test.float64, n.Float64) 136 } 137 } else if n.IsFloat { 138 t.Errorf("did not expect float for %q", test.text) 139 } 140 if test.isComplex { 141 if !n.IsComplex { 142 t.Errorf("expected complex for %q", test.text) 143 } 144 if n.Complex128 != test.complex128 { 145 t.Errorf("complex128 for %q should be %g Is %g", test.text, test.complex128, n.Complex128) 146 } 147 } else if n.IsComplex { 148 t.Errorf("did not expect complex for %q", test.text) 149 } 150 } 151 } 152 153 type parseTest struct { 154 name string 155 input string 156 ok bool 157 result string // what the user would see in an error message. 158 } 159 160 const ( 161 noError = true 162 hasError = false 163 ) 164 165 var parseTests = []parseTest{ 166 {"empty", "", noError, 167 ``}, 168 {"comment", "{{/*\n\n\n*/}}", noError, 169 ``}, 170 {"spaces", " \t\n", noError, 171 `" \t\n"`}, 172 {"text", "some text", noError, 173 `"some text"`}, 174 {"emptyAction", "{{}}", hasError, 175 `{{}}`}, 176 {"field", "{{.X}}", noError, 177 `{{.X}}`}, 178 {"simple command", "{{printf}}", noError, 179 `{{printf}}`}, 180 {"$ invocation", "{{$}}", noError, 181 "{{$}}"}, 182 {"variable invocation", "{{with $x := 3}}{{$x 23}}{{end}}", noError, 183 "{{with $x := 3}}{{$x 23}}{{end}}"}, 184 {"variable with fields", "{{$.I}}", noError, 185 "{{$.I}}"}, 186 {"multi-word command", "{{printf `%d` 23}}", noError, 187 "{{printf `%d` 23}}"}, 188 {"pipeline", "{{.X|.Y}}", noError, 189 `{{.X | .Y}}`}, 190 {"pipeline with decl", "{{$x := .X|.Y}}", noError, 191 `{{$x := .X | .Y}}`}, 192 {"nested pipeline", "{{.X (.Y .Z) (.A | .B .C) (.E)}}", noError, 193 `{{.X (.Y .Z) (.A | .B .C) (.E)}}`}, 194 {"field applied to parentheses", "{{(.Y .Z).Field}}", noError, 195 `{{(.Y .Z).Field}}`}, 196 {"simple if", "{{if .X}}hello{{end}}", noError, 197 `{{if .X}}"hello"{{end}}`}, 198 {"if with else", "{{if .X}}true{{else}}false{{end}}", noError, 199 `{{if .X}}"true"{{else}}"false"{{end}}`}, 200 {"if with else if", "{{if .X}}true{{else if .Y}}false{{end}}", noError, 201 `{{if .X}}"true"{{else}}{{if .Y}}"false"{{end}}{{end}}`}, 202 {"if else chain", "+{{if .X}}X{{else if .Y}}Y{{else if .Z}}Z{{end}}+", noError, 203 `"+"{{if .X}}"X"{{else}}{{if .Y}}"Y"{{else}}{{if .Z}}"Z"{{end}}{{end}}{{end}}"+"`}, 204 {"simple range", "{{range .X}}hello{{end}}", noError, 205 `{{range .X}}"hello"{{end}}`}, 206 {"chained field range", "{{range .X.Y.Z}}hello{{end}}", noError, 207 `{{range .X.Y.Z}}"hello"{{end}}`}, 208 {"nested range", "{{range .X}}hello{{range .Y}}goodbye{{end}}{{end}}", noError, 209 `{{range .X}}"hello"{{range .Y}}"goodbye"{{end}}{{end}}`}, 210 {"range with else", "{{range .X}}true{{else}}false{{end}}", noError, 211 `{{range .X}}"true"{{else}}"false"{{end}}`}, 212 {"range over pipeline", "{{range .X|.M}}true{{else}}false{{end}}", noError, 213 `{{range .X | .M}}"true"{{else}}"false"{{end}}`}, 214 {"range []int", "{{range .SI}}{{.}}{{end}}", noError, 215 `{{range .SI}}{{.}}{{end}}`}, 216 {"range 1 var", "{{range $x := .SI}}{{.}}{{end}}", noError, 217 `{{range $x := .SI}}{{.}}{{end}}`}, 218 {"range 2 vars", "{{range $x, $y := .SI}}{{.}}{{end}}", noError, 219 `{{range $x, $y := .SI}}{{.}}{{end}}`}, 220 {"constants", "{{range .SI 1 -3.2i true false 'a' nil}}{{end}}", noError, 221 `{{range .SI 1 -3.2i true false 'a' nil}}{{end}}`}, 222 {"template", "{{template `x`}}", noError, 223 `{{template "x"}}`}, 224 {"template with arg", "{{template `x` .Y}}", noError, 225 `{{template "x" .Y}}`}, 226 {"with", "{{with .X}}hello{{end}}", noError, 227 `{{with .X}}"hello"{{end}}`}, 228 {"with with else", "{{with .X}}hello{{else}}goodbye{{end}}", noError, 229 `{{with .X}}"hello"{{else}}"goodbye"{{end}}`}, 230 // Errors. 231 {"unclosed action", "hello{{range", hasError, ""}, 232 {"unmatched end", "{{end}}", hasError, ""}, 233 {"missing end", "hello{{range .x}}", hasError, ""}, 234 {"missing end after else", "hello{{range .x}}{{else}}", hasError, ""}, 235 {"undefined function", "hello{{undefined}}", hasError, ""}, 236 {"undefined variable", "{{$x}}", hasError, ""}, 237 {"variable undefined after end", "{{with $x := 4}}{{end}}{{$x}}", hasError, ""}, 238 {"variable undefined in template", "{{template $v}}", hasError, ""}, 239 {"declare with field", "{{with $x.Y := 4}}{{end}}", hasError, ""}, 240 {"template with field ref", "{{template .X}}", hasError, ""}, 241 {"template with var", "{{template $v}}", hasError, ""}, 242 {"invalid punctuation", "{{printf 3, 4}}", hasError, ""}, 243 {"multidecl outside range", "{{with $v, $u := 3}}{{end}}", hasError, ""}, 244 {"too many decls in range", "{{range $u, $v, $w := 3}}{{end}}", hasError, ""}, 245 {"dot applied to parentheses", "{{printf (printf .).}}", hasError, ""}, 246 {"adjacent args", "{{printf 3`x`}}", hasError, ""}, 247 {"adjacent args with .", "{{printf `x`.}}", hasError, ""}, 248 {"extra end after if", "{{if .X}}a{{else if .Y}}b{{end}}{{end}}", hasError, ""}, 249 // Equals (and other chars) do not assignments make (yet). 250 {"bug0a", "{{$x := 0}}{{$x}}", noError, "{{$x := 0}}{{$x}}"}, 251 {"bug0b", "{{$x = 1}}{{$x}}", hasError, ""}, 252 {"bug0c", "{{$x ! 2}}{{$x}}", hasError, ""}, 253 {"bug0d", "{{$x % 3}}{{$x}}", hasError, ""}, 254 // Check the parse fails for := rather than comma. 255 {"bug0e", "{{range $x := $y := 3}}{{end}}", hasError, ""}, 256 // Another bug: variable read must ignore following punctuation. 257 {"bug1a", "{{$x:=.}}{{$x!2}}", hasError, ""}, // ! is just illegal here. 258 {"bug1b", "{{$x:=.}}{{$x+2}}", hasError, ""}, // $x+2 should not parse as ($x) (+2). 259 {"bug1c", "{{$x:=.}}{{$x +2}}", noError, "{{$x := .}}{{$x +2}}"}, // It's OK with a space. 260 } 261 262 var builtins = map[string]interface{}{ 263 "printf": fmt.Sprintf, 264 } 265 266 func testParse(doCopy bool, t *testing.T) { 267 textFormat = "%q" 268 defer func() { textFormat = "%s" }() 269 for _, test := range parseTests { 270 tmpl, err := New(test.name).Parse(test.input, "", "", make(map[string]*Tree), builtins) 271 switch { 272 case err == nil && !test.ok: 273 t.Errorf("%q: expected error; got none", test.name) 274 continue 275 case err != nil && test.ok: 276 t.Errorf("%q: unexpected error: %v", test.name, err) 277 continue 278 case err != nil && !test.ok: 279 // expected error, got one 280 if *debug { 281 fmt.Printf("%s: %s\n\t%s\n", test.name, test.input, err) 282 } 283 continue 284 } 285 var result string 286 if doCopy { 287 result = tmpl.Root.Copy().String() 288 } else { 289 result = tmpl.Root.String() 290 } 291 if result != test.result { 292 t.Errorf("%s=(%q): got\n\t%v\nexpected\n\t%v", test.name, test.input, result, test.result) 293 } 294 } 295 } 296 297 func TestParse(t *testing.T) { 298 testParse(false, t) 299 } 300 301 // Same as TestParse, but we copy the node first 302 func TestParseCopy(t *testing.T) { 303 testParse(true, t) 304 } 305 306 type isEmptyTest struct { 307 name string 308 input string 309 empty bool 310 } 311 312 var isEmptyTests = []isEmptyTest{ 313 {"empty", ``, true}, 314 {"nonempty", `hello`, false}, 315 {"spaces only", " \t\n \t\n", true}, 316 {"definition", `{{define "x"}}something{{end}}`, true}, 317 {"definitions and space", "{{define `x`}}something{{end}}\n\n{{define `y`}}something{{end}}\n\n", true}, 318 {"definitions and text", "{{define `x`}}something{{end}}\nx\n{{define `y`}}something{{end}}\ny\n", false}, 319 {"definition and action", "{{define `x`}}something{{end}}{{if 3}}foo{{end}}", false}, 320 } 321 322 func TestIsEmpty(t *testing.T) { 323 if !IsEmptyTree(nil) { 324 t.Errorf("nil tree is not empty") 325 } 326 for _, test := range isEmptyTests { 327 tree, err := New("root").Parse(test.input, "", "", make(map[string]*Tree), nil) 328 if err != nil { 329 t.Errorf("%q: unexpected error: %v", test.name, err) 330 continue 331 } 332 if empty := IsEmptyTree(tree.Root); empty != test.empty { 333 t.Errorf("%q: expected %t got %t", test.name, test.empty, empty) 334 } 335 } 336 } 337 338 func TestErrorContextWithTreeCopy(t *testing.T) { 339 tree, err := New("root").Parse("{{if true}}{{end}}", "", "", make(map[string]*Tree), nil) 340 if err != nil { 341 t.Fatalf("unexpected tree parse failure: %v", err) 342 } 343 treeCopy := tree.Copy() 344 wantLocation, wantContext := tree.ErrorContext(tree.Root.Nodes[0]) 345 gotLocation, gotContext := treeCopy.ErrorContext(treeCopy.Root.Nodes[0]) 346 if wantLocation != gotLocation { 347 t.Errorf("wrong error location want %q got %q", wantLocation, gotLocation) 348 } 349 if wantContext != gotContext { 350 t.Errorf("wrong error location want %q got %q", wantContext, gotContext) 351 } 352 } 353 354 // All failures, and the result is a string that must appear in the error message. 355 var errorTests = []parseTest{ 356 // Check line numbers are accurate. 357 {"unclosed1", 358 "line1\n{{", 359 hasError, `unclosed1:2: unexpected unclosed action in command`}, 360 {"unclosed2", 361 "line1\n{{define `x`}}line2\n{{", 362 hasError, `unclosed2:3: unexpected unclosed action in command`}, 363 // Specific errors. 364 {"function", 365 "{{foo}}", 366 hasError, `function "foo" not defined`}, 367 {"comment", 368 "{{/*}}", 369 hasError, `unclosed comment`}, 370 {"lparen", 371 "{{.X (1 2 3}}", 372 hasError, `unclosed left paren`}, 373 {"rparen", 374 "{{.X 1 2 3)}}", 375 hasError, `unexpected ")"`}, 376 {"space", 377 "{{`x`3}}", 378 hasError, `missing space?`}, 379 {"idchar", 380 "{{a#}}", 381 hasError, `'#'`}, 382 {"charconst", 383 "{{'a}}", 384 hasError, `unterminated character constant`}, 385 {"stringconst", 386 `{{"a}}`, 387 hasError, `unterminated quoted string`}, 388 {"rawstringconst", 389 "{{`a}}", 390 hasError, `unterminated raw quoted string`}, 391 {"number", 392 "{{0xi}}", 393 hasError, `number syntax`}, 394 {"multidefine", 395 "{{define `a`}}a{{end}}{{define `a`}}b{{end}}", 396 hasError, `multiple definition of template`}, 397 {"eof", 398 "{{range .X}}", 399 hasError, `unexpected EOF`}, 400 {"variable", 401 // Declare $x so it's defined, to avoid that error, and then check we don't parse a declaration. 402 "{{$x := 23}}{{with $x.y := 3}}{{$x 23}}{{end}}", 403 hasError, `unexpected ":="`}, 404 {"multidecl", 405 "{{$a,$b,$c := 23}}", 406 hasError, `too many declarations`}, 407 {"undefvar", 408 "{{$a}}", 409 hasError, `undefined variable`}, 410 } 411 412 func TestErrors(t *testing.T) { 413 for _, test := range errorTests { 414 _, err := New(test.name).Parse(test.input, "", "", make(map[string]*Tree)) 415 if err == nil { 416 t.Errorf("%q: expected error", test.name) 417 continue 418 } 419 if !strings.Contains(err.Error(), test.result) { 420 t.Errorf("%q: error %q does not contain %q", test.name, err, test.result) 421 } 422 } 423 }