Cleanup Context Checker
c3 is a tool to analyze and warn against calling (*testing.common).Context
within (*testing.common).Cleanup
functions in Go tests.
(*testing.common).Context
is canceled before (*testing.common).Cleanup
functions are called, so calling (*testing.common).Context
within (*testing.common).Cleanup
functions can cause unexpected behavior.
Context returns a context that is canceled just before Cleanup-registered functions are called.1
package a
import (
"context"
"testing"
)
func cleanup(t *testing.T) {
t.Context()
}
func f(ctx context.Context) { }
func TestA(t *testing.T) {
t.Cleanup(func() { t.Context() }) // want `avoid calling \(\*testing\.common\)\.Context inside Cleanup`
t.Cleanup(func() { cleanup(t) }) // want `avoid calling \(\*testing\.common\)\.Context inside Cleanup`
t.Cleanup(func() { f(t.Context()) }) // want `avoid calling \(\*testing\.common\)\.Context inside Cleanup`
t.Cleanup(func() { context.Background() }) // ok
}
go install github.com/ikura-hamu/c3@latest
go vet -vettool=$(which c3) ./...
https://golangci-lint.run/plugins/module-plugins/
- Configure golangci-lint customization.
.custom-gcl.yml
version: "v1.64.1" # golangci-lint version
destination: "."
name: "custom-gcl"
plugins:
- module: "github.com/ikura-hamu/c3"
path: "github.com/ikura-hamu/c3"
version: "latest"
- Build custom golangci-lint bianry.
golangci-lint custom
- Set up golangci-lint configuration.
.golangci.yml
linters:
enable:
- c3
linters-settings:
custom:
c3:
type: "module"
- Run custom golangci-lint.
./custom-gcl run