29 · 测试:pytest 的 fixture 体系与 mock
学完这章,你能写隔离、可参数化、能测异常与副作用的测试,并知道 mock 应该打在哪。
本章目标
- 理解 pytest 的发现规则与
assert重写 - 能用 fixture 的
scope/yield/autouse/conftest.py管理依赖 - 能用
parametrize写表驱动测试,用ids/xfail表达预期 - 能用
capsys/tmp_path/monkeypatch/caplog测输出、文件、环境与日志 - 能正确使用
unittest.mock.patch(打在使用处)与autospec - 能用 Hypothesis 做属性测试,知道它不替代边界用例
- 能用
asyncio.run包装异步测试,避免引入额外插件
前置知识
- 第 06/09 章(函数、异常)、第 10/11 章(类型)、第 12 章(装饰器)
- 用过 JUnit/Go test/cargo test 任一测试框架
从你熟悉的语言出发
| 概念 | Go | Java | Rust | Python |
|---|---|---|---|---|
| 测试发现 | _test.go |
JUnit 注解 | #[test] |
test_*.py/test_* |
| 断言 | t.Errorf |
assertEquals |
assert! |
原生 assert(被重写) |
| 初始化 | TestMain | @BeforeEach |
手写 | fixture |
| 参数化 | 表驱动 | @ParameterizedTest |
手写 | parametrize |
| mock | 手写接口 | Mockito | trait/手写 | unittest.mock |
| 属性测试 | testing/quick | jqwik | proptest | Hypothesis |
类比一:fixture 是「依赖注入 + 生命周期管理」。 测试函数声明需要什么,pytest 按 scope 创建/复用/清理;类似 JUnit 的 @BeforeEach,但可以组合、按名注入,不必继承。
类比二:patch 是「临时替换模块属性」。 它改的是某个模块命名空间里的名字;所以必须打在使用处,而不是定义处——类似在调用方替换接口实现,而不是改实现类。
正文
29.1 发现与断言
- 默认发现
test_*.py/*_test.py,函数名test_*,类名Test*。 - 本仓库用
--import-mode=importlib,避免 200+ 个同名测试模块互相覆盖。 - pytest 重写
assert,失败时打印表达式中间值;不需要assertEqual。 pytest.raises(E, match="...")测异常;pytest.approx测浮点。-q简洁、-ra显示跳过/失败原因、--collect-only只收集。
29.2 fixture
@pytest.fixture(scope="module")
def db():
conn = connect()
yield conn
conn.close()scope:function(默认)/class/module/package/session。yield前是 setup,后是 teardown;即使测试失败也会执行。autouse=True自动应用;conftest.py让 fixture 在目录/子目录共享。- fixture 可以依赖 fixture;请求参数名即注入。
- 共享状态越多,越容易互相污染;默认 function 最安全。
29.3 parametrize 与 xfail
@pytest.mark.parametrize(("value", "expected"), [(1, 2), (2, 4)], ids=["one", "two"])
def test_double(value, expected):
assert value * 2 == expected- 第一个参数用元组;
ids让失败信息可读。 pytest.param(..., marks=pytest.mark.xfail(...))可标记个别用例。xfail(strict=True):意外通过会 XPASS 失败,防止「已知问题」过期。- 参数化组合不要爆炸:把等价类合并,边界单独列。
29.4 内置 fixture
| fixture | 用途 |
|---|---|
capsys |
捕获 Python 层 stdout/stderr |
capfd |
捕获文件描述符(C 扩展/子进程) |
tmp_path |
每测试独立临时目录(pathlib.Path) |
monkeypatch |
临时改环境变量/属性/sys.path |
caplog |
捕获 logging 记录 |
recwarn |
捕获 warnings |
approx |
浮点近似比较 |
tmp_path/monkeypatch 自动清理,不要手写 os.environ 恢复。
29.5 mock 的边界
from unittest.mock import patch
with patch("service.fetch", return_value="mock"): # 使用处
assert service.get_data() == "mock"patch("pkg.module.attr")替换的是pkg.module里的attr。- 如果
service.py写的是from client import fetch,client.fetch的替换不会影响service.fetch。 autospec=True按原签名校验调用;create_autospec可造完整 mock。patch尽量窄:只包住需要替换的调用,不要 patch 整个测试。- 不要 mock 被测对象本身;mock 外部边界(网络、时间、随机、文件系统)。
29.6 Hypothesis
from hypothesis import given, strategies as st
@given(st.text())
def test_roundtrip(text):
assert decode(encode(text)) == text- 自动生成大量输入,失败时 shrinking 到最小反例。
- 适合不变量(往返/幂等/排序稳定),不替代具体边界/错误用例。
- 用
@settings(max_examples=...)控成本;CI 可用 profile 区分。 - 依赖缺失时
pytest.importorskip("hypothesis")。
29.7 异步测试与隔离
- 本教程不引入
pytest-asyncio;用asyncio.run(coro)包装。 - 每个测试新建事件循环;不要在模块级共享 loop。
- 隔离:清缓存/
sys.modules/环境变量;用tmp_path而不是固定路径。 - flaky 常见来源:时间、随机、端口、并发;用事件/队列协调,避免
sleep赌时序。
报错现场
真实 pytest 缺 fixture 输出:
==================================== ERRORS ====================================
_____________________ ERROR at setup of test_needs_fixture _____________________
file /tmp/.../test_missing.py, line 1
def test_needs_fixture(db):
E fixture 'db' not found
> available fixtures: cache, capfd, caplog, capsys, monkeypatch, tmp_path, ...
> use 'pytest --fixtures [testpath]' for help on them.逐行读:
ERROR at setup:不是测试体失败,而是依赖注入失败。fixture 'db' not found:没有同名 fixture,或conftest.py不在搜索路径。available fixtures:列出当前可用项,先确认拼写/作用域。- 修法:在测试文件或上层
conftest.py定义dbfixture;检查目录层级与插件是否加载。
另一个常见错误是 AttributeError: <module ...> does not have the attribute 'x':patch 目标拼错/打错模块。用 python -c "import module; print(module.__file__)" 确认使用处。
反直觉差异:patch 打在使用处,fixture 是依赖注入
你的直觉:patch("client.fetch") 应该让所有导入 fetch 的地方都变成 mock;fixture 就是全局变量。
实际行为:
from client import fetch会在service模块里创建一个新名字fetch;patchclient.fetch不会改service.fetch。- fixture 是按参数名注入的;同名 fixture 在不同层级会覆盖,不是全局单例(除非 scope 大)。
- pytest 会重写
assert,所以失败信息包含中间值;生产代码的assert仍会被-O删除(第 26 章)。 xfail(strict=True)在问题被修复后会失败,提醒你移除标记。
为什么这样设计:Python 的 from x import y 是名字绑定,不是引用链接;patch 只能改命名空间里的对象。fixture 的依赖注入让测试显式声明依赖,便于组合和隔离。
正确写法:
- patch 字符串写「使用处的模块 + 属性」;不确定时打印
module.__file__。 - fixture 按测试需要声明,不要用全局可变状态偷懒。
- 外部边界 mock,核心逻辑用真实实现 + 属性测试。
- 每个测试独立;共享昂贵资源用 module/session scope,但保持只读。
性能与复杂度
| 操作 | 说明 |
|---|---|
| 测试收集 | --collect-only 只解析/导入,不执行 |
| fixture scope | function 每次新建;module/session 省初始化但共享状态 |
tmp_path |
每测试一个临时目录,文件系统操作有成本 |
| Hypothesis | 默认 100 例;max_examples 可调 |
| mock | 替换属性是 O(1),但过度 mock 会让测试失真 |
测试慢通常来自 IO/启动/重复 fixture,而不是断言本身;先看 --durations=10。
示例索引
| 目录 | 演示什么 | 预期看到 |
|---|---|---|
examples/29-testing-pytest/01-fixture-scopes/ |
fixture 作用域 | 对象身份不同、创建计数 |
examples/29-testing-pytest/02-parametrize-matrix/ |
参数化 + xfail | 6 通过 + 1 xfail |
examples/29-testing-pytest/03-capsys-and-tmp-path/ |
输出/临时文件 | stdout 精确匹配、文件读写 |
examples/29-testing-pytest/04-patch-target/ |
patch 使用处 | 错误目标 real、正确目标 mock |
examples/29-testing-pytest/05-monkeypatch-env/ |
环境变量 | 默认值/覆盖值 |
examples/29-testing-pytest/06-hypothesis-property/ |
属性测试 | UTF-8 往返 |
练习题
- 用
tmp_pathfixture 读写文件。见exercises/29/01-fixture-tmp/。 - 用
parametrize覆盖 clamp 的边界与非法区间。见exercises/29/02-parametrize-clamp/。 - 验证 patch 打在使用处才生效。见
exercises/29/03-patch-service/。 - 用
monkeypatch覆盖环境变量。见exercises/29/04-monkeypatch-env/。
- fixture 接收
tmp_path,返回写入后的文件路径。 @pytest.mark.parametrize(("value","low","high","expected"), [...], ids=[...])。patch("upstream.fetch")不影响solution.fetch;patch("solution.fetch")生效。monkeypatch.setenv("API_URL", ...)/delenv(..., raising=False)。
章末自检
- pytest 的发现规则?
assert为什么不需要assertEqual? - fixture 的 scope 有哪些?
yieldfixture 的清理何时执行? parametrize的ids/xfail(strict=True)各解决什么?capsys与capfd的区别?tmp_path何时清理?patch为什么必须打在使用处?autospec做什么?- Hypothesis 适合什么、不适合什么?
- 异步测试为什么不引
pytest-asyncio?怎么包装? - flaky 的常见来源与避免方式?
test_*.py/test_*;pytest 重写 assert 显示中间值。- function/class/module/package/session;测试结束(含失败)执行。
- 可读用例名;防止已知问题过期。
- Python 层 vs 文件描述符;自动清理。
from x import y是名字绑定;按原签名校验调用。- 不变量/大量输入;不替代边界与错误用例。
- 避免额外依赖;
asyncio.run(coro)。 - 时间/随机/端口/并发;事件协调、固定种子、临时端口。
延伸阅读
- pytest 文档:Get Started、Fixtures、Parametrize、Monkeypatching/mocking modules and environments、Capturing of stdout/stderr
- Python 文档:
unittest.mock(patch、autospec、MagicMock) - Hypothesis 文档:What is property-based testing?、Settings
- The Python Standard Library §26.4
unittest.mock pytest文档:How to invoke pytest、Configuration