alecxe alecxe - 6 months ago 46
Python Question

addCleanUp vs tearDown

Recently, Ned Batchelder during his talk at PyCon 2016 noted:


If you are using
unittest
to write your tests, definitely use
addCleanup
, it's much better than
tearDown
.


Up until now, I've never used
addCleanUp()
and got used to
setUp()
/
tearDown()
pair of methods for test "set up" and "tear down" phases.

Why should I switch to
addCleanUp()
instead of
tearDown()
?

Answer

Per the addCleanup doc string:

Cleanup items are called even if setUp fails (unlike tearDown)

addCleanup can be used to register multiple functions, so you could use separate functions for each resource you wish to clean up. That would allow your code to be a bit more reusable/modular.

Comments