Skip to content

testing: Deferred functions run before parallel subtests are executed #17791

@adamwg

Description

@adamwg

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)?

GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/awg/code/golang"
GORACE=""
GOROOT="/usr/local/Cellar/go/1.7.3/libexec"
GOTOOLDIR="/usr/local/Cellar/go/1.7.3/libexec/pkg/tool/darwin_amd64"
CC="clang"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/py/0t98br4x7ys6byx0d284gcn80000gn/T/go-build516232238=/tmp/go-build -gno-record-gcc-switches -fno-common"
CXX="clang++"
CGO_ENABLED="1"

What did you do?

Ran the following test:

package testbug

import "testing"

func TestBug(t *testing.T) {
	asdf := 1337
	defer func() {
		asdf = 7331
	}()

	t.Run("asdf", func(t *testing.T) {
		t.Parallel()
		if asdf != 1337 {
			t.Fatalf("wanted 1337, got %d\n", asdf)
		}
	})
}

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 after t.Run returns.

What did you see instead?

The test fails:

% go test -v .
=== RUN   TestBug
=== RUN   TestBug/asdf
--- FAIL: TestBug (0.00s)
    --- FAIL: TestBug/asdf (0.00s)
        foo_test.go:14: wanted 1337, got 7331
FAIL
exit status 1
FAIL    github.com/adamwg/testbug       0.007s

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsFixThe path to resolution is known, but the work has not been done.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions