1.2 KiB
title | date | tags | ||
---|---|---|---|---|
Conditional Cleanups in Pytest | 2024-04-28T16:55:37-07:00 |
|
A helpful pattern in testing is to take some cleanup action only if the test passes/fails. For instance, for a test which interacts with an on-filesystem database, the database should be deleted if the test passes, but it should stick around if the test fails so that the developer can examine it and debug.
In JUnit, this is possible via a @Rule
, but as far as I can tell there's no pre-built equivalent in Python's pytest
. I did find this StackOverflow answer describing an approach using the pytest_runtest_makereport
hook, though the syntax appears to have changed since that answer. I put together an example implementation here, which also adds the ability for fixtures and tests to add "cleanup" actions to a stack, which will be executed in reverse order.