Django rest framework unit test viewsets mixins

I need unit test Django REST framework mixin. so I go for a test that looks like this:

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)

However, when I run this test, I get:

raise ContentNotRenderedError('The response content must be 'django.template.response.ContentNotRenderedError: The response content must be rendered before it can be accessed.

It seems that the django REST framework would have a different approach to unit test viewsets, mixinsand views.
But I can’t figure out what to do instead.
The white papers page suggests using real URLs, but is more suitable for acceptance tests rather than unit tests.

+4
source share
1 answer

- , , _is_rendered is False 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)
+4

Source: https://habr.com/ru/post/1629167/


All Articles