Recently, Ned Batchelder during his talk at PyCon 2016 noted:
If you are using
unittest
to write your tests, definitely useaddCleanup
, it's much better thantearDown
.
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()
?
It was also recently discussed in the Python unittest with Robert Collins podcast.
When a setUp() method is defined, the test runner will run that method prior to each test. Likewise, if a tearDown() method is defined, the test runner will invoke that method after each test.
The command to run the tests is python -m unittest filename.py . In our case, the command to run the tests is python -m unittest test_utils.py .
A unit test is a test that checks a single component of code, usually modularized as a function, and ensures that it performs as expected. Unit tests are an important part of regression testing to ensure that the code still functions as expected after making changes to the code and helps ensure code stability.
Create a class called TestSum that inherits from the TestCase class. Convert the test functions into methods by adding self as the first argument. Change the assertions to use the self. assertEqual() method on the TestCase class.
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.
addCleanup()
methods will run even if one of them fails, and will run even if setUp()
fails. You should also consider using pytest.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With