Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()?


It was also recently discussed in the Python unittest with Robert Collins podcast.

like image 621
alecxe Avatar asked May 30 '16 21:05

alecxe


People also ask

What is tearDown in unit testing?

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.

How do I run a unit test in Python?

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 .

What are unit tests in Python?

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.

How do you write a test case in python?

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.


2 Answers

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.

like image 144
unutbu Avatar answered Sep 22 '22 15:09

unutbu


addCleanup() methods will run even if one of them fails, and will run even if setUp() fails. You should also consider using pytest.

like image 25
Raphaël Gomès Avatar answered Sep 22 '22 15:09

Raphaël Gomès