Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rule for detecting useless os.Exit in TestMain #1189

Open
alexandear opened this issue Dec 12, 2024 · 2 comments
Open

Rule for detecting useless os.Exit in TestMain #1189

alexandear opened this issue Dec 12, 2024 · 2 comments
Labels
good first issue rule proposal Issue proposing a new rule

Comments

@alexandear
Copy link
Contributor

alexandear commented Dec 12, 2024

Is your feature request related to a problem? Please describe.

Implement a rule that suggests removing os.Exit in TestMain for test files.

Before:

// simple case
func TestMain(m *testing.M) {
	os.Exit(m.Run())
}

// real case
func TestMain(m *testing.M) {
	code = m.Run()
	cleanup()
	os.Exit(code)
}

After:

// simple case
func TestMain(m *testing.M) {
	m.Run()
}

// real case
func TestMain(m *testing.M) {
	defer cleanup()
	m.Run()
}

Describe the solution you'd like

A new rule redundant-test-main-os-exit that suggests removing os.Exit.

Describe alternatives you've considered

Search for os.Exit manually and refactor TestMain functions.

Additional context

As of Go 1.15, we do not need to call os.Exit(m.Run()) explicitly, as value returned by m.Run() is stored into unexported field of m and go test executable is smart enough to automatically call os.Exit(retValue) when TestMain returns. See golang/go#34129 and https://pkg.go.dev/testing#hdr-Main

These PRs performs removing os.Exit from TestMain in a wild:

@alexandear
Copy link
Contributor Author

Connected issues: #290

@ccoVeille
Copy link
Contributor

As of Go 1.15, we do not need to call os.Exit(m.Run()) explicitly, as value returned by m.Run() is stored into unexported field of m and go test executable is smart enough to automatically call os.Exit(retValue) when TestMain returns.

TIL

@chavacava chavacava added rule proposal Issue proposing a new rule good first issue labels Dec 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
good first issue rule proposal Issue proposing a new rule
Projects
None yet
Development

No branches or pull requests

3 participants