python - Django 测试 : TransactionManagementError: You can't execute queries until the end of the 'atomic' block

标签 python django unit-testing

这里是 Django 新手。我正在尝试为我开发的一个简单 API 实现单元测试。您可以在下面找到我的测试实现,它运行良好:

from django.test import TestCase
from my_app.models import MyModel


class TestMyViewSet(TestCase):
    """
    Unit tests for endpoints in MyViewSet.
    """
    fixtures = ['my_app/fixtures/data.yaml']

    def setUp(self):
        # Making setup for the test case here.


    def test_post_my_resource(self):

        # Checking that fixture is loaded correctly.
        self.assertEqual(MyModel.objects.all().count(),1)

        request_body = {
            'my_resource': "input_for_my_resource"
        }

        response = self.client.post('/my_resources/', data=request_body)
        self.assertEqual(response.status_code, 201)
        # self.assertEqual(MyModel.objects.all().count(),2)

但是当我从评论中删除最后一行 self.assertEqual(MyModel.objects.all().count(),2) 以测试 my_resource 是通过检查实例数在相应的模型上成功创建,我得到一个错误说明如下:

TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.

我在这里错过了什么?

提前致谢!

PS:我遇到了以下问题:TransactionManagementError “You can't execute queries until the end of the 'atomic' block” while using signals, but only during Unit Testing但我不确定我的情况是否相同。

最佳答案

显然,从 django.test.TestCase 移动到 django.test.TransactionTestCase 解决了这个问题。以下是关于 django.test.TestCasedjango.test.TransactionTestCase 之间差异的一些要点:

TransactionTestCase and TestCase are identical except for the manner in which the database is reset to a known state and the ability for test code to test the effects of commit and rollback:

  • TransactionTestCase resets the database after the test runs by truncating all tables. A TransactionTestCase may call commit and rollback and observe the effects of these calls on the database.

  • A TestCase, on the other hand, does not truncate tables after a test. Instead, it encloses the test code in a database transaction that is rolled back at the end of the test. This guarantees that the rollback at the end of the test restores the database to its initial state.

在这里您可以从文档中找到更多详细信息 TransactionTestCase

关于python - Django 测试 : TransactionManagementError: You can't execute queries until the end of the 'atomic' block,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43978468/

相关文章:

django - 如何在模板中设置重定向 url?

python - 机器学习 - 图像特征设计

Python tweepy : find users who favorited you tweet given tweet ID

python - 在 Numpy/PyTorch 中快速查找值大于阈值的索引

python - Django REST 框架验证错误 : 'Enter a valid URL.'

python - Django with MySQL : DatabaseError (1406, "Data too long for column ' name' at row 1")

c# - 如何围绕私有(private)方法编写单元测试

javascript - Jasmine 期待(结果代码)。toBe(200 或 409)

c# - 如何为 Mediatr INotificationHandler 的单元测试提供最小起订量通知

python - 检索当前模型之外的 Django ManyToMany 结果