You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pytest运行Apache Airflow项目出现ImportError导入错误如何解决

问题根因

Airflow运行时默认会自动将dags目录加入Python模块搜索路径sys.path,因此from utils.A.B import C的写法可以正常识别到dags/utils下的模块。而pytest默认仅将执行命令的当前工作目录加入sys.path,找不到dags下的utils模块,就会抛出导入错误。

解决方案(无需修改dags目录下业务代码)
  • 方案1:单次运行pytest时临时指定PYTHONPATH
    在项目根目录(dags和tests目录的父目录)执行以下测试命令即可:
    PYTHONPATH=./dags python3 -m pytest tests/*
    
  • 方案2:通过pytest配置文件永久生效
    在项目根目录新建pytest.ini配置文件,写入以下内容:
    [pytest]
    pythonpath = dags
    
    之后直接执行python3 -m pytest tests/*即可正常运行,无需额外加环境变量。如果使用pyproject.toml管理项目配置,可写入以下内容:
    [tool.pytest.ini_options]
    pythonpath = ["dags"]
    
  • 方案3:通过conftest.py配置搜索路径
    在tests目录下新建conftest.py文件(pytest会自动加载该文件),写入以下代码:
    import sys
    from pathlib import Path
    
    # 将项目根目录下的dags目录加入Python搜索路径
    sys.path.append(str(Path(__file__).parent.parent / "dags"))
    
    该方案同样不需要修改业务代码,也不需要每次执行命令加额外参数。

内容的提问来源于stack exchange,提问作者malibu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 10:57:08