【发布时间】: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