Reputation: 64739
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
Reputation: 48952
Use TransactionTestCase
:
TransactionTestCase
andTestCase
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: ATransactionTestCase
resets the database after the test runs by truncating all tables. ATransactionTestCase
may call commit and rollback and observe the effects of these calls on the database.
Upvotes: 1