Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does import work with Python nose when test directory contains __init__.py?

Tags:

python

nose

Consider the following project structure:

a.py
test/
  test_a.py

with test_a.py importing module a:

import a

As expected, running nosetests in the test directory results in import error:

ERROR: Failure: ImportError (No module named a)

However, I noticed that adding an empty __init__.py file to the test directory makes import work with nosetests (but not when you run test_a.py with Python). Could you explain why?

I understand that adding __init__.py makes test a package. But does it mean that import includes the directory containing the package in the lookup?

like image 535
vitaut Avatar asked Jun 05 '15 17:06

vitaut


People also ask

How to run tests using nose framework in Python?

As the Nose module is installed for the existing Python distribution as well as nosetests.exe, tests using Nose framework can be executed by triggering either of the following commands: Like other Python automation frameworks, Nose also automatically executes all the tests that are present in the parent folder (and its sub-folders)

Do I need __init__ Py for import?

To be clear - this is python-level stuff, not pants specific. You'd need that __init__.py for the given import using plain old python with a PYTHONPATH of src/python:tests/python too. Sorry, something went wrong. I do have src/python/project/__init__.py. Thanks for the help! Sorry, something went wrong.

Is it intentional that all test targets don't have init Pys?

For twitter/common, I found that all the test targets are not having init .pys. Is it intentional? ~Yes. Packages are not needed for tests since they generally only import production code.

How to fix importerror no module named in Python?

#1. ImportError No Module Named If you want to import module in the same folder, it’s highly because of type error. Therefore, please check if there are some typo first. If you want to import module in sub folder, then please check if the sub folder is claimed as package, which means check if there is __init__.py file in the folder. #2.


1 Answers

The presence of an __init__.py file in the directory transforms test from just a plain old directory into a python package. This has an effect on sys.path.

Modify your test_a.py module like this:

import sys

def test_thing():
    for i, p in enumerate(sys.path):
        print i, p

try:
    import a
except ImportError:
    print('caught import error')

Then try running nosetests -s from the test directory, with and without an __init__.py in there.

Note: it is the test runner that munges sys.path. And that is documented in the second "Note" of this section here (thanks @davidism). You won't see any change there just by running python test_a.py with and without the package structure.

like image 156
wim Avatar answered Oct 19 '22 21:10

wim