使用python时FileNotFoundError-m pytest vs.pytest
我最近将使用的IDE更改为VSCode。在很大程度上我喜欢它,但有一个特别的问题,我似乎无法解决。直到我搬家,我才意识到这是个问题 我的目录结构如下:使用python时FileNotFoundError-m pytest vs.pytest,python,visual-studio-code,pytest,pathlib,Python,Visual Studio Code,Pytest,Pathlib,我最近将使用的IDE更改为VSCode。在很大程度上我喜欢它,但有一个特别的问题,我似乎无法解决。直到我搬家,我才意识到这是个问题 我的目录结构如下: my_app ├── env │ ├── bin │ ├── include │ ├── lib │ ├── lib64 -> lib │ ├── pyvenv.cfg │ └── share ├── my_app │ ├── expected_results │ ├── __init__.py │ ├─
my_app
├── env
│ ├── bin
│ ├── include
│ ├── lib
│ ├── lib64 -> lib
│ ├── pyvenv.cfg
│ └── share
├── my_app
│ ├── expected_results
│ ├── __init__.py
│ ├── test_data
│ └── tests
├── pytest.ini
├── README.rst
├── setup.cfg
└── setup.py
当我启动虚拟环境时,我坐在这个目录结构的根目录下
我通过发出此命令(或提供其他选项)来运行测试。这项工作目前有效:
pytest
但是,当VSCode启动时,它会抛出一个错误,表示找不到预期的文件:
E FileNotFoundError: [Errno 2] No such file or directory: 'my_app/expected_results/expected_available_items.yml'
经过一些调查,我发现这是因为VSCode启动时会发出以下命令:
python -m pytest
我通过以下操作设置该路径:
import pathlib
EXPECTED_RESULTS_BASE = pathlib.Path("my_app/expected_results")
expected_results = EXPECTED_RESULTS_BASE.joinpath('expected_available_items.yml')
我需要修改什么,以便在我发出pytest
命令时,我的测试将继续运行,并且在我(或我的IDE)发出python-m pytest
时运行
我希望可以安全地假设VSCode是从
我的应用程序的根目录启动的,就像我一样?可能没有足够的信息来直接回答这个问题,但是让我们尝试一下:
- 在测试代码中,在出现错误的行的上方插入一些类似的行,看看它们是否打印出您期望的内容
- 由于您使用的是venv,并且错误是使用不同的命令调用pytest的结果,请尝试使用
which
查看您是否实际调用了不同的东西。激活venv之前和之后:
python-m pytest
将调用与刚才调用的python版本一起安装的pytest模块。如果python
调用的版本与您在venv中从pytest
获得的版本不同,那么这可能就是问题所在
通过查看文件顶部的hashbang,您应该能够检查pytest正在调用哪个python版本
head -1 $(which pytest)
在安装了anacondapython的macOS系统上,我从这些命令中获得以下信息
$ which pytest
/Users/Shannon/anaconda/bin/pytest
$ which python
/Users/Shannon/anaconda/bin/python
$ head -1 $(which pytest)
#!/Users/Shannon/anaconda/bin/python
这告诉我,pytest
正在调用与我调用python
时得到的相同版本的python。同样地,pytest
和python-m pytest
应该在我的默认环境中产生同样的结果
在运行测试之前,您确定VSCode正确加载了venv吗?假设您在VS代码中为Python解释器选择了一个虚拟环境:
在VS代码中打开终端
让虚拟环境激活
运行python-mpipinstallpytest
这将把pytest安装到虚拟环境中,这就是为什么python-m
失败的原因(在您路径上的pytest全局安装在虚拟环境无法访问的一些全局python安装中)。使用与模块相关的路径,例如预期结果\u BASE=pathlib.PATH(\uuuu文件\uuuu,“…”,“预期结果”).absolute()
。如何确保VS代码正确加载我的venv(通过powershell在Windows10上使用VirtualEnvrapper)?我的问题与OP相同,但反过来说:当使用pytest
时,它抛出modulenotfounderror
,但当使用python-m pytest
时,它的工作非常有魅力。我已经用我的全局环境和我的venv检查并安装了pytest。如果你能看一下,我的问题是,我已经提交了一个好吧,因为它似乎更复杂:我自己解决了它,它只是test文件夹中缺少的一个\uuuu init\uuuuuuuuuuuuupy
,这在某些设置中似乎需要pytest
,而unittest
中的\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuupy.py
只需要位于被测试模块所在的文件夹中:
head -1 $(which pytest)
$ which pytest
/Users/Shannon/anaconda/bin/pytest
$ which python
/Users/Shannon/anaconda/bin/python
$ head -1 $(which pytest)
#!/Users/Shannon/anaconda/bin/python