Reputation: 673
I am using Python unittest integrated in VSCode for test. I have directory like this
project_root/
src/
module/
__init__.py
a.py
test/
module/
__init__.py
test_a.py
The test_a.py
has import from module.a import SomeClass
And I have args
"-v",
"-s",
"./test",
"-p",
"test*.py"
When run test discovery it fails and raises ModuleNotFound
or Can not import
the module or classes in a.py
PS: I have set the PYTHONPATH
in settings.json
and both code analysis and program launch works fine. But it seems does not help with unittest
plugin. And one concern is that both src
, test
has the module named module
and I am not sure this matters.
How to make it work?
Update: Seems it is a name conflict issue and unittest_discovery could not handle this. After I change the args to -s ./test/module
it could import the src modules.
Upvotes: 2
Views: 4078
Reputation: 41
Maybe it will be useful for someone else. I deep dive into the source code of the python extension and it is revealed that there is an additional argument --top-level-directory
/ -t
which isn't mentioned in VS Code documentation.
So providing argument -t .
to the settings.json
file solved the issue in my case.
{
...,
"python.testing.unittestArgs": [
"-v",
"-t",
".",
"-s",
"./test",
"-p",
"test_*.py"
]
}
As a result, command generated by the extension will look like this:
ms-python.python-2023.20.0/pythonFiles/unittestadapter/discovery.py --udiscovery -v -t . -s ./test -p test_*.py
Using PYTHONPATH
environment variable didn't help as was already mentioned in one of the commentaries to the accepted answer.
Upvotes: 3
Reputation: 8431
You need to configure the PYTHONPATH
in the .env
file.
An example of when to use PYTHONPATH would be if you have source code in a src folder and tests in a tests folder. When running tests, however, those tests can't normally access modules in src unless you hard-code relative paths.
To solve this problem, you could add the path to src to PYTHONPATH by creating an .env file within your VS Code workspace.
PYTHONPATH=src
Because
When the terminal settings are used, PYTHONPATH affects any tools that are run within the terminal by a user, as well as any action the extension performs for a user that is routed through the terminal such as debugging. However, in this case when the extension is performing an action that isn't routed through the terminal, such as the use of a linter or formatter, then this setting will not have an effect on module look-up.
You can refer to the official docs for more details.
Upvotes: 6