迁移setuptools test至tox:解决源码目录模块导入问题
解决tox扁平布局包导入路径问题
问题根源
扁平布局的项目中,Python会自动将当前工作目录(项目根)加入sys.path。运行测试时,pytest会优先导入项目根下的mymodule纯Python代码,但这个目录里没有编译生成的_api扩展模块——编译后的模块仅存在于tox虚拟环境的site-packages目录中,因此出现ModuleNotFoundError。
解决方案
方案1:切换测试工作目录至tox临时环境
修改tox.ini的[testenv]段,将工作目录切换到tox虚拟环境的临时目录,同时指定测试目录的绝对路径:
[testenv] description = run the tests with pytest package = wheel wheel_build_env = .pkg deps = pytest changedir = {envtmpdir} commands = pytest {tty:--color=yes} {toxinidir}/tests
{envtmpdir}是tox内置变量,指向当前虚拟环境的临时目录,该目录不包含项目根的mymodule,Python会自动从虚拟环境的site-packages导入已安装的完整包(含编译模块)。
方案2:使用pytest的--no-pythonpath选项
通过pytest参数禁止自动添加项目目录到sys.path,强制依赖虚拟环境的路径:
[testenv] description = run the tests with pytest package = wheel wheel_build_env = .pkg deps = pytest commands = pytest {tty:--color=yes} --no-pythonpath tests
此选项会让pytest完全使用虚拟环境的sys.path,确保导入的是已安装到虚拟环境的包。
方案3:清空PYTHONPATH环境变量
在[testenv]中设置PYTHONPATH为空,避免Python加载项目根目录的模块:
[testenv] description = run the tests with pytest package = wheel wheel_build_env = .pkg deps = pytest set_env = PYTHONPATH= commands = pytest {tty:--color=yes} tests
清空PYTHONPATH后,Python仅会加载虚拟环境默认的sys.path,不会包含项目根目录。
验证方法
可以临时添加命令打印sys.path,确认项目根目录已被排除:
commands = python -c "import sys; print('\n'.join(sys.path))" pytest {tty:--color=yes} --no-pythonpath tests
运行tox run后检查输出,确保虚拟环境的site-packages在路径中,且项目根目录不在列表内。
内容的提问来源于stack exchange,提问作者Balatous
相关产品推荐
相关产品推荐

