I have a file dir/subdir/module.py
using relative imports so that
python3 dir/subdir/module.py
fails with
ModuleNotFoundError: No module named '__main__.test_forward'; '__main__' is not a package
but
python3 -m dir.subdir.module
runs.
Unsurprisingly,
python3 -m pytest dir/subdir/module.py
pytest dir/subdir/module.py
fail as well. Can I run this module's tests from pytest (without changing it)?
Of course, I've looked at How to test single file under pytest and https://docs.pytest.org/en/latest/usage.html#cmdline, but failed to find an answer.
Here is a minimal reproducing example:
File proj/main.py
:
def func():
return 1
File proj/tests.py
:
from .main import func
def test_func():
assert func() == 1
if __name__ == "__main__":
test_func()
Note that I omitted __init__.py
in proj
as per PEP 420.
(venv) romanov@k9-09:~/temp$ python3 -m proj.tests
(venv) romanov@k9-09:~/temp$
Tests run and pass (if I change test_func
to fail, I get the expected result).
(venv) romanov@k9-09:~/temp$ python3 proj/tests.py
Traceback (most recent call last):
File "proj/tests.py", line 1, in <module>
from .main import func
SystemError: Parent module '' not loaded, cannot perform relative import
With pytest:
(venv) romanov@k9-09:~/temp$ pytest proj/tests.py
============================================================================================ test session starts =============================================================================================
platform linux -- Python 3.5.2, pytest-4.3.1, py-1.8.0, pluggy-0.9.0
hypothesis profile 'default' -> database=DirectoryBasedExampleDatabase('/home/romanov/temp/.hypothesis/examples')
rootdir: /home/romanov/temp, inifile:
plugins: hypothesis-4.0.1
collected 0 items / 1 errors
=================================================================================================== ERRORS ===================================================================================================
_______________________________________________________________________________________ ERROR collecting proj/tests.py _______________________________________________________________________________________
proj/tests.py:1: in <module>
from .main import func
E SystemError: Parent module '' not loaded, cannot perform relative import
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
========================================================================================== 1 error in 0.09 seconds ===========================================================================================
Unfortunately, this doesn't fully reproduce the problem; here pytest --pyargs proj.tests
suggested in ivan_pozdeev's answer says ERROR: file or package not found: proj.tests (missing __init__.py?)
and adding empty proj/__init__.py
lets it run.