Description
We had an open discussion in a longer design review thread about when user-authored custom TestMain
(debuted in release 1.4) entrypoints are necessary or not compared to func init
. We were able to offer at best fuzzy criteria for this. It would be beneficial for the newcomer's perspective if some basic litmus tests, advice, or criteria were provided. I have no opinion on where but rather that they are central and findable.
I don't want to bike shed the reasoning, but I will enumerate some of the tradeoffs I heard:
- More individuals are familiar with
func init
semantics, so that speaks in favor offunc init
for setup. One counterpoint is that a setup routine that requires all package initializers to have been run by the time it is executed could become flaky or error-prone. - Not all tests strictly need what is commonly setup, making the test setup process more expensive than it needs to be (e.g., when a test execution filter
-test.run=pattern
is used). This also speaks againstfunc init
above. - From a code health standpoint, central setup in
func init
orfunc TestMain
, could imply mutated global state. Unless the tests use whatever is setup in a hermetic way individually, it could accidentally encode test ordering assumptions between test functions. Might be better to encourage tests to locally set up what they need versus not and to enforce cleanup, especially now that we have(*testing.T).Cleanup
.
One final ancillary point I heard in an earlier discussion related to user-authored TestMain
that a documentation treatment should also cover:
- what is the preferred way to handle errors in
TestMain
?panic
,os.Exit(1)
,log.Fatal
? - where should text output be written:
stdout
orstderr
?
Before stating that the answers to the above is obvious, it may be obvious to a seasoned practitioner but not a newcomer.