Problem
I cannot get VSCode/unittest to recognize submodules (i.e., common.nested_module
in the example in background) that I wrote unittests for.
VSCode discovers the tests cases and executes those in test_my_module.py
but complains that there is no module common.nested_module
on the import
statement line in test_nested_module.py
(in Output: ModuleNotFoundError: No module named 'common.nested_module'
).
I added print(sys.path)
to the executed test case and in Python Test log I even get the following output when adding .env
file as described below in What I tried 2.:
test_get_version (test_my_module.TestCase1) ... ['/workspaces/test_project/project/tests', '/workspaces/test_project/project/src', '/workspaces/test_project/project/common', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/home/vscode/.local/lib/python3.9/site-packages', '/usr/local/lib/python3.9/site-packages']
Background
Following the PyPA tutorial for packaging and distribution I created a project structure, leaving out other details (e.g., README.md
), as follows:
project
|--src
|--common
|-- __init__.py
|-- nested_module.py
|-- __init__.py
|-- my_module.py
|--tests
|--__init__.py
|--test_my_module.py
|--test_nested_module.py
Settings related to testing in settings.json
:
{
"python.testing.unittestArgs": [
"-v",
"-s",
"${workspaceFolder}/project/tests",
"-p",
"test_*.py"
],
"python.testing.cwd": "project/src",
"python.testing.pytestEnabled": false,
"python.testing.unittestEnabled": true,
}
What I tried
- Adding the following to my
__init__.py
inproject/tests
as well as totest_nested_module.py
as suggested here.
import os
import sys
PROJECT_PATH = os.getcwd()
SOURCE_PATH = os.path.join(
PROJECT_PATH,"project/src/common"
)
sys.path.append(SOURCE_PATH)
- Adding an
.env
toproject
containing the following while adding"python.envFile": "${workspaceFolder}/afinad/.env"
tosettings.json
similar to what was suggested here.
PYTHONPATH = ./common
- Adding
-t
option with${workspaceFolder}/project/src
and.
tosettings.json
forpython.testing.unittestArgs
as sggested here:
"python.testing.unittestArgs": [
"-v",
"-s",
"${workspaceFolder}/project/tests",
"-p",
"test_*.py",
"-t",
"${workspaceFolder}/project/src"
],
- Running
python3 -m unittest discover
after changing into./tests
in terminal gives me:
ModuleNotFoundError: No module named 'my_module'
Thanks for taking time to read. Any help is much appreciated!