pytest-forked不支持单个用例独立进程,因其fork发生在模块级而非用例级,仅对整个测试文件生效;真正实现per-test-case进程隔离需使用pytest-xdist的--boxed模式。

直接用 pytest-forked 无法让「每个测试用例」都在独立进程中运行——它只支持「每个测试文件」或「每个测试会话」级的 fork,不支持 per-test-case 粒度。
为什么 pytest-forked 不支持单个用例独立进程?
pytest-forked 的设计目标是解决模块级副作用(比如全局状态污染、C 扩展内存泄漏),它的 fork 发生在 pytest_runtest_makereport 钩子之前,但仅对整个 Module 或 Session 生效。pytest 的执行模型中,“用例”(Function item)本身不触发 fork,fork 是在加载完该文件所有用例后、开始执行前一次性发生的。
常见误判现象:
– 写了 @pytest.mark.forked 却发现多个用例共享同一进程
– 用 --forked 启动,但 os.getpid() 在同一文件内多个用例中输出相同 PID
-
pytest-forked的@pytest.mark.forked只对整个测试函数所在模块生效,不是对单个函数生效 - 它不干预 pytest 的 test item 调度逻辑,无法在
setup → call → teardown每次循环中 fork - 即使配合
--forked,一个.py文件里所有def test_*仍跑在同一个 fork 出来的子进程里
替代方案:用 pytest-xdist 的 --boxed 实现 per-test-case 进程隔离
真正能实现「每个用例独立进程」的是 pytest-xdist 的 --boxed 模式(注意:不是 --forked)。它通过为每个 Function item 单独 fork + exec 来启动新进程,且默认禁用跨用例的 fixture 缓存,天然隔离。
使用前提:
– 安装 pytest-xdist(pip install pytest-xdist)
– 测试函数不能依赖模块级/会话级全局状态(因为进程完全隔离)
- 运行命令:
pytest --boxed test_module.py - 验证方式:在测试函数里加
import os; print(os.getpid()),每个test_*输出不同 PID - 注意
--boxed会禁用scope="session"和scope="module"fixture 的复用,所有 fixture 默认降级为function级 - 性能开销明显:每次 fork + import + setup 成本高,不适合大量轻量用例
如果必须用 pytest-forked,怎么最大化隔离效果?
当你的问题本质是「某个测试文件里多个用例相互污染」,而你又不想换插件,可以手动拆分测试结构,把高风险用例单独成文件,并配合 @pytest.mark.forked 标记该文件:
# test_isolated_1.py import pytest <p>@pytest.mark.forked def test_leaks_global_state(): import sys assert "bad_module" not in sys.modules</p><h1>... 触发 C 扩展加载等敏感操作</h1><p>@pytest.mark.forked def test_another_unsafe_op(): pass </p>
这样两个用例虽在同一文件,但 pytest-forked 会为整个文件 fork 一次;若想真正分开,就得写成:
-
test_case_a.py(只含一个test_*+@pytest.mark.forked) -
test_case_b.py(同上) - 然后运行:
pytest test_case_a.py test_case_b.py --forked
此时每个文件各 fork 一次,达到「每个用例一个进程」的间接效果——但代价是工程组织变重、报告聚合困难。
真正需要 per-test-case 进程隔离时,--boxed 是唯一可靠路径;拿 pytest-forked 硬凑只是绕远路,而且容易因误解标记行为而漏掉污染点。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











