可导入pytest插件结构及共享Fixtures项目重构技术咨询
背景
我有多个项目共用的测试数据和fixtures,打算将其重构为独立项目,供各项目导入使用。原项目结构如下:
my-project/ src/ db/ __init__.py module1.py tests/ data/ test_data.csv test_module1.py
其中test_module1.py包含待重构的fixtures,以及module1.py的单元测试。官方推荐通过pytest插件的方式共享fixtures,并给出了pyproject.toml示例:
# sample ./pyproject.toml file [build-system] requires = ["hatchling"] build-backend = "hatchling.build" [project] name = "myproject" classifiers = [ "Framework :: Pytest", ] [tool.setuptools] packages = ["myproject"] [project.entry_points] pytest11 = [ "myproject = myproject.pluginmodule", ]
同时补充了构建常规包的配置信息:
pyproject.toml配置:
[build-system] requires = ["setuptools", "wheel"] build-backend = "setuptools.build_meta"
setup.cfg配置:
[options.entry_points] pytest11 = test_data = test_data.plugin
我有两个问题需要解答:
- 需将tests/下的fixtures和数据重构至
new-fixture-project/src/test_data/(常规包形式)还是new-fixture-project/tests/? - 无论哪种情况,入口点应如何设置?若已将fixtures重构至
test_data/data.py,是否为new-fixture-project = test_data.data?
问题1:目录结构选择
必须选择new-fixture-project/src/test_data/的常规包形式,原因很明确:
- pytest默认将
tests/目录视为当前项目的测试专属目录,不会被打包分发。如果把共享的fixtures和数据放在这里,其他项目安装该包后完全无法访问这些内容。 - 采用src布局的常规包会被完整打包,其他项目安装后可以直接导入
test_data包,同时能正确访问到包内的测试数据文件(需额外配置资源文件打包规则)。
问题2:入口点设置
核心逻辑
pytest的pytest11入口点需要指向一个包含fixtures定义的模块(模块里可以直接写fixtures,也可以导入其他模块的fixtures),pytest会自动发现并加载该模块中的fixtures。
具体配置
假设fixtures已放在new-fixture-project/src/test_data/data.py中,分两种构建工具场景配置:
场景1:使用Hatchling构建
在pyproject.toml中配置:
[project] name = "new-fixture-project" classifiers = [ "Framework :: Pytest", ] [tool.setuptools] packages = ["test_data"] [project.entry_points] pytest11 = [ "new-fixture-project = test_data.data", ]
这里new-fixture-project是自定义的插件名称(只要全局唯一即可),test_data.data是fixtures所在的模块路径。
场景2:使用Setuptools构建
保留你补充的pyproject.toml配置,然后修改setup.cfg的入口点:
[options.entry_points] pytest11 = new-fixture-project = test_data.data
优化建议
如果fixtures分散在多个模块中,建议创建一个test_data/plugin.py作为统一入口:
# test_data/plugin.py from .data import * from .other_fixtures import *
然后将入口点设为:
# setup.cfg 示例 [options.entry_points] pytest11 = new-fixture-project = test_data.plugin
这种方式更便于维护和扩展。
额外配置:打包测试数据
要确保test_data.csv这类资源文件被打包进安装包,需要添加资源文件配置:
- 若用Hatchling,在
pyproject.toml中添加:
[tool.setuptools.package-data] test_data = ["data/*.csv"]
- 若用Setuptools,在
setup.cfg中添加:
[options.package_data] test_data = data/*.csv
其他项目可以通过importlib.resources安全访问这些资源,示例代码:
from importlib.resources import files data_path = files("test_data.data").joinpath("test_data.csv")
内容的提问来源于stack exchange,提问作者stevew

