pytest fixture中--record标记的请求录制功能失效问题求助
修复方案
核心问题分析
- MonkeyPatch作用域失效:你用
pytest.MonkeyPatch().context()创建的上下文管理器,在with块结束后会自动还原补丁。这意味着当return api_client执行时,补丁已经被撤销,ApiClient后续调用requests.request时不会触发你的记录函数。 - 变量名错误:代码里定义的变量是
api_client,但返回的是未定义的mp_api_client,会导致运行时错误。 - 目录缺失隐患:直接写入
recorded_responses目录会因目录不存在抛出异常,需要提前创建。 - 文件名逻辑问题:
args[0]是请求方法(如GET),会导致不同URL的同方法请求覆盖同一个JSON文件,应该基于URL生成唯一文件名。
修复后的代码
import os import json import requests import pytest from your_module import get_api_client, FakeAPIClient # 替换成你的实际模块路径 def record_requested_data(*args, **kwargs): response = requests.request(*args, **kwargs) # 确保记录目录存在 os.makedirs("recorded_responses", exist_ok=True) # 基于请求URL生成唯一文件名(处理特殊字符) url = args[1].replace("https://", "").replace("http://", "").replace("/", "_").replace("?", "_").replace("=", "_") record_path = os.path.join("recorded_responses", f"{args[0]}_{url}.json") # 记录完整的响应信息,包含状态码、请求头等元数据 record_data = { "status_code": response.status_code, "headers": dict(response.headers), "json": response.json() if response.content else None } with open(record_path, 'w', encoding='utf-8') as record_file: json.dump(record_data, record_file, indent=2) return response @pytest.fixture(scope="function") def api_client(record_mode: bool, monkeypatch): # 使用pytest内置的monkeypatch fixture if record_mode: api_client = get_api_client() # 直接用内置monkeypatch打补丁,作用域覆盖整个测试函数周期 monkeypatch.setattr(requests, 'request', record_requested_data) return api_client else: return FakeAPIClient()
关键修改说明
- 使用pytest内置
monkeypatchfixture:它的补丁会自动在测试结束后还原,且作用域覆盖整个测试函数周期,无需手动管理上下文。 - 修正变量名:返回正确的
api_client变量,避免未定义错误。 - 创建记录目录:用
os.makedirs(..., exist_ok=True)确保目录存在,防止写入失败。 - 优化文件名生成:结合请求方法和URL生成唯一文件名,避免不同请求覆盖记录文件。
- 增强记录内容:额外记录状态码、请求头,方便后续调试和校验。
内容的提问来源于stack exchange,提问作者elias velardez
相关产品推荐
相关产品推荐

