Privacy Policy
Snippets index

  Catch exception in unittest with assertRaises

Assert raises only accepts a callable. It evalutes to see if the callable raises an exception, not if the statement itself does. To use on arbitrary blocks of code in the middle of a test, rather than having to create a new function just to define the block of code to which it applies, use a lambda:

from django.db import IntegrityError

self.assertRaises(IntegrityError, lambda: self._create_new_order(progressivo=10))

or use a a context manager to further inspect the exception:

from django.db import IntegrityError

with self.assertRaises(IntegrityError) as raise_context:
    self._create_new_order(progressivo=10)
self.assertTrue('UNIQUE constraint failed' in raise_context.exception.message)

Note

if you receive a:

TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.

exception when you further access the database in the same unittest, either:

  • Inherit from TransactionTestCase instead of TestCase, or
  • Run each of your create() tests inside a new atomic block