'Python ModuleNotFoundError while importing a module in conftest for Pytest framework

My project structure

mt-kart
     |
      --> src/data_kart
     |        |
     |         -->apis
     |        |
     |         -->__init__.py
     |        |  
     |         -->main.py
      --> tests
             |
              -->__init__.py
             |
              -->conftest.py
             |
              -->test_others.py

  

conftest.py has the following line.

from data_kart.main import fastapi_app

When run pytest from command line from project root(mt-kart). I get the following error

ModuleNotFoundError No module named 'data_kart'

How to make data_kart visible for conftest.py .



Solution 1:[1]

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).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1