unittest’s addCleanup schedules a function to run at the end of a test, so it doesn’t work for a subTest that needs to clean up after itself, before another subtest runs.
Parametrizing tests using subTest
involves two levels of indentation; cleanup using try
/finally
would add another. Also, finally
won’t mark its contents as clean-up (i.e. use testPartExecutor
), unless it calls doCleanups
(which runs all of the tests cleanups and so doesn’t work well if there are multiple subTest
blocks, or code outside subTest).
It’s too late to change the scope of existing cleanups, but, would it make sense to add a addCleanup
method to the subTest
context, like this?
for param in 'a', 'b', 'c':
with self.subTest() as sub:
tempfile = make_tempfile()
sub.addCleanup(os.unlink, tempfile)
do_actual_test(tempfile, param)
If so, adding enterContext
and doCleanups
would also make sense.