Skeleton Directory: Why does script fail when nosetests returns no errors?

156 Views Asked by At

(Using bash command line, Python 2.7.12 on Debian Linux.)

Following Zed Shaw's LPTHW, I built a project skeleton that helps with testing software. First, the outline.

The setup:

    bin  docs  first_project  setup.py  tests

./bin:

./docs:

./first_project:
__init__.py  wasp.py

./tests:
first_project_tests.py  __init__.py

Contents of wasp.py:

def paint(color):
    print color * 10

Contents of first_projects_tests.py:

from nose.tools import *
from first_project import wasp

def test_paint():
    wasp.paint("blue")

Per my understanding of Zed Shaw's explanation, the __init__.py in the first_project directory tells Python that the files in it can be imported as modules. Thus the script first_project_tests.py in the test directory imports the wasp.py module from the first_project directory and calls the paint function from it.

Following Shaw's directions, I ran nosetests from above the tests directory and I got an ok with zero errors.

I then changed into the tests directory and typed python first_project_tests.py from the command line, assuming that I'd be able to run the script with no issues as the nosetests command gave no errors.

I got the following error:

Traceback (most recent call last):
  File "first_project_tests.py", line 2, in <module>
    from first_project import wasp
ImportError: No module named first_project

So why does the first_project_tests.py script fail when nosetests returns no errors?

1

There are 1 best solutions below

0
On BEST ANSWER

Python imports work relative from the module search path. The current directory is automatically included on this path.

When you run the nosetests at the top level of your project, the first_project module with wasp inside is found at the relative path, since first_project/wasp.py exists relative from the execution directory.

When you go inside tests and try to run first_project_tests.py, the import statement fails because the relative path first_project/wasp.py doesn't exist from inside that directory.

You could run from the project root like this:

python tests/first_project_tests.py