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

AWS SAM Python Lambda单元测试出现ModuleNotFoundError求助

解决AWS SAM Python Lambda单元测试中的ModuleNotFoundError问题

问题原因

你的app.py位于hello_world目录下,使用from response import Response这种绝对导入时,单元测试的运行环境无法将hello_world目录识别为Python包搜索路径,导致找不到response模块。

解决方案

方案1:修改app.py为相对导入

将app.py中的导入语句改为相对导入,指向同一目录下的response.py:

from .response import Response

方案2:在测试文件中添加路径配置

在tests/unit/test_handler.py开头添加以下代码,把hello_world目录加入Python的搜索路径:

import sys
import os

# 将hello_world目录的绝对路径添加到sys.path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../hello_world')))

方案3:运行pytest时设置PYTHONPATH环境变量

执行测试命令时,通过环境变量指定hello_world为Python包路径:

PYTHONPATH=./hello_world python -m pytest tests/unit -v

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 07:42:38