Django测试:TransactionManagementError:在“atomic”b结束之前不能执行查询

2024-04-19 01:42:36 发布

您现在位置:Python中文网/ 问答频道 /正文

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)以测试{}是否通过检查实例数在相应的模型上成功创建时,我得到了一个错误,说明了以下内容:

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

我错过了什么?在

提前谢谢!在

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


Tags: thefromtestimportselfappforobjects
1条回答
网友
1楼 · 发布于 2024-04-19 01:42:36

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

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中找到更多详细信息

相关问题 更多 >