Cerin
Cerin

Reputation: 64739

Testing manual transactions inside Django unittests

How do you test code that disables autocommit and uses savepoints, inside a Django unittest?

The default Django unittest class wraps all tests inside an @atomic decorator, which is usually exactly what you want, to ensure the sqlite database gets reset between tests. However, any code that touches transaction.set_autocommit() from a test throws the error:

TransactionManagementError: This is forbidden when an 'atomic' block is active.

even if it works fine outside the unittest.

How do you temporarily disable the transaction autocommit in a unittest, so you can test manual commits?

Upvotes: 3

Views: 3196

Answers (1)

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 48952

Use TransactionTestCase:

TransactionTestCase and TestCase are identical except for the manner in which the database is reset to a known state and the ability for test code to test the effects of commit and rollback: A TransactionTestCase resets the database after the test runs by truncating all tables. A TransactionTestCase may call commit and rollback and observe the effects of these calls on the database.

Upvotes: 1

Related Questions