Home > Enterprise >  python importerror while import main module in conftest for pytest framework
python importerror while import main module in conftest for pytest framework

Time:02-12

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 .

CodePudding user response:

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()
  • Related