Testing multiple IntegrityErrors in the same Django unittest test case

I am trying to run the following Django unittest:

class MyModelTests(TestCase): def test_failed_duplicate(self): m = MyModel.objects.create(a='a', b='a') with self.assertRaises(IntegrityError): MyModel.objects.create(a='a', b='b') with self.assertRaises(IntegrityError): MyModel.objects.create(a='a', b='c') with self.assertRaises(IntegrityError): MyModel.objects.create(a='a', b='d') 

There are several tests that should fail due to a violation of the uniqueness constraint in field a . (I am a bit confused about the statements, but they all test different values โ€‹โ€‹of a , which should fail.)

However, at startup, I get:

 Traceback (most recent call last): File "...", line 21, in test_failed_duplicate MyModel.objects.create(a='a', b='c') TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. 

What am I missing?

+6
source share
1 answer

(Ah, yes, I stumbled upon this a while ago and handed in a ticket about it. Perhaps an interesting discussion may be interesting.)

The reason you see this is as follows:

  • For performance reasons, TestCase tests run inside a transaction.
  • Raising an IntegrityError will ruin the current transaction (more precisely, the current atomic block), regardless of whether it is caught or not.

So, in your code, the first assertRaises works correctly, but since IntegrityError was raised, the transaction becomes corrupted. When you try to access the database with the following create() , you will get a TransactionManagementError .

There are two possible solutions:

  • Inherit from TransactionTestCase instead of TestCase . This uses table truncation instead of transactions to reset the database, so you won't have this problem.
  • Run each of your create() tests inside a new atomic block. You can see an example on the ticket and a more detailed description in the documents .
+16
source

Source: https://habr.com/ru/post/971806/


All Articles