-
Notifications
You must be signed in to change notification settings - Fork 159
Description
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?