The reason you’re seeing this is that:
- For performance reasons,
TestCasetests run inside a transaction.
- The raising of an
IntegrityErrorwill spoil the current transaction (more precisely, the current atomic block), regardless of whether or not it is caught.
So, in your code, the first
assertRaises works correctly, but because an
IntegrityError was raised the transaction becomes spoiled. When you try to access the database with the next
create() you get the
TransactionManagementError. See this ticket for more information.
There are two possible solutions:
- Inherit from
TestCase. This uses table truncation instead of transactions to reset the databse, so you won’t have this problem.
- Run each of your
create()tests inside a new atomic block. You can see an example in the ticket, and a broader description in the docs.