GitHub Actions执行coverage run -m pytest遇ModuleNotFoundError的原因与解决
Python项目在GitHub Actions中模块导入失败的问题解决
项目结构
├─ src/ │ ├─ sample/ │ │ ├─ __init__.py │ │ ├─ simple.py ├─ tests/ │ ├─ __init__.py │ ├─ test_simple.py
GitHub Actions配置
- uses: actions/setup-python@v4 with: python-version: '3.11' - name: Install dependencies run: | python -m pip install --upgrade pip pip install pytest coverage - name: Run test run: | coverage run -m pytest . coverage xml
错误信息
Run coverage run -m pytest . ============================= test session starts ============================== platform linux -- Python 3.11.6, pytest-7.4.3, pluggy-1.3.0 rootdir: /home/runner/work/openapi-splitter/openapi-splitter collected 0 items / 1 error ==================================== ERRORS ==================================== ____________________ ERROR collecting tests/test_simple.py _____________________ ImportError while importing test module '/home/runner/work/openapi-splitter/openapi-splitter/tests/test_simple.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /opt/hostedtoolcache/Python/3.11.6/x64/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_simple.py:7: in <module> from sample.simple import add_one E ModuleNotFoundError: No module named 'sample' =========================== short test summary info ============================ ERROR tests/test_simple.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.11s ===============================
错误原因
本地环境中,Python解释器默认将项目根目录或src目录加入了模块搜索路径(sys.path),所以能正常导入sample模块。但GitHub Actions的Linux runner环境中,不会自动把src目录添加到sys.path,测试代码里的from sample.simple import add_one找不到位于src/sample下的模块,因此抛出ModuleNotFoundError。
解决方法
方法1:安装项目为可编辑模式
在依赖安装步骤中,添加项目的可编辑安装命令,这样会把src下的包注册到Python的模块搜索路径:
- name: Install dependencies run: | python -m pip install --upgrade pip pip install pytest coverage pip install -e .
注:此方法需要项目根目录存在setup.py或pyproject.toml配置文件,用于定义包结构。
方法2:手动设置PYTHONPATH环境变量
在测试运行步骤中,将src目录添加到PYTHONPATH:
- name: Run test run: | export PYTHONPATH="$PYTHONPATH:./src" coverage run -m pytest . coverage xml
方法3:使用pytest配置文件指定模块路径
在项目根目录创建pytest.ini文件,内容如下:
[pytest] pythonpath = src
将该文件提交到仓库后,GitHub Actions中的pytest会自动读取配置,把src目录加入模块搜索路径,无需修改Actions命令。
内容的提问来源于stack exchange,提问作者Petra Barus
相关产品推荐
相关产品推荐

