Django-rest框架单元测试视图集mixin

2024-10-01 22:39:08 发布

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

我需要对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框架似乎对单元测试viewsetsmixins和{}有一些不同的方法。
但我不知道该怎么办。
官方文档页面建议使用真实的url,但它更适合于验收测试而不是单元测试。在


Tags: nameself框架viewrestjsongetobjects
1条回答
网友
1楼 · 发布于 2024-10-01 22:39:08

出现此问题是因为视图的响应没有得到呈现,因此_is_renderedFalse,并引发了ContentNotRenderedError异常。在

您可以在django.template.response源代码中看到发生这种情况的原因和方式。在

您可以通过在响应中手动调用.render()来解决该问题:

response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_200_OK)

# Render the response manually
response.render()
json_dict = json.loads(response.content.decode('utf-8'))
self.assertEqual(json_dict['name'],instance.name)

相关问题 更多 >

    热门问题