gopkg.in/golangci/golangci-lint.v1@v1.10.1/test/linters_test.go (about) 1 package test 2 3 import ( 4 "bytes" 5 "io/ioutil" 6 "os/exec" 7 "path/filepath" 8 "runtime" 9 "strings" 10 "testing" 11 12 "github.com/golangci/golangci-lint/pkg/exitcodes" 13 "github.com/stretchr/testify/assert" 14 ) 15 16 func runGoErrchk(c *exec.Cmd, t *testing.T) { 17 output, err := c.CombinedOutput() 18 assert.NoError(t, err, "Output:\n%s", output) 19 20 // Can't check exit code: tool only prints to output 21 assert.False(t, bytes.Contains(output, []byte("BUG")), "Output:\n%s", output) 22 } 23 24 const testdataDir = "testdata" 25 const binName = "golangci-lint" 26 27 func testSourcesFromDir(t *testing.T, dir string) { 28 t.Log(filepath.Join(dir, "*.go")) 29 sources, err := filepath.Glob(filepath.Join(dir, "*.go")) 30 assert.NoError(t, err) 31 assert.NotEmpty(t, sources) 32 33 installBinary(t) 34 35 for _, s := range sources { 36 s := s 37 t.Run(filepath.Base(s), func(t *testing.T) { 38 t.Parallel() 39 testOneSource(t, s) 40 }) 41 } 42 } 43 44 func TestSourcesFromTestdataWithIssuesDir(t *testing.T) { 45 testSourcesFromDir(t, testdataDir) 46 } 47 48 func TestTypecheck(t *testing.T) { 49 testSourcesFromDir(t, filepath.Join(testdataDir, "notcompiles")) 50 } 51 52 func testOneSource(t *testing.T, sourcePath string) { 53 goErrchkBin := filepath.Join(runtime.GOROOT(), "test", "errchk") 54 args := []string{ 55 binName, "run", 56 "--no-config", 57 "--disable-all", 58 "--print-issued-lines=false", 59 "--print-linter-name=false", 60 "--out-format=line-number", 61 } 62 63 for _, addArg := range []string{"", "-Etypecheck"} { 64 caseArgs := append([]string{}, args...) 65 caseArgs = append(caseArgs, getAdditionalArgs(t, sourcePath)...) 66 if addArg != "" { 67 caseArgs = append(caseArgs, addArg) 68 } 69 70 caseArgs = append(caseArgs, sourcePath) 71 72 cmd := exec.Command(goErrchkBin, caseArgs...) 73 t.Log(caseArgs) 74 runGoErrchk(cmd, t) 75 } 76 } 77 78 func getAdditionalArgs(t *testing.T, sourcePath string) []string { 79 data, err := ioutil.ReadFile(sourcePath) 80 assert.NoError(t, err) 81 82 lines := strings.SplitN(string(data), "\n", 2) 83 firstLine := lines[0] 84 85 parts := strings.Split(firstLine, "args:") 86 if len(parts) == 1 { 87 return nil 88 } 89 90 return strings.Split(parts[len(parts)-1], " ") 91 } 92 93 func TestGolintConsumesXTestFiles(t *testing.T) { 94 dir := filepath.Join(testdataDir, "withxtest") 95 const expIssue = "if block ends with a return statement, so drop this else and outdent its block" 96 97 out, ec := runGolangciLint(t, "--no-config", "--disable-all", "-Egolint", dir) 98 assert.Equal(t, exitcodes.IssuesFound, ec) 99 assert.Contains(t, out, expIssue) 100 101 out, ec = runGolangciLint(t, "--no-config", "--disable-all", "-Egolint", filepath.Join(dir, "p_test.go")) 102 assert.Equal(t, exitcodes.IssuesFound, ec) 103 assert.Contains(t, out, expIssue) 104 }