使用 pytest 在 VSCODE 中设置 python 测试的问题
Issues setting up python testing in VSCODE using pytest
我正在尝试将 VSCode 中的测试扩展与 Python 扩展一起使用。我正在使用 pytest 作为我的测试库。我的文件夹结构如下所示:
PACKAGENAME/
├─ PACKAGENAME/
│ ├─ __init__.py
│ ├─ main.py
├─ tests/
│ ├─ test_main.py
├─ requirements.txt
在 test_main.py
文件中,我试图导入包代码,以便对其进行测试:
from PACKAGENAME import *
从命令行,在根目录 PACKAGENAME
中,我可以使用运行测试的命令 python -m pytest
。找不到模块没有问题。但是,当我尝试使用 VSCode 测试选项卡时,发现了测试,但出现以下错误:
=================================== ERRORS ====================================
_____________________ ERROR collecting tests/test_main.py _____________________
ImportError while importing test module 'd:\PATH\TO\PACKAGENAME\tests\test_main.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
C:\Users\USER\anaconda3\envs\uni\lib\importlib\__init__.py:127: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
tests\test_main.py:1: in <module>
from PACKAGENAME import *
E ModuleNotFoundError: No module named 'PACKAGENAME'
=========================== short test summary info ===========================
有什么方法可以在不使用命令行的情况下让它工作吗?
我建议你这样尝试:
- 确保您的 VS Code 工作区设置为(根目录)
PACKAGENAME
的 parent 目录
- 在
tests
目录 中添加一个空的__init__.py
文件
- 在
test_main.py
中,将 from PACKAGENAME import *
替换为 from PACKAGENAME.main import *
我正在尝试将 VSCode 中的测试扩展与 Python 扩展一起使用。我正在使用 pytest 作为我的测试库。我的文件夹结构如下所示:
PACKAGENAME/
├─ PACKAGENAME/
│ ├─ __init__.py
│ ├─ main.py
├─ tests/
│ ├─ test_main.py
├─ requirements.txt
在 test_main.py
文件中,我试图导入包代码,以便对其进行测试:
from PACKAGENAME import *
从命令行,在根目录 PACKAGENAME
中,我可以使用运行测试的命令 python -m pytest
。找不到模块没有问题。但是,当我尝试使用 VSCode 测试选项卡时,发现了测试,但出现以下错误:
=================================== ERRORS ====================================
_____________________ ERROR collecting tests/test_main.py _____________________
ImportError while importing test module 'd:\PATH\TO\PACKAGENAME\tests\test_main.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
C:\Users\USER\anaconda3\envs\uni\lib\importlib\__init__.py:127: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
tests\test_main.py:1: in <module>
from PACKAGENAME import *
E ModuleNotFoundError: No module named 'PACKAGENAME'
=========================== short test summary info ===========================
有什么方法可以在不使用命令行的情况下让它工作吗?
我建议你这样尝试:
- 确保您的 VS Code 工作区设置为(根目录)
PACKAGENAME
的 parent 目录
- 在
tests
目录 中添加一个空的 - 在
test_main.py
中,将from PACKAGENAME import *
替换为from PACKAGENAME.main import *
__init__.py
文件