How to fix pytest E ModuleNotFoundError: No module named ...

Problem

When running pytest in your project, you see the following error message:

________ ERROR collecting test/test_Algorithms.py ________
ImportError while importing test module '/home/uli/dev/MyModule/test/test_Algorithms.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/usr/lib/python3.10/importlib/__init__.py:126: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
test/test_Algorithms.py:3: in <module>
    from MyModule.Algorithms import Algorithms
E   ModuleNotFoundError: No module named 'MyModule'

Solution

Inside your tests directory, create __init__.py:

touch tests/__init__.py

In the unlikely case that doesn’t help, you might need to add the project root to your PYTHONPATH:

PYTHONPATH=. pytests