在VSCODE中使用pytest设置python测试的问题



我试图在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:PATHTOPACKAGENAMEteststest_main.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
C:UsersUSERanaconda3envsunilibimportlib__init__.py:127: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
teststest_main.py:1: in <module>
from PACKAGENAME import *
E   ModuleNotFoundError: No module named 'PACKAGENAME'
=========================== short test summary info ===========================

是否有任何方法可以让这个工作而不必使用命令行?

我建议你这样尝试:

  • 确保你的VS Code工作区被设置为父目录PACKAGENAME
  • 目录(根目录)
  • tests目录
  • 添加一个空的__init__.py文件
  • test_main.py,取代from PACKAGENAME import *from PACKAGENAME.main import *