Search code examples
pythonpython-unittest

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?


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.