golangci-lint icon indicating copy to clipboard operation
golangci-lint copied to clipboard

proposal: add a way to exclude rules only for non-test code

Open ashanbrown opened this issue 3 years ago • 3 comments

Your feature request related to a problem? Please describe.

I'd like to include some linter rules for only test code but I don't believe is possible to write a golang regexp that excludes lint errors for files that don't end in _test.go (see https://stackoverflow.com/questions/42515407/is-there-a-way-to-match-everything-except-a-constant-string-using-go-regexp, explaining that in order to meet the O(n) golang regexps don't support lookahead). In my particular case, I'm looking to use forbidigo to exclude calls to time.Sleep to keep people from adding sleep to tests.

Describe the solution you'd like.

I'd suggest we add a includeTests field to BaseRule. Then an exclude rule would like:

  exclude-rules:
    - linters:
        - forbidigo
      source: time\.Sleep
      includeTests: false

The default value for includeTests would be true.

Describe alternatives you've considered.

I could build selective configuration per pattern for tests into forbidigo but that would require significantly changing the interface and also imagine other linters may have a similar issue. Alternatively, a notpath field that specified files to skip might work, allowing me to exclude test files. That approach might also have other applications as well.

Additional context.

No response

ashanbrown avatar Dec 30 '21 21:12 ashanbrown

You can do something like that:

func TestName(t *testing.T) {
	compile := regexp.MustCompile(`^.*[^_][^t][^e][^s][^t]\.go$`)

	fmt.Println(compile.MatchString("foobar_test.go"))
	fmt.Println(compile.MatchString("foobar.go"))
}

The limitation: it doesn't handle file with less than 5 characters.

ldez avatar Dec 30 '21 23:12 ldez

Thanks for the suggestion. I agree that would work but it doesn't express the intent very obviously and doesn't lend itself to discovery. Might we consider something more direct?

ashanbrown avatar Jan 02 '22 15:01 ashanbrown

I bumped into the same issue when I tried to forbid os.MkdirTemp in tests, so people use T.TempDir instead, but I'm reluctant to go for the RegEx pattern you suggested. Would be great to have a includeTests feature. Happy to explore adding it if you're open to having this addition.

mihaitodor avatar Feb 14 '22 01:02 mihaitodor

I've proposed an implementation based on not-path instead of notpath (hyphen for readability) in https://github.com/golangci/golangci-lint/pull/3617.

pohly avatar Feb 19 '23 19:02 pohly