Python 在 Pytest 框架的 conftest 中导入模块时出现 ModuleNotFoundError

Python ModuleNotFoundError while importing a module in conftest for Pytest framework

我的项目结构

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

  

conftest.py 有以下行。

from data_kart.main import fastapi_app

当 运行 pytest 来自项目根目录 (mt-kart) 的命令行时。我收到以下错误

ModuleNotFoundError No module named 'data_kart'

如何使 data_kart 对 conftest.py 可见。

选项 1

使用相对导入:

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

请注意,上面需要 运行 conftest.py 在项目目录之外,像这样:

python -m mt-kart.tests.conftest

选项 2

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

如果模块发生在 tests 的父目录之外,那么您可以获取父目录的父目录并将其添加到 sys.path。例如:

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

选项 3

与选项 2 相同,但更短。

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

选项 4

选项 2 和 3 适用于较小的项目,其中只有几个文件需要用上面的代码更新。但是,对于较大的项目,您可以考虑在 PYTHONPATH, as described (选项 3)中包含包含您的包目录的目录。