【发布时间】:2021-11-20 09:14:23
【问题描述】:
这是一个 AWS lambda 函数
#service.py
from configs import SENDER, DESTINATIONS
from constants import LOG_FORMAT
import logging
def send_mail(body, SENDER, DESTINATIONS):
...
...
在配置文件中,它从 AWS 参数存储中检索数据
# configs.py
from handlers.ssm_handler import load_parameters
from common import constants
import os
environment = os.environ.get(constants.ENVIRONMENT)
JSON_BUCKET = load_parameters(constants.OT_ARCHIVAL_PREFIX+environment+constants.MIGRATION_BUCKET)
SENDER = load_parameters(constants.OT_ARCHIVAL_PREFIX+environment+constants.MAIL_SENDER)
DESTINATIONS = load_parameters(constants.OT_ARCHIVAL_PREFIX+environment+constants.MAIL_DESTINATIONS)
...
所以当我尝试测试它时
# test_service.py
from unittest import TestCase, main, mock
from service import send_mail
class TestMailService(TestCase):
def test_service(self):
with mock.patch('service.SENDER', 'abc@sys.com') as mocked_sender:
with mock.patch('service.DESTINATIONS', 'def@sys.com') as mocked_sender:
with mock.patch('service.logging.Logger.info') as mocked_logging:
send_mail(...)
mocked_logging.assert_called_with('mail sent Successfully')
当我导出 AWS 安全凭证时,此测试用例通过。但它不会,如果我不通过凭据。我想这是因为在 service.py 文件中它打开了整个 config.py 文件。因此,调用 AWS 需要 sec 凭证。 作为解决方案,我尝试模拟 SENDER 和 DESTINATIONS。但它给我带来了错误(期待安全令牌)
我希望单元测试独立于安全令牌。提出解决方案
【问题讨论】:
标签: python amazon-web-services python-unittest python-unittest.mock