kovac
kovac

Reputation: 5389

What is the correct way to import modules/packages for Python projects with unit tests?

I have the following directory structure:

|_ director_script.py
|_ app/
      |_ __init__.py
      |_ ParentClass.py
      |_ my_module/
                 |_ __init__.py
                 |_ MyClass.py
                 |_ MyClassTestCase.py

In my director_script.py I use MyClass and when I run python director_script.py the scripts run as expected without any error. However, when I cd into my_module folder and run the unit tests using python -m unittest MyClassTestCase, I get the error:

ModuleNotFoundError: No module named 'app'

This caused by the import statement in MyClass.py that is

from app.ParentClass import ParentClass

This import is fine when I run it from director_script.py and only happens with the unit test.

Upvotes: 0

Views: 46

Answers (3)

uwain12345
uwain12345

Reputation: 386

A bit of a kludge, but this is how I usually do it:

import sys
sys.path.append('../app')

Or under Windows:

sys.path.append('..\\app')

This needs to come before your module import, of course.

Upvotes: 0

vumaasha
vumaasha

Reputation: 2845

You should run from outside the app folder, any folder that has an __init__.py is a submodule in python. If you set the current working directory to my_module, it cannot see the app module, unless you have the folder path corresponding to the app folder set in the PYTHONPATH environment variable

Upvotes: 2

CBen
CBen

Reputation: 13

Add a file called __init__.py into the top floder

Upvotes: 0

Related Questions