运行pytest与tox测试Python包时出现ModuleNotFoundError导入错误
故障根因
- 项目采用Python标准
src目录布局,pytest默认运行时不会自动将./src目录加入Python模块搜索路径,导致测试文件导入包失败。 - 你的
setup.py未正确配置包查找规则,缺少find_packages(where="src")和package_dir={"": "src"}配置项,哪怕执行pip install -e .也无法将hello包正确注册到当前环境。 - tox配置中虽然手动加了
pip install -e .命令,但受setup.py配置错误影响,tox虚拟环境内同样没有正确安装目标包,且原有pytest命令参数存在格式错误,进一步影响执行结果。
解决方法
- 修正setup.py配置,确保包可以被正确识别、安装:
from setuptools import setup, find_packages setup( name="hello", version="0.1.0", packages=find_packages(where="src"), package_dir={"": "src"}, # 保留你原本的其他配置项,如作者、license、依赖等 )
- 项目根目录新增
pytest.ini配置文件,显式指定模块搜索路径:
[pytest] testpaths = tests pythonpath = src
- 修正tox.ini配置,优化安装逻辑、修复pytest参数错误:
[tox] envlist = py39 skipsdist = True [testenv] deps = flake8 pytest pytest-cov safety -e . commands = safety check --full-report flake8 --max-line-length=120 --statistics setup.py src/ tests/ pytest -p no:warnings --cov=hello --cov-fail-under=80 --cov-report=term --cov-report=xml --junitxml=report.xml
- 验证修复结果:
- 执行
pip uninstall -y hello清理历史错误安装的包 - 执行
pip install -e .重新安装开发版包 - 执行
pytest即可正常运行测试,执行tox也不会再报模块找不到错误
内容的提问来源于stack exchange,提问作者Skynet
相关产品推荐
相关产品推荐

