使用请求库的Django Rest Framework测试功能

时间:2018-12-12 11:33:54

标签: django testing django-rest-framework

如何在Django项目中测试以下功能?

@api_view(['GET'])
def get_films(request):
    if request.method == "GET":
        r = requests.get('https://swapi.co/api/films')
        if r.status_code == 200:
            data = r.json()
            return Response(data, status=status.HTTP_200_OK)
        else:
            return Response({"error": "Request failed"}, status=r.status_code)
    else:
        return Response({"error": "Method not allowed"}, status=status.HTTP_400_BAD_REQUEST)

1 个答案:

答案 0 :(得分:0)

您需要模拟请求。

from unittest.mock import Mock, patch
from rest_framework.test import APITestCase

class YourTests(APITestCase):

    def test_get_films_success(self):
        with patch('*location of your get_films_file*.requests') as mock_requests:
            mock_requests.post.return_value = mock_response = Mock()
            mock_response.status_code = 200
            mock_response.json.return_value = {'message': "Your expected response"}
            response = self.client.get(f'{your_url_for_get_films_view}')
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            self.assertEqual(response.data, {'message': f'{expected_response}'})

使用类似的方法,您可以测试所有条件的错误方法或404响应。