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?
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)
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.
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.
#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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With