[英]Unittest on AWS python Lambda
我在 handler.py 上有这个 python handler.py
def isolate_endpoints(event=None, context=None):
endpoint_id = event['event']['endpoint_id']
client = get_edr_client()
response = client.isolate_endpoints(endpoint_id=endpoint_id)
return response # E.g {"reply":{"status":"success", "error_msg":null}}
我想为这个 lambda 写一个单元测试。 然而,在阅读了单元测试并看到了测试的实际实现之后,我可以轻松地说我不知道正在测试什么。 (我知道理论,但很难理解模拟、魔术等的实现。 )
我现在拥有的单元测试在test_calls
上,如下所示:
@mock.patch('project_module.utils.get_edr_client')
def test_isolate_endpoints(get_edr_client: MagicMock):
client = MagicMock()
get_edr_client.return_value = client
mock_event = {"event": {"endpoint_id":"foo"}}
resp = isolate_endpoints(event=mock_event) # Is it right to call this lambda directly from here?
assert resp is not None
expected = [call()] ## what is this ?? # What is supposed to follow this?
assert client.isolate_endpoints.call_args_list == expected
get_edr_client
中utils.py
的定义和主体:
from EDRAPI import EDRClient
def get_edr_client():
return EDRClient(api_key="API_KEY")
我将尝试解释您编写的测试的各个方面
@mock.patch('project_module.utils.get_edr_client')
这会将依赖项注入您的测试。 您实际上是在使用作为测试参数get_edr_client
传递给您的自动创建的 MagicMock object 修补名称'project_module.utils.get_edr_client'
。 这对于绕过测试代码中的外部依赖关系很有用。 您可以传递正在测试的代码中使用的对象的模拟实现,但不需要在此测试本身中进行测试。
def test_isolate_endpoints(get_edr_client: MagicMock):
client = MagicMock()
get_edr_client.return_value = client
设置:您正在设置修补到测试中的外部模拟。 使其返回更多模拟对象,以便被测代码按预期工作。
mock_event = {"event": {"endpoint_id":"foo"}}
resp = isolate_endpoints(event=mock_event)
调用:使用一些(可能是模拟的)参数调用您要测试的代码。 由于您想测试isolate_endpoints
隔离端点,这就是您应该调用的。 在其他测试中,您还可以尝试传递无效的 arguments ,例如isolate_endpoints(event=None)
以查看您的代码在这些场景中的行为。
assert resp is not None
验证:检查从您的 function 返回的值是否符合您的预期。 如果您的 function 正在执行2+2
,这是您检查结果是否等于4
的部分。
expected = [call()]
assert client.isolate_endpoints.call_args_list == expected
验证副作用:您的 function 除了返回值之外还有副作用。 因此,您应该检查这些是否正确发生。 您希望 function 在您之前注入的client
模拟上调用isolate_endpoint
。 因此,您正在检查该方法是否在没有 arguments 的情况下调用过一次。 call()
用于匹配没有 arguments 的方法的一次调用。 [call()]
表示只有一次调用,没有 arguments。 然后你只需检查断言是否确实如此。
一个更简洁的方法是这样做:
client.isolate_endpoints.assert_called_once()
哪个做同样的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.