Search code examples
djangoexceptionpython-3.7django-tests

How to test if exception was caught while running a django test


Suppose this is my code:

def fun():
   try:
      raise Exception("An exception")
   except Exception as e:
      logger.debug(f'{e}')

Now how can I write a test case which checks if that particular exception was caught? I could have tested by reading sys.stderr, but I'm using logger.debug. I'm using django TestCase


Solution

  • You can use assertLogs, but i suggest to add a "prefix" to your log, this way you can test that the right message was logged.

    Example:

    logger = logging.getLogger('foo')
    
    def fun():
       try:
          raise Exception("An exception")
       except Exception as e:
          logger.debug(f'[error-x]: {e}')
    

    Your test:

    with self.assertLogs('foo', level=logging.DEBUG) as cm:
        call_your_method()
    self.assertEqual(cm.output, ["DEBUG:foo:[error-x]: An exception"])
    

    If you have more log messages with your exception message you can do:

    self.assertIn("DEBUG:foo:[error-x]: An exception", cm.output)
    

    You can check the full example here