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

Python编码后如何用Pytest测试请求异常场景的Except代码块

用pytest测试requests请求的ConnectionError异常场景

要测试这段代码里的except代码块,核心是模拟requests.get抛出ConnectionError,而非发起真实网络请求。下面是具体实现步骤:

1. 将业务逻辑封装为可测试的函数

如果你的代码是脚本级别的零散代码,建议先把请求逻辑封装成函数,方便测试:

import requests

def fetch_target_data(url, thing):
    try:
        r = requests.get(url, params={'s': thing})
        return r  # 正常返回响应对象
    except requests.ConnectionError as e:
        print(f"连接错误: {e}")
        # 可选:若需让测试捕获异常,可重新抛出;否则返回错误标记
        # raise

2. 编写pytest测试用例

使用unittest.mock.patch替换真实的requests.get方法,让它抛出指定异常,同时验证逻辑是否正确执行:

import pytest
from unittest.mock import patch
import requests
from your_script import fetch_target_data  # 替换为你的脚本/模块名

def test_fetch_data_connection_error(capsys):
    # 模拟requests.get抛出ConnectionError
    with patch('requests.get') as mock_get:
        mock_get.side_effect = requests.ConnectionError("无法连接到目标服务器")
        
        # 调用封装好的函数
        fetch_target_data("https://test.example.com", "test_param")
        
        # 1. 验证请求参数是否正确传递
        mock_get.assert_called_once_with(
            "https://test.example.com",
            params={'s': "test_param"}
        )
        
        # 2. 验证异常被捕获后是否正确打印信息
        captured_output = capsys.readouterr()
        assert "无法连接到目标服务器" in captured_output.out

# 若函数里重新抛出了异常,用以下测试方式
def test_fetch_data_raises_connection_error():
    with patch('requests.get') as mock_get:
        mock_get.side_effect = requests.ConnectionError("模拟连接失败")
        
        with pytest.raises(requests.ConnectionError) as exc_info:
            fetch_target_data("https://test.example.com", "test_param")
        
        assert str(exc_info.value) == "模拟连接失败"

关键说明

  • mock的作用:用patch替换真实网络请求,避免测试依赖外部服务,同时精准控制异常场景
  • 断言要点:既要验证请求参数是否正确(确保业务逻辑未偏离),也要验证异常处理行为(比如是否打印正确信息、是否抛出预期异常)
  • capsys fixture:pytest自带工具,用于捕获标准输出/错误,方便测试print内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 05:31:34