VSCODE pytest不与命令行pytest相同地构建sys.path

问题描述

使用VSCODE python扩展运行pytest时,出现导入错误。从命令行运行pytest时,我没有收到错误消息。

我有一个具有以下设置的python 2.7项目。

provision/
|-- venv/
|-- requirements.txt
|-- model_config/
|   |-- ifrs9model_config/
|   |-- |-- __init__.py
|   |-- |-- model_config.py
|   |
|   |-- data/
|   |   |-- input.csv
|   | 
|   |-- tests/
|   |   |--conftest.py
|   |   |--test_model_config.py
|   |   
|   |-- setup.py
|   |-- README

我已将软件包ifrs9model_config安装到venv中。这样,我就可以将conftest.py文件中的ifrs9model_config导入如下:

from ifrs9model_config import model_config

当我直接运行conftest.py时,它可以正常工作。当我从命令行运行pytest时(激活venv之后),它也可以正常工作。但是,当我使用VSCODE的python扩展名运行pytest时,出现错误

ImportError while loading conftest '/sasdata/Lev3/apps/provision/model_config/tests/conftest.py'.
tests/conftest.py:6: in <module>
    from ifrs9model_config import model_config
E   ImportError: No module named ifrs9model_config

vscode pytest运行以下命令:

python /home/<userid>/.vscode-server-insiders/extensions/ms-python.python-2020.10.332292344/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir /sasdata/Lev3/apps/provision/model_config -s --cache-clear tests

具有打印的sys.path(主要来自conftest.py脚本),我注意到VSCODE运行pytest时,sys.path中不包含pytest rootdir(/ sasdata / Lev3 / apps / provision / model_config)。但是,当我使用以下命令从命令行运行pytest时,它会包括在内:

pytest --rootdir /sasdata/Lev3/apps/provision/model_config/ -s --cache-clear tests

run_adapter.py脚本确实将一些目录插入sys.path值,但这不能解释为什么缺少上面的内容

现在,如果我将这样的一行添加到conftest.py文件中:

sys.path.append('/sasdata/Lev3/apps/provision/model_config/')

它在VSCODE中工作。

对此我特别困惑,因为我认为通过使用setup.py和'pip install -e'将ifrs9model_config软件包安装到venv中,该模块将可用于venv中的任何python会话吗?

我还读到,搞乱sys.path是一种不好的形式,无论哪种方式,我都不希望将代码添加到脚本中只是为了帮助VSCODE运行。

为什么从VSCODE与命令行执行pytest时,sys.path会有所不同?解决我的错误的最佳方法是什么?

解决方法

我刚刚在基于 devcontainer 的 Python 项目中遇到了同样的问题,并通过配置插件使用的 pytest 可执行文件(在 .vscode/settings.json 中)解决了这个问题:

{
  "python.testing.pytestPath": "/usr/local/bin/pytest"
}