Debian Codegraph @

modfile/read_test.go

raw
1 // Copyright 2018 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 modfile
6
7 import (
8 "bytes"
9 "fmt"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "reflect"
14 "strings"
15 "testing"
16 )
17
18 // exists reports whether the named file exists.
19 func exists(name string) bool {
20 _, err := os.Stat(name)
21 return err == nil
22 }
23
24 // Test that reading and then writing the golden files
25 // does not change their output.
26 func TestPrintGolden(t *testing.T) {
27 outs, err := filepath.Glob("testdata/*.golden")
28 if err != nil {
29 t.Fatal(err)
30 }
31 for _, out := range outs {
32 name := strings.TrimSuffix(filepath.Base(out), ".golden")
33 t.Run(name, func(t *testing.T) {
34 t.Parallel()
35 testPrint(t, out, out)
36 })
37 }
38 }
39
40 // testPrint is a helper for testing the printer.
41 // It reads the file named in, reformats it, and compares
42 // the result to the file named out.
43 func testPrint(t *testing.T, in, out string) {
44 data, err := os.ReadFile(in)
45 if err != nil {
46 t.Error(err)
47 return
48 }
49
50 golden, err := os.ReadFile(out)
51 if err != nil {
52 t.Error(err)
53 return
54 }
55
56 base := "testdata/" + filepath.Base(in)
57 f, err := parse(in, data)
58 if err != nil {
59 t.Error(err)
60 return
61 }
62
63 ndata := Format(f)
64
65 if !bytes.Equal(ndata, golden) {
66 t.Errorf("formatted %s incorrectly: diff shows -golden, +ours", base)
67 tdiff(t, string(golden), string(ndata))
68 return
69 }
70 }
71
72 // TestParsePunctuation verifies that certain ASCII punctuation characters
73 // (brackets, commas) are lexed as separate tokens, even when they're
74 // surrounded by identifier characters.
75 func TestParsePunctuation(t *testing.T) {
76 for _, test := range []struct {
77 desc, src, want string
78 }{
79 {"paren", "require ()", "require ( )"},
80 {"brackets", "require []{},", "require [ ] { } ,"},
81 {"mix", "require a[b]c{d}e,", "require a [ b ] c { d } e ,"},
82 {"block_mix", "require (\n\ta[b]\n)", "require ( a [ b ] )"},
83 {"interval", "require [v1.0.0, v1.1.0)", "require [ v1.0.0 , v1.1.0 )"},
84 } {
85 t.Run(test.desc, func(t *testing.T) {
86 f, err := parse("go.mod", []byte(test.src))
87 if err != nil {
88 t.Fatalf("parsing %q: %v", test.src, err)
89 }
90 var tokens []string
91 for _, stmt := range f.Stmt {
92 switch stmt := stmt.(type) {
93 case *Line:
94 tokens = append(tokens, stmt.Token...)
95 case *LineBlock:
96 tokens = append(tokens, stmt.Token...)
97 tokens = append(tokens, "(")
98 for _, line := range stmt.Line {
99 tokens = append(tokens, line.Token...)
100 }
101 tokens = append(tokens, ")")
102 default:
103 t.Fatalf("parsing %q: unexpected statement of type %T", test.src, stmt)
104 }
105 }
106 got := strings.Join(tokens, " ")
107 if got != test.want {
108 t.Errorf("parsing %q: got %q, want %q", test.src, got, test.want)
109 }
110 })
111 }
112 }
113
114 func TestParseLax(t *testing.T) {
115 badFile := []byte(`module m
116 surprise attack
117 x y (
118 z
119 )
120 exclude v1.2.3
121 replace <-!!!
122 retract v1.2.3 v1.2.4
123 retract (v1.2.3, v1.2.4]
124 retract v1.2.3 (
125 key1 value1
126 key2 value2
127 )
128 require good v1.0.0
129 `)
130 f, err := ParseLax("file", badFile, nil)
131 if err != nil {
132 t.Fatalf("ParseLax did not ignore irrelevant errors: %v", err)
133 }
134 if f.Module == nil || f.Module.Mod.Path != "m" {
135 t.Errorf("module directive was not parsed")
136 }
137 if len(f.Require) != 1 || f.Require[0].Mod.Path != "good" {
138 t.Errorf("require directive at end of file was not parsed")
139 }
140 }
141
142 // Test that when files in the testdata directory are parsed
143 // and printed and parsed again, we get the same parse tree
144 // both times.
145 func TestPrintParse(t *testing.T) {
146 outs, err := filepath.Glob("testdata/*")
147 if err != nil {
148 t.Fatal(err)
149 }
150 for _, out := range outs {
151 name := filepath.Base(out)
152 if !strings.HasSuffix(out, ".in") && !strings.HasSuffix(out, ".golden") {
153 continue
154 }
155 t.Run(name, func(t *testing.T) {
156 t.Parallel()
157 data, err := os.ReadFile(out)
158 if err != nil {
159 t.Fatal(err)
160 }
161
162 base := "testdata/" + filepath.Base(out)
163 f, err := parse(base, data)
164 if err != nil {
165 t.Fatalf("parsing original: %v", err)
166 }
167
168 ndata := Format(f)
169 f2, err := parse(base, ndata)
170 if err != nil {
171 t.Fatalf("parsing reformatted: %v", err)
172 }
173
174 eq := eqchecker{file: base}
175 if err := eq.check(f, f2); err != nil {
176 t.Errorf("not equal (parse/Format/parse): %v", err)
177 }
178
179 pf1, err := Parse(base, data, nil)
180 if err != nil {
181 switch base {
182 case "testdata/block.golden",
183 "testdata/block.in",
184 "testdata/comment.golden",
185 "testdata/comment.in",
186 "testdata/rule1.golden":
187 // ignore
188 default:
189 t.Errorf("should parse %v: %v", base, err)
190 }
191 }
192 if err == nil {
193 pf2, err := Parse(base, ndata, nil)
194 if err != nil {
195 t.Fatalf("Parsing reformatted: %v", err)
196 }
197 eq := eqchecker{file: base}
198 if err := eq.check(pf1, pf2); err != nil {
199 t.Errorf("not equal (parse/Format/Parse): %v", err)
200 }
201
202 ndata2, err := pf1.Format()
203 if err != nil {
204 t.Errorf("reformat: %v", err)
205 }
206 pf3, err := Parse(base, ndata2, nil)
207 if err != nil {
208 t.Fatalf("Parsing reformatted2: %v", err)
209 }
210 eq = eqchecker{file: base}
211 if err := eq.check(pf1, pf3); err != nil {
212 t.Errorf("not equal (Parse/Format/Parse): %v", err)
213 }
214 ndata = ndata2
215 }
216
217 if before, ok := strings.CutSuffix(out, ".in"); ok {
218 golden, err := os.ReadFile(before + ".golden")
219 if err != nil {
220 t.Fatal(err)
221 }
222 if !bytes.Equal(ndata, golden) {
223 t.Errorf("formatted %s incorrectly: diff shows -golden, +ours", base)
224 tdiff(t, string(golden), string(ndata))
225 return
226 }
227 }
228 })
229 }
230 }
231
232 // An eqchecker holds state for checking the equality of two parse trees.
233 type eqchecker struct {
234 file string
235 pos Position
236 }
237
238 // errorf returns an error described by the printf-style format and arguments,
239 // inserting the current file position before the error text.
240 func (eq *eqchecker) errorf(format string, args ...any) error {
241 return fmt.Errorf("%s:%d: %s", eq.file, eq.pos.Line,
242 fmt.Sprintf(format, args...))
243 }
244
245 // check checks that v and w represent the same parse tree.
246 // If not, it returns an error describing the first difference.
247 func (eq *eqchecker) check(v, w any) error {
248 return eq.checkValue(reflect.ValueOf(v), reflect.ValueOf(w))
249 }
250
251 var (
252 posType = reflect.TypeFor[Position]()
253 commentsType = reflect.TypeFor[Comments]()
254 )
255
256 // checkValue checks that v and w represent the same parse tree.
257 // If not, it returns an error describing the first difference.
258 func (eq *eqchecker) checkValue(v, w reflect.Value) error {
259 // inner returns the innermost expression for v.
260 // if v is a non-nil interface value, it returns the concrete
261 // value in the interface.
262 inner := func(v reflect.Value) reflect.Value {
263 for {
264 if v.Kind() == reflect.Interface && !v.IsNil() {
265 v = v.Elem()
266 continue
267 }
268 break
269 }
270 return v
271 }
272
273 v = inner(v)
274 w = inner(w)
275 if v.Kind() == reflect.Invalid && w.Kind() == reflect.Invalid {
276 return nil
277 }
278 if v.Kind() == reflect.Invalid {
279 return eq.errorf("nil interface became %s", w.Type())
280 }
281 if w.Kind() == reflect.Invalid {
282 return eq.errorf("%s became nil interface", v.Type())
283 }
284
285 if v.Type() != w.Type() {
286 return eq.errorf("%s became %s", v.Type(), w.Type())
287 }
288
289 if p, ok := v.Interface().(Expr); ok {
290 eq.pos, _ = p.Span()
291 }
292
293 switch v.Kind() {
294 default:
295 return eq.errorf("unexpected type %s", v.Type())
296
297 case reflect.Bool, reflect.Int, reflect.String:
298 vi := v.Interface()
299 wi := w.Interface()
300 if vi != wi {
301 return eq.errorf("%v became %v", vi, wi)
302 }
303
304 case reflect.Slice:
305 vl := v.Len()
306 wl := w.Len()
307 for i := 0; i < vl || i < wl; i++ {
308 if i >= vl {
309 return eq.errorf("unexpected %s", w.Index(i).Type())
310 }
311 if i >= wl {
312 return eq.errorf("missing %s", v.Index(i).Type())
313 }
314 if err := eq.checkValue(v.Index(i), w.Index(i)); err != nil {
315 return err
316 }
317 }
318
319 case reflect.Struct:
320 // Fields in struct must match.
321 t := v.Type()
322 n := t.NumField()
323 for i := range n {
324 tf := t.Field(i)
325 switch {
326 default:
327 if err := eq.checkValue(v.Field(i), w.Field(i)); err != nil {
328 return err
329 }
330
331 case tf.Type == posType: // ignore positions
332 case tf.Type == commentsType: // ignore comment assignment
333 }
334 }
335
336 case reflect.Pointer, reflect.Interface:
337 if v.IsNil() != w.IsNil() {
338 if v.IsNil() {
339 return eq.errorf("unexpected %s", w.Elem().Type())
340 }
341 return eq.errorf("missing %s", v.Elem().Type())
342 }
343 if err := eq.checkValue(v.Elem(), w.Elem()); err != nil {
344 return err
345 }
346 }
347 return nil
348 }
349
350 // diff returns the output of running diff on b1 and b2.
351 func diff(b1, b2 []byte) (data []byte, err error) {
352 f1, err := os.CreateTemp("", "testdiff")
353 if err != nil {
354 return nil, err
355 }
356 defer os.Remove(f1.Name())
357 defer f1.Close()
358
359 f2, err := os.CreateTemp("", "testdiff")
360 if err != nil {
361 return nil, err
362 }
363 defer os.Remove(f2.Name())
364 defer f2.Close()
365
366 f1.Write(b1)
367 f2.Write(b2)
368
369 data, err = exec.Command("diff", "-u", f1.Name(), f2.Name()).CombinedOutput()
370 if len(data) > 0 {
371 // diff exits with a non-zero status when the files don't match.
372 // Ignore that failure as long as we get output.
373 err = nil
374 }
375 return
376 }
377
378 // tdiff logs the diff output to t.Error.
379 func tdiff(t *testing.T, a, b string) {
380 data, err := diff([]byte(a), []byte(b))
381 if err != nil {
382 t.Error(err)
383 return
384 }
385 t.Error(string(data))
386 }
387
388 var modulePathTests = []struct {
389 input []byte
390 expected string
391 }{
392 {input: []byte("module \"github.com/rsc/vgotest\""), expected: "github.com/rsc/vgotest"},
393 {input: []byte("module github.com/rsc/vgotest"), expected: "github.com/rsc/vgotest"},
394 {input: []byte("module \"github.com/rsc/vgotest\""), expected: "github.com/rsc/vgotest"},
395 {input: []byte("module github.com/rsc/vgotest"), expected: "github.com/rsc/vgotest"},
396 {input: []byte("module `github.com/rsc/vgotest`"), expected: "github.com/rsc/vgotest"},
397 {input: []byte("module \"github.com/rsc/vgotest/v2\""), expected: "github.com/rsc/vgotest/v2"},
398 {input: []byte("module github.com/rsc/vgotest/v2"), expected: "github.com/rsc/vgotest/v2"},
399 {input: []byte("module \"gopkg.in/yaml.v2\""), expected: "gopkg.in/yaml.v2"},
400 {input: []byte("module gopkg.in/yaml.v2"), expected: "gopkg.in/yaml.v2"},
401 {input: []byte("module \"gopkg.in/check.v1\"\n"), expected: "gopkg.in/check.v1"},
402 {input: []byte("module \"gopkg.in/check.v1\n\""), expected: ""},
403 {input: []byte("module gopkg.in/check.v1\n"), expected: "gopkg.in/check.v1"},
404 {input: []byte("module \"gopkg.in/check.v1\"\r\n"), expected: "gopkg.in/check.v1"},
405 {input: []byte("module gopkg.in/check.v1\r\n"), expected: "gopkg.in/check.v1"},
406 {input: []byte("module \"gopkg.in/check.v1\"\n\n"), expected: "gopkg.in/check.v1"},
407 {input: []byte("module gopkg.in/check.v1\n\n"), expected: "gopkg.in/check.v1"},
408 {input: []byte("module \n\"gopkg.in/check.v1\"\n\n"), expected: ""},
409 {input: []byte("module \ngopkg.in/check.v1\n\n"), expected: ""},
410 {input: []byte("module \"gopkg.in/check.v1\"asd"), expected: ""},
411 {input: []byte("module \n\"gopkg.in/check.v1\"\n\n"), expected: ""},
412 {input: []byte("module \ngopkg.in/check.v1\n\n"), expected: ""},
413 {input: []byte("module \"gopkg.in/check.v1\"asd"), expected: ""},
414 {input: []byte("module \nmodule a/b/c "), expected: "a/b/c"},
415 {input: []byte("module \" \""), expected: " "},
416 {input: []byte("module "), expected: ""},
417 {input: []byte("module \" a/b/c \""), expected: " a/b/c "},
418 {input: []byte("module \"github.com/rsc/vgotest1\" // with a comment"), expected: "github.com/rsc/vgotest1"},
419 }
420
421 func TestModulePath(t *testing.T) {
422 for _, test := range modulePathTests {
423 t.Run(string(test.input), func(t *testing.T) {
424 result := ModulePath(test.input)
425 if result != test.expected {
426 t.Fatalf("ModulePath(%q): %s, want %s", string(test.input), result, test.expected)
427 }
428 })
429 }
430 }
431
432 func TestParseVersions(t *testing.T) {
433 tests := []struct {
434 desc, input string
435 ok bool
436 laxOK bool // ok=true implies laxOK=true; only set if ok=false
437 }{
438 // go lines
439 {desc: "empty", input: "module m\ngo \n", ok: false},
440 {desc: "one", input: "module m\ngo 1\n", ok: false},
441 {desc: "two", input: "module m\ngo 1.22\n", ok: true},
442 {desc: "three", input: "module m\ngo 1.22.333", ok: true},
443 {desc: "before", input: "module m\ngo v1.2\n", ok: false},
444 {desc: "after", input: "module m\ngo 1.2rc1\n", ok: true},
445 {desc: "space", input: "module m\ngo 1.2 3.4\n", ok: false},
446 {desc: "alt1", input: "module m\ngo 1.2.3\n", ok: true},
447 {desc: "alt2", input: "module m\ngo 1.2rc1\n", ok: true},
448 {desc: "alt3", input: "module m\ngo 1.2beta1\n", ok: true},
449 {desc: "alt4", input: "module m\ngo 1.2.beta1\n", ok: false, laxOK: true},
450 {desc: "alt1", input: "module m\ngo v1.2.3\n", ok: false, laxOK: true},
451 {desc: "alt2", input: "module m\ngo v1.2rc1\n", ok: false, laxOK: true},
452 {desc: "alt3", input: "module m\ngo v1.2beta1\n", ok: false, laxOK: true},
453 {desc: "alt4", input: "module m\ngo v1.2.beta1\n", ok: false, laxOK: true},
454 {desc: "alt1", input: "module m\ngo v1.2\n", ok: false, laxOK: true},
455
456 // toolchain lines
457 {desc: "tool", input: "module m\ntoolchain go1.2\n", ok: true},
458 {desc: "tool1", input: "module m\ntoolchain go1.2.3\n", ok: true},
459 {desc: "tool2", input: "module m\ntoolchain go1.2rc1\n", ok: true},
460 {desc: "tool3", input: "module m\ntoolchain go1.2rc1-gccgo\n", ok: true},
461 {desc: "tool4", input: "module m\ntoolchain default\n", ok: true},
462 {desc: "tool5", input: "module m\ntoolchain inconceivable!\n", ok: false, laxOK: true},
463 }
464 t.Run("Strict", func(t *testing.T) {
465 for _, test := range tests {
466 t.Run(test.desc, func(t *testing.T) {
467 if _, err := Parse("go.mod", []byte(test.input), nil); err == nil && !test.ok {
468 t.Error("unexpected success")
469 } else if err != nil && test.ok {
470 t.Errorf("unexpected error: %v", err)
471 }
472 })
473 }
474 })
475 t.Run("Lax", func(t *testing.T) {
476 for _, test := range tests {
477 t.Run(test.desc, func(t *testing.T) {
478 if _, err := ParseLax("go.mod", []byte(test.input), nil); err == nil && !(test.ok || test.laxOK) {
479 t.Error("unexpected success")
480 } else if err != nil && test.ok {
481 t.Errorf("unexpected error: %v", err)
482 }
483 })
484 }
485 })
486 }
487
488 func TestComments(t *testing.T) {
489 for _, test := range []struct {
490 desc, input, want string
491 }{
492 {
493 desc: "comment_only",
494 input: `
495 // a
496 // b
497 `,
498 want: `
499 comments before "// a"
500 comments before "// b"
501 `,
502 }, {
503 desc: "line",
504 input: `
505 // a
506
507 // b
508 module m // c
509 // d
510
511 // e
512 `,
513 want: `
514 comments before "// a"
515 line before "// b"
516 line suffix "// c"
517 comments before "// d"
518 comments before "// e"
519 `,
520 }, {
521 desc: "block",
522 input: `
523 // a
524
525 // b
526 block ( // c
527 // d
528
529 // e
530 x // f
531 // g
532
533 // h
534 ) // i
535 // j
536
537 // k
538 `,
539 want: `
540 comments before "// a"
541 block before "// b"
542 lparen suffix "// c"
543 blockline before "// d"
544 blockline before ""
545 blockline before "// e"
546 blockline suffix "// f"
547 rparen before "// g"
548 rparen before ""
549 rparen before "// h"
550 rparen suffix "// i"
551 comments before "// j"
552 comments before "// k"
553 `,
554 }, {
555 desc: "cr_removed",
556 input: "// a\r\r\n",
557 want: `comments before "// a\r"`,
558 },
559 } {
560 t.Run(test.desc, func(t *testing.T) {
561 f, err := ParseLax("go.mod", []byte(test.input), nil)
562 if err != nil {
563 t.Fatal(err)
564 }
565
566 buf := &bytes.Buffer{}
567 printComments := func(prefix string, cs *Comments) {
568 for _, c := range cs.Before {
569 fmt.Fprintf(buf, "%s before %q\n", prefix, c.Token)
570 }
571 for _, c := range cs.Suffix {
572 fmt.Fprintf(buf, "%s suffix %q\n", prefix, c.Token)
573 }
574 for _, c := range cs.After {
575 fmt.Fprintf(buf, "%s after %q\n", prefix, c.Token)
576 }
577 }
578
579 printComments("file", &f.Syntax.Comments)
580 for _, stmt := range f.Syntax.Stmt {
581 switch stmt := stmt.(type) {
582 case *CommentBlock:
583 printComments("comments", stmt.Comment())
584 case *Line:
585 printComments("line", stmt.Comment())
586 case *LineBlock:
587 printComments("block", stmt.Comment())
588 printComments("lparen", stmt.LParen.Comment())
589 for _, line := range stmt.Line {
590 printComments("blockline", line.Comment())
591 }
592 printComments("rparen", stmt.RParen.Comment())
593 }
594 }
595
596 got := strings.TrimSpace(buf.String())
597 want := strings.TrimSpace(test.want)
598 if got != want {
599 t.Errorf("got:\n%s\nwant:\n%s", got, want)
600 }
601 })
602 }
603 }
604
605 func TestCleanup(t *testing.T) {
606 for _, test := range []struct {
607 desc string
608 want string
609 input []Expr
610 }{
611 {
612 desc: "simple_lines",
613 want: `line: module a
614 line: require b v1.0.0
615 `,
616 input: []Expr{
617 &Line{
618 Token: []string{"module", "a"},
619 },
620 &Line{
621 Token: []string{"require", "b", "v1.0.0"},
622 },
623 &Line{
624 Token: nil,
625 },
626 },
627 }, {
628 desc: "line_block",
629 want: `line: module a
630 block: require
631 blockline: b v1.0.0
632 blockline: c v1.0.0
633 `,
634 input: []Expr{
635 &Line{
636 Token: []string{"module", "a"},
637 },
638 &LineBlock{
639 Token: []string{"require"},
640 Line: []*Line{
641 {
642 Token: []string{"b", "v1.0.0"},
643 InBlock: true,
644 },
645 {
646 Token: nil,
647 InBlock: true,
648 },
649 {
650 Token: []string{"c", "v1.0.0"},
651 InBlock: true,
652 },
653 },
654 },
655 },
656 }, {
657 desc: "collapse",
658 want: `line: module a
659 line: require b v1.0.0
660 `,
661 input: []Expr{
662 &Line{
663 Token: []string{"module", "a"},
664 },
665 &LineBlock{
666 Token: []string{"require"},
667 Line: []*Line{
668 {
669 Token: []string{"b", "v1.0.0"},
670 InBlock: true,
671 },
672 {
673 Token: nil,
674 InBlock: true,
675 },
676 },
677 },
678 },
679 },
680 } {
681 t.Run(test.desc, func(t *testing.T) {
682 syntax := &FileSyntax{
683 Stmt: test.input,
684 }
685 syntax.Cleanup()
686
687 buf := &bytes.Buffer{}
688 for _, stmt := range syntax.Stmt {
689 switch stmt := stmt.(type) {
690 case *Line:
691 fmt.Fprintf(buf, "line: %v\n", strings.Join(stmt.Token, " "))
692 case *LineBlock:
693 fmt.Fprintf(buf, "block: %v\n", strings.Join(stmt.Token, " "))
694 for _, line := range stmt.Line {
695 fmt.Fprintf(buf, "blockline: %v\n", strings.Join(line.Token, " "))
696 }
697 }
698 }
699
700 got := strings.TrimSpace(buf.String())
701 want := strings.TrimSpace(test.want)
702 if got != want {
703 t.Errorf("got:\n%s\nwant:\n%s", got, want)
704 }
705 })
706 }
707 }
708
709 // Issue 45130: File.Cleanup breaks references so future edits do nothing
710 func TestCleanupMaintainsRefs(t *testing.T) {
711 lineB := &Line{
712 Token: []string{"b", "v1.0.0"},
713 InBlock: true,
714 }
715 syntax := &FileSyntax{
716 Stmt: []Expr{
717 &LineBlock{
718 Token: []string{"require"},
719 Line: []*Line{
720 lineB,
721 {
722 Token: nil,
723 InBlock: true,
724 },
725 },
726 },
727 },
728 }
729 syntax.Cleanup()
730
731 if syntax.Stmt[0] != lineB {
732 t.Errorf("got:\n%v\nwant:\n%v", syntax.Stmt[0], lineB)
733 }
734 }