Pytest非根目录定义插件报错,求解决方案
解决pytest非根目录插件定义错误的方案
方案1:统一在根目录加载公共插件
删掉test1、test2子目录conftest.py里的import common_conftest和pytest_plugins = "common_conftest",然后在根目录新建conftest.py,内容如下:
import common_conftest pytest_plugins = ["common_conftest"]
这样不管从根目录还是子目录运行测试,pytest都会从根目录的conftest加载公共插件,不会触发非根目录定义插件的限制。子目录的conftest只保留各自业务相关的fixture即可。
方案2:把公共插件改成标准可安装插件
把根目录的common_conftest改成符合pytest规范的可安装插件:
- 根目录新建
pytest_myplugin文件夹,把common_conftest.py里的内容移到该文件夹下的plugin.py,并添加空的__init__.py。 - 根目录创建
setup.py,内容示例:
from setuptools import setup setup( name="pytest-myplugin", packages=["pytest_myplugin"], entry_points={ "pytest11": [ "myplugin = pytest_myplugin.plugin", ] }, )
- 执行
pip install -e .安装本地开发版插件。 - 子目录的conftest.py不再需要导入公共插件,直接通过pytest的插件机制自动加载,或者在需要时用
pytest_plugins = ["pytest_myplugin"]声明。
这种方式彻底遵循pytest插件规范,完全规避目录结构带来的问题。
方案3:运行时指定根目录参数
从根目录运行子目录测试时,加上--rootdir参数指定根目录,比如:
pytest test1/ --rootdir=.
这样pytest会将根目录识别为配置根,子目录conftest里的插件导入操作就不会被判定为非根目录定义插件。
方案4:动态判断加载插件(临时 workaround)
修改子目录conftest.py的逻辑,只在当前运行目录是子目录本身时加载公共插件:
import os current_dir = os.path.abspath(os.curdir) conftest_dir = os.path.dirname(os.path.abspath(__file__)) if current_dir == conftest_dir: import common_conftest pytest_plugins = ["common_conftest"]
这种方式属于临时解决手段,不如前两种方案规范,适合快速应急处理。
内容的提问来源于stack exchange,提问作者user20663427
相关产品推荐
相关产品推荐

