Django测试:TransactionManagementError:在"原子"块结束之前,您无法执行查询

hnr*_*oot 8 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)
Run Code Online (Sandbox Code Playgroud)

但是,当我通过检查实例数量self.assertEqual(MyModel.objects.all().count(),2)从注释中删除最后一行以测试my_resource在相应模型上成功创建时,我收到一条错误,说明以下内容:

TransactionManagementError:当前事务中发生错误.在"原子"块结束之前,您无法执行查询.

我在这里错过了什么?

提前致谢!

PS:我遇到了以下问题:TransactionManagementError"在使用信号时你不能在'原子'块结束之前执行查询",但仅在单元测试期间但我不确定在我的情况下发生的情况是相同的.

hnr*_*oot 11

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

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

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

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

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