I am getting TransactionManagementError when trying to save a Django User model instance and in its post_save signal, I\'m saving some models that have the user as the forei
Here is another way to do it, based on the answer to this question:
with transaction.atomic():
self.assertRaises(IntegrityError, models.Question.objects.create, **{'domain':self.domain, 'slug':'barks'})
I have the same issue, but with transaction.atomic()
and TransactionTestCase
didn't work for me.
python manage.py test -r
instead of python manage.py test
is ok for me, maybe the order of execution is crucial
then i find a doc about Order in which tests are executed, It mentions which test will run first.
So, i use TestCase for database interaction, unittest.TestCase
for other simple test, it works now!
def test_wrong_user_country_db_constraint(self):
"""
Check whether or not DB constraint doesnt allow to save wrong country code in DB.
"""
self.test_user_data['user_country'] = 'XX'
expected_constraint_name = "country_code_within_list_of_countries_check"
with transaction.atomic():
with self.assertRaisesRegex(IntegrityError, expected_constraint_name) as cm:
get_user_model().objects.create_user(**self.test_user_data)
self.assertFalse(
get_user_model().objects.filter(email=self.test_user_data['email']).exists()
)
with transaction.atomic() seems do the job correct
For me, the proposed fixes did not work. In my tests, I open some subprocesses with Popen
to analyze/lint migrations (e.g. one test checks if there are no model changes).
For me, subclassing from SimpleTestCase
instead of TestCase
did do the trick.
Note that SimpleTestCase
doesn't allow to use the database.
While this does not answer the original question, I hope this helps some people anyway.
Since @mkoistinen never made his comment, an answer, I'll post his suggestion so people won't have to dig through comments.
consider just declaring your test class as a TransactionTestCase rather than just TestCase.
From the Django docs: A TransactionTestCase may call commit and rollback and observe the effects of these calls on the database.