如何在@pytest.mark.parametrize中添加默认Mock行为参数?
参数化Mock PyTest用例实现方案
核心实现思路
把默认JSON加载行为(复用现有fixture)和异常场景(如抛出异常)作为参数化条目,通过pytest.mark.parametrize结合fixture注入实现;同时单独mockasync_check_api_key,满足async_validate_coordinates的依赖要求。
具体代码实现
1. 确认/完善JSON加载fixture
假设你已经有mock_nearby_sensors_json fixture,若没有可以按下面定义:
import pytest import json from pathlib import Path @pytest.fixture def mock_nearby_sensors_json(): # 从预制JSON文件读取测试数据 json_file = Path(__file__).parent / "test_data" / "nearby_sensors.json" with open(json_file, "r", encoding="utf-8") as f: return json.load(f)
2. 添加async_check_api_key的mock fixture
因为async_validate_coordinates依赖这个接口,直接mock校验通过:
@pytest.fixture def mock_check_api_key(mocker): mock = mocker.patch("your_module.async_check_api_key") mock.return_value = True return mock
3. 构建参数化测试用例
参数化数组中通过lambda间接调用fixture,避免作用域问题;异常场景直接传递异常类型或mock逻辑:
# 辅助函数:生成抛出指定异常的mock副作用 def api_exception_side_effect(exc_type): def _side_effect(*args, **kwargs): raise exc_type("API调用失败") return _side_effect @pytest.mark.parametrize( "mock_setup, expected", [ # 默认场景:用fixture加载的JSON数据作为返回值 ( lambda mocker, fixture: mocker.patch( "your_module.async_get_nearby_sensors", return_value=fixture ), {"status": "success"} # 这里写你预期的返回结构/值 ), # 异常场景1:模拟连接错误 ( lambda mocker, fixture: mocker.patch( "your_module.async_get_nearby_sensors", side_effect=api_exception_side_effect(ConnectionError) ), ConnectionError ), # 异常场景2:模拟返回无效数据触发ValueError ( lambda mocker, fixture: mocker.patch( "your_module.async_get_nearby_sensors", return_value={"invalid_field": "data"} ), ValueError ), ] ) @pytest.mark.asyncio async def test_api_behavior(mock_setup, expected, mocker, mock_nearby_sensors_json, mock_check_api_key): # 应用当前场景的mock mock_setup(mocker, mock_nearby_sensors_json) # 测试async_get_nearby_sensors if isinstance(expected, dict): result = await your_module.async_get_nearby_sensors(1.0, 2.0) assert result["status"] == expected["status"] # 可根据需要添加更细致的字段校验 else: with pytest.raises(expected): await your_module.async_get_nearby_sensors(1.0, 2.0) # 测试async_validate_coordinates(依赖mock_check_api_key已生效) assert await your_module.async_validate_coordinates("valid_key", 0.0, 0.0) is True
关键注意事项
- 参数化时用lambda封装mock逻辑,能间接引用fixture,避免直接在参数数组中使用fixture导致的作用域错误
- 通用依赖(如
async_check_api_key)单独抽成fixture,所有测试用例可复用,减少重复代码 - 异常场景直接传递异常类型,结合
pytest.raises做断言,逻辑清晰直观
内容的提问来源于stack exchange,提问作者PieterV
相关产品推荐
相关产品推荐

