Pytest无法找到在Lambda Layer中定义的函数。

4

最近我在工作项目中添加了一个Lambda层,虽然在几乎所有方面都取得了巨大的成功,但现在我在运行测试时遇到了问题。以下是我的简化目录结构:

root
  - dependencies-layer
    - python
      - __init__.py
      - boto3
      - (list of other modules)
      - dependencies.py
      - requirements.txt
  - src
    - hello_world
      - __init__.py
      - hello_world.py
      - requirements.txt
  - tests
    - hello_world
      - unit
        - test_hello_world.py
  - pytest.ini
  - template.yaml

dependencies.py:

import boto3

def db_conn():
  db = boto3.resource("dynamodb")
  return db

hello_world.py

from dependencies import db_conn

def hw_handler():
  (unimportant functionality)

test_hello_world.py

from src.hello_world import hello_world

(unimportant unit tests)

所有的功能都很好用。在我运行sam build之后,我可以本地运行和触发hw_handler,然后也可以部署并触发它,一切都没有问题。但当我运行pytest并触发test_hello_world.py时,问题就出现了。我会收到以下错误信息:

(Traceback)
src/hello_world/hello_world.py:1: in <module>
ImportError: cannot import name 'db_conn' from 'dependencies' (unknown location)

因此,错误在于当pytest导入要测试的lambda时,它无法从已导入的lambda中导入来自我的lambda层的函数。显然,pytest找不到我的依赖文件夹,所以我的问题是,将Lambda层合并到我的pytest代码中的最佳方法是什么?


这个回答解决了你的问题吗?为什么我一直收到'ImportError:无法导入名称db'的错误? - petey
1个回答

2
将以下步骤添加到包含测试的文件夹的根目录中的__init__.py中的lambda层路径。
请见下方 - 查找当前目录和文件所在目录 为了使我的测试运行,我最终进行了以下操作:
import sys, os

dir_path = os.path.dirname(os.path.realpath(__file__))

sys.path.append(dir_path + "/../../hubspot_cdk/code/layers/hubspotDeps/python")
sys.path.append(dir_path + "/../../hubspot_cdk/code/layers/hubspotUtils/python")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接