Say I have the following Python UnitTest:
import unittest
def Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Get some resources
...
if error_occurred:
assert(False)
@classmethod
def tearDownClass(cls):
# release resources
...
If the setUpClass call fails, the tearDownClass is not called so the resources are never released. This is a problem during a test run if the resources are required by the next test.
Is there a way to do a clean up when the setUpClass call fails?
you can put a try catch in the setUpClass method and call directly the tearDown in the except.
def setUpClass(cls):
try:
# setUpClassInner()
except Exception, e:
cls.tearDownClass()
raise # to still mark the test as failed.
Requiring external resources to run your unittest is bad practice. If those resources are not available and you need to test part of your code for a strange bug you will not be able to quickly run it. Try to differentiate Integration tests from Unit Tests.
The same way you protect resources elsewhere. try-except
:
def setUpClass(cls):
# ... acquire resources
try:
# ... some call that may fail
except SomeError, e:
# cleanup here
Cleanup could be as simple as calling cls.tearDownClass()
in your except
block. Then you can call assert(False)
or whatever method you prefer to exit the test early.
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