Debian Codegraph @

go/analysis/multichecker/multichecker_test.go

raw symbols SCIP
1 // Copyright 2018 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 //go:build go1.12
6
7 package multichecker_test
8
9 import (
10 "fmt"
11 "os"
12 "os/exec"
13 "runtime"
14 "testing"
15
16 "golang.org/x/tools/go/analysis"
17 "golang.org/x/tools/go/analysis/multichecker"
18 "golang.org/x/tools/go/analysis/passes/findcall"
19 "golang.org/x/tools/internal/testenv"
20 )
21
22 func main() {
23 fail := &analysis.Analyzer{
24 Name: "fail",
25 Doc: "always fail on a package 'sort'",
26 Run: func(pass *analysis.Pass) (any, error) {
27 if pass.Pkg.Path() == "sort" {
28 return nil, fmt.Errorf("failed")
29 }
30 return nil, nil
31 },
32 }
33 multichecker.Main(findcall.Analyzer, fail)
34 }
35
36 // TestExitCode ensures that analysis failures are reported correctly.
37 // This test fork/execs the main function above.
38 func TestExitCode(t *testing.T) {
39 if runtime.GOOS != "linux" {
40 t.Skipf("skipping fork/exec test on this platform")
41 }
42
43 if os.Getenv("MULTICHECKER_CHILD") == "1" {
44 // child process
45
46 // replace [progname -test.run=TestExitCode -- ...]
47 // by [progname ...]
48 os.Args = os.Args[2:]
49 os.Args[0] = "vet"
50 main()
51 panic("unreachable")
52 }
53
54 testenv.NeedsTool(t, "go")
55
56 for _, test := range []struct {
57 args []string
58 want int
59 }{
60 {[]string{"nosuchdir/..."}, 1}, // matched no packages
61 {[]string{"nosuchpkg"}, 1}, // matched no packages
62 {[]string{"-unknownflag"}, 2}, // flag error
63 {[]string{"-findcall.name=panic", "io"}, 3}, // finds diagnostics
64 {[]string{"-findcall=0", "io"}, 0}, // no checkers
65 {[]string{"-findcall.name=nosuchfunc", "io"}, 0}, // no diagnostics
66 {[]string{"-findcall.name=panic", "sort", "io"}, 1}, // 'fail' failed on 'sort'
67
68 // -json: exits zero even in face of diagnostics or package errors.
69 {[]string{"-findcall.name=panic", "-json", "io"}, 0},
70 {[]string{"-findcall.name=panic", "-json", "io"}, 0},
71 {[]string{"-findcall.name=panic", "-json", "sort", "io"}, 0},
72 } {
73 args := []string{"-test.run=TestExitCode", "--"}
74 args = append(args, test.args...)
75 cmd := exec.Command(os.Args[0], args...)
76 cmd.Env = append(os.Environ(), "MULTICHECKER_CHILD=1")
77 out, err := cmd.CombinedOutput()
78 if len(out) > 0 {
79 t.Logf("%s: out=<<%s>>", test.args, out)
80 }
81 var exitcode int
82 if err, ok := err.(*exec.ExitError); ok {
83 exitcode = err.ExitCode() // requires go1.12
84 }
85 if exitcode != test.want {
86 t.Errorf("%s: exited %d, want %d", test.args, exitcode, test.want)
87 }
88 }
89 }