'Python unittest discovery can not import source code

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.



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Steven-MSFT