How to fail a python unittest if the setUpClass throws exception

Viewed 5895

I am having little trouble using the python setUpClass.

For example consider the following case

class MyTest(unittest.case.TestCase):

    @classmethod
    def setUpClass(cls):
        print "Test setup"
        try:
            1/0
        except:
            raise

    @classmethod
    def tearDownClass(cls):
        print "Test teardown"

A couple of questions

  1. Is the above code the right way to handle test setUpClass exceptions (by raising it so that the python unittest can take care of it), there are fail(), skip() methods, but those can only be used by test instances and not the test classes.

  2. When there is a setUpClass exception, how can we ensure that tearDownClass runs (unittest doesn't run it, should we manualy call it).

4 Answers

The best option would be is to add handler for the except which calls tearDownClass and re-raise exception.

@classmethod
def setUpClass(cls):
    try:
        super(MyTest, cls).setUpClass()
        # setup routine...
    except Exception:  # pylint: disable = W0703
        super(MyTest, cls).tearDownClass()
        raise
import contextlib

class MyTestCase(unitest.TestCase):

    @classmethod
    def setUpClass(cls):
        with contextlib.ExitStack() as stack:
            # ensure teardown is called if error occurs
            stack.callback(cls.tearDownClass)

            # Do the things here!

            # remove callback at the end if no error found
            stack.pop_all()

use tearDownModule. It should be called after setUpClass runs.

Related