Plopp
Plopp

Reputation: 977

unittest error when importing from different directory

I've been trying to use unittest in my latest project but I have some difficulties with the imports.

I've managed to import the script I want to test successfully but this script fails when it comes to its own imports.

My folder is structured as:

Project
 |
 +-- src
 |   |
 |   +-- __init__.py
 |   +-- script1.py
 |   +-- script2.py
 |
 +-- test
  |  |
  |  +-- __init__.py
  |  +-- test_script1.py

The script1.py contains:

#!/usr/bin/env python3.6
# -*- encoding: utf-8 -*-
"""
    This is the script I want to run tests on
"""
import networkx as nx  # works just fine
from script2 import blablabla  # does not work when called from unittest

and this is what my test_script1.py look like:

#!/usr/bin/env python3.6
# -*- encoding: utf-8 -*-

import unittest
import networkx as nx
import src.script1

When I'm trying to run the tests using this command ~/Project$ python -m unittest discover I get a ModuleNotFoundError: No module named 'script2'.

If I change in script1.py to from .script2 import blablabla then unittests runs just fine but script1.py alone (not using unittest) is not anymore since it can not find script2.

Any idea how I can solve this ?

Upvotes: 2

Views: 744

Answers (1)

Will Keeling
Will Keeling

Reputation: 23054

An alternative is to keep your imports and packages as they are, but just set the PYTHONPATH before running the test.

PYTHONPATH=$PYTHONPATH:src python -m unittest discover

Upvotes: 2

Related Questions