How to Solve the ModuleNotFoundError With Pytest?

Better Stack Team
Updated on May 15, 2024

To fix the ModuleNotFoundError in pytest, you can start by making your tests directory a Python package.This can be achieved by including an empty __init__.py file to the directory:

 
└── tests/
    ├── __init__.py  # Make sure to include this
    └── test_module_functions.py

If this does not solve the issue, you may need to modify the __init__.py file to adjust the Python path:

__init__.py
import sys
sys.path.append('.')

If you're still encountering errors, another approach involves configuring your project settings with a pyproject.toml file:

 
[ pyproject.toml]

[tool.pytest.ini_options]
pythonpath = "src"
addopts = [
    "--import-mode=importlib",
]