如何配置pytest解决引用Lambda Layer的SAM应用单元测试导入错误
该问题的本质是Lambda运行环境会自动将Layer中的
python目录加入模块搜索路径,而本地pytest运行时默认不会识别这个自定义目录,因此会出现导入报错。你可以通过以下几种方式配置解决,均不需要修改现有业务代码的导入语句:
方法1:全局pytest配置(最推荐,一次配置全项目生效)
在项目根目录(与template.yaml同级)新建pytest配置文件,二选一即可:
- 若使用
pytest.ini,内容如下:
[pytest] pythonpath = _layer-folder/_python
- 若使用
pyproject.toml管理项目配置,内容如下:
[tool.pytest.ini_options] pythonpath = ["_layer-folder/_python"]
配置完成后直接运行pytest即可正常识别Layer内的模块。
方法2:conftest.py动态加载路径
如果不想修改全局配置,可以在_lambda/_tests/目录下新建conftest.py文件,添加以下代码:
import sys from pathlib import Path # 定位到Layer的python目录并加入搜索路径 layer_code_path = Path(__file__).parent.parent.parent / "_layer-folder" / "_python" sys.path.insert(0, str(layer_code_path.resolve()))
pytest运行时会自动加载该文件,自动将Layer路径加入搜索列表,无需修改其他测试文件。
方法3:单个测试文件临时修改路径
如果只有个别测试文件需要引用Layer代码,可以直接在对应测试文件的最开头添加以下代码:
import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent.parent / "_layer-folder" / "_python")) # 后续正常导入Layer模块即可 from shared_code import some_layer_function
注意事项
按照你给出的文件结构,Layer内的模块名为shared_code,因此业务代码和测试代码的导入语句都要和Lambda线上运行时保持一致,写为from shared_code import xxx即可,不需要额外调整导入写法。
内容的提问来源于stack exchange,提问作者dev_bri
相关产品推荐
相关产品推荐

