Python unittest failing to resolve import statements

Question:

I have a file structure that looks like the following

project
    src
        __init__.py
        main.py
        module.py
        secondary.py
    test
        test_module.py        

module.py

import secondary
x = False

secondary.py

pass

test_module.py

from unittest import TestCase

from src import module

 class ModuleTest(TestCase):
    def test_module(self):
        self.assertTrue(module.x)

Invoking python3 -m unittest discover in /project/ gives an error:

 File "/Users/Me/Code/project/test/test_module.py", line 6, in <module>
  from src import module
 File "/Users/Me/Code/project/src/module.py", line 1, in <module>
  import secondary
ImportError: No module named 'secondary'

What can I do so that secondary.py is imported without error?

Asked By: Max Bo

||

Answers:

In Python 3 (and Python 2 with from __future__ import absolute_import), you must be explicit about what module you want when importing another module from the same package. The syntax you’re using in module.py (import secondary) only works if secondary is a top-level module in a folder in the Python module search path.

To explicitly request a relative import from your own package, use from . import secondary instead. Or, make an absolute import, using the name of the package as well as the module (from src import secondary, or import src.secondary and use src.secondary elsewhere the module instead of just secondary).

Answered By: Blckknght

Try adding this to the top of the test file

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

Note: Depending on the project structure we have to specify the root folder

Answered By: u_1