lunarmodules / busted

Elegant Lua unit testing.
https://lunarmodules.github.io/busted/
MIT License
1.38k stars 184 forks source link

[feature request] Support clean up function for it() #722

Closed StarlightIbuki closed 1 year ago

StarlightIbuki commented 1 year ago

For some tests, we need to clean up, which means even if the test fails some callbacks need to be called. We can achieve that with an after_each() in a describe() block like:

describe("test", function()
  local mocking
  after_each(function()
    if mocking then kill_thread(mocking) end
  end)
  it("test", function()
    mocking = create_thread(...)
    -- ...
  end)
end)

but it would be much more straightforward if we support:

it("test", function()
  local mocking = create_thread(...)
  clean_up(function() kill_thread(mocking) end)
  -- ...
end)
alerque commented 1 year ago

It seems like this would create a new problem: in order for this to work one has to assume the test fails in an assert or other protected call, not by throwing an error in the body of the test. Part of what it() does is insulate the stuff running in it from being able to kill the test runner. In your example case the cleanup function would be at risk of not getting run in the event of a test error. That doesn't seem like a good design and I don't understand why after_each() is not suitable. That's exactly the kind of thing it is documented to handle.

Tieske commented 1 year ago

try finally;

it("test", function()
  local mocking = create_thread(...)
  finally(function() kill_thread(mocking) end)
  -- ...
end)
Tieske commented 1 year ago

haven't tried what happens in case of an error as @alerque mentioned...

Tieske commented 1 year ago

did a quick test; and the finally callback is called in case of success, failure, and error.