为 pytest 导入模块时出现 ModuleNotFound 错误

ModuleNotFound error when importing modules for pytest

我正在尝试 运行 对我在 Airflow 中编写的一些函数进行 pytest。我正在使用 Python 3.8,顺便说一句。

文件夹结构为

airflow
   -- dags
       -- includes
           -- common
               -- functions.py
   -- tests
       -- test_functions.py

我尝试了 from includes.common.functions import functionA, functionB,但一直收到错误 ModuleNotFoundError: No module named 'functions'

如果我尝试 from dags.includes.common.functions import functionA, functionB,我会得到 ModuleNotFoundError: No module named 'dags'

我已经在 airflow 文件夹中尝试 python -m pytest tests,同样的导入错误。

我对导入模块不是很熟悉,如果能帮助解决这个错误,我将不胜感激。

您可以使用.向上一级目录搜索文件。在 test_functions.py:

中使用此导入语句
from ..dags.includes.common.functions import functionA, functionB

此外,每个文件夹都需要一个空的 __init.py__ 文件。为文件夹 airflow、dags、includes、common 和 tests 创建它们。

我将以下内容添加到我的脚本中,并且能够 运行 pytest 而没有导入错误。

import sys
sys.path.insert(0, '../dags/')

from includes.common.functions import functionA, functionB

我也能够 运行 它没有任何文件夹中的任何 __init__.py

帮助了我。