Search code examples
pythonunit-testingvisual-studio-codedependencies

python: import class from a different subfolder in the parent folder (tests)


I moved my tests to a separate subfolder in the project, and now testing my classes does not work anymore.

|--  project
|   |main.py
|   |-- lib
|   |   |__init__.py
|   |   |myclass.py
|   |-- tests
|   |   |__init__.py
|   |   |test_myclass.py

Both init files are empty.

but when I run the test (i'm in the tests folder and typing python -m unittest) I get the following error:

ModuleNotFoundError: No module named 'lib'

at the line from lib.myclass import Myclass

I also saw that one could use sys and os to add the parent folder to the path, but each time that I do it, the code that adds it is automatically going under all the imports in vscode (I guess due to some automatic formatting?) and therefore is not ran on time.


Solution

  • That's because once you are in tests folder your working directory dir is:

    .\
    .\test_mycalss.py
    

    You should run tests from project so your working directory will cover whole tree:

    .\
    .\main.py
    .\lib\
    and so on
    

    Your project cannot view lib.myclass because in folder tests there is no folder lib.