Repository navigation
Description
There have been various previous proposals (#16221 #18182 #18199 #18368) to add a Context method to testing.T. #16221 was even accepted and implemented but then reverted.
By my understanding, the principal argument against adding a Context method was that Context provides a way to tell things to shut down, but no way to wait for things to actually finish, so adding this functionality doesn't actually provide a good way to wait for tests to gracefully shut down, because they might fail and resources might continue to be used even after the testing package has marked the tests as successful.
A Context that is canceled when the test fails would be fine, but trying to use it in isolation to signal the return of the Test function seems like a mistake. Context cancellation is asynchronous, so nothing guarantees that the goroutines started as part of the test have actually returned when the test ends, which means they are likely to interfere with subsequent tests.
Similarly from @niemeyer here:
Such a flagging mechanism that by definition will only be useful when things will continue running in the background past the test completion does feel like a wart to me. We should be discouraging people from doing that in the first place, because arbitrary background logic delayed for arbitrary periods of time while other things are being tested is a common source of testing pain, breaking in curious and hard to reproduce ways.
However, @dsnet, who reverted the code, suggested that the decision wasn't necessarily final:
I am personally still in support adding t.Context in conjunction with a wait mechanism as this will counter the current detriment of adding t.Context only. However, I don't believe that we should rush on more API design and we can revisit this for Go 1.9.
I propose that the recently added T.Cleanup method can now provide the wait mechanism that's needed - the other half of Context.Done. We can define the semantics such that the the testing context is cancelled just before invoking the Cleanup-registered functions. That way, it's easy to both listen for the test being done, and also to wait for asynchronous operations to finish when it is.
By hooking into the Cleanup mechanism, we don't presuppose any particular kind of waiting - this can hook into whatever mechanism your infrastructure provides for graceful shutdown.
A possible API description:
// Context returns a context that's cancelled just before
// Cleanup-registered functions are called.
//
// This allows Cleanup-registered functions to wait for any resources
// that are listening on Context.Done before the test completes.
func (t *T) Context() context.Context
Example usage:
func TestFoo(t *testing.T) {
ctx := t.Context()
var wg sync.WaitGroup
t.Cleanup(wg.Wait)
wg.Add(1)
go func() {
defer wg.Done()
doSomething(ctx)
}()
}
Activity
seh commentedon Jan 13, 2020
Did you intend for your sample
TestFoofunction to include a call toWaitGroup.Done?rogpeppe commentedon Jan 13, 2020
@seh yup, fixed, thanks!
[-]proposal: reconsider adding Context method to testing.T[/-][+]proposal: testing: reconsider adding Context method to testing.T[/+]rogpeppe commentedon Jan 17, 2020
I'm having second thoughts about this proposal. Given that it's so simple to define your own test-context function, does
T.Contextactually justify its place?I believe the function below does almost exactly the same thing as the
T.Contextmethod proposed above (the difference being that it returns a new context value every time, but that shouldn't make any significant semantic difference beyond extra memory use):bcmills commentedon Jan 21, 2020
I think the changes to
golang.org/x/sync/errgroupproposed in CL 134395 are probably cleaner, and wouldn't require any changes to the standard-librarytestingpackage.In particular, that change would allow you to do something like:
bcmills commentedon Jan 22, 2020
Thinking about this some more: I think a
(*T).Contextmethod would still be too confusing.Some users would likely assume that it is (only) cancelled if and when the test is marked as failed. Others might assume that it is cancelled at start of the
Cleanupphase, before the cleanup functions are invoked. Yet others might assume that it is cancelled after all of theCleanupfunctions have completed.Since there is no single “intuitive” interpretation, we should avoid the ambiguous name. Perhaps we could find a less ambiguous name, but given that the explicit code isn't much longer I'm not sure that's worth the API weight.
rogpeppe commentedon Jan 22, 2020
After some discussion with @mvdan, I realised that my original proposal here was not sufficient for his use case (he wants to start tearing things down immediately there's a test error).
I don't agree with tearing everything down on any call to
Fail, but ISTM that there's an alternative: provide a context that's canceled wheneverFailNowis called and we document that it's OK to callFailNowin a goroutine.Calling
FailNowin a goroutine still won't tear down the entire test (it can't, of course) but at least then there's a mechanism whereby that can happen. And people really like callingFailNowin goroutines, and there's no really reason AFAICS why it needs to be disallowed. We could even document that it callsruntime.GoExitunder the hood.wdyt?
bcmills commentedon Jan 22, 2020
The approach in that
errgroupCL still seems more general and a bit cleaner to me.We don't need to couple cancellation to
FailNow; we only need to have a mechanism to tie the call toruntime.Goexitto the cancellation of a correspondingContext, and tying goroutines to higher-level tasks is literally the only purpose oferrgroup.Group, so that seems like a natural place for it.Note that one of the changes in that
errgroupCL specifically adds handling and propagation forruntime.Goexit: aruntime.Goexitin any of the associated goroutines cancels the associatedContext, and also propagates to any pending or subsequentWaitcalls. So one of the effects of that CL is to enableerrgroupto tear down (concurrent portions of) a test in the natural way on failure.rogpeppe commentedon Jan 22, 2020
I like that thought. The only issue is that you'd have to be careful to add the corresponding code to every goroutine, I guess. That might turn out to be a pain (and it's error-prone).
We'd still need to drop the "FailNow must be called from the goroutine running the test or benchmark function, not from other goroutines created during the test." sentence from the docs. Does that seem reasonable to you?
bcmills commentedon Jan 23, 2020
That seems reasonable. I would probably replace that sentence with a more explicit one, rather than dropping it outright. Perhaps something like:
And in the comment for
type T:And for
(*T).Parallel:carnott-snap commentedon Jul 28, 2020
I am interested in continuing this discussion, can we add this to the proposal rotation, or was there something blocking the discussion?
invidian commentedon Oct 12, 2021
What I've done for couple of projects was to introduce the following function:
This allows to properly respect
-timeoutflag ingo test. Having a function like this in standard library would be indeed useful, perhaps in a form of:We could also validate that
gracePeriod > now - deadlineor alternatively usecontext.WithTimeout.iangudger commentedon Feb 3, 2022
I am strongly in favor of adding this.
It seems like every single test that I write begins with:
I have also found that tests which use contexts and don't begin with that preamble usually leak resources or contain other context related bugs. I think making this functionality built-in would help encourage better testing.
35 remaining items
ianlancetaylor commentedon Nov 21, 2024
See #70480 for a follow-up.
gopherbot commentedon Dec 17, 2024
Change https://go.dev/cl/637236 mentions this issue:
testing: support B.Context and F.Contexttesting: support B.Context and F.Context
aclements commentedon Dec 18, 2024
CL 603959 also added
B.Context,F.Context, andTB.Context, which were not part of the accepted proposal, and were missed in code review. It looks like these additions may have just been an oversight. Separately,B.Context,F.Contextalways returned nil, which was reported in #70866.@ianlancetaylor brought up the additional API at proposal review today and we did a mini-review and signed off on the addition. (Honestly, I'm surprised that, as far as I can tell, this never came up in the original discussion!)
Obviously we should endeavor to not bypass the usual process like this, but mistakes happen, and I'm glad we caught this before the 1.24 release. I think this is also a great demonstration of why we should have a formalized process for small proposals, which is something I plan on working on soon.
Thanks everyone!
jerome-laforge commentedon Jan 3, 2025
Do you think that is possible to add in the changelog a command (gofmt?) to bulk replace the
context.Background()byt.Context()that also removes context import if not used?ianlancetaylor commentedon Jan 3, 2025
I'm not aware of a tool that will do that today. And it's not obviously better. The real advantage of
t.Contextis when it is combined witht.Cleanupor at least withcontext.WithCancel(context.Background()).aclements commentedon Jan 6, 2025
I've added a mention of this to the "modernizers" issue: #70815 (comment)
database/sql: use t.Context in tests
gopherbot commentedon Feb 7, 2025
Change https://go.dev/cl/647555 mentions this issue:
database/sql: use t.Context in testsdatabase/sql: use t.Context in tests
database/sql: use t.Context in tests
apparentlymart commentedon Aug 1, 2025
Back near the start of the discussion #36532 (comment) raised the concern that users might misunderstand where the context gets cancelled.
I'm sorry to report that, despite the clear documentation otherwise, I got so accustomed to just "mindlessly" using
t.Context()instead ofcontext.Background()in test code that I started using it insideCleanupfunctions, thereby causing some subtle misbehavior where sometimes the cleanup behavior itself gets canceled.I don't mean this comment to suggest that anything about the design should change. The functionality is useful despite this small opportunity for mistakes. Perhaps using
t.Context()anywhere inside a function passed tot.Cleanupwould be a good thing for static analysis tools to flag as a likely mistake. 🤷♂️