Django 1.6 test cases for code which calls transaction.set_autocommit()

262 views
Skip to first unread message

Justin Michalicek

unread,
Mar 6, 2014, 5:11:59 PM3/6/14
to django...@googlegroups.com
It appears that due to test cases running in an atomic block, testing methods which use transaction.set_autocommit() all fail.  I've got a small handful of test cases around methods which need to use manual transaction management and they are definitely working when I actually use the site, but in test cases they all fail and raise the exception "TransactionManagementError: This is forbidden when an 'atomic' block is active." at the line where I call transaction.set_autocommit(False)

Is there something I'm missing here?

Anssi Kääriäinen

unread,
Mar 7, 2014, 2:58:29 AM3/7/14
to django...@googlegroups.com
On Friday, March 7, 2014 12:11:59 AM UTC+2, Justin Michalicek wrote:
It appears that due to test cases running in an atomic block, testing methods which use transaction.set_autocommit() all fail.  I've got a small handful of test cases around methods which need to use manual transaction management and they are definitely working when I actually use the site, but in test cases they all fail and raise the exception "TransactionManagementError: This is forbidden when an 'atomic' block is active." at the line where I call transaction.set_autocommit(False)

Is there something I'm missing here?

Django's default TestCase runs the whole test inside a transaction, thus code trying to manage transactions fail. The reason for this is that if the tests are ran inside transactions, there is no need to clean up the database after the test, as doing rollback at the end of the test will guarantee clean state. If you need to test transactional code, use TransactionTestCase.

 - Anssi

Justin Michalicek

unread,
Mar 7, 2014, 7:33:25 AM3/7/14
to django...@googlegroups.com

Ah hah, thanks.  I knew there had to be something I'd overlooked here.  In previous versions of Django you could test code which used transaction.commit_manually() in a regular TestCase, although I am now questioning whether it tested it properly or not.  The fact that this would no longer work was not made clear by the Django 1.6 release notes and info specifically covering backwards-incompatible changes.
 
Reply all
Reply to author
Forward
0 new messages