Python ModuleNotFoundError when importing a package

Viewed 65

I getting and error when I try to import a package from another folder. I have the folowing:

project  
|  
|-- main.py  
|  
|-- lib  
|   |-- __init__.py
|   |-- main_class.py
|   |-- global_functions.py
|   |-- cg_api_simple
|   |-- cg_api_status
|  
|-- tests    
    |-- __init__.py  
    |-- test_main_class.py  

Where my lib/__init__.py has:

from lib.main_class import PyGecko

and my test/__init__.py is empty.

When I run python3 -m unittest test_main_class.py I get:

======================================================================
ERROR: test_main_class (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: test_main_class
Traceback (most recent call last):
  File "/usr/lib/python3.8/unittest/loader.py", line 154, in loadTestsFromName
    module = __import__(module_name)
  File "/home/someone/Documents/pythoncoingecko/tests/test_main_class.py", line 1, in <module>
    from lib import PyGecko
ModuleNotFoundError: No module named 'lib'


----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)

I've already tried:

  • Add /project and /project/lib to my PYTHONPATH
  • Use sys before import
  • Add .. before the import
  • Try to remove __init__.py from both folders

The only time I don't get an error is when I move test_main_class.py to where main.py is located. How could I solve this? You can see more on github

https://github.com/SrJMaia/pythoncoingecko

Thanks

1 Answers

All you need is a proper combination of your current working directory, the PYTHONPATH environment variable and the path to the test.

If you run python3 -m unittest test_main_class.py from the tests directory, you need to add the project directory to PYTHONPATH. I.e.:

$ PYTHONPATH=.. python3 -m unittest test_main_class.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
$ PYTHONPATH=/tmp/project python3 -m unittest test_main_class.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

Or you can run python3 -m unittest tests/test_main_class.py from the project directory. In that case, you do not need to modify PYTHONPATH. I.e.

$ python3 -m unittest tests/test_main_class.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
Related