python 测试框架 pytest 作者:马育民 • 2026-05-07 22:40 • 阅读:10009 pytest 是 Python 生态最主流的测试框架,支持单元测试、接口/自动化测试,以**简洁语法、自动用例发现、灵活 fixture、丰富插件**著称,比内置 unittest 更易用、更强大。 --- ### 一、核心优势(vs unittest) - ✅ **语法极简**:无需继承 `TestCase`,直接写函数 + 原生 `assert`,错误信息自动细化。 - ✅ **自动发现**:默认匹配 `test_*.py` / `*_test.py` 文件、`test_*` 函数/方法,无需手动注册。 - ✅ **Fixture 机制**:替代 setUp/tearDown,支持**作用域(function/class/module/session)、依赖注入、参数化**,复用性强。 - ✅ **兼容 unittest**:可直接运行 unittest 用例,平滑迁移。 - ✅ **插件生态**:1300+ 插件(如 pytest-cov、pytest-xdist、pytest-html),扩展能力强。 --- ### 二、快速安装 ```bash # 虚拟环境(推荐) python -m venv venv source venv/bin/activate # Linux/macOS venv\Scripts\activate # Windows # 安装 pytest pip install pytest ``` 验证:`pytest --version` --- ### 三、第一个测试用例 创建 `test_sample.py`: ```python # 被测函数 def func(x): return x + 1 # 测试用例(test_ 开头) def test_answer(): assert func(3) == 4 # 原生 assert,无需 self.assert* ``` 运行: ```bash pytest test_sample.py -v ``` 输出(成功): ``` collected 1 item test_sample.py::test_answer PASSED ``` --- ### 四、核心用法 #### 1. 用例发现规则 - 文件:`test_*.py` 或 `*_test.py` - 函数:`def test_*():` - 类:`class Test*():`(无 __init__) - 类方法:`def test_*(self):` #### 2. Fixture(夹具) 替代 setUp/tearDown,支持依赖注入与作用域控制。 ```python import pytest # 定义 fixture(默认 function 作用域) @pytest.fixture def db_connection(): # 前置:创建连接 conn = "模拟数据库连接" yield conn # 注入测试用例 # 后置:关闭连接 print("关闭连接") # 测试用例依赖 fixture def test_query(db_connection): assert db_connection == "模拟数据库连接" ``` **常用作用域**: - `@pytest.fixture(scope="function")`:默认,每个用例运行 - `scope="class"`:每个测试类一次 - `scope="module"`:每个文件一次 - `scope="session"`:整个测试会话一次(全局) #### 3. 参数化测试 ```python import pytest # 多组参数驱动用例 @pytest.mark.parametrize("a, b, expected", [ (1, 2, 3), (0, 0, 0), (-1, 1, 0), ]) def test_add(a, b, expected): assert a + b == expected ``` #### 4. 异常捕获 ```python def test_divide_by_zero(): with pytest.raises(ZeroDivisionError, match="division by zero"): 1 / 0 ``` #### 5. 常用命令 ```bash # 运行当前目录所有用例 pytest # 详细输出 pytest -v # 仅运行失败用例 pytest --lf # 生成 HTML 报告(需 pytest-html) pytest --html=report.html # 并行运行(需 pytest-xdist) pytest -n auto ``` --- ### 五、配置文件(pytest.ini) 项目根目录创建,统一配置: ```ini [pytest] testpaths = tests python_files = test_*.py python_functions = test_* python_classes = Test* addopts = -v --strict-markers ``` --- ### 六、常用插件 - `pytest-cov`:覆盖率统计 - `pytest-xdist`:并行执行 - `pytest-html`:HTML 报告 - `pytest-mock`:mock 支持 - `pytest-django`:Django 测试适配 --- ### 七、总结 pytest 是 Python 测试的**工业级标准**,以简洁、灵活、可扩展为核心,适合从小型脚本到大型项目的全场景测试。掌握 **Fixture、参数化、插件** 即可覆盖 90% 日常需求。 要不要我把上面内容整理成一份可直接复制的 pytest 项目模板(含目录结构、示例用例、fixture 和配置文件)? 原文出处:http://www.malaoshi.top/show_1GW3Gm4REg7C.html