1

This question is related to Relative imports with unittest in Python but I would like to specifically ask about the importance of how unittest handles/modifies imports.

Say I have a package structure:

containing_folder/
    project/
        main_program.py
        random_module_a/
            a.py
            a_test.py

a_test.py contains a relative import of a.py like:

import a

To run my unit tests I go to the outer folder and run unittest:

cd project
python -m unittest random_module_a/a_test.py

This does not work and I get the error:

ModuleNotFoundError: No module named 'a' 

However, if I modify the import as follows the test runs fine:

# in `test_a.py`
from random_module_a import a

Why does the relative import (the first version) not work with unittest? I am confused because if I wanted to run a_test as a script then it can import a just fine without the from random_module_a bit.

zephyrus
  • 1,266
  • 1
  • 12
  • 29

1 Answers1

0

To import a.py from the current directory, use:

from . import a

Note that you must do this inside a package.

Ken Kinder
  • 12,654
  • 6
  • 50
  • 70