Serge Bazanski | 8bd2ab1 | 2021-12-17 17:32:16 +0100 | [diff] [blame] | 1 | package importsort |
| 2 | |
| 3 | import ( |
| 4 | "embed" |
| 5 | "io/fs" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | |
| 11 | "golang.org/x/tools/go/analysis/analysistest" |
| 12 | |
| 13 | "source.monogon.dev/build/toolbase/gotoolchain" |
| 14 | ) |
| 15 | |
| 16 | //go:embed testdata/* |
| 17 | var testdata embed.FS |
| 18 | |
| 19 | func init() { |
| 20 | // analysistest uses x/go/packages which in turns uses runtime.GOROOT(). |
| 21 | // runtime.GOROOT itself is neutered by rules_go for hermeticity. We provide our |
| 22 | // own GOROOT that we get from gotoolchain (which is still hermetic, but depends |
| 23 | // on runfiles). However, for runtime.GOROOT to pick it up, this env var must be |
| 24 | // set in init(). |
| 25 | os.Setenv("GOROOT", gotoolchain.Root) |
| 26 | } |
| 27 | |
| 28 | func TestImportsort(t *testing.T) { |
| 29 | // Add `go` to PATH for x/go/packages. |
| 30 | os.Setenv("PATH", filepath.Dir(gotoolchain.Go)) |
| 31 | |
| 32 | // Make an empty GOCACHE for x/go/packages. |
| 33 | gocache, err := os.MkdirTemp("/tmp", "gocache") |
| 34 | if err != nil { |
| 35 | panic(err) |
| 36 | } |
| 37 | defer os.RemoveAll(gocache) |
| 38 | os.Setenv("GOCACHE", gocache) |
| 39 | |
| 40 | // Make an empty GOPATH for x/go/packages. |
| 41 | gopath, err := os.MkdirTemp("/tmp", "gopath") |
| 42 | if err != nil { |
| 43 | panic(err) |
| 44 | } |
| 45 | defer os.RemoveAll(gopath) |
| 46 | os.Setenv("GOPATH", gopath) |
| 47 | |
| 48 | // Convert testdata from an fs.FS to a path->contents map as expected by |
| 49 | // analysistest.WriteFiles, rewriting paths to build a correct GOPATH-like |
| 50 | // layout. |
| 51 | filemap := make(map[string]string) |
| 52 | fs.WalkDir(testdata, ".", func(path string, d fs.DirEntry, err error) error { |
| 53 | if err != nil { |
| 54 | t.Fatalf("WalkDir: %v", err) |
| 55 | } |
| 56 | if d.IsDir() { |
| 57 | return nil |
| 58 | } |
| 59 | bytes, _ := testdata.ReadFile(path) |
| 60 | path = strings.TrimPrefix(path, "testdata/") |
| 61 | path = strings.ReplaceAll(path, ".notgo", ".go") |
| 62 | filemap[path] = string(bytes) |
| 63 | return nil |
| 64 | }) |
| 65 | |
| 66 | // Run the actual tests, which are all declared within testdata/**. |
| 67 | dir, cleanup, err := analysistest.WriteFiles(filemap) |
| 68 | if err != nil { |
| 69 | t.Fatalf("WriteFiles: %v", err) |
| 70 | } |
| 71 | defer cleanup() |
| 72 | analysistest.Run(t, dir, Analyzer, "source.monogon.dev/...") |
| 73 | } |