-
Notifications
You must be signed in to change notification settings - Fork 17.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
testing: Deferred functions run before parallel subtests are executed #17791
Comments
Interesting test. Not sure it's a bug however. Depends on the definition of Parallel function and what sort of contract or agreement it has with the compiler. |
Note that this issue isn't actually limited to deferred functions. Any code after the parallel subtests runs before they do: package testbug
import "testing"
func TestBug(t *testing.T) {
asdf := 1337
t.Run("asdf", func(t *testing.T) {
t.Parallel()
if asdf != 1337 {
t.Fatalf("wanted 1337, got %d\n", asdf)
}
})
asdf = 7331
} % go test -v .
=== RUN TestBug
=== RUN TestBug/asdf
--- FAIL: TestBug (0.00s)
--- FAIL: TestBug/asdf (0.00s)
foo_test.go:11: wanted 1337, got 7331
FAIL
exit status 1
FAIL github.com/adamwg/testbug 0.007s |
The following works: package testbug
import "testing"
func TestBug(t *testing.T) {
asdf := 1337
defer func() {
asdf = 7331
}()
t.Run("group", func(t *testing.T) {
t.Run("asdf", func(t *testing.T) {
t.Parallel()
if asdf != 1337 {
t.Fatalf("wanted 1337, got %d\n", asdf)
}
})
})
}
(Adapted from the example in "Cleaning up after a group of parallel tests" in the blog.) |
@0xmohit Thanks, I can do that as a workaround. However, based on the documentation (https://golang.org/pkg/testing/#T.Run) it's not clear that's necessary. I'd suggest either this should be fixed, or the documentation should be updated to make it clear that a call to |
This is working correctly. The docs for t.Run say:
In this code:
t.Parallel is making the t.Run itself a parallel subtest of TestBug. There is no parallel subtest of the t.Run subtest. TestBug will not complete until the parallel test completes. But TestBug's body has to finish because that is what triggers running the parallel tests in the first place. In this code:
The group has one parallel subtest, asdf. Once the group's body returns, the parallel subtests are allowed to run in parallel (there's only one so that's not saying much), and once the parallel subtest finishes, t.Run("group"...) returns. |
What version of Go are you using (
go version
)?go version go1.7.3 darwin/amd64
What operating system and processor architecture are you using (
go env
)?What did you do?
Ran the following test:
What did you expect to see?
The test should pass, as according to the documentation
t.Run
should block until all parallel subtests are completed, and the deferred function should run only aftert.Run
returns.What did you see instead?
The test fails:
The text was updated successfully, but these errors were encountered: