【问题标题】:Django test: TransactionManagementError: You can't execute queries until the end of the 'atomic' blockDjango 测试:TransactionManagementError:直到“原子”块结束才能执行查询
【发布时间】:2017-10-14 04:16:35
【问题描述】:

这里是 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:当前事务发生错误。在“原子”块结束之前,您无法执行查询。

我在这里缺少什么?

提前致谢!

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

【问题讨论】:

    标签: python django unit-testing


    【解决方案1】:

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

    TransactionTestCaseTestCase 是相同的,除了将数据库重置为已知状态的方式以及测试代码测试提交和回滚效果的能力:

    • TransactionTestCase 在测试运行后通过截断所有表来重置数据库。 TransactionTestCase 可以调用 commit 和 rollback 并观察这些调用对数据库的影响。

    • 另一方面,TestCase 在测试后不会截断表。相反,它将测试代码包含在一个在测试结束时回滚的数据库事务中。这保证了测试结束时的回滚将数据库恢复到其初始状态。

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

    【讨论】:

    • 你也可以通过从django.db导入事务来使用transaction.atomic
    猜你喜欢
    • 2014-02-22
    • 2015-11-19
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多