TransactionManagementError “You can't execute queries until the end of the 'atomic' block” while using signals, but only during Unit Testing

后端 未结 11 2032
有刺的猬
有刺的猬 2020-12-02 06:03

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

相关标签:
11条回答
  • 2020-12-02 06:37

    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'})
    
    0 讨论(0)
  • 2020-12-02 06:37

    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!

    0 讨论(0)
  • 2020-12-02 06:41
    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
    
    0 讨论(0)
  • 2020-12-02 06:43

    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.

    0 讨论(0)
  • 2020-12-02 06:44

    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.

    0 讨论(0)
提交回复
热议问题