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 unittest unable to import other modules

Project level:

├─project_root    
├───application
│   └─── target.py
│   └─── utils.py
├───tests
├   └─── test_*.py

When I run py -m unittest discoveron the CLI from the project_root directory it discovers all tests. However, the tests cannot run as they cannot find the utils.py (the target.py relies on this).

Anyone know how to fix this?

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

>Solution :

This is a scope issue, you need to use relative imports, as test_*.py is located within a folder that doesn’t contain utils.py in its scope.

So, two options, copy utils.py into the directory or use relative imports to find and import the library.

Will update answer with example of relative import when I can find one – its been a while since I’ve had to use them.

EDIT – Found one.
Haven’t tested it, but the generic format for relative import of this nature (using the scope you showed above would be:)

from .application import utils

The dot out the front of "application" : ".application" tells the python interpreter to go one directory back, and locate a module called "application" (that other folder) and then to import the file from there.

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