I'm new to Python and having some trouble understanding importing modules into Pytest. I solved the problem using Python 2.7 (through much searching and not much understanding). I've now switched to using Python 3.4 in a virtualenv.
My directory structure is (based this on http://pytest.org/latest/goodpractises.html):
-root
-Extractor
Extractor.py
-test
test_extractor.py
.
# test_extractor.py
import Extractor # I assume this is where I'm going wrong
import Extractor.Extractor # Or this?
I've tried running py.test
and py.test tests/test_extractor.py
both from the root directory. The test runs in both cases, and gives the error:
E ImportError: No module named 'Extractor'
Running py.test
gives the following info:
platform darwin -- Python 3.4.2 -- py-1.4.30 -- pytest-2.7.2
rootdir: /my/user/path/root
Running py.test tests/test_extractor.py
gives the following:
platform darwin -- Python 3.4.2 -- py-1.4.30 -- pytest-2.7.2
rootdir: my/user/path/root/test
I'd understand the latter example not working (cannot find the module as the /test
directory is not the project root) but why does it not find it from the root dir?
This seems like it should be obvious but I'm struggling to understand exactly what is going on. Do I need __init__.py
files (even in Python 3.4?) From http://pytest.org/latest/goodpractises.html:
Note
You can use Python3 namespace packages (PEP420) for your application but pytest will still perform test package name discovery based on the presence of init.py files. If you use one of the two recommended file system layouts above but leave away the init.py files from your directories it should just work on Python3.3 and above. From “inlined tests”, however, you will need to use absolute imports for getting at your application code.
Am I fundamentally misunderstanding what this means? Or writing the import
statement wrong? Or calling the tests wrongly?