Init
function, main
function for the test.flag.Parse
during package
Calling flag.Parse in an init function never worked reliably, unless
you took special care. Flags are themselves often defined in init
functions, so calling flag.Parse in an init function will see the
flags that were defined before the point of the call but not the flags
defined after the point of the call. I guess it was working for you,
but small changes in your code could have caused it to stop working.
We didn't document that calling flags.Parse in an init function didn't
work reliably because we didn't realize that anybody would ever do it.
The documentation always just said "After all flags are defined, call
flag.Parse", and "Must be called after all flags are defined and
before flags are accessed by the program" without spelling out that if
you call it in an init function you won't necessarily be calling it
after all flags are defined.
The change to the testing package changed exactly when the testing
flags are defined with respect to init functions, and it caused many
cases of calling flag.Parse from an init function to break. But those
cases were already fragile and could have been broken in other ways
also.
If you don't call flag.Parse from an init function you will be
following the documentation, and that will continue to work.
Sorry for the trouble.
func init() {
flag.Parse()
}
TestXYZ(t *testing.T) {}
with
func TestMain(m *testing.M) {
flag.Parse()
os.Exit(m.Run())
}
TestXYZ(t *testing.T) {}
I searched further and saw that the documentation for TestMain at https://golang.org/pkg/testing/#hdr-Main
explicitly mentions that calling flag.Parse() should be done in TestMain. So I think that is a fair place to
document this.
I guess I was unlucky enough to inherit a codebase where calling flag.Parse() inside init() "just worked" before. :(
--
Craig