Home > other >  Issues setting up python testing in VSCODE using pytest
Issues setting up python testing in VSCODE using pytest

Time:10-10

I am trying to use the testing extension in VSCode with the Python extension. I am using pytest as my testing library. 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:

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. 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:

=================================== 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?

CodePudding user response:

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
  • add an empty __init__.py file in testsdirectory
  • in test_main.py, replace from PACKAGENAME import * with from PACKAGENAME.main import *
  • Related