How to fail a python unittest if the setUpClass throws exception

前端 未结 4 2102
我在风中等你
我在风中等你 2021-02-13 21:49

I am having little trouble using the python setUpClass.

For example consider the following case

class MyTest(unittest.case.TestCase):

    @classmethod
          


        
相关标签:
4条回答
  • 2021-02-13 22:34

    use tearDownModule. It should be called after setUpClass runs.

    0 讨论(0)
  • 2021-02-13 22:40

    You can call tearDownClass on an exception as Jeff points it out, but you may also implements the __del__(cls) method :

    import unittest
    
    class MyTest(unittest.case.TestCase):
    
        @classmethod
        def setUpClass(cls):
            print "Test setup"
            try:
                1/0
            except:
                raise
    
        @classmethod
        def __del__(cls):
            print "Test teardown"
    
        def test_hello(cls):
            print "Hello"
    
    if __name__ == '__main__':
        unittest.main()
    

    Will have the following output :

    Test setup
    E
    ======================================================================
    ERROR: setUpClass (__main__.MyTest)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "my_test.py", line 8, in setUpClass
        1/0
    ZeroDivisionError: integer division or modulo by zero
    
    ----------------------------------------------------------------------
    Ran 0 tests in 0.000s
    
    FAILED (errors=1)
    Test teardown
    

    Note : you should be aware that the __del__ method will be called at the end of the program execution, which is maybe not what you want if you have a more than one test class.

    Hope it helps

    0 讨论(0)
  • 2021-02-13 22:41
    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()
    
    0 讨论(0)
  • 2021-02-13 22:56

    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
    
    0 讨论(0)
提交回复
热议问题