В соответствии с документацией unittest doCleanups () - это метод, отвечающий за вызов всех методов очистки.
Один из способов - проверить результат теста в методе doCleanups. Если тест не пройден, всплыть все методы очистки и пропустить остальные тесты
Ниже приведен код:
import unittest
class SimpleTestCases(unittest.TestCase):
FAILURE = False
def setUp(self):
print "\nmessage from function: setUp"
if SimpleTestCases.FAILURE:
self.skipTest("Test is skipped due to first failure")
return super(SimpleTestCases, self).setUp()
self.createResource()
self.addCleanup(self.cleanResource)
def createResource(self):
msg = "\nmessage from function: createResource"
def cleanResource(self):
print "\nmessage from function: cleanResource"
def test_func1(self):
print "message from function: test_func1::start"
print "message from function: test_func1::end"
def test_func2(self):
print "message from function: test_func2::start"
self.assertTrue(False)
print "message from function: test_func2::end"
def test_func3(self):
print "message from function: test_func3::start"
print "message from function: test_func3:end"
def doCleanups(self):
print "message from function: doCleanups"
if SimpleTestCases.FAILURE:
return super(SimpleTestCases, self).doCleanups()
result = getattr(self, '_outcomeForDoCleanups', self._resultForDoCleanups)
ok_result = True
exc_list = getattr(result, 'failures')
if exc_list and exc_list[-1][0] is self:
ok_result = ok_result and not exc_list[-1][1]
if not ok_result:
SimpleTestCases.FAILURE = True
while self._cleanups:
(func, args, kwargs) = self._cleanups.pop()
return super(SimpleTestCases, self).doCleanups()
if __name__ == "__main__":
result = unittest.main()
Выполнить как
python -m unittest test_cases
И вывод:
message from function: setUp
message from function: test_func1::start
message from function: test_func1::end
message from function: doCleanups
message from function: cleanResource
.
message from function: setUp
message from function: test_func2::start
Fmessage from function: doCleanups
message from function: setUp
smessage from function: doCleanups
======================================================================
FAIL: test_func2 (test_cases.SimpleTestCases)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_cases.py", line 30, in test_func2
self.assertTrue(False)
AssertionError: False is not true
----------------------------------------------------------------------
Ran 3 tests in 0.000s
FAILED (failures=1, skipped=1)