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