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

consider WithFinalizer option (or similar) #133

Open
jon-whit opened this issue Nov 8, 2024 · 0 comments
Open

consider WithFinalizer option (or similar) #133

jon-whit opened this issue Nov 8, 2024 · 0 comments

Comments

@jon-whit
Copy link

jon-whit commented Nov 8, 2024

Consider a scenario where you have a package that is widely used across different packages (e.g. metrics or trace). This package provides a global provider (MetricProvider, TracerProvider) as a default global variable the package. You may have a lot of tests that don't explicitly close the MetricProvider and TracerProvider globals in those packages because if you did, then parallel execution of those tests could interfere with each other (they are globals after all).

It would be nice if we could provide a "finalizer" perse that is a function that is run prior to the goroutine stacktrace analysis but after the m.Run. Here's the intended usage pattern:

func TestMain(m *testing.M) {
  goleak.VerifyTestMain(m, goleak.WithFinalizer(func() {
    metrics.GetGlobalProvider().Shutdown()
    trace.GetGlobalProvider().Shutdown()
  }))
}

Here's what I'm thinking about changing in goleak/testmain.go:

func VerifyTestMain(m TestingM, options ...Option) {
	exitCode := m.Run()
	opts := buildOpts(options...)

        ....
	
	if finalizer != nil {
          finalizer()
        }

	if run {
		if err := Find(opts); err != nil {
			fmt.Fprintf(_osStderr, errorMsg, err)
			// rewrite exitCode if test passed and is set to 0.
			if exitCode == 0 {
				exitCode = 1
			}
		}
	}

This may seem a bit odd as it introduces a potential alternative to the existing ignoring functionality in goleak today and/or it sort of undermines the potential that there are goroutines leaked in each test unless the test itself is closing these things, but since they are a global singleton and in other consuming code the last step would otherwise be to close them, then I think it makes sense in terms of ergonomics of using goleak to be able to finalize the closure of them prior to the stack analysis.

Thoughts?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant