简体   繁体   中英

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 discover on 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM