Skip to content

Commit

Permalink
Refactor Defer and fix detection of 'missing Done' for Defer in Defer
Browse files Browse the repository at this point in the history
Refactor Defer to make clearer that running the defered function is
just delegated to Cleanup.
The 'Done called' hook is now installed in its own Cleanup.

Note that the panic about missing Done call will now also happen after
the run of the last deferred function. Also it will be correctly
installed multiple times for the weired case where Defer() is called
from a deferred function.
  • Loading branch information
dolmen committed Jun 10, 2023
1 parent e7bb3ab commit 3ecf279
Showing 1 changed file with 12 additions and 15 deletions.
27 changes: 12 additions & 15 deletions quicktest.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,22 +109,19 @@ func (c *C) Defer(f func()) {
// Use TB.Cleanup when available, but add a check
// that Done has been called so that we don't run
// into unexpected Go version incompatibilities.
if c.doneNeeded {
// We've already installed the wrapper func that checks for Done
// so we can avoid doing it again.
cleaner.Cleanup(f)
return
if !c.doneNeeded {
c.doneNeeded = true
cleaner.Cleanup(func() {
c.mu.Lock()
defer c.mu.Unlock()
if c.doneNeeded {
panic("Done not called after Defer")
}
})
}
c.doneNeeded = true
cleaner.Cleanup(func() {
c.mu.Lock()
doneNeeded := c.doneNeeded
c.mu.Unlock()
if doneNeeded {
panic("Done not called after Defer")
}
f()
})

cleaner.Cleanup(f)

return
}

Expand Down

0 comments on commit 3ecf279

Please sign in to comment.