-
Notifications
You must be signed in to change notification settings - Fork 18.4k
Description
#32111 added TB.Cleanup, which I find really useful. However, more often than not I actually have a func() error rather than a func() - and I want the cleanup to fail the test if a non-nil error appears.
Right now you can sort of get away with this by either ignoring the error, e.g. t.Cleanup(func() { returnsErr() }), or something similar which checks the error and calls t.Error if it's not nil.
t.Cleanup(func() {
if err := returnsErr(); err != nil {
t.Error(err)
}
})
I'm left wishing for t.CleanupErr taking func() error due to this being a relatively common scenario in my experience - then I could do e.g. t.CleanupErr(returnsErr), or t.CleanupErr(f.Close), or t.CleanupErr(cmd.Wait), or t.CleanupErr(proc.Kill), etc.
The API would call TB.Error instead of TB.Fatal if an error is returned, since we still want all cleanups to run even when some of them fail. If an early cleanup fails and makes others fail as well, getting more errors is better than skipping some cleanups and potentially not releasing/deleting resources.
In #32111 (comment), @egonelbre suggested that TB.Cleanup should have taken func() error from the start, and I disagreed with that, funnily enough :) I've changed my mind since then per the above. It's worth noting that I still think the func() form is useful - plenty of use cases don't return an error, such as t.Cleanup(cancel) or t.Cleanup(func() { global = nil }).
Worth noting that this should also make cases where parameters are involved simpler, even if a func literal would still be needed. For example,
t.Cleanup(func() {
if err := os.Chdir(orig); err != nil {
t.Error(err)
}
})
could become just t.CleanupErr(func() error { return os.Chdir(orig) }), avoiding the need for multiple lines.
I'm also reminded of the new sync.OnceX APIs too - OnceFunc takes func(), OnceValue takes func() T, OnceValues takes func() (T1, T2). I don't think generics make sense here, since the testing package can only do something reasonably useful with an error.
Metadata
Metadata
Assignees
Labels
Type
Projects
Status