我需要对Django REST框架mixin进行单元测试。所以我去做一个测试,看起来像这样:
class TestMyMixin(APITestCase):
class DummyView(MyMixin,
viewsets.ModelViewSet):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
#some properties omitted
def setUp(self):
self.view = self.DummyView.as_view(\
actions={'get':'list'})
def test_basic_query(self):
instance = MyModel.objects.create(\
**{'name':'alex'})
request = APIRequestFactory().get(\
'/fake-path?query=ale',
content_type='application/json')
response = self.view(request)
self.assertEqual(\
response.status_code,status.HTTP_200_OK)
json_dict = json.loads(\
response.content.decode('utf-8'))
self.assertEqual(json_dict['name'],instance.name)
但是,当我运行此测试时,我确实得到:
^{pr2}$django REST框架似乎对单元测试viewsets
、mixins
和{
但我不知道该怎么办。
官方文档页面建议使用真实的url,但它更适合于验收测试而不是单元测试。在
出现此问题是因为视图的响应没有得到呈现,因此
_is_rendered
是False
,并引发了ContentNotRenderedError
异常。在您可以在django.template.response源代码中看到发生这种情况的原因和方式。在
您可以通过在响应中手动调用
.render()
来解决该问题:相关问题 更多 >
编程相关推荐