1
2
3
4
5 package gotestchecker_test
6
7 import (
8 "encoding/json"
9 "go/analysis"
10 "go/ast"
11 "go/types"
12 "internal/testenv"
13 "os"
14 "path/filepath"
15 "runtime"
16 "strings"
17 "testing"
18
19 "internal/analysis/gotestchecker"
20 "internal/analysis/gotestchecker/protocol"
21 )
22
23
24
25 const toolEnv = "GOTESTCHECKER_TEST_TOOL"
26
27 const toolSymbol = "example.com/special.Analyzer"
28
29 var toolVars = []gotestchecker.Var{{Symbol: toolSymbol, Value: specialAnalyzer}}
30
31 func TestMain(m *testing.M) {
32 if os.Getenv(toolEnv) != "" {
33 gotestchecker.Main(toolVars)
34 os.Exit(0)
35 }
36 os.Exit(m.Run())
37 }
38
39
40
41
42
43
44
45
46 func TestRun(t *testing.T) {
47 testenv.MustHaveExec(t)
48 dir := t.TempDir()
49 file := func(name string) string { return filepath.Join(dir, name) }
50 writeFile := func(name, content string) string {
51 t.Helper()
52 if err := os.WriteFile(file(name), []byte(content), 0666); err != nil {
53 t.Fatal(err)
54 }
55 return file(name)
56 }
57
58
59 tool := func(args ...string) {
60 t.Helper()
61 cmd := testenv.Command(t, testenv.Executable(t), args...)
62 cmd.Env = append(os.Environ(), toolEnv+"=1")
63 if out, err := cmd.CombinedOutput(); err != nil {
64 t.Fatalf("%v failed: %v\n%s", cmd, err, out)
65 }
66 }
67
68
69 tool("-describe=" + file("metadata.json"))
70 data, err := os.ReadFile(file("metadata.json"))
71 if err != nil {
72 t.Fatal(err)
73 }
74 var md protocol.Metadata
75 if err := json.Unmarshal(data, &md); err != nil {
76 t.Fatal(err)
77 }
78 info := md.Var(toolSymbol)
79 if info == nil || info.Error != "" || len(info.Members) != 1 {
80 t.Fatalf("metadata for %s: %+v", toolSymbol, info)
81 }
82 special := info.Members[0].Analyzer
83 if a := md.Analyzers[special]; a.Name != "special" || !a.Facts {
84 t.Fatalf("analyzer %d: got %+v, want special, which uses facts", special, a)
85 }
86
87
88
89 analyze := func(req *protocol.AnalyzeRequest) *protocol.Pass {
90 t.Helper()
91 data, err := json.Marshal(req)
92 if err != nil {
93 t.Fatal(err)
94 }
95 tool(writeFile(req.ID+".json", string(data)))
96 pass, err := protocol.ReadPass(req.Outputs[special])
97 if err != nil {
98 t.Fatal(err)
99 }
100 if pass.Failure != nil || pass.Skipped {
101 t.Fatalf("%s: pass failed (%v) or was skipped (%t)", req.ID, pass.Failure, pass.Skipped)
102 }
103 return pass
104 }
105
106
107
108 libPass := analyze(&protocol.AnalyzeRequest{
109 ID: "lib",
110 ImportPath: "lib",
111 Dir: dir,
112 GoFiles: {writeFile("lib.go", "package lib\n\nfunc SpecialF() {}\n\nfunc G() { SpecialF() }\n")},
113 GoVersion: "go1.28",
114 GOARCH: runtime.GOARCH,
115 TypeImports: {},
116 TypeExport: file("lib.export"),
117 Facts: {},
118 Outputs: {special: file("lib.pass")},
119 })
120 if len(libPass.Facts) == 0 {
121 t.Errorf("lib: no facts")
122 }
123 if len(libPass.Diagnostics) > 0 {
124 t.Errorf("lib: unexpected diagnostics: %v", libPass.Diagnostics)
125 }
126
127
128 aPass := analyze(&protocol.AnalyzeRequest{
129 ID: "a",
130 ImportPath: "a",
131 Dir: dir,
132 GoFiles: {writeFile("a.go", "package a\n\nimport \"lib\"\n\nfunc f() {\n\tlib.SpecialF()\n\tlib.G()\n}\n")},
133 ImportMap: {"lib": "lib"},
134 GoVersion: "go1.28",
135 GOARCH: runtime.GOARCH,
136 TypeImports: {"lib": file("lib.export")},
137 Facts: {special: {"lib": file("lib.pass")}},
138 Outputs: {special: file("a.pass")},
139 Report: {special},
140 })
141 if len(aPass.Diagnostics) != 1 {
142 t.Fatalf("a: got diagnostics %v, want one", aPass.Diagnostics)
143 }
144 d := aPass.Diagnostics[0]
145 if want := "call of special function lib.SpecialF"; d.Message != want {
146 t.Errorf("a: got diagnostic %q, want %q", d.Message, want)
147 }
148 if want := "a.go:6:2"; !strings.HasSuffix(d.Posn, want) {
149 t.Errorf("a: got diagnostic at %s, want %s", d.Posn, want)
150 }
151 }
152
153
154
155 var specialAnalyzer = &analysis.Analyzer{
156 Name: "special",
157 Doc: "report calls of special functions",
158 FactTypes: []analysis.Fact{new(isSpecial)},
159 Run: func(pass *analysis.Pass) (any, error) {
160 for _, f := range pass.Files {
161 for _, decl := range f.Decls {
162 if decl, ok := decl.(*ast.FuncDecl); ok && strings.HasPrefix(decl.Name.Name, "Special") {
163 pass.ExportObjectFact(pass.TypesInfo.Defs[decl.Name], &isSpecial{true})
164 }
165 }
166 }
167 for _, f := range pass.Files {
168 ast.Inspect(f, func(n ast.Node) bool {
169 if sel, ok := n.(*ast.SelectorExpr); ok {
170 if fn, ok := pass.TypesInfo.Uses[sel.Sel].(*types.Func); ok && pass.ImportObjectFact(fn, new(isSpecial)) {
171 pass.ReportRangef(sel, "call of special function %s.%s", fn.Pkg().Name(), fn.Name())
172 }
173 }
174 return true
175 })
176 }
177 return nil, nil
178 },
179 }
180
181
182 type isSpecial struct{ Special bool }
183
184 func (*isSpecial) AFact() {}
185
View as plain text