1
2
3
4
5 package modindex
6
7 import (
8 "encoding/hex"
9 "encoding/json"
10 "go/build"
11 "internal/diff"
12 "path/filepath"
13 "reflect"
14 "runtime"
15 "testing"
16 )
17
18 func init() {
19 isTest = true
20 enabled = true
21 }
22
23 func TestIndex(t *testing.T) {
24 src := filepath.Join(runtime.GOROOT(), "src")
25 checkPkg := func(t *testing.T, m *Module, pkg string, data []byte) {
26 p := m.Package(pkg)
27 bp, err := p.Import(build.Default, build.ImportComment)
28 if err != nil {
29 t.Fatal(err)
30 }
31 bp1, err := build.Default.Import(".", filepath.Join(src, pkg), build.ImportComment)
32 if err != nil {
33 t.Fatal(err)
34 }
35
36 if !reflect.DeepEqual(bp, bp1) {
37 t.Errorf("mismatch")
38 t.Logf("index:\n%s", hex.Dump(data))
39
40 js, err := json.MarshalIndent(bp, "", "\t")
41 if err != nil {
42 t.Fatal(err)
43 }
44 js1, err := json.MarshalIndent(bp1, "", "\t")
45 if err != nil {
46 t.Fatal(err)
47 }
48 t.Logf("diff:\n%s", diff.Diff("index", js, "correct", js1))
49 t.FailNow()
50 }
51 }
52
53
54 pkgs := []string{
55 "crypto",
56 "encoding",
57 "unsafe",
58 "encoding/json",
59 "runtime",
60 "net",
61 }
62 var raws []*rawPackage
63 for _, pkg := range pkgs {
64 raw := importRaw(src, pkg)
65 raws = append(raws, raw)
66 t.Run(pkg, func(t *testing.T) {
67 data := encodeModuleBytes([]*rawPackage{raw})
68 m, err := fromBytes(src, data)
69 if err != nil {
70 t.Fatal(err)
71 }
72 checkPkg(t, m, pkg, data)
73 })
74 }
75
76
77 t.Run("all", func(t *testing.T) {
78 data := encodeModuleBytes(raws)
79 m, err := fromBytes(src, data)
80 if err != nil {
81 t.Fatal(err)
82 }
83 for _, pkg := range pkgs {
84 checkPkg(t, m, pkg, data)
85 }
86 })
87 }
88
89 func TestImportRaw_IgnoreNonGo(t *testing.T) {
90 path := filepath.Join("testdata", "ignore_non_source")
91 p := importRaw(path, ".")
92
93 wantFiles := []string{"a.syso", "b.go", "c.c"}
94
95 var gotFiles []string
96 for i := range p.sourceFiles {
97 gotFiles = append(gotFiles, p.sourceFiles[i].name)
98 }
99
100 if !reflect.DeepEqual(gotFiles, wantFiles) {
101 t.Errorf("names of files in importRaw(testdata/ignore_non_source): got %v; want %v",
102 gotFiles, wantFiles)
103 }
104 }
105
View as plain text