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:
JavaScript
x
8
1
PACKAGENAME/
2
├─ PACKAGENAME/
3
│ ├─ __init__.py
4
│ ├─ main.py
5
├─ tests/
6
│ ├─ test_main.py
7
├─ requirements.txt
8
In the test_main.py
file I am trying to import the package code, in order to test it:
JavaScript
1
2
1
from PACKAGENAME import *
2
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:
JavaScript
1
12
12
1
=================================== ERRORS ====================================
2
_____________________ ERROR collecting tests/test_main.py _____________________
3
ImportError while importing test module 'd:PATHTOPACKAGENAMEteststest_main.py'.
4
Hint: make sure your test modules/packages have valid Python names.
5
Traceback:
6
C:UsersUSERanaconda3envsunilibimportlib__init__.py:127: in import_module
7
return _bootstrap._gcd_import(name[level:], package, level)
8
teststest_main.py:1: in <module>
9
from PACKAGENAME import *
10
E ModuleNotFoundError: No module named 'PACKAGENAME'
11
=========================== short test summary info ===========================
12
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 intests
directory - in
test_main.py
, replacefrom PACKAGENAME import *
withfrom PACKAGENAME.main import *