Skip to content

testing: clarify when TestMain is appropriate and not #44200

Open
@matttproud

Description

@matttproud

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:

  1. More individuals are familiar with func init semantics, so that speaks in favor of func 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.
  2. 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 against func init above.
  3. From a code health standpoint, central setup in func init or func 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:

  1. what is the preferred way to handle errors in TestMain? panic, os.Exit(1), log.Fatal?
  2. where should text output be written: stdout or stderr?

Before stating that the answers to the above is obvious, it may be obvious to a seasoned practitioner but not a newcomer.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DocumentationIssues describing a change to documentation.NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions