Python ModuleNotFoundError while importing a module in conftest for Pytest framework

Option 1

Use relative imports:

from ..src.data_kart.main import fastapi_app
fastapi_app()

Please note, the above requires running conftest.py outside the project’s directory, like this:

python -m mt-kart.tests.conftest

Option 2

Use the below in conftest.py (ref):

import sys
import os
  
# getting the name of the directory where the this file is present.
current = os.path.dirname(os.path.realpath(__file__))
  
# Getting the parent directory name where the current directory is present.
parent = os.path.dirname(current)

# adding the parent directory to the sys.path.
sys.path.append(parent)
  
# import the module
from src.data_kart.main import fastapi_app

# call the function
fastapi_app()

And if it happens for a module being outside the parent directory of tests, then you can get the parent of the parent direcory and add that one to the sys.path. For example:

parentparent = os.path.dirname(parent)
sys.path.append(parentparent)

Option 3

Same as Option 2, but shorter.

import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from src.data_kart.main import fastapi_app
fastapi_app()

Option 4

Options 2 and 3 would work for smaller projects, where only a couple of files need to be updated with the code above. However, for larger projects, you may consider including the directory containing your package directory in PYTHONPATH, as described here (Option 3).

Leave a Comment