Skip to content
Advertisement

Issues setting up python testing in VSCODE using pytest

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

Is there any way to get this working without having to use the command line?

Advertisement

Answer

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 *
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement