Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you cleanup a Python UnitTest when setUpClass fails?

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?

like image 879
sickgemini Avatar asked Jul 09 '13 00:07

sickgemini


2 Answers

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.

like image 69
fabrizioM Avatar answered Nov 02 '22 23:11

fabrizioM


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.

like image 29
ACEfanatic02 Avatar answered Nov 02 '22 23:11

ACEfanatic02