pytest Python 单元测试快速上手:从安装到跑通真实场景的 5 步指南
【免费下载链接】pytestThe pytest framework makes it easy to write small tests, yet scales to support complex functional testing项目地址: https://gitcode.com/GitHub_Trending/py/pytest
pytest 是什么 & 解决什么问题
pytest 是一个 Python 单元测试框架,断言直接写原生 assert,不用继承 TestCase,也不用手写 setUp/tearDown 样板。它把"写一个测试"压缩到几行代码,同时靠插件生态撑住大型测试套件。
核心特性一览
- 原生 assert 自动断言重写
- 按命名约定自动发现用例
- fixture 做资源依赖注入
- parametrize 参数化批量跑
- 插件机制可持续扩展
环境准备 & 一键安装
版本要求
需要 Python 3.10 及以上,准备一个干净的 pip 环境即可,这也是项目自身要求的最低版本。
安装命令
pip install pytest安装验证
运行pytest --version,终端回显形如pytest 8.4.1 from ...的版本号与安装路径,说明 pytest 测试框架已就绪。如果提示 command not found,检查是否装进了当前激活的虚拟环境。
最小可运行示例
创建示例文件
# sample.py def is_even(n): return n % 2 == 0 # test_sample.py from sample import is_even def test_is_even(): assert is_even(4) is True def test_is_odd(): assert is_even(5) is False执行 & 预期输出
pytest -v # 预期输出 test_sample.py::test_is_even PASSED test_sample.py::test_is_odd PASSED ========================= 2 passed in 0.02s =========================看到 2 passed 即跑通;断言失败时它会直接打印表达式两侧的变量值,定位问题不用加 print,这来自断言重写机制(源码位置)。文件以 test_ 开头命名,是自动发现用例的前提。
一个真实场景走一遍
场景描述
电商后台每天导出一份订单 CSV,字段包含金额与支付渠道。上线新渠道前,你需要校验这批数据:金额必须为正、渠道必须在白名单内,并核对合法订单的总额。下面用 pytest 测试闭环来自动化这件事。
完整代码
# order_check.py 订单数据校验逻辑 import csv VALID_CHANNELS = {"wechat", "alipay", "card"} def load_orders(path): """读取 CSV,返回字典列表""" with open(path, newline="", encoding="utf-8") as f: return list(csv.DictReader(f)) def audit_orders(orders): """逐行校验,返回 (问题列表, 合法订单总额)""" problems, total = [], 0.0 for i, row in enumerate(orders, 1): if float(row["amount"]) <= 0: problems.append(f"第{i}行金额非法") if row["channel"] not in VALID_CHANNELS: problems.append(f"第{i}行渠道 {row['channel']} 不在白名单") else: total += float(row["amount"]) return problems, total # test_order_check.py 对应的 pytest 用例 import pytest from order_check import audit_orders, load_orders SAMPLE = "amount,channel\n100.5,wechat\n20,alipay\n-3,card\n99,bank\n" def test_audit_orders(tmp_path): csv_file = tmp_path / "orders.csv" # tmp_path 由 pytest 内置提供 csv_file.write_text(SAMPLE, encoding="utf-8") problems, total = audit_orders(load_orders(csv_file)) assert len(problems) == 2 # 负金额 + 未知渠道各一条 assert "bank" in problems[1] assert total == pytest.approx(120.5)关键逻辑拆解
- tmp_path 由 pytest 内置提供,每个用例拿到隔离的临时目录(源码位置)。
- 先把样例 CSV 落盘,再用 csv.DictReader 把每行读成字典,便于按字段取值。
- audit_orders 一次遍历完成两条规则:金额必须为正、渠道必须命中白名单。
- 只累加合法渠道的金额,得到应核对的总额 120.5。
- 总额用 pytest.approx 比较,避免浮点精度导致的偶发失败。
延伸技巧
- parametrize 批量喂渠道组合
- -k 可按名字只跑订单用例
- -l 让失败用例打印局部变量
进阶建议 & 周边生态
容易踩的坑 ⚠️
- 测试文件不叫 test_*.py 导致收集为 0 → 按命名约定改名
- float 直接 == 断言偶发失败 → 换 pytest.approx
- 被测模块导入报 ModuleNotFoundError → 测试文件与被测代码放同目录
值得关注的扩展 / 插件
- pytest-cov:生成行级覆盖率报告
- pytest-xdist:多进程并行,提速大套件
- pytest-mock:一行注入 mock 依赖
- pytest-django:Django 项目的测试支撑
【免费下载链接】pytestThe pytest framework makes it easy to write small tests, yet scales to support complex functional testing项目地址: https://gitcode.com/GitHub_Trending/py/pytest
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考