Import packages inside tests with python

Asked

Viewed 38 times

0

I have a project with the following structure:

__init__.py
setup.py
- convert_keys/
    - __init__.py
    - convert.py
- tests/
    - test_convert_keys.py

Inside my file of tests I tried to import the following way;

from convert_keys import convert

but while trying to run the test file the error below appears;

python tests/test_convert_keys.py

Traceback (Most recent call last): File "tests/test_convert_keys.py", line 3, in from convert_keys import Convert Import: No module named convert_keys

My test file has only one class that inherits unittest.TestCase, what is missing for that file inside tests can import the file into convert_keys?

1 answer

1

Since I don’t know how is the structure of your project the simplest solution is you put its directory in the path of Python. You can do it in two ways. The first is by the environment variable PYTHONPATH:

export PYTHONPATH=$( pwd )
python tests/test_convert_keys.py

The other, by altering your code, would be to add it to the path of the system directly from within the Python.

import sys
sys.path.append('/tmp/project') # no caso o diretório do teu projeto
from convert_keys import convert
  • the structure is exactly what I put in the question friend.

  • opa, I ended up not being clear... I was talking about the contents of the archives __init__.py, setup,py and things like this -- paths reset within setup.py, defining how to load the modules into __init__.py etc..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.