有很多资源用于使用pytest、Moto和botocore Stubber来编写单元测试。
编辑。经进一步调查后,我现将此问题重新措辞如下:
我有一个lambda_function python脚本,我想用pytest和Boto进行测试。在lambda_function内部,我从另一个python文件(ssm_clt = boto3.client('ssm', region_name=region))导入一个ssm_client。
问题是,当我像这样设置pytest时:
def test_lambda_handler(ssm_stubber):
ssm_stubber.activate()
ssm_stubber.add_response(
'get_parameters_by_path',
expected_params={'Path': 'my/ssm/parameter', 'Recursive': 'True'},
service_response={
'Parameters': [
{
'Name': 'my/ssm/parameter',
'Type': 'String',
'Value': 'my_string returned',
},
],
},
)
ssm_stubber.deactivate()
ssm_stubber.assert_no_pending_responses()将ssm_stubber定义为pytest夹具:
@pytest.fixture(autouse=True)
def ssm_stubber():
with Stubber(clients.ssm_clt) as stubber:
yield stubber它使用的是实际的boto3客户机,而不是顽固的客户机,因为我在lambda_function中有一个导入语句。我在努力想办法克服这一切。我不想将一堆代码放在只用于测试的常规lambda_function中。
这几乎就像我需要一个有条件的导入,但据我所知,这是不好的做法。
我是否以这样的方式构造了我的项目,使其几乎不可能在pytest中使用pytest?
发布于 2021-01-28 13:40:56
最后,我只使用了pytest的猴盖功能。这是一个简单得多,然后试图修补Boto 3客户端,并使它正确存根。下面是我所做的一些示例代码。
这是我想测试的函数。问题是param_dictionary = setup.get_ssm_parameters()函数中的AWS调用从未被正确删除。这并没有被删节,因为它超出了测试所测试的功能。这导致它试图在测试期间使用真正的boto3客户端调用。lambda_handler中的所有其他API调用总是被正确删除。
"""lambda_function.py"""
import another_function
# this was the function that has an SSM AWS client call in it that wasn't get properly stubbed because it is outside of the function I am testing but is still executed as part of the script
param_dictionary = another_function.get_ssm_parameters()
def lambda_handler(event, context):
# other code here that runs fine and AWS API calls that are properly stubbed这是包含对参数存储的AWS调用的文件。
"""another_function.py"""
import boto3
ssm_clt = boto3.client('ssm', region_name='us-west-2')
def get_ssm_parameters()
param_dict = {}
ssm_resp = ssm_clt.get_parameters_by_path(
Path=f'/{os.environ["teamName"]}/{os.environ["environment"]}/etl',
Recursive=True
)
for parameter in ssm_resp["Parameters"]:
param_dict.update(json.loads(parameter["Value"]))
return param_dict 这是我的测试。您可以看到,我传入money修补程序pytest.fixture,它将修补来自函数get_ssm_parameters()的响应,这样它就不会发出API调用。
"""test_lambda_function.py"""
def test_my_func_one(return_param_dict):
from lambda_function import lambda_handler
# insert other snubbers and "add_response" code here for AWS API calls that occur inside of the lambda_handler
lambda_handler('my_event', None)这是pytest的配置文件,我在这里设置了猴键盘。我使用monkeypatch的setattr功能覆盖get_ssm_parameters()的返回。此返回在函数param_dict()中定义。
"""conftest.py"""
import pytest
import another function
def param_dict():
param_dict = {"my_key": "my_value"}
return param_dict
@pytest.fixture(autouse=True)
def return_param_dict(monkeypatch):
monkeypatch.setattr(another_function, "get_ssm_parameters", param_dict)最终,这比尝试在我测试的功能之外的另一个模块中修补客户端要简单得多。
https://stackoverflow.com/questions/65834259
复制相似问题