On Monday, February 3, 2020 at 11:37:08 AM UTC-8, Ian Lance Taylor wrote: > > On Mon, Feb 3, 2020 at 8:13 AM Craig Rodrigues <crod...@gmail.com > <javascript:>> wrote: > > > > Regarding the fact that I should not call flag.Parse() from inside an > init() method in my_test.go file, > > if a note for this is not added to the documentation at > https://golang.org/pkg/flag/#Parse , > > how would an end user know about this? This detail is buried deep, and > the only way to > > understand this problem was to read the release notes for golang 1.13 > and to ask on this mailing list. > > The docs for flag.Parse already say "Must be called after all flags > are defined and before flags are accessed by the program." I think > that is precise and accurate. The testing package defines flags, so > you have to call flag.Parse after the testing package defines those > flags. When you call flag.Parse in an init function, you are making > an assumption about how the testing package defines the flags, an > assumption that happened to work before the 1.13 release and happened > to fail after the 1.13 release. > > I personally don't think it is appropriate to add docs for flag.Parse > that say "Note that the testing package defines flags after init > functions are run, so in a test don't call flag.Parse in an init > function." That makes the docs longer and somewhat harder to > understand for an unusual situation that I hope is already somewhat > clear. >
I did some more web searching and found that someone else ran across a similar issue: https://www.bountysource.com/issues/79987300-flag-provided-but-not-defined-test-timeout-go-1-13 where antoineco recommended replacing: 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 -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/0b64e4ff-1f8e-47d6-acae-421c71f62da7%40googlegroups.com.