如何通过Github Actions同时测试Python父仓库及其Git子模块
问题原因
- Github Actions 默认的
checkout动作不会自动拉取Git子模块,子模块目录为空自然无法导入对应模块 - 子模块单独执行测试时,Python的模块搜索路径默认不包含子模块的上级目录,
from my_submodule.my_module import MyClass的导入规则无法匹配路径
修复步骤
1. 修改Github Actions配置,拉取全量子模块
修改父仓库.github/workflows/pytest.yml中的checkout步骤,添加子模块拉取参数:
- uses: actions/checkout@v4 with: submodules: 'recursive' # 递归拉取所有子模块 fetch-depth: 0
如果子模块自己的Actions也要单独跑测试,同步修改子模块内的pytest.yml的checkout步骤即可。
2. 兼容子模块单独测试的导入路径
两种方案选其一即可,保证from my_submodule.my_module import MyClass的导入格式在父仓库、子模块单独测试两个场景都生效:
方案A:修改子模块的conftest.py
在my_submodule/conftest.py中添加如下代码,自动将上级目录加入Python搜索路径:
import sys from pathlib import Path # 将子模块的上级目录加入模块搜索路径 sys.path.insert(0, str(Path(__file__).parent.parent.resolve()))
方案B:配置pytest默认参数
在my_submodule目录下新建pyproject.toml,添加pytest全局配置:
[tool.pytest.ini_options] pythonpath = [".."]
验证方法
- 父仓库根目录执行
python -m pytest,父子模块所有测试通过 - 进入
my_submodule目录执行python -m pytest,子模块测试通过 - 推送代码触发Github Actions,测试任务正常运行通过
内容的提问来源于stack exchange,提问作者stefano
相关产品推荐
相关产品推荐

