-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathpackages_test.go
3402 lines (3082 loc) · 101 KB
/
packages_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package packages_test
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"go/ast"
constantpkg "go/constant"
"go/parser"
"go/token"
"go/types"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"slices"
"sort"
"strings"
"testing"
"testing/fstest"
"time"
"github.com/google/go-cmp/cmp"
"golang.org/x/tools/go/packages"
"golang.org/x/tools/internal/packagesinternal"
"golang.org/x/tools/internal/packagestest"
"golang.org/x/tools/internal/testenv"
"golang.org/x/tools/internal/testfiles"
"golang.org/x/tools/txtar"
)
// testCtx is canceled when the test binary is about to time out.
//
// If https://golang.org/issue/28135 is accepted, uses of this variable in test
// functions should be replaced by t.Context().
var testCtx = context.Background()
func TestMain(m *testing.M) {
testenv.ExitIfSmallMachine()
timeoutFlag := flag.Lookup("test.timeout")
if timeoutFlag != nil {
if d := timeoutFlag.Value.(flag.Getter).Get().(time.Duration); d != 0 {
aBitShorter := d * 95 / 100
var cancel context.CancelFunc
testCtx, cancel = context.WithTimeout(testCtx, aBitShorter)
defer cancel()
}
}
os.Exit(m.Run())
}
func skipIfShort(t *testing.T, reason string) {
if testing.Short() {
t.Skipf("skipping slow test in short mode: %s", reason)
}
}
// testAllOrModulesParallel tests f, in parallel, against all packagestest
// exporters in long mode, but only against the Modules exporter in short mode.
func testAllOrModulesParallel(t *testing.T, f func(*testing.T, packagestest.Exporter)) {
t.Parallel()
packagestest.TestAll(t, func(t *testing.T, exporter packagestest.Exporter) {
t.Helper()
switch exporter.Name() {
case "Modules":
case "GOPATH":
if testing.Short() {
t.Skipf("skipping GOPATH test in short mode")
}
default:
t.Fatalf("unexpected exporter %q", exporter.Name())
}
t.Parallel()
f(t, exporter)
})
}
// TODO(adonovan): more test cases to write:
//
// - When the tests fail, make them print a 'cd & load' command
// that will allow the maintainer to interact with the failing scenario.
// - errors in go-list metadata
// - a foo.test package that cannot be built for some reason (e.g.
// import error) will result in a JSON blob with no name and a
// nonexistent testmain file in GoFiles. Test that we handle this
// gracefully.
// - test more Flags.
//
// LoadSyntax & LoadAllSyntax modes:
// - Fset may be user-supplied or not.
// - Packages.Info is correctly set.
// - typechecker configuration is honored
// - import cycles are gracefully handled in type checker.
// - test typechecking of generated test main and cgo.
// The zero-value of Config has LoadFiles mode.
func TestLoadZeroConfig(t *testing.T) {
testenv.NeedsGoPackages(t)
t.Parallel()
initial, err := packages.Load(nil, "hash")
if err != nil {
t.Fatal(err)
}
if len(initial) != 1 {
t.Fatalf("got %s, want [hash]", initial)
}
hash := initial[0]
// Even though the hash package has imports,
// they are not reported.
got := fmt.Sprintf("srcs=%v imports=%v", srcs(hash), hash.Imports)
want := "srcs=[hash.go] imports=map[]"
if got != want {
t.Fatalf("got %s, want %s", got, want)
}
}
func TestLoadImportsGraph(t *testing.T) { testAllOrModulesParallel(t, testLoadImportsGraph) }
func testLoadImportsGraph(t *testing.T, exporter packagestest.Exporter) {
exported := packagestest.Export(t, exporter, []packagestest.Module{{
Name: "golang.org/fake",
Files: map[string]any{
"a/a.go": `package a; const A = 1`,
"b/b.go": `package b; import ("golang.org/fake/a"; _ "container/list"); var B = a.A`,
"c/c.go": `package c; import (_ "golang.org/fake/b"; _ "unsafe")`,
"c/c2.go": "// +build ignore\n\n" + `package c; import _ "fmt"`,
"subdir/d/d.go": `package d`,
"subdir/d/d_test.go": `package d; import _ "math/bits"`,
"subdir/d/x_test.go": `package d_test; import _ "golang.org/fake/subdir/d"`, // TODO(adonovan): test bad import here
"subdir/e/d.go": `package e`,
"e/e.go": `package main; import _ "golang.org/fake/b"`,
"e/e2.go": `package main; import _ "golang.org/fake/c"`,
"f/f.go": `package f`,
}}})
defer exported.Cleanup()
exported.Config.Mode = packages.LoadImports
initial, err := packages.Load(exported.Config, "golang.org/fake/c", "golang.org/fake/subdir/d", "golang.org/fake/e")
if err != nil {
t.Fatal(err)
}
// Check graph topology.
graph, _ := importGraph(initial)
wantGraph := `
container/list
golang.org/fake/a
golang.org/fake/b
* golang.org/fake/c
* golang.org/fake/e
* golang.org/fake/subdir/d
* golang.org/fake/subdir/d [golang.org/fake/subdir/d.test]
* golang.org/fake/subdir/d.test
* golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test]
math/bits
unsafe
golang.org/fake/b -> container/list
golang.org/fake/b -> golang.org/fake/a
golang.org/fake/c -> golang.org/fake/b
golang.org/fake/c -> unsafe
golang.org/fake/e -> golang.org/fake/b
golang.org/fake/e -> golang.org/fake/c
golang.org/fake/subdir/d [golang.org/fake/subdir/d.test] -> math/bits
golang.org/fake/subdir/d.test -> golang.org/fake/subdir/d [golang.org/fake/subdir/d.test]
golang.org/fake/subdir/d.test -> golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test]
golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test] -> golang.org/fake/subdir/d [golang.org/fake/subdir/d.test]
`[1:]
if graph != wantGraph {
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
}
exported.Config.Tests = true
initial, err = packages.Load(exported.Config, "golang.org/fake/c", "golang.org/fake/subdir/d", "golang.org/fake/e")
if err != nil {
t.Fatal(err)
}
// Check graph topology.
graph, all := importGraph(initial)
wantGraph = `
container/list
golang.org/fake/a
golang.org/fake/b
* golang.org/fake/c
* golang.org/fake/e
* golang.org/fake/subdir/d
* golang.org/fake/subdir/d [golang.org/fake/subdir/d.test]
* golang.org/fake/subdir/d.test
* golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test]
math/bits
unsafe
golang.org/fake/b -> container/list
golang.org/fake/b -> golang.org/fake/a
golang.org/fake/c -> golang.org/fake/b
golang.org/fake/c -> unsafe
golang.org/fake/e -> golang.org/fake/b
golang.org/fake/e -> golang.org/fake/c
golang.org/fake/subdir/d [golang.org/fake/subdir/d.test] -> math/bits
golang.org/fake/subdir/d.test -> golang.org/fake/subdir/d [golang.org/fake/subdir/d.test]
golang.org/fake/subdir/d.test -> golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test]
golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test] -> golang.org/fake/subdir/d [golang.org/fake/subdir/d.test]
`[1:]
if graph != wantGraph {
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
}
// Check node information: kind, name, srcs.
for _, test := range []struct {
id string
wantName string
wantKind string
wantSrcs string // = {Go,Other,Embed}Files
wantIgnored string
}{
{"golang.org/fake/a", "a", "package", "a.go", ""},
{"golang.org/fake/b", "b", "package", "b.go", ""},
{"golang.org/fake/c", "c", "package", "c.go", "c2.go"}, // c2.go is ignored
{"golang.org/fake/e", "main", "command", "e.go e2.go", ""},
{"container/list", "list", "package", "list.go", ""},
{"golang.org/fake/subdir/d", "d", "package", "d.go", ""},
{"golang.org/fake/subdir/d.test", "main", "command", "0.go", ""},
{"unsafe", "unsafe", "package", "unsafe.go", ""},
} {
p, ok := all[test.id]
if !ok {
t.Errorf("no package %s", test.id)
continue
}
if p.Name != test.wantName {
t.Errorf("%s.Name = %q, want %q", test.id, p.Name, test.wantName)
}
// kind
var kind string
if p.Name == "main" {
kind += "command"
} else {
kind += "package"
}
if kind != test.wantKind {
t.Errorf("%s.Kind = %q, want %q", test.id, kind, test.wantKind)
}
if srcs := strings.Join(srcs(p), " "); srcs != test.wantSrcs {
t.Errorf("%s.{Go,Other,Embed}Files = [%s], want [%s]", test.id, srcs, test.wantSrcs)
}
if ignored := strings.Join(cleanPaths(p.IgnoredFiles), " "); ignored != test.wantIgnored {
t.Errorf("%s.IgnoredFiles = [%s], want [%s]", test.id, ignored, test.wantIgnored)
}
}
// Test an ad-hoc package, analogous to "go run hello.go".
if initial, err := packages.Load(exported.Config, exported.File("golang.org/fake", "c/c.go")); len(initial) == 0 {
t.Errorf("failed to obtain metadata for ad-hoc package: %s", err)
} else {
got := fmt.Sprintf("%s %s", initial[0].ID, srcs(initial[0]))
if want := "command-line-arguments [c.go]"; got != want {
t.Errorf("oops: got %s, want %s", got, want)
}
}
// Wildcards
// See StdlibTest for effective test of "std" wildcard.
// TODO(adonovan): test "all" returns everything in the current module.
{
// "..." (subdirectory)
initial, err = packages.Load(exported.Config, "golang.org/fake/subdir/...")
if err != nil {
t.Fatal(err)
}
graph, _ = importGraph(initial)
wantGraph = `
* golang.org/fake/subdir/d
* golang.org/fake/subdir/d [golang.org/fake/subdir/d.test]
* golang.org/fake/subdir/d.test
* golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test]
* golang.org/fake/subdir/e
math/bits
golang.org/fake/subdir/d [golang.org/fake/subdir/d.test] -> math/bits
golang.org/fake/subdir/d.test -> golang.org/fake/subdir/d [golang.org/fake/subdir/d.test]
golang.org/fake/subdir/d.test -> golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test]
golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test] -> golang.org/fake/subdir/d [golang.org/fake/subdir/d.test]
`[1:]
if graph != wantGraph {
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
}
}
}
func TestLoadImportsTestVariants(t *testing.T) {
testAllOrModulesParallel(t, testLoadImportsTestVariants)
}
func testLoadImportsTestVariants(t *testing.T, exporter packagestest.Exporter) {
exported := packagestest.Export(t, exporter, []packagestest.Module{{
Name: "golang.org/fake",
Files: map[string]any{
"a/a.go": `package a; import _ "golang.org/fake/b"`,
"b/b.go": `package b`,
"b/b_test.go": `package b`,
"b/bx_test.go": `package b_test; import _ "golang.org/fake/a"`,
}}})
defer exported.Cleanup()
exported.Config.Mode = packages.LoadImports
exported.Config.Tests = true
initial, err := packages.Load(exported.Config, "golang.org/fake/a", "golang.org/fake/b")
if err != nil {
t.Fatal(err)
}
// Check graph topology.
graph, _ := importGraph(initial)
wantGraph := `
* golang.org/fake/a
golang.org/fake/a [golang.org/fake/b.test]
* golang.org/fake/b
* golang.org/fake/b [golang.org/fake/b.test]
* golang.org/fake/b.test
* golang.org/fake/b_test [golang.org/fake/b.test]
golang.org/fake/a -> golang.org/fake/b
golang.org/fake/a [golang.org/fake/b.test] -> golang.org/fake/b [golang.org/fake/b.test]
golang.org/fake/b.test -> golang.org/fake/b [golang.org/fake/b.test]
golang.org/fake/b.test -> golang.org/fake/b_test [golang.org/fake/b.test]
golang.org/fake/b_test [golang.org/fake/b.test] -> golang.org/fake/a [golang.org/fake/b.test]
`[1:]
if graph != wantGraph {
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
}
}
func TestLoadAbsolutePath(t *testing.T) {
t.Parallel()
exported := packagestest.Export(t, packagestest.GOPATH, []packagestest.Module{{
Name: "golang.org/gopatha",
Files: map[string]any{
"a/a.go": `package a`,
}}, {
Name: "golang.org/gopathb",
Files: map[string]any{
"b/b.go": `package b`,
}}})
defer exported.Cleanup()
initial, err := packages.Load(exported.Config, filepath.Dir(exported.File("golang.org/gopatha", "a/a.go")), filepath.Dir(exported.File("golang.org/gopathb", "b/b.go")))
if err != nil {
t.Fatalf("failed to load imports: %v", err)
}
got := []string{}
for _, p := range initial {
got = append(got, p.ID)
}
sort.Strings(got)
want := []string{"golang.org/gopatha/a", "golang.org/gopathb/b"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("initial packages loaded: got [%s], want [%s]", got, want)
}
}
func TestLoadArgumentListIsNotTooLong(t *testing.T) {
// NOTE: this test adds about 2s to the test suite running time
t.Parallel()
// using the real ARG_MAX for some platforms increases the running time of this test by a lot,
// 1_000_000 seems like enough to break Windows and macOS if Load doesn't split provided patterns
argMax := 1_000_000
exported := packagestest.Export(t, packagestest.GOPATH, []packagestest.Module{{
Name: "golang.org/mod",
Files: map[string]any{
"main.go": `package main"`,
}}})
defer exported.Cleanup()
numOfPatterns := argMax/16 + 1 // the pattern below is approx. 16 chars
patterns := make([]string, numOfPatterns)
for i := range numOfPatterns {
patterns[i] = fmt.Sprintf("golang.org/mod/p%d", i)
} // patterns have more than argMax number of chars combined with whitespaces b/w patterns
_, err := packages.Load(exported.Config, patterns...)
if err != nil {
t.Fatalf("failed to load: %v", err)
}
}
func TestVendorImports(t *testing.T) {
t.Parallel()
exported := packagestest.Export(t, packagestest.GOPATH, []packagestest.Module{{
Name: "golang.org/fake",
Files: map[string]any{
"a/a.go": `package a; import _ "b"; import _ "golang.org/fake/c";`,
"a/vendor/b/b.go": `package b; import _ "golang.org/fake/c"`,
"c/c.go": `package c; import _ "b"`,
"c/vendor/b/b.go": `package b`,
}}})
defer exported.Cleanup()
exported.Config.Mode = packages.LoadImports
initial, err := packages.Load(exported.Config, "golang.org/fake/a", "golang.org/fake/c")
if err != nil {
t.Fatal(err)
}
graph, all := importGraph(initial)
wantGraph := `
* golang.org/fake/a
golang.org/fake/a/vendor/b
* golang.org/fake/c
golang.org/fake/c/vendor/b
golang.org/fake/a -> golang.org/fake/a/vendor/b
golang.org/fake/a -> golang.org/fake/c
golang.org/fake/a/vendor/b -> golang.org/fake/c
golang.org/fake/c -> golang.org/fake/c/vendor/b
`[1:]
if graph != wantGraph {
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
}
for _, test := range []struct {
pattern string
wantImports string
}{
{"golang.org/fake/a", "b:golang.org/fake/a/vendor/b golang.org/fake/c:golang.org/fake/c"},
{"golang.org/fake/c", "b:golang.org/fake/c/vendor/b"},
{"golang.org/fake/a/vendor/b", "golang.org/fake/c:golang.org/fake/c"},
{"golang.org/fake/c/vendor/b", ""},
} {
// Test the import paths.
pkg := all[test.pattern]
if imports := strings.Join(imports(pkg), " "); imports != test.wantImports {
t.Errorf("package %q: got %s, want %s", test.pattern, imports, test.wantImports)
}
}
}
func imports(p *packages.Package) []string {
if p == nil {
return nil
}
keys := make([]string, 0, len(p.Imports))
for k, v := range p.Imports {
keys = append(keys, fmt.Sprintf("%s:%s", k, v.ID))
}
sort.Strings(keys)
return keys
}
func TestConfigDir(t *testing.T) { testAllOrModulesParallel(t, testConfigDir) }
func testConfigDir(t *testing.T, exporter packagestest.Exporter) {
exported := packagestest.Export(t, exporter, []packagestest.Module{{
Name: "golang.org/fake",
Files: map[string]any{
"a/a.go": `package a; const Name = "a" `,
"a/b/b.go": `package b; const Name = "a/b"`,
"b/b.go": `package b; const Name = "b"`,
}}})
defer exported.Cleanup()
aDir := filepath.Dir(exported.File("golang.org/fake", "a/a.go"))
bDir := filepath.Dir(exported.File("golang.org/fake", "b/b.go"))
baseDir := filepath.Dir(aDir)
for _, test := range []struct {
dir string
pattern string
want string // value of Name constant
fails bool
}{
{dir: bDir, pattern: "golang.org/fake/a", want: `"a"`},
{dir: bDir, pattern: "golang.org/fake/b", want: `"b"`},
{dir: bDir, pattern: "./a", fails: true},
{dir: bDir, pattern: "./b", fails: true},
{dir: baseDir, pattern: "golang.org/fake/a", want: `"a"`},
{dir: baseDir, pattern: "golang.org/fake/b", want: `"b"`},
{dir: baseDir, pattern: "./a", want: `"a"`},
{dir: baseDir, pattern: "./b", want: `"b"`},
{dir: aDir, pattern: "golang.org/fake/a", want: `"a"`},
{dir: aDir, pattern: "golang.org/fake/b", want: `"b"`},
{dir: aDir, pattern: "./a", fails: true},
{dir: aDir, pattern: "./b", want: `"a/b"`},
} {
exported.Config.Mode = packages.LoadSyntax // Use LoadSyntax to ensure that files can be opened.
exported.Config.Dir = test.dir
initial, err := packages.Load(exported.Config, test.pattern)
var got string
fails := false
if err != nil {
fails = true
} else if len(initial) > 0 {
if len(initial[0].Errors) > 0 {
fails = true
} else if c := constant(initial[0], "Name"); c != nil {
got = c.Val().String()
}
}
if got != test.want {
t.Errorf("dir %q, pattern %q: got %s, want %s",
test.dir, test.pattern, got, test.want)
}
if fails != test.fails {
t.Errorf("dir %q, pattern %q: error %v, want %v",
test.dir, test.pattern, fails, test.fails)
}
}
}
func TestConfigFlags(t *testing.T) { testAllOrModulesParallel(t, testConfigFlags) }
func testConfigFlags(t *testing.T, exporter packagestest.Exporter) {
// Test satisfying +build line tags, with -tags flag.
exported := packagestest.Export(t, exporter, []packagestest.Module{{
Name: "golang.org/fake",
Files: map[string]any{
// package a
"a/a.go": `package a; import _ "golang.org/fake/a/b"`,
"a/b.go": `// +build tag
package a`,
"a/c.go": `// +build tag tag2
package a`,
"a/d.go": `// +build tag,tag2
package a`,
// package a/b
"a/b/a.go": `package b`,
"a/b/b.go": `// +build tag
package b`,
}}})
defer exported.Cleanup()
for _, test := range []struct {
pattern string
tags []string
wantSrcs string
wantImportSrcs string
}{
{`golang.org/fake/a`, []string{}, "a.go", "a.go"},
{`golang.org/fake/a`, []string{`-tags=tag`}, "a.go b.go c.go", "a.go b.go"},
{`golang.org/fake/a`, []string{`-tags=tag2`}, "a.go c.go", "a.go"},
{`golang.org/fake/a`, []string{`-tags=tag tag2`}, "a.go b.go c.go d.go", "a.go b.go"},
} {
exported.Config.Mode = packages.LoadImports
exported.Config.BuildFlags = test.tags
initial, err := packages.Load(exported.Config, test.pattern)
if err != nil {
t.Error(err)
continue
}
if len(initial) != 1 {
t.Errorf("test tags %v: pattern %s, expected 1 package, got %d packages.", test.tags, test.pattern, len(initial))
continue
}
pkg := initial[0]
if srcs := strings.Join(srcs(pkg), " "); srcs != test.wantSrcs {
t.Errorf("test tags %v: srcs of package %s = [%s], want [%s]", test.tags, test.pattern, srcs, test.wantSrcs)
}
for path, ipkg := range pkg.Imports {
if srcs := strings.Join(srcs(ipkg), " "); srcs != test.wantImportSrcs {
t.Errorf("build tags %v: srcs of imported package %s = [%s], want [%s]", test.tags, path, srcs, test.wantImportSrcs)
}
}
}
}
func TestLoadTypes(t *testing.T) { testAllOrModulesParallel(t, testLoadTypes) }
func testLoadTypes(t *testing.T, exporter packagestest.Exporter) {
// In LoadTypes and LoadSyntax modes, the compiler will
// fail to generate an export data file for c, because it has
// a type error. The loader should fall back loading a and c
// from source, but use the export data for b.
exported := packagestest.Export(t, exporter, []packagestest.Module{{
Name: "golang.org/fake",
Files: map[string]any{
"a/a.go": `package a; import "golang.org/fake/b"; import "golang.org/fake/c"; const A = "a" + b.B + c.C`,
"b/b.go": `package b; const B = "b"`,
"c/c.go": `package c; const C = "c" + 1`,
}}})
defer exported.Cleanup()
exported.Config.Mode = packages.LoadTypes
initial, err := packages.Load(exported.Config, "golang.org/fake/a")
if err != nil {
t.Fatal(err)
}
graph, all := importGraph(initial)
wantGraph := `
* golang.org/fake/a
golang.org/fake/b
golang.org/fake/c
golang.org/fake/a -> golang.org/fake/b
golang.org/fake/a -> golang.org/fake/c
`[1:]
if graph != wantGraph {
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
}
for _, id := range []string{
"golang.org/fake/a",
"golang.org/fake/b",
"golang.org/fake/c",
} {
p := all[id]
if p == nil {
t.Errorf("missing package: %s", id)
continue
}
if p.Types == nil {
t.Errorf("missing types.Package for %s", p)
continue
} else if !p.Types.Complete() {
t.Errorf("incomplete types.Package for %s", p)
} else if p.TypesSizes == nil {
t.Errorf("TypesSizes is not filled in for %s", p)
}
}
}
// TestLoadTypesBits is equivalent to TestLoadTypes except that it only requests
// the types using the NeedTypes bit.
func TestLoadTypesBits(t *testing.T) { testAllOrModulesParallel(t, testLoadTypesBits) }
func testLoadTypesBits(t *testing.T, exporter packagestest.Exporter) {
exported := packagestest.Export(t, exporter, []packagestest.Module{{
Name: "golang.org/fake",
Files: map[string]any{
"a/a.go": `package a; import "golang.org/fake/b"; const A = "a" + b.B`,
"b/b.go": `package b; import "golang.org/fake/c"; const B = "b" + c.C`,
"c/c.go": `package c; import "golang.org/fake/d"; const C = "c" + d.D`,
"d/d.go": `package d; import "golang.org/fake/e"; const D = "d" + e.E`,
"e/e.go": `package e; import "golang.org/fake/f"; const E = "e" + f.F`,
"f/f.go": `package f; const F = "f"`,
}}})
defer exported.Cleanup()
exported.Config.Mode = packages.NeedTypes | packages.NeedImports
initial, err := packages.Load(exported.Config, "golang.org/fake/a", "golang.org/fake/c")
if err != nil {
t.Fatal(err)
}
graph, all := importGraph(initial)
wantGraph := `
* golang.org/fake/a
golang.org/fake/b
* golang.org/fake/c
golang.org/fake/d
golang.org/fake/e
golang.org/fake/f
golang.org/fake/a -> golang.org/fake/b
golang.org/fake/b -> golang.org/fake/c
golang.org/fake/c -> golang.org/fake/d
golang.org/fake/d -> golang.org/fake/e
golang.org/fake/e -> golang.org/fake/f
`[1:]
if graph != wantGraph {
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
}
for _, test := range []struct {
id string
}{
{"golang.org/fake/a"},
{"golang.org/fake/b"},
{"golang.org/fake/c"},
{"golang.org/fake/d"},
{"golang.org/fake/e"},
{"golang.org/fake/f"},
} {
p := all[test.id]
if p == nil {
t.Errorf("missing package: %s", test.id)
continue
}
if p.Types == nil {
t.Errorf("missing types.Package for %s", p)
continue
}
// We don't request the syntax, so we shouldn't get it.
if p.Syntax != nil {
t.Errorf("Syntax unexpectedly provided for %s", p)
}
if p.Errors != nil {
t.Errorf("errors in package: %s: %s", p, p.Errors)
}
}
// Check value of constant.
aA := constant(all["golang.org/fake/a"], "A")
if aA == nil {
t.Fatalf("a.A: got nil")
}
if got, want := fmt.Sprintf("%v %v", aA, aA.Val()), `const golang.org/fake/a.A untyped string "abcdef"`; got != want {
t.Errorf("a.A: got %s, want %s", got, want)
}
}
func TestLoadSyntaxOK(t *testing.T) { testAllOrModulesParallel(t, testLoadSyntaxOK) }
func testLoadSyntaxOK(t *testing.T, exporter packagestest.Exporter) {
exported := packagestest.Export(t, exporter, []packagestest.Module{{
Name: "golang.org/fake",
Files: map[string]any{
"a/a.go": `package a; import "golang.org/fake/b"; const A = "a" + b.B`,
"b/b.go": `package b; import "golang.org/fake/c"; const B = "b" + c.C`,
"c/c.go": `package c; import "golang.org/fake/d"; const C = "c" + d.D`,
"d/d.go": `package d; import "golang.org/fake/e"; const D = "d" + e.E`,
"e/e.go": `package e; import "golang.org/fake/f"; const E = "e" + f.F`,
"f/f.go": `package f; const F = "f"`,
}}})
defer exported.Cleanup()
exported.Config.Mode = packages.LoadSyntax
initial, err := packages.Load(exported.Config, "golang.org/fake/a", "golang.org/fake/c")
if err != nil {
t.Fatal(err)
}
graph, all := importGraph(initial)
wantGraph := `
* golang.org/fake/a
golang.org/fake/b
* golang.org/fake/c
golang.org/fake/d
golang.org/fake/e
golang.org/fake/f
golang.org/fake/a -> golang.org/fake/b
golang.org/fake/b -> golang.org/fake/c
golang.org/fake/c -> golang.org/fake/d
golang.org/fake/d -> golang.org/fake/e
golang.org/fake/e -> golang.org/fake/f
`[1:]
if graph != wantGraph {
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
}
for _, test := range []struct {
id string
wantSyntax bool
wantComplete bool
}{
{"golang.org/fake/a", true, true}, // source package
{"golang.org/fake/b", true, true}, // source package because depends on initial package
{"golang.org/fake/c", true, true}, // source package
{"golang.org/fake/d", false, true}, // export data package
{"golang.org/fake/e", false, false}, // export data package
{"golang.org/fake/f", false, false}, // export data package
} {
// TODO(matloob): LoadSyntax and LoadAllSyntax are now equivalent, wantSyntax and wantComplete
// are true for all packages in the transitive dependency set. Add test cases on the individual
// Need* fields to check the equivalents on the new API.
p := all[test.id]
if p == nil {
t.Errorf("missing package: %s", test.id)
continue
}
if p.Types == nil {
t.Errorf("missing types.Package for %s", p)
continue
} else if p.Types.Complete() != test.wantComplete {
if test.wantComplete {
t.Errorf("incomplete types.Package for %s", p)
} else {
t.Errorf("unexpected complete types.Package for %s", p)
}
}
if (p.Syntax != nil) != test.wantSyntax {
if test.wantSyntax {
t.Errorf("missing ast.Files for %s", p)
} else {
t.Errorf("unexpected ast.Files for for %s", p)
}
}
if p.Errors != nil {
t.Errorf("errors in package: %s: %s", p, p.Errors)
}
}
// Check value of constant.
aA := constant(all["golang.org/fake/a"], "A")
if aA == nil {
t.Fatalf("a.A: got nil")
}
if got, want := fmt.Sprintf("%v %v", aA, aA.Val()), `const golang.org/fake/a.A untyped string "abcdef"`; got != want {
t.Errorf("a.A: got %s, want %s", got, want)
}
}
func TestLoadDiamondTypes(t *testing.T) { testAllOrModulesParallel(t, testLoadDiamondTypes) }
func testLoadDiamondTypes(t *testing.T, exporter packagestest.Exporter) {
// We make a diamond dependency and check the type d.D is the same through both paths
exported := packagestest.Export(t, exporter, []packagestest.Module{{
Name: "golang.org/fake",
Files: map[string]any{
"a/a.go": `package a; import ("golang.org/fake/b"; "golang.org/fake/c"); var _ = b.B == c.C`,
"b/b.go": `package b; import "golang.org/fake/d"; var B d.D`,
"c/c.go": `package c; import "golang.org/fake/d"; var C d.D`,
"d/d.go": `package d; type D int`,
}}})
defer exported.Cleanup()
exported.Config.Mode = packages.LoadSyntax
initial, err := packages.Load(exported.Config, "golang.org/fake/a")
if err != nil {
t.Fatal(err)
}
packages.Visit(initial, nil, func(pkg *packages.Package) {
for _, err := range pkg.Errors {
t.Errorf("package %s: %v", pkg.ID, err)
}
})
graph, _ := importGraph(initial)
wantGraph := `
* golang.org/fake/a
golang.org/fake/b
golang.org/fake/c
golang.org/fake/d
golang.org/fake/a -> golang.org/fake/b
golang.org/fake/a -> golang.org/fake/c
golang.org/fake/b -> golang.org/fake/d
golang.org/fake/c -> golang.org/fake/d
`[1:]
if graph != wantGraph {
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
}
}
func TestLoadSyntaxError(t *testing.T) { testAllOrModulesParallel(t, testLoadSyntaxError) }
func testLoadSyntaxError(t *testing.T, exporter packagestest.Exporter) {
// A type error in a lower-level package (e) prevents go list
// from producing export data for all packages that depend on it
// [a-e]. Only f should be loaded from export data, and the rest
// should be IllTyped.
exported := packagestest.Export(t, exporter, []packagestest.Module{{
Name: "golang.org/fake",
Files: map[string]any{
"a/a.go": `package a; import "golang.org/fake/b"; const A = "a" + b.B`,
"b/b.go": `package b; import "golang.org/fake/c"; const B = "b" + c.C`,
"c/c.go": `package c; import "golang.org/fake/d"; const C = "c" + d.D`,
"d/d.go": `package d; import "golang.org/fake/e"; const D = "d" + e.E`,
"e/e.go": `package e; import "golang.org/fake/f"; const E = "e" + f.F + 1`, // type error
"f/f.go": `package f; const F = "f"`,
}}})
defer exported.Cleanup()
exported.Config.Mode = packages.LoadSyntax
initial, err := packages.Load(exported.Config, "golang.org/fake/a", "golang.org/fake/c")
if err != nil {
t.Fatal(err)
}
all := make(map[string]*packages.Package)
packages.Visit(initial, nil, func(p *packages.Package) {
all[p.ID] = p
})
for _, test := range []struct {
id string
wantSyntax bool
wantIllTyped bool
}{
{"golang.org/fake/a", true, true},
{"golang.org/fake/b", true, true},
{"golang.org/fake/c", true, true},
{"golang.org/fake/d", true, true},
{"golang.org/fake/e", true, true},
{"golang.org/fake/f", false, false},
} {
p := all[test.id]
if p == nil {
t.Errorf("missing package: %s", test.id)
continue
}
if p.Types == nil {
t.Errorf("missing types.Package for %s", p)
continue
} else if !p.Types.Complete() {
t.Errorf("incomplete types.Package for %s", p)
}
if (p.Syntax != nil) != test.wantSyntax {
if test.wantSyntax {
t.Errorf("missing ast.Files for %s", test.id)
} else {
t.Errorf("unexpected ast.Files for for %s", test.id)
}
}
if p.IllTyped != test.wantIllTyped {
t.Errorf("IllTyped was %t for %s", p.IllTyped, test.id)
}
}
// Check value of constant.
aA := constant(all["golang.org/fake/a"], "A")
if aA == nil {
t.Fatalf("a.A: got nil")
}
if got, want := aA.String(), `const golang.org/fake/a.A invalid type`; got != want {
t.Errorf("a.A: got %s, want %s", got, want)
}
}
// This function tests use of the ParseFile hook to modify
// the AST after parsing.
func TestParseFileModifyAST(t *testing.T) { testAllOrModulesParallel(t, testParseFileModifyAST) }
func testParseFileModifyAST(t *testing.T, exporter packagestest.Exporter) {
exported := packagestest.Export(t, exporter, []packagestest.Module{{
Name: "golang.org/fake",
Files: map[string]any{
"a/a.go": `package a; const A = "a" `,
}}})
defer exported.Cleanup()
exported.Config.Mode = packages.LoadAllSyntax
exported.Config.ParseFile = func(fset *token.FileSet, filename string, src []byte) (*ast.File, error) {
const mode = parser.AllErrors | parser.ParseComments
f, err := parser.ParseFile(fset, filename, src, mode)
// modify AST to change `const A = "a"` to `const A = "b"`
spec := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec)
spec.Values[0].(*ast.BasicLit).Value = `"b"`
return f, err
}
initial, err := packages.Load(exported.Config, "golang.org/fake/a")
if err != nil {
t.Error(err)
}
// Check value of a.A has been set to "b"
a := initial[0]
got := constant(a, "A").Val().String()
if got != `"b"` {
t.Errorf("a.A: got %s, want %s", got, `"b"`)
}
}
func TestAdHocPackagesBadImport(t *testing.T) {
t.Parallel()
testenv.NeedsTool(t, "go")
// This test doesn't use packagestest because we are testing ad-hoc packages,
// which are outside of $GOPATH and outside of a module.
tmp, err := os.MkdirTemp("", "a")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmp)
filename := filepath.Join(tmp, "a.go")
content := []byte(`package a
import _ "badimport"
const A = 1
`)
if err := os.WriteFile(filename, content, 0775); err != nil {
t.Fatal(err)
}
// Make sure that the user's value of GO111MODULE does not affect test results.
for _, go111module := range []string{"off", "auto", "on"} {
config := &packages.Config{
Env: append(os.Environ(), "GOPACKAGESDRIVER=off", fmt.Sprintf("GO111MODULE=%s", go111module)),
Dir: tmp,
Mode: packages.LoadAllSyntax,
Logf: t.Logf,
}
initial, err := packages.Load(config, fmt.Sprintf("file=%s", filename))
if err != nil {
t.Error(err)
}
if len(initial) == 0 {
t.Fatalf("no packages for %s with GO111MODULE=%s", filename, go111module)
}
// Check value of a.A.
a := initial[0]
// There's an error because there's a bad import.
aA := constant(a, "A")
if aA == nil {
t.Errorf("a.A: got nil")
return
}
got := aA.Val().String()
if want := "1"; got != want {
t.Errorf("a.A: got %s, want %s", got, want)
}