【问题标题】:Django Rest Framework testing function that uses requests library使用请求库的 Django Rest Framework 测试功能
【发布时间】:2018-12-12 11:33:54
【问题描述】:

如何在 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)

【问题讨论】:

    标签: django testing django-rest-framework


    【解决方案1】:

    您需要模拟请求。

    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 响应。

    【讨论】:

    • 谢谢。当您说“get_films_file 的位置.requests”时……我在 views.py 中有我的功能。还有'your_url_for_get_films_view' ..你的意思是我为视图创建的端点吗?例如 /films 或调用外部 api?
    • location of get_films_file 是的,我的意思是像yourapp.views.requests 这样的视图位置,因为在调用它的文件中模拟requests 很重要。对于 url your_url_for_get_films_view,绝对是您发送获取请求以触发此视图工作的端点。
    • 对不起,我以前没有这样做过:你的意思是这样的吗:response = self.client.get(f'{'api/films/'}') 因为我收到语法错误。我的查看网址是url(r'films/$',views.get_films,name="get-films"),
    • 如果你需要打电话给example.com/api/films/,可以。你可以简单地self.client.get('api/films/')
    • 我得到一个 assertionError 404!=200
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    相关资源
    最近更新 更多