Coming in Go 1.8, the proposal,
issue #16221, adds a method on testing.T that returns a Context that is canceled when the Test function returns.
This feature is really useful when writing tests with multiple goroutines as a way to signal to those goroutines that it is time to terminate. However, in using the Context method, I feel like it is still lacking. In addition to signaling of termination, I want the testing framework to also wait until all goroutines have finished before starting the next test to ensure that they do not have any side effects on the next test.
As a possible approach, we could add some method that returns a *sync.WaitGroup. When the Test function returns, the testing framework implicitly cancels the Context and then calls WaitGroup.Wait().
The downside to this is that we would now be adding two additional methods (Context and WaitGroup) to testing.T, which already has a fairly large API surface. Also, most tests are probably not running with multiple goroutines.
On the flipside, this would assists concurrent tests from needing to manually create a Context and a WaitGroup and then defer on canceling and waiting on them. It also cleans up helper functions since they would only need to take in a testing.T object as opposed to (testing.T, context.Context, sync.WaitGroup).
My concluding thoughts; we should either add both:
- A mechanism to signal termination of goroutines (achieved via the Context method)
- A mechanism for the testing framework to wait until all goroutines to finish (achieved via a WaitGroup method)
Or
- We should not add anything at all.
What are people's thoughts?
JT