Home > Blockchain >  How to assertRaises in unittest an exception caught in try except block?
How to assertRaises in unittest an exception caught in try except block?

Time:11-30

In my production function:

def myfunction():
   try:
        do_stuff()
        (...)
        raise MyException("...")
    except MyException as exception:
         do_clean_up(exception)

My test fails, because the exception is caught in the try/except block

def test_raise(self):
   with self.assertRaises(MyException):
       myfunction()

self.assertRaises is never called.

How to guarantee that the exception is caught during testing?

The exception is never asserted AssertionError: MyException not raised

CodePudding user response:

This is because you caught the exception MyException direct in myFunction().

Comment out out the try-except clause and try again, test should pass.

assertRaises is used for uncaught errors. You can also re-raise in except block.

CodePudding user response:

The exception is handled internally, so there is no external evidence that the exception is raised.

However, both MyException and do_clean_up are external names, which means you can patch them and make assertions about whether they do or do not get used. For example,

# Make sure the names you are patching are correct
with unittest.mock.patch('MyException', wraps=MyException) as mock_exc, \
     unittest.mock.patch('do_clean_up', wraps=do_clean_up) as mock_cleanup:
    myfunction()
    if mock_exc.called:
        mock_cleanup.assert_called()
  • Related