pytest 框架用法总结
一、核心用法速览
测试发现 | 文件: 函数: 类: | 自动递归搜索测试文件和函数,无需继承基类 |
基本断言 |
| 支持智能错误提示(如列表/字典差异) |
Fixture |
| 管理测试资源(如数据库连接、临时文件),支持依赖注入 |
参数化测试 |
| 同一测试函数运行多组数据 |
测试标记 |
| 分类筛选测试用例(如冒烟测试、性能测试) |
异常断言 |
| 验证代码是否抛出预期异常 |
二、典型示例
1. Fixture 管理资源
# conftest.py(自动加载) import pytest @pytest.fixture(scope="session") # 整个测试会话只创建一次 def database(): db = connect_db() # 连接数据库 yield db # 返回数据库对象给测试函数 db.close() # 测试结束后清理 # test_db.py def test_user_count(database): assert database.query(User).count() > 0
2. 参数化与标记结合
import pytest @pytest.mark.parametrize( "user, password, expected", [ ("admin", "correct", True), ("admin", "wrong", False), pytest.param("guest", "any", False, marks=pytest.mark.xfail), # 预期失败 ] ) def test_login(user, password, expected): result = login(user, password) assert result == expected
3. 并行测试(需安装 pytest-xdist
)
pytest -n 4 # 4个进程并行执行
三、框架亮点
1.简洁灵活:
无需继承 TestCase,用纯函数和类编写测试
支持自然语言断言(如 assert a == b)
2.强大的 Fixture 系统:
支持参数化 fixture(同一 fixture 返回多组数据)
支持依赖嵌套(fixture 可依赖其他 fixture)
作用域灵活(function/class/module/session)
3.丰富的插件生态
pytest-html:生成美观的 HTML 报告
pytest-mock:轻松 mock 外部依赖
pytest-rerunfailures:失败用例自动重试
pytest-xdist:多进程/分布式执行
4.测试生命周期钩子
通过自定义 pytest_collection_modifyitems 等 hook 函数,灵活控制测试流程
四、面试高频问题
1.pytest 与 unittest 的区别?
pytest 语法更简洁,无需继承基类;
unittest 是 Python 内置库,更适合简单场景。pytest 支持更强大的 fixture 和参数化,插件生态丰富。
2.如何处理测试用例的依赖关系?
使用 pytest-dependency 插件标记依赖关系:
@pytest.mark.dependency() def test_login(): ... @pytest.mark.dependency(depends=["test_login"]) def test_logout(): ...
3.Fixture 的作用域有哪些?
function(默认)、class、module、session,控制 fixture 的创建和销毁时机。
4.如何优化测试执行速度?
使用 pytest-xdist 并行执行测试通过 pytest -k "keyword" 筛选特定测试使用 pytest --lf 只运行上次失败的测试
5.如何实现测试数据与代码分离?
从 JSON/CSV 文件读取数据:
import json @pytest.mark.parametrize("data", json.load(open("test_data.json"))) def test_api(data): assert request_api(data) == data["expected"]
五、实战技巧
1.生成测试覆盖率报告
pytest --cov=src --cov-report=html # 生成 HTML 格式覆盖率报告
2.自定义标记在 pytest.ini 中注册标记:
[pytest] markers = smoke: 冒烟测试 regression: 回归测试
3.失败时自动调试
pytest --pdb # 失败时进入 PDB 调试模式
4.结合 Allure 生成美观报告
pytest --alluredir=./allure-results allure serve allure-results # 生成交互式报告
六、总结
pytest 以其 简洁的语法、强大的 Fixture 系统 和 丰富的插件生态,成为 Python 测试的首选框架。掌握参数化测试、Fixture 管理和插件使用,可大幅提升测试效率和质量。在面试中,重点突出其灵活性、可扩展性和解决实际问题的能力。