Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting ImportError when running nosetests

my_project
    -my_project
        - __init__.py
        - main.py
        - constants.py
        -test
            - __init__.py
            - test_main.py

test_main.py from my_project import main

main.py import constants

When I run nosetests in my_project, I end up getting ImportError: No module named 'constants'

Both __init__.py files are blank.

If I change import constants to from my_project import constants in main.py, nosetests work. However, now if I just run python main.py I get ImportError: No module named 'my_project'.

Can someone help me point out what I'm doing wrong? I've searched quite a few posts but I haven't been able to fix it myself. Thanks.

like image 705
koreebay Avatar asked Nov 17 '15 18:11

koreebay


1 Answers

In main.py -> import constants is an implicit relative import (bad). It should be changed to the more usual from my_project import constants.

You mentioned this makes nosetests work. Note: you don't need the __init__.py in the tests sub-directory, and in fact this is usually discouraged.

Now to fix your error with python main.py having an import error, well that is normal if you haven't included it in your sys.path. There are various ways around this -

  • execute from the project root directory (i.e. the uppermost my_project one)
  • set the PYTHONPATH environment variable
  • properly package and install your app using setuptools / easy_install etc
like image 165
wim Avatar answered Oct 31 '22 13:10

wim