| 1 | // Copyright 2026 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 checker_test |
| 6 | |
| 7 | import ( |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "testing" |
| 11 | |
| 12 | "golang.org/x/tools/go/analysis" |
| 13 | "golang.org/x/tools/go/analysis/checker" |
| 14 | "golang.org/x/tools/go/packages" |
| 15 | "golang.org/x/tools/internal/testenv" |
| 16 | "golang.org/x/tools/txtar" |
| 17 | ) |
| 18 | |
| 19 | // TestPassModule checks that an analyzer observes the correct Pass.Module |
| 20 | // fields (GoMod, Dir, Path, Main, GoVersion) when run on a module. |
| 21 | func TestPassModule(t *testing.T) { |
| 22 | testenv.NeedsGoPackages(t) |
| 23 | |
| 24 | const src = ` |
| 25 | -- go.mod -- |
| 26 | module example.com/hello |
| 27 | go 1.13 |
| 28 | |
| 29 | -- hello.go -- |
| 30 | package hello |
| 31 | ` |
| 32 | dir, err := os.MkdirTemp("", "") |
| 33 | if err != nil { |
| 34 | t.Fatal(err) |
| 35 | } |
| 36 | defer os.RemoveAll(dir) |
| 37 | |
| 38 | fs, err := txtar.FS(txtar.Parse([]byte(src))) |
| 39 | if err != nil { |
| 40 | t.Fatal(err) |
| 41 | } |
| 42 | if err := os.CopyFS(dir, fs); err != nil { |
| 43 | t.Fatal(err) |
| 44 | } |
| 45 | |
| 46 | // Capture the Module seen by the analyzer. |
| 47 | var got *analysis.Module |
| 48 | testAnalyzer := &analysis.Analyzer{ |
| 49 | Name: "testmodule", |
| 50 | Doc: "Captures Pass.Module for testing.", |
| 51 | Run: func(pass *analysis.Pass) (any, error) { |
| 52 | got = pass.Module |
| 53 | return nil, nil |
| 54 | }, |
| 55 | } |
| 56 | |
| 57 | cfg := &packages.Config{ |
| 58 | Mode: packages.LoadAllSyntax | packages.NeedModule, |
| 59 | Dir: dir, |
| 60 | } |
| 61 | pkgs, err := packages.Load(cfg, "example.com/hello") |
| 62 | if err != nil { |
| 63 | t.Fatal(err) |
| 64 | } |
| 65 | |
| 66 | if _, err := checker.Analyze([]*analysis.Analyzer{testAnalyzer}, pkgs, nil); err != nil { |
| 67 | t.Fatal(err) |
| 68 | } |
| 69 | |
| 70 | if got == nil { |
| 71 | t.Fatal("Pass.Module is nil") |
| 72 | } |
| 73 | if got.Path != "example.com/hello" { |
| 74 | t.Errorf("Pass.Module.Path = %q, want %q", got.Path, "example.com/hello") |
| 75 | } |
| 76 | if !got.Main { |
| 77 | t.Errorf("Pass.Module.Main = false, want true") |
| 78 | } |
| 79 | wantGoMod := filepath.Join(dir, "go.mod") |
| 80 | if got.GoMod != wantGoMod { |
| 81 | t.Errorf("Pass.Module.GoMod = %q, want %q", got.GoMod, wantGoMod) |
| 82 | } |
| 83 | if got.Dir != dir { |
| 84 | t.Errorf("Pass.Module.Dir = %q, want %q", got.Dir, dir) |
| 85 | } |
| 86 | if got.GoVersion != "1.13" { |
| 87 | t.Errorf("Pass.Module.GoVersion = %q, want %q", got.GoVersion, "1.13") |
| 88 | } |
| 89 | } |