0

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 ?

Plopp
  • 855
  • 7
  • 16

2 Answers2

1

Remove __init__.py from your tests directory and leave the rest of your code as-is. Having one in there is actually discouraged: https://stackoverflow.com/a/30167059/769971

Trying it out locally with that fixes it for me.

EDIT: I should also mention that, like the linked answer, you'll have to modify your python path to include the module you're testing. That, or use something like nose which will figure it all out for you.

wholevinski
  • 3,373
  • 16
  • 21
1

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
Will Keeling
  • 19,819
  • 4
  • 48
  • 55