简体   繁体   English

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

[英]Issues setting up python testing in VSCODE using pytest

I am trying to use the testing extension in VSCode with the Python extension.我正在尝试将 VSCode 中的测试扩展与 Python 扩展一起使用。 I am using pytest as my testing library.我使用 pytest 作为我的测试库。 My folder structure looks like this:我的文件夹结构如下所示:

PACKAGENAME/
├─ PACKAGENAME/
│  ├─ __init__.py
│  ├─ main.py
├─ tests/
│  ├─ test_main.py
├─ requirements.txt

In the test_main.py file I am trying to import the package code, in order to test it:test_main.py文件中,我试图导入 package 代码,以便对其进行测试:

from PACKAGENAME import *

From the command line, in the root directory, PACKAGENAME , I can use the command python -m pytest which runs the tests fine.从命令行,在根目录PACKAGENAME中,我可以使用命令python -m pytest运行测试。 There are no issues with modules not being found.找不到模块没有问题。 However, when I try to use the VSCode testing tab, the tests are discovered, but this errors:但是,当我尝试使用 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 ===========================

Is there any way to get this working without having to use the command line?有什么方法可以在不使用命令行的情况下让它工作吗?

I suggest that you try like this:我建议你这样尝试:

  • make sure that your VS Code workspace is set to the parent directory of (the root directory) PACKAGENAME确保您的 VS Code 工作区设置为(根目录) PACKAGENAME目录
  • add an empty __init__.py file in tests directorytests目录中添加一个空的__init__.py文件
  • in test_main.py , replace from PACKAGENAME import * with from PACKAGENAME.main import *test_main.py中,将from PACKAGENAME import *替换为from PACKAGENAME.main import *

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM