pytest配置在pyproject.toml中必须置于[tool.pytest.ini_options]表下,写成[pytest]或[tool.pytest]等均被静默忽略;键名如addopts、testpaths须用数组格式(如addopts = ["-v", "-m", "not slow"]),且文件须位于项目根目录。

pyproject.toml 里怎么写 pytest 配置才生效
pytest 不读 setup.cfg 或 pytest.ini 以外的配置文件,除非你明确告诉它——而 pyproject.toml 是默认支持的,但必须放在项目根目录,且 section 名必须是 [tool.pytest.ini_options]。写成 [pytest] 或 [tool.pytest] 都不会被识别。
常见错误现象:pytest 运行时完全忽略你在 toml 里写的 addopts 或 testpaths,命令行输出也不报错,让人误以为“配置成功了”。
- 确保顶层是
[tool.pytest.ini_options],不是其他名字 - 所有键名与传统
pytest.ini一致(如addopts、testpaths、python_files),不加前缀、不驼峰 - 字符串值不用引号包裹也可以,但含空格或特殊字符时建议用双引号
addopts 怎么写才能避免参数冲突
addopts 是最常用也最容易出问题的配置项。pytest 启动时会把 addopts 的值拆成参数列表传给解析器,如果格式不对,就会报 unrecognized arguments 或静默失效。
使用场景:想默认启用 -v、跳过慢测试、指定 markers。但直接写 addopts = "-v --skip-slow -m 'not slow'" 在 toml 里会被当做一个字符串,pytest 拆分失败。
立即学习“Python免费学习笔记(深入)”;
- 正确写法是用数组:
addopts = ["-v", "--skip-slow", "-m", "not slow"] - 不要在数组里拼接带空格的值(比如
"-m not slow"),pytest 会把它当一个参数,而不是两个 - 如果用了
--override-ini命令行参数,它会完全屏蔽addopts,调试时注意这点
如何让 pytest 自动发现 tests/ 下的包结构
默认 pytest 只找 test_*.py 和 *_test.py,如果你的测试组织成 tests/unit/、tests/integration/ 包结构(含 __init__.py),需要显式告诉 pytest 哪些路径可导入、哪些模式匹配测试文件。
性能影响:不配 pythonpath 或 python_files,可能导致测试发现变慢,或因模块导入失败而跳过部分测试。
- 用
testpaths = ["tests"]限定搜索起点,避免遍历整个项目 - 用
python_files = ["test_*.py", "*_test.py"]明确匹配规则(注意不是python_tests) - 若测试代码需 import 项目源码,加
pythonpath = ["src"](假设源码在src/),别用相对路径如"./src",pytest 当前工作目录不固定
为什么 conftest.py 里的 fixture 不生效
这不是 toml 配置问题,但常被误认为是——因为改了 pyproject.toml 后跑测试,fixture 报 fixture 'xxx' not found。根本原因是 pytest 的目录发现逻辑和 conftest.py 作用域绑定,而 toml 配置可能改变了测试起点。
容易踩的坑:把 testpaths = ["tests"] 写死,但 conftest.py 放在 tests/ 外层;或者 conftest.py 在 tests/unit/,但 testpaths 指向了更上层,导致 pytest 没加载到那个 conftest。
- 运行
pytest --debug查看 “rootdir” 和 “inifile” 路径,确认 pytest 认为的项目根和配置文件位置是否符合预期 - 用
pytest --collect-only看 fixture 是否出现在 collected items 的 scope 列表中 - conftest.py 必须放在测试文件的**同级或父级目录**,且不能跨 package 边界被自动继承(比如
tests/unit/conftest.py对tests/integration/下的测试无效)
pytest --debug 输出的 rootdir 和 inifile,比反复改 toml 更快定位问题。


















