Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading