PEP8 – import not at top of file with sys.path
Often I have multiple files with tests in a subdirectory foo/tests
of my project, while the modules I'm testing are in foo/src
. To run the tests from foo/tests
without import errors I create a file foo/tests/pathmagic.py
that looks like this;
"""Path hack to make tests work."""
import os
import sys
bp = os.path.dirname(os.path.realpath('.')).split(os.sep)
modpath = os.sep.join(bp + ['src'])
sys.path.insert(0, modpath)
In every test file, I then use
import pathmagic # noqa
as the first import. The "noqa" comment prevents pycodestyle
/pep8
from complaining about an unused import.
If there are just a few imports, you can just ignore PEP8 on those import
lines:
import sys
sys.path.insert("..", 0)
import my_module # noqa: E402