cmd/go: move automatic testing.Init call into generated test code

In CL 173722, we moved the flag registration in the testing package into
an Init function. In order to avoid needing changes to user code, we
called Init automatically as part of testing.MainStart.

However, that isn't early enough if flag.Parse is called before the
tests run, as part of package initialization.

Fix this by injecting a bit of code to call testing.Init into test
packages. This runs before any other initialization code in the user's
test package, so testing.Init will be called before any user code can
call flag.Parse.

Fixes #31859

Change-Id: Ib42cd8d3819150c49a3cecf7eef2472319d0c7e9
Reviewed-on: https://go-review.googlesource.com/c/go/+/176098
Run-TryBot: Caleb Spare <cespare@gmail.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Bryan C. Mills <bcmills@google.com>
This commit is contained in:
Caleb Spare 2019-05-08 13:38:14 -07:00 committed by Bryan C. Mills
parent 5833aa507b
commit 49a1a01bb1
10 changed files with 163 additions and 44 deletions

View file

@ -1078,6 +1078,11 @@ type testDeps interface {
// It is not meant to be called directly and is not subject to the Go 1 compatibility document.
// It may change signature from release to release.
func MainStart(deps testDeps, tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) *M {
// In most cases, Init has already been called by the testinginit code
// that 'go test' injects into test packages.
// Call it again here to handle cases such as:
// - test packages that don't import "testing" (such as example-only packages)
// - direct use of MainStart (though that isn't well-supported)
Init()
return &M{
deps: deps,