PyCharm配置pytest需三步:先确保解释器安装pytest 8.2+(兼容Python 3.12),再在Settings→Tools→Python Integrated Tools中将Default test runner设为pytest,最后严格遵循test_.py、test_函数、Test*类等命名规则。

PyCharm 中配置 pytest 运行环境本身不依赖 Python 3.12 的特殊处理,但 Python 3.12 的包兼容性、虚拟环境行为和部分 pytest 插件支持确实存在实际限制——直接用 pip install pytest 在 Python 3.12 下可能失败或安装旧版,必须明确指定兼容版本。
确认 pytest 对 Python 3.12 的支持现状
截至 2026 年 10 月,pytest 8.2.x 是首个完整支持 Python 3.12 的稳定系列。低于 8.2.0 的版本(如 8.1.x)在运行时可能抛出 ImportError: cannot import name 'cached_property' from 'functools' 或类似错误,因为 Python 3.12 移除了 functools.cached_property 的别名兼容层(该类已移至 typing 模块并重构)。
- 执行
pip install pytest==8.2.0或更高(如8.2.3),避免无版本约束的pip install pytest - 验证安装:运行
python -m pytest --version,输出应含pytest 8.2.x且无警告 - 若看到
pytest 7.4.4或更低,说明 pip 从缓存或旧索引拉取了不兼容版本,需加--force-reinstall --no-deps重装
PyCharm 中必须手动设置测试运行器为 pytest
PyCharm 不会自动识别你装了 pytest,即使解释器里有 pytest 包,它默认仍用 unittest 发现机制。不设这一步,右键 Run 会跑成 Unittests in xxx.py,导致 fixture、参数化、conftest.py 全部失效。
- 打开
File → Settings → Tools → Python Integrated Tools(macOS 是PyCharm → Preferences) - 在
Default test runner下拉框中,**必须选择pytest**,不能留空或选Unittest - 下方
Test folder建议填tests(若项目用此目录),否则 PyCharm 可能漏发现测试文件 - 改完后点击
OK,重启 PyCharm —— 这步常被跳过,导致配置看似生效实则未加载
测试文件命名与结构必须严格匹配 pytest 规则
PyCharm 的 pytest 集成完全依赖 pytest 自身的发现逻辑。一旦文件/类/函数命名不合规,IDE 就不会在右键菜单显示 Run pytest in xxx,也不会在测试工具窗口列出用例。
- 测试文件名必须是
test_*.py或*_test.py(例如test_api.py✅,api_test.py❌) - 测试类名必须是
Test*且**不能有__init__方法**(class TestLogin:✅,class TestLogin(object):且含def __init__❌) - 测试函数/方法必须以
test_开头(def test_valid_login(self):✅,def valid_login(self):❌) - 若用
conftest.py,它必须位于测试文件的**任意父目录**中,且该目录需含__init__.py(否则 pytest 3.12+ 会忽略)
避免在测试脚本里调用 pytest.main()
很多教程教你在 test_xxx.py 末尾写 if __name__ == '__main__': pytest.main(),这在 Python 3.12 + pytest 8.2 下极易引发 RecursionError 或工作目录错乱——因为 PyCharm 实际是用子进程调用 python -m pytest,再触发内部 pytest.main() 造成嵌套。
- 彻底删除测试文件中的
pytest.main()调用 - 所有执行都通过 PyCharm 界面操作:右键文件/类/方法 →
Run 'pytest in test_xxx.py' - 如需命令行调试,直接在终端进项目根目录,运行
python -m pytest tests/test_api.py -v,不要进测试文件内部再跑
最易被忽略的是:Python 3.12 的 venv 模块默认不再自动安装 setuptools 和 wheel,而 pytest 8.2 构建时依赖它们。创建新虚拟环境后,务必先运行 python -m pip install --upgrade pip setuptools wheel,否则 pip install pytest 可能静默失败或降级安装。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











