You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何测试使用了requests模块get方法的Django视图?

测试包含第三方HTTP请求的Django视图方案

核心思路

第三方服务的响应不可控,测试时不需要真实发起网络请求,直接Mock requests.get 方法的返回结果/异常,即可覆盖所有业务分支,测试过程完全不依赖外部服务的可用性。

测试实现步骤

1. 依赖工具

直接使用Python标准库自带的unittest.mock模块即可,无需额外安装第三方依赖。

2. 测试代码示例

from django.test import TestCase
from rest_framework.test import APIClient
from rest_framework import status
from unittest.mock import patch, Mock
import requests
from your_app.models import User # 替换为你自己的用户模型路径
# 替换为你自己的视图路径
from your_app.views import CertificateAPIView

class CertificateAPITest(TestCase):
    def setUp(self):
        self.client = APIClient()
        # 构造登录用户,满足视图的权限校验要求
        self.user = User.objects.create_user(username='test_user', password='test_pass_123')
        self.client.force_authenticate(user=self.user)
    
    # Mock路径要填写视图文件内引用的requests对象位置
    @patch('your_app.views.requests.get')
    def test_cert_failed_when_uid_is_none(self, mock_get):
        # 模拟第三方返回uid为空的响应
        mock_third_response = Mock()
        mock_third_response.get.return_value = None
        mock_get.return_value = mock_third_response

        # 发起接口请求,imp传任意符合格式的值即可
        response = self.client.put(
            '/your/certificate/api/path/', 
            data={'imp': 'test_fake_imp'}, 
            format='json'
        )

        # 校验返回结果符合预期
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertIn('Certification is failed', response.json()['detail'])
        # 校验requests.get确实被调用,且调用参数正确
        mock_get.assert_called_once_with('another server')
    
    @patch('your_app.views.requests.get')
    def test_cert_success_when_uid_valid(self, mock_get):
        # 模拟第三方返回正常uid的场景
        mock_third_response = Mock()
        mock_third_response.get.return_value = 'valid_test_uid_12345'
        mock_get.return_value = mock_third_response

        response = self.client.put(
            '/your/certificate/api/path/', 
            data={'imp': 'test_fake_imp'}, 
            format='json'
        )
        
        # 根据你的业务逻辑修改此处的校验规则
        self.assertEqual(response.status_code, status.HTTP_200_OK)
    
    @patch('your_app.views.requests.get')
    def test_handle_third_party_request_exception(self, mock_get):
        # 模拟第三方接口超时、报错等异常场景
        mock_get.side_effect = requests.exceptions.Timeout

        response = self.client.put(
            '/your/certificate/api/path/', 
            data={'imp': 'test_fake_imp'}, 
            format='json'
        )
        # 根据你对异常的处理逻辑校验返回结果
        self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)

3. 注意事项

  • Mock路径要准确:需要Mock的是视图代码所在文件里导入的requests对象,不能直接写@patch('requests.get'),否则Mock不会生效
  • 无需真实可用的imp参数:测试时只要传符合格式的任意imp值即可,因为第三方请求已经被Mock拦截,不会真实发起网络调用
  • 所有分支都要覆盖:包括正常返回、返回异常字段、第三方请求报错、超时等所有你代码里处理的场景,都可以通过Mock不同的返回值/异常来覆盖
  • 可以用mock.assert_called_once_with()方法校验请求的URL、参数是否符合预期,避免请求参数写错的问题

内容的提问来源于stack exchange,提问作者Sammy Kim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 04:06:00