When writing a test using the unittest module, you may write a fixture to prepare for the test. Although tearDown receives and handles exceptions in the test function. Exceptions during setUp will be bypassed. Use doCleanups for setUps that can fail.
When writing a test using the unittest module, you may write a fixture to prepare for the test. For example, setUp / tearDown corresponds to that.
Write as follows.
class Tests(unittest.TestCase):
def setUp(self):
print("setUp")
def tearDown(self):
print("tearDown")
def test_it(self):
print("before execute")
_callFUT()
print("after execute")
At this time, it is executed in the following order.
tearDown is also called when an exception occurs in the test function in 2.
class Tests2(unittest.TestCase):
def setUp(self):
print("setUp")
def tearDown(self):
print("tearDown")
def doCleanups(self):
print("cleanup")
def test_it(self):
print("before execute")
raise Exception
print("after execute")
The execution order is the same.
Of course, the code written in setUp of test is also python code, so there are some that may raise exceptions. In such a case, it is dangerous to think that tearDown guarantees the cleanup after execution. In fact, tearDown is unaware of the exceptions in setUp.
class Tests3(unittest.TestCase):
def setUp(self):
print("setUp")
raise Exception("setup")
def tearDown(self):
print("tearDown")
def test_it(self):
print("before execute")
raise Exception("execute")
print("after execute")
Only the following are called
tearDown is not called. At this time, if you want to add some post-processing, use doCleanups. doCleanups is called unconditionally regardless of exceptions at setUp and tearDown.
class Tests4(unittest.TestCase):
def setUp(self):
print("setUp")
raise Exception("setup")
def tearDown(self):
print("tearDown")
def doCleanups(self):
print("cleanup")
def test_it(self):
print("before execute")
print("after execute")
The execution order in this case is
Will be.
Recommended Posts