| 1 | // Copyright 2019 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 | "reflect" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | |
| 14 | "golang.org/x/tools/go/analysis" |
| 15 | "golang.org/x/tools/go/analysis/analysistest" |
| 16 | "golang.org/x/tools/go/analysis/internal/analysisflags" |
| 17 | "golang.org/x/tools/go/analysis/internal/checker" |
| 18 | "golang.org/x/tools/go/analysis/passes/inspect" |
| 19 | "golang.org/x/tools/internal/testenv" |
| 20 | "golang.org/x/tools/internal/testfiles" |
| 21 | "golang.org/x/tools/txtar" |
| 22 | ) |
| 23 | |
| 24 | func TestApplyFixes(t *testing.T) { |
| 25 | testenv.NeedsGoPackages(t) |
| 26 | testenv.RedirectStderr(t) // associated checker.Run output with this test |
| 27 | |
| 28 | files := map[string]string{ |
| 29 | "rename/test.go": `package rename |
| 30 | |
| 31 | func Foo() { |
| 32 | bar := 12 |
| 33 | _ = bar |
| 34 | } |
| 35 | |
| 36 | // the end |
| 37 | `} |
| 38 | want := `package rename |
| 39 | |
| 40 | func Foo() { |
| 41 | baz := 12 |
| 42 | _ = baz |
| 43 | } |
| 44 | |
| 45 | // the end |
| 46 | ` |
| 47 | |
| 48 | testdata, cleanup, err := analysistest.WriteFiles(files) |
| 49 | if err != nil { |
| 50 | t.Fatal(err) |
| 51 | } |
| 52 | path := filepath.Join(testdata, "src/rename/test.go") |
| 53 | |
| 54 | analysisflags.Fix = true |
| 55 | checker.Run([]string{"file=" + path}, []*analysis.Analyzer{renameAnalyzer}) |
| 56 | analysisflags.Fix = false |
| 57 | |
| 58 | contents, err := os.ReadFile(path) |
| 59 | if err != nil { |
| 60 | t.Fatal(err) |
| 61 | } |
| 62 | |
| 63 | got := string(contents) |
| 64 | if got != want { |
| 65 | t.Errorf("contents of rewritten file\ngot: %s\nwant: %s", got, want) |
| 66 | } |
| 67 | |
| 68 | defer cleanup() |
| 69 | } |
| 70 | |
| 71 | func TestRunDespiteErrors(t *testing.T) { |
| 72 | testenv.NeedsGoPackages(t) |
| 73 | testenv.RedirectStderr(t) // associate checker.Run output with this test |
| 74 | |
| 75 | files := map[string]string{ |
| 76 | "rderr/test.go": `package rderr |
| 77 | |
| 78 | // Foo deliberately has a type error |
| 79 | func Foo(s string) int { |
| 80 | return s + 1 |
| 81 | } |
| 82 | `, |
| 83 | "cperr/test.go": `package copyerr |
| 84 | |
| 85 | import "sync" |
| 86 | |
| 87 | func bar() { } // for renameAnalyzer |
| 88 | |
| 89 | type T struct{ mu sync.Mutex } |
| 90 | type T1 struct{ t *T } |
| 91 | |
| 92 | func NewT1() *T1 { return &T1{T} } |
| 93 | `, |
| 94 | } |
| 95 | |
| 96 | testdata, cleanup, err := analysistest.WriteFiles(files) |
| 97 | if err != nil { |
| 98 | t.Fatal(err) |
| 99 | } |
| 100 | defer cleanup() |
| 101 | |
| 102 | rderrFile := "file=" + filepath.Join(testdata, "src/rderr/test.go") |
| 103 | cperrFile := "file=" + filepath.Join(testdata, "src/cperr/test.go") |
| 104 | |
| 105 | // A no-op analyzer that should finish regardless of |
| 106 | // parse or type errors in the code. |
| 107 | noop := &analysis.Analyzer{ |
| 108 | Name: "noop", |
| 109 | Doc: "noop", |
| 110 | Requires: []*analysis.Analyzer{inspect.Analyzer}, |
| 111 | Run: func(pass *analysis.Pass) (any, error) { |
| 112 | return nil, nil |
| 113 | }, |
| 114 | RunDespiteErrors: true, |
| 115 | } |
| 116 | |
| 117 | // A no-op analyzer, with facts, that should finish |
| 118 | // regardless of parse or type errors in the code. |
| 119 | noopWithFact := &analysis.Analyzer{ |
| 120 | Name: "noopfact", |
| 121 | Doc: "noopfact", |
| 122 | Requires: []*analysis.Analyzer{inspect.Analyzer}, |
| 123 | Run: func(pass *analysis.Pass) (any, error) { |
| 124 | return nil, nil |
| 125 | }, |
| 126 | RunDespiteErrors: true, |
| 127 | FactTypes: []analysis.Fact{&EmptyFact{}}, |
| 128 | } |
| 129 | |
| 130 | for _, test := range []struct { |
| 131 | name string |
| 132 | pattern []string |
| 133 | analyzers []*analysis.Analyzer |
| 134 | code int |
| 135 | }{ |
| 136 | // parse/type errors |
| 137 | {name: "skip-error", pattern: []string{rderrFile}, analyzers: []*analysis.Analyzer{renameAnalyzer}, code: 1}, |
| 138 | // RunDespiteErrors allows a driver to run an Analyzer even after parse/type errors. |
| 139 | // |
| 140 | // The noop analyzer doesn't use facts, so the driver loads only the root |
| 141 | // package from source. For the rest, it asks 'go list' for export data, |
| 142 | // which fails because the compiler encounters the type error. Since the |
| 143 | // errors come from 'go list', the driver doesn't run the analyzer. |
| 144 | {name: "despite-error", pattern: []string{rderrFile}, analyzers: []*analysis.Analyzer{noop}, code: exitCodeFailed}, |
| 145 | // The noopfact analyzer does use facts, so the driver loads source for |
| 146 | // all dependencies, does type checking itself, recognizes the error as a |
| 147 | // type error, and runs the analyzer. |
| 148 | {name: "despite-error-fact", pattern: []string{rderrFile}, analyzers: []*analysis.Analyzer{noopWithFact}, code: exitCodeFailed}, |
| 149 | // combination of parse/type errors and no errors |
| 150 | {name: "despite-error-and-no-error", pattern: []string{rderrFile, "sort"}, analyzers: []*analysis.Analyzer{renameAnalyzer, noop}, code: exitCodeFailed}, |
| 151 | // non-existing package error |
| 152 | {name: "no-package", pattern: []string{"xyz"}, analyzers: []*analysis.Analyzer{renameAnalyzer}, code: exitCodeFailed}, |
| 153 | {name: "no-package-despite-error", pattern: []string{"abc"}, analyzers: []*analysis.Analyzer{noop}, code: exitCodeFailed}, |
| 154 | {name: "no-multi-package-despite-error", pattern: []string{"xyz", "abc"}, analyzers: []*analysis.Analyzer{noop}, code: exitCodeFailed}, |
| 155 | // combination of type/parsing and different errors |
| 156 | {name: "different-errors", pattern: []string{rderrFile, "xyz"}, analyzers: []*analysis.Analyzer{renameAnalyzer, noop}, code: exitCodeFailed}, |
| 157 | // non existing dir error |
| 158 | {name: "no-match-dir", pattern: []string{"file=non/existing/dir"}, analyzers: []*analysis.Analyzer{renameAnalyzer, noop}, code: exitCodeFailed}, |
| 159 | // no errors |
| 160 | {name: "no-errors", pattern: []string{"sort"}, analyzers: []*analysis.Analyzer{renameAnalyzer, noop}, code: exitCodeSuccess}, |
| 161 | // duplicate list error with no findings |
| 162 | {name: "list-error", pattern: []string{cperrFile}, analyzers: []*analysis.Analyzer{noop}, code: exitCodeFailed}, |
| 163 | // duplicate list errors with findings (issue #67790) |
| 164 | {name: "list-error-findings", pattern: []string{cperrFile}, analyzers: []*analysis.Analyzer{renameAnalyzer}, code: exitCodeDiagnostics}, |
| 165 | } { |
| 166 | t.Run(test.name, func(t *testing.T) { |
| 167 | if got := checker.Run(test.pattern, test.analyzers); got != test.code { |
| 168 | t.Errorf("got incorrect exit code %d for test %s; want %d", got, test.name, test.code) |
| 169 | } |
| 170 | }) |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | type EmptyFact struct{} |
| 175 | |
| 176 | func (f *EmptyFact) AFact() {} |
| 177 | |
| 178 | func TestURL(t *testing.T) { |
| 179 | // TestURL test that URLs get forwarded to diagnostics by internal/checker. |
| 180 | testenv.NeedsGoPackages(t) |
| 181 | |
| 182 | files := map[string]string{ |
| 183 | "p/test.go": `package p // want "package name is p"`, |
| 184 | } |
| 185 | pkgname := &analysis.Analyzer{ |
| 186 | Name: "pkgname", |
| 187 | Doc: "trivial analyzer that reports package names", |
| 188 | URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/internal/checker", |
| 189 | Run: func(p *analysis.Pass) (any, error) { |
| 190 | for _, f := range p.Files { |
| 191 | p.ReportRangef(f.Name, "package name is %s", f.Name.Name) |
| 192 | } |
| 193 | return nil, nil |
| 194 | }, |
| 195 | } |
| 196 | |
| 197 | testdata, cleanup, err := analysistest.WriteFiles(files) |
| 198 | if err != nil { |
| 199 | t.Fatal(err) |
| 200 | } |
| 201 | defer cleanup() |
| 202 | path := filepath.Join(testdata, "src/p/test.go") |
| 203 | results := analysistest.Run(t, testdata, pkgname, "file="+path) |
| 204 | |
| 205 | var urls []string |
| 206 | for _, r := range results { |
| 207 | for _, d := range r.Diagnostics { |
| 208 | urls = append(urls, d.URL) |
| 209 | } |
| 210 | } |
| 211 | want := []string{"https://pkg.go.dev/golang.org/x/tools/go/analysis/internal/checker"} |
| 212 | if !reflect.DeepEqual(urls, want) { |
| 213 | t.Errorf("Expected Diagnostics.URLs %v. got %v", want, urls) |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | // TestPassReadFile exercises the Pass.ReadFile function. |
| 218 | func TestPassReadFile(t *testing.T) { |
| 219 | cwd, _ := os.Getwd() |
| 220 | |
| 221 | const src = ` |
| 222 | -- go.mod -- |
| 223 | module example.com |
| 224 | |
| 225 | -- p/file.go -- |
| 226 | package p |
| 227 | |
| 228 | -- p/ignored.go -- |
| 229 | //go:build darwin && mips64 |
| 230 | |
| 231 | package p |
| 232 | |
| 233 | hello from ignored |
| 234 | |
| 235 | -- p/other.s -- |
| 236 | hello from other |
| 237 | ` |
| 238 | |
| 239 | // Expand archive into tmp tree. |
| 240 | fs, err := txtar.FS(txtar.Parse([]byte(src))) |
| 241 | if err != nil { |
| 242 | t.Fatal(err) |
| 243 | } |
| 244 | tmpdir := testfiles.CopyToTmp(t, fs) |
| 245 | |
| 246 | ran := false |
| 247 | a := &analysis.Analyzer{ |
| 248 | Name: "a", |
| 249 | Requires: []*analysis.Analyzer{inspect.Analyzer}, |
| 250 | Doc: "doc", |
| 251 | Run: func(pass *analysis.Pass) (any, error) { |
| 252 | if len(pass.OtherFiles)+len(pass.IgnoredFiles) == 0 { |
| 253 | t.Errorf("OtherFiles and IgnoredFiles are empty") |
| 254 | return nil, nil |
| 255 | } |
| 256 | |
| 257 | for _, test := range []struct { |
| 258 | filename string |
| 259 | want string // substring of file content or error message |
| 260 | }{ |
| 261 | { |
| 262 | pass.OtherFiles[0], // [other.s] |
| 263 | "hello from other", |
| 264 | }, |
| 265 | { |
| 266 | pass.IgnoredFiles[0], // [ignored.go] |
| 267 | "hello from ignored", |
| 268 | }, |
| 269 | { |
| 270 | "nonesuch", |
| 271 | "nonesuch is not among OtherFiles, ", // etc |
| 272 | }, |
| 273 | { |
| 274 | filepath.Join(cwd, "checker_test.go"), |
| 275 | "checker_test.go is not among OtherFiles, ", // etc |
| 276 | }, |
| 277 | } { |
| 278 | content, err := pass.ReadFile(test.filename) |
| 279 | var got string |
| 280 | if err != nil { |
| 281 | got = err.Error() |
| 282 | } else { |
| 283 | got = string(content) |
| 284 | if len(got) > 100 { |
| 285 | got = got[:100] + "..." |
| 286 | } |
| 287 | } |
| 288 | if !strings.Contains(got, test.want) { |
| 289 | t.Errorf("Pass.ReadFile(%q) did not contain %q; got:\n%s", |
| 290 | test.filename, test.want, got) |
| 291 | } |
| 292 | } |
| 293 | ran = true |
| 294 | return nil, nil |
| 295 | }, |
| 296 | } |
| 297 | |
| 298 | analysistest.Run(t, tmpdir, a, "example.com/p") |
| 299 | |
| 300 | if !ran { |
| 301 | t.Error("analyzer did not run") |
| 302 | } |
| 303 | |
| 304 | // TODO(adonovan): test that fixes are applied to the |
| 305 | // pass.ReadFile virtual file tree. |
| 306 | } |