3

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?

2
  • I am not entirely sure this works in tests, but try adding a @transaction.commit_on_success decorator to the test function Commented Jul 4, 2018 at 1:37
  • 1
    @SimasJoneliunas That decorator was removed several versions ago and is not available to me. Commented Jul 4, 2018 at 1:46

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.