Feb 17, 2012

Test Django transaction using mocking and TransactionTestCase

It's pretty simple using mock side_effect:
class MyTransactionTestCase(TransactionTestCase):
    fixtures = ['some_fixture.json',]

    @patch.object(SomeObjectInsideTransaction, 'some_method')
    def test_disable_transaction(self, some_method):
        some_method.side_effect = IOError("Unexpected exception")

        try:
            self.client.get('/your/view/url/')
        except IOError:
            pass

        # assertions here
You have to use TransactionTestCase:
Django TestCase classes make use of database transaction facilities, if available, to speed up the process of resetting the database to a known state at the beginning of each test. A consequence of this, however, is that the effects of transaction commit and rollback cannot be tested by a Django TestCase class. If your test requires testing of such transactional behavior, you should use a Django TransactionTestCase.

No comments: