Skip to content

testing: allow tests to control main execution #8202

@rsc

Description

@rsc
A few things have come up recently that could be solved by giving tests a bit more
control over func main.

Suppose we define a type testing.Main analogous to testing.T or testing.PB - it's there
just to have methods to call - with one method Run() (exitcode int). Then the default
test main.main would refactor to:

func main() {
    // various registration
    // create m
    os.Exit(m.Run())
}

But if a test package contains a func TestMain(m *testing.Main), then the main.main
becomes:

func main() {
    // various registration
    // create m
    pkg.TestMain(m.Run())
}

The minimal TestMain is

func TestMain(m *testing.Main) { os.Exit(m.Run()) }

but giving people the ability to write this solves a few problems that have been asked
for.

issue #7905: need to run graphics on main thread

func TestMain(m *testing.Main) {
    go func() {
        os.Exit(m.Run())
    }()
    runGraphics()
}

issue #8159: testing setup/shutdown hook:

func TestMain(m *testing.Main) {
    setup()
    exitCode := m.Run()
    shutdown()
    os.Exit(exitCode)
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions