pytest: ImportError ModuleNotFoundError in pytest

Running python 3.7.3 on mac using pytest

My folder structure/files is src/tests/pn/tests/functional/test_something.py src/tests/pn/tests/functional/config.py src/tests/pn/lib/util.py

PYTHONPATH is set to …src/tests/pn which means ‘pn’ folder is in relative path

In test_something.py I have two import statements

from lib.util import *
from tests/functional/config import *

I run pytest -s tests/functional/test_something.py

Both paths are relative to ‘pn’ folder, import of ‘lib.util’ seems successful…however it fails to import ‘tests/functional/config’ and gives the error

ImportError while importing test module ‘… src/tests/pn/tests/functional/test_something.py’. Hint: make sure your test modules/packages have valid Python names. Traceback: tests/functional/reportgen/test_something.py:23: in <module> from tests.functional.config import * E ModuleNotFoundError: No module named ‘tests.functional’

I am confused how the relative import works for one but fails for the other… Is it because the source file and import file share the same folder hierarchy ‘tests/functional’?

It works when I import with full path like 'from src.tests.pn.tests.functional.config import *

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 23 (10 by maintainers)

Most upvoted comments

Sometimes when pytest is installed outside your development environment, it can cause this issue. So if you are using virtual/conda environment, then deactivate the environment - then uninstall pytest from the system; then again activate your environment and run the tests.

In my case, I deleted __init__.py in the root folder and it resolved an exact same problem.