混用 pytest 和 unittest 极其危险:fixture 在 unittest 中完全失效,pytest ≥ 8.0 可能静默破坏 setUp/断言,sys.modules 缓存污染导致 AttributeError,PyCharm 默认误判测试框架,必须严格隔离运行、锁定 pytest==7.4.4 并避免全局副作用。

混用 pytest 和 unittest 不是“能跑通”就安全,而是埋雷现场——fixture 失效、测试跳过、断言静默失败,都是典型症状。
conftest.py 里的 @pytest.fixture 在 unittest.TestCase 中完全不生效
pytest 的 fixture 注入机制只作用于它自己发现的测试函数或类;unittest.TestCase 子类绕过整个 pytest 生命周期,conftest.py 对它形同虚设。常见报错:TypeError: test_something() missing 1 required positional argument: 'db',哪怕你已经在 conftest.py 里定义了 @pytest.fixture。
- 别指望
pytest.main()包裹unittest.TestLoader能让 fixture 生效——它直接跳过 fixture 初始化流程 - 如果必须保留旧的
unittest用例,改用setUpClass/tearDownClass手动初始化/清理资源,而不是依赖conftest.py - 运行时加
--tb=short能更快暴露这类参数缺失错误,避免误判为业务逻辑 bug
pytest 先跑、unittest 后跑会触发 sys.modules 缓存污染
pytest 加载过的模块(比如 numpy 或自定义 utils),再被 unittest.TestLoader 重新导入时,可能残留旧状态。典型表现:AttributeError: module 'xxx' has no attribute 'y',但单独运行 unittest 完全正常。
- 强制清空
sys.modules不可靠,更稳妥的是进程隔离:先python -m pytest tests/pytest_style/,再python -m unittest discover -s tests/unittest_style/ - 避免在
__init__.py或conftest.py中做全局副作用操作(如patch、monkeypatch),这些会污染后续unittest进程 - CI/CD 中务必用
pytest --collect-only验证 pytest 是否真发现了你预期的测试,防止“看似跑完实则漏掉”
pytest ≥ 8.0 版本会静默破坏 unittest 行为
新版 pytest(尤其是 ≥ 8.0)或某些插件(如 pytest-asyncio)可能重写 unittest.TestCase.run(),导致 setUp 不执行、测试静默跳过、断言失败却不报错。
将测试、lint、构建和文档流程编码为命名的Python会话,以便人类和代理每次运行相同的workflow。
立即学习“Python免费学习笔记(深入)”;
- 检查
pip list | grep pytest,若版本 ≥ 8.0,回退到pytest==7.4.4(该版本对unittest兼容性最稳定) - 在
pyproject.toml中显式锁定:requires = ["pytest==7.4.4"],避免 CI 环境因 pip install 自动升级 - 不要在混合项目中启用
--reuse-db或--nomigrations之类 pytest-django 选项——它们对unittest无感知,反而加剧数据库状态混乱
PyCharm 里右键运行总走 unittest 而不是 pytest
PyCharm 默认按文件结构和命名模式识别测试框架,但当项目同时存在两种风格时,容易误判。右键菜单显示 “Run ‘Unittests in…’” 并不代表 pytest 不能跑,只是 IDE 没选对 runner。
- 进入
Settings → Tools → Python Testing → Test Framework,把默认测试运行器设为pytest - 单个测试文件右键运行前,先确认编辑配置里没有残留
pytest相关的 runner 设置(尤其注意_jb_pytest_runner报错时,要删掉所有以pytest开头的配置项) - 确保测试文件名符合 pytest 发现规则(如
test_*.py),且不含unittest.TestCase继承——否则 PyCharm 仍倾向用 unittest 模式
真正麻烦的不是“怎么让两者共存”,而是“哪些地方看起来共存了,其实已经失效”。fixture 不注入、缓存污染、版本踩坑,三者叠加后问题会延迟暴露,等上线前才发现,修复成本远高于早期拆分决策。

















