chore(lint): add forbidigo rules to enforce t.Context() in tests

Add linter rules to prevent usage of context.Background() and
context.TODO() in test files - t.Context() should be used instead.

The rules only apply to *_test.go files, not production code.

Note: os.Setenv is not covered by forbidigo due to a limitation where
it only catches calls when the return value is assigned. However,
errcheck will flag unchecked os.Setenv calls.

Assisted-By: cagent
Signed-off-by: David Gageot <david.gageot@docker.com>
This commit is contained in:
David Gageot 2026-01-20 10:56:25 +01:00 • committed by Guillaume Lours
parent 27faa3b84e
commit 04b4a832dc
2 changed files with 15 additions and 0 deletions

View file

@ -8,6 +8,7 @@ linters:
- depguard
- errcheck
- errorlint
- forbidigo
- gocritic
- gocyclo
- gomodguard
@ -38,6 +39,15 @@ linters:
desc: use stdlib slices package
- pkg: gopkg.in/yaml.v2
desc: compose-go uses yaml.v3
forbidigo:
analyze-types: true
forbid:
- pattern: 'context\.Background'
pkg: '^context$'
msg: "in tests, use t.Context() instead of context.Background()"
- pattern: 'context\.TODO'
pkg: '^context$'
msg: "in tests, use t.Context() instead of context.TODO()"
gocritic:
disabled-checks:
- paramTypeCombine
@ -74,6 +84,10 @@ linters:
- third_party$
- builtin$
- examples$
rules:
- path-except: '_test\.go'
linters:
- forbidigo
issues:
max-issues-per-linter: 0
max-same-issues: 0

View file

@ -127,6 +127,7 @@ func containerLabels(service string, oneOff bool) map[string]string {
}
func anyCancellableContext() gomock.Matcher {
//nolint:forbidigo // This creates a context type for gomock matching, not for actual test usage
ctxWithCancel, cancel := context.WithCancel(context.Background())
cancel()
return gomock.AssignableToTypeOf(ctxWithCancel)