gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:14:58 24 4
gpt4 key购买 nike

这里是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com