Skip to content

Conversation

@brasic
Copy link

@brasic brasic commented May 1, 2025

Fixes #4.

What does this PR do?

Suggesting the replacement of t.Context() for context.Background() inside a test's t.Cleanup() functions is usually not a good suggestion since inside t.Cleanup functions the test context will already be cancelled so doing meaningful cleanup that uses context for timeout is not possible.

This PR detects the use of t.Cleanup and prunes further inspection of the child-nodes (i.e. the cleanup function literal).

Motivation

I'd like to enable the usetesting linter in codebases I maintain but we make wide use of t.Cleanup with timeout contexts to close resources after a test ends in a limited amount of time (see the example in the added test case). Following this linter's suggestions causes such tests to fail because no time is allowed to clean up the resources (as the context returned by t.Context() is closed before cleanup functions are invoked)

Additional Notes

Note that this fix cancels all checking within t.Cleanup functions, not just for context.Background/context.Todo. Ideally within t.Cleanup functions we would still check for the other things this linter looks at, but I wasn't able to see a good way to do that given the structure of the linter.

See ldez#4

This is not a safe replacement and not usually a good suggestion since
inside t.Cleanup functions the test context will already be cancelled so
doing meaningful cleanup that uses context for timeout is not possible.
@ldez ldez added the duplicate This issue or pull request already exists label May 1, 2025
@ldez ldez closed this May 1, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

duplicate This issue or pull request already exists

Projects

None yet

Development

Successfully merging this pull request may close these issues.

False positive on context usage within Cleanup funcs

2 participants