pytest + pytest-mock + pytest-parametrize为基础构建测试框架

一、框架核心组件整合

pytest作为基础测试框架,与pytest-mock(unittest.mock封装)和pytest-parametrize(参数化测试)形成黄金三角。三者协同可实现:

  • 依赖隔离:通过mocker fixture模拟外部API/数据库交互
  • 场景覆盖:利用参数化实现多输入组合测试
  • 代码复用:通过fixture机制实现测试资源共享
二、项目结构设计(推荐方案)
python 复制代码
my_project/
├── src/                  # 业务代码
│   ├── api/              # API模块
│   └── utils/            # 工具函数
├── tests/                # 测试目录
│   ├── unit/             # 单元测试
│   │   ├── test_api.py
│   │   └── test_utils.py
│   ├── integration/      # 集成测试
│   ├── conftest.py       # 全局fixture定义
│   └── pytest.ini        # 配置文件
└── requirements.txt      # 依赖管理
三、核心功能实现示例

1. 参数化测试(pytest-parametrize)

python 复制代码
import pytest

# 基础参数化
@pytest.mark.parametrize("a,b,expected", [
    (2, 3, 5),          # 正常场景
    (0, 0, 0),          # 边界值
    (-1, 1, 0),         # 异常输入
])
def test_add(a, b, expected):
    assert a + b == expected

# 高级用法:结合fixture实现动态参数
@pytest.fixture(params=[
    {"input": "valid", "expected": True},
    {"input": "invalid", "expected": False}
])
def dynamic_data(request):
    return request.param

def test_validation(dynamic_data):
    assert validate(dynamic_data["input"]) == dynamic_data["expected"]

2. Mock服务集成(pytest-mock

python 复制代码
def test_api_call(mocker):
    # 模拟requests.get方法
    mock_get = mocker.patch("requests.get")
    mock_get.return_value.json.return_value = {"status": "ok"}
    
    # 执行测试
    result = fetch_data("https://api.example.com")
    
    # 验证调用
    mock_get.assert_called_once_with("https://api.example.com")
    assert result["status"] == "ok"

3. 复杂场景测试(三者结合)

python 复制代码
@pytest.mark.parametrize("scenario", [
    {"url": "/v1/users", "expected_code": 200},
    {"url": "/v2/users", "expected_code": 404},
])
def test_api_versioning(scenario, mocker):
    # 模拟API响应
    mock_response = mocker.Mock()
    mock_response.status_code = scenario["expected_code"]
    mocker.patch("requests.get", return_value=mock_response)
    
    # 执行测试
    response = call_api(scenario["url"])
    
    # 断言结果
    assert response.status_code == scenario["expected_code"]
四、最佳实践建议
  1. fixture管理

    • 使用conftest.py定义跨模块fixture
    • 合理设置作用域(function/module/session)
    • 实现fixture依赖链(如db_conn → api_client)
  2. 测试分类

    • 单元测试:使用mock隔离外部依赖
    • 集成测试:通过--integration标记单独执行
    • 性能测试:添加@pytest.mark.slow标记
  3. 报告与集成

    • 生成HTML报告:pytest --html=report.html
    • CI集成:配置pytest.ini实现零配置执行
    • 覆盖率分析:结合pytest-cov生成覆盖率报告
五、常用命令参考
python 复制代码
# 运行所有测试
pytest

# 运行指定测试
pytest tests/unit/test_api.py::test_create_user

# 仅运行标记测试
pytest -m "smoke and not slow"

# 生成详细报告
pytest --cov=src --cov-report=html

这套框架设计遵循了测试金字塔原则,既保证了单元测试的执行效率,又通过集成测试验证了模块间协作。通过参数化和mock的结合使用,可在最少代码量下实现最大测试覆盖率。

相关推荐
阿蔹17 小时前
Python-Pytest
python·自动化·pytest
智航GIS19 小时前
8.11 sys 模块
数据库·windows·microsoft
阿蔹1 天前
Python-Pytest-Requests-API接口测试自动化框架
python·自动化·pytest
简简单单OnlineZuozuo1 天前
设计共情:面向真实系统的人本AI模式
人工智能·microsoft·架构·图像识别·banana·the stanford ai
玄同7652 天前
Python 系统编程双雄:sys 与 os 模块深度实践指南
开发语言·数据库·人工智能·windows·笔记·python·microsoft
qq_447429412 天前
claude code
microsoft
qq_447429412 天前
Gemini CLI 非交互模式工具调用问题解析
windows·microsoft·交互
天庭鸡腿哥3 天前
大小不足1M,干翻Windows!
microsoft·macos·visual studio·everything
2501_946244783 天前
Flutter & OpenHarmony OA系统弹窗对话框组件开发指南
javascript·flutter·microsoft