如何以本地模块方式加载插件,而无需打包上传到 PyPI?

解读

国内一线互联网公司的面试里,这道题常被用来区分“只会用 pytest 跑用例”与“能深度定制测试框架”的候选人。
核心考点有三层:

  1. 插件加载机制:pytest 启动时会扫描哪些入口点(entry point)?
  2. 本地模块路径:如何让解释器在“不安装”的前提下把插件当成普通 Python 模块 import 进来?
  3. 零侵入配置:能否做到既不改 pytest 源码,也不污染全局 site-packages,就能让插件生效。

如果候选人只回答“放到 conftest.py”只能拿 60 分;能讲清 setuptools entry point、pytest_plugins 列表以及 PYTHONPATH/editable install 差异,才能拿到 90+。

知识点

  • pytest 插件识别顺序:内置 → 第三方包 entry point pytest11 → 命令行 -p → conftest.py 里的 pytest_plugins 列表。
  • pytest_plugins 变量:在 conftest.py 中显式声明需要加载的“本地模块名”,支持相对或绝对导入。
  • 模块可见性:解释器只要能 import,就能被 pytest 当成插件;因此关键是把插件目录加入 sys.path。
  • 三种“不上传 PyPI”的落地方式:
    1. 纯路径追加:临时修改 PYTHONPATH 或 sys.path.insert(0, ...)。
    2. editable 安装:pip install -e . 生成 .pth 文件,不拷贝代码,仍指向本地目录。
    3. 统一项目布局:把插件作为包放在工程内部,顶层 conftest.py 用 pytest_plugins = ['myproj.plugins.xdist_extra'] 声明即可。
  • 版本一致性:CI 流水线里必须保证本地插件目录与测试代码一起被检出,否则会出现“本地能跑、CI 找不到插件”的尴尬。
  • 隔离性:避免插件与业务代码循环 import;推荐插件只依赖 pytest 的 hookwrapper 与 fixture,不依赖业务层。

答案

推荐“项目内嵌包 + pytest_plugins 声明”方案,步骤如下:

  1. 目录结构
    myproj/
    ├─ tests/
    │ └─ conftest.py
    ├─ myproj/
    │ └─ plugins/
    │ ├─ init.py
    │ └─ custom_marker.py # 插件源码
    └─ pyproject.toml

  2. 插件代码(myproj/plugins/custom_marker.py)

    import pytest
    def pytest_configure(config):
        config.addinivalue_line(
            "markers", "slow: marks tests as slow (deselect with '-m \"not slow\"')"
        )
    
  3. 在 tests/conftest.py 中声明

    pytest_plugins = ['myproj.plugins.custom_marker']
    

    不需要任何 sys.path 手动追加,因为 pytest 启动时会把“工程根目录”自动加入 sys.path,myproj 可被直接 import。

  4. 运行
    在项目根执行 pytest -m slow,即可看到自定义 marker 已生效;全程无需打包、无需上传到 PyPI,也不污染全局环境。

  5. CI 适配
    GitHub Actions / GitLab CI 只需 checkout 代码后 pip install -e .(若工程本身有依赖)或直接 pytest,插件随代码一起被加载,保证线上线下行为一致。

拓展思考

  • 如果插件需要跨多个仓库复用,但又暂不上 PyPI,可搭一个私有的 Git pip 源:
    pip install git+ssh://git@your.gitlab.cn/qa/pytest-qt-enhance.git@main
    这样仍符合“本地开发、零上传”,同时避免每个项目都拷贝一份插件源码。
  • 对于 monorepo 场景,可以在顶层 conftest.py 统一 pytest_plugins = ['monorepo.lib.pytest.hooks'],所有子包测试自动继承,实现“一处编写、全库生效”。
  • 若插件需要兼容多套 pytest 版本,可在 pytest_configure 里检查 pytest.version_tuple,动态决定是否注册新 hook,防止老版本报错。