pytest默认递归查找test_.py或_test.py文件中以test_开头的函数,要求测试目录为合法Python包(含__init__.py),否则可能因导入失败导致测试未收集。

pytest默认如何识别测试目录
pytest 会自动递归查找当前目录及子目录下符合命名规则的文件和函数:test_*.py 或 *_test.py,且内部函数名以 test_ 开头。它不依赖 __init__.py 是否存在,但**必须是合法的 Python 包结构(即含 __init__.py)才能被正确导入和参数化**——这点常被忽略,导致 ImportError 或 ModuleNotFoundError。
常见错误现象:pytest tests/unit/ 能跑通,但 pytest tests/ 报错说找不到模块;或使用 -k 时部分测试未被收集。
- 确保每个测试子目录(如
tests/unit、tests/integration)都包含空的__init__.py - 避免在测试目录中混放非测试代码(如
conftest.py放错位置会导致作用域混乱) - 如果项目根目录不是包根(比如
src/下才是实际模块),需用--pythonpath src或设PYTHONPATH
用目录名控制测试执行范围
直接传入路径是最简单、最可靠的按目录组织方式。pytest 不需要额外配置就能识别目录层级,关键是路径参数是否精确匹配你期望的边界。
例如,项目结构为:
myproject/ ├── src/ │ └── mylib/ ├── tests/ │ ├── __init__.py │ ├── unit/ │ │ ├── __init__.py │ │ └── test_math.py │ └── integration/ │ ├── __init__.py │ └── test_api.py
- 只运行单元测试:
pytest tests/unit/ - 跳过集成测试:
pytest tests/ --ignore=tests/integration/ - 组合多个目录:
pytest tests/unit/ tests/integration/(注意:不能写成pytest tests/{unit,integration}/,shell 展开后 pytest 会报路径不存在) - 用
-k配合目录名筛选(需测试函数名含目录特征):pytest -k "unit and test_add",但不如直接指定路径稳定
通过conftest.py实现目录级fixture与配置
每个测试目录下的 conftest.py 是 pytest 的“本地配置中心”,它的作用域默认限于该目录及其子目录。这是实现按目录隔离 fixture、hook、mark 注册的关键机制。
容易踩的坑:conftest.py 中定义的 fixture 若未加 scope="module" 或更宽作用域,在跨文件调用时可能重复执行;同名 fixture 在不同 conftest.py 中不会合并,而是就近覆盖。
让 macOS 自动化像说话一样简单 —— 用代码控制你的 Mac,无需学习 AppleScript 系统要求 macOS 14+ (Sonoma) Python 3.9+ 需要开启:辅助功能 + 屏幕录制权限
- 在
tests/unit/conftest.py中定义@pytest.fixture(scope="function"),仅对tests/unit/下所有测试生效 - 若需共享 setup/teardown 逻辑,可在
tests/conftest.py中定义scope="session"fixture,但要小心副作用污染 - 用
pytest_addoption在顶层conftest.py添加命令行参数,再在子目录conftest.py中读取,实现条件化 fixture 加载
标记(mark)目录级测试分类并批量启用
pytest 的 @pytest.mark 本身不绑定目录,但你可以约定用目录名作为 mark 名(如 @pytest.mark.unit),再配合 pytest.ini 自动打标,让目录组织真正可操作。
推荐做法:不用手动给每个测试加 @pytest.mark.unit,而是在 pytest.ini 中配置自动标记规则:
[tool:pytest]
markers =
unit: tests in tests/unit/
integration: tests in tests/integration/
然后在 tests/conftest.py 中注入逻辑:
import pytest
def pytest_collection_modifyitems(config, items):
for item in items:
if "tests/unit/" in str(item.fspath):
item.add_marker("unit")
elif "tests/integration/" in str(item.fspath):
item.add_marker("integration")
- 之后即可用
pytest -m unit或pytest -m "not integration"精确控制 - 注意
item.fspath是py.path.local对象,转字符串才可做路径判断 - 这个钩子在收集阶段运行,不影响性能;但若目录嵌套深(如
tests/unit/models/),建议用.relto()或parts更健壮地提取层级
目录组织本身不难,难的是 fixture 作用域、mark 注入时机、路径解析精度这三者的耦合。一旦 conftest.py 放错位置或 __init__.py 缺失,pytest 就可能静默跳过某些测试——这种失败没有报错,只有覆盖率下降或 CI 漏测,最难排查。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










