我有這個 python lambdahandler.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_clientin的定義和正文utils.py:
from EDRAPI import EDRClient
def get_edr_client():
return EDRClient(api_key="API_KEY")
uj5u.com熱心網友回復:
我將嘗試解釋您撰寫的測驗的各個方面
@mock.patch('project_module.utils.get_edr_client')
這會將依賴項注入您的測驗。您實際上是在'project_module.utils.get_edr_client'使用自動創建的 MagicMock 物件修補名稱,該物件作為測驗引數傳遞給您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)
呼叫:使用一些(可能是模擬的)引數呼叫您要測驗的代碼。既然你想測驗 function isolate_endpoints,那就是你應該呼叫的。在其他測驗中,您還可以嘗試傳遞無效引數,例如isolate_endpoints(event=None)查看您的代碼在這些場景中的行為方式。
assert resp is not None
驗證:檢查函式回傳的值是否符合您的預期。如果您的函式正在執行2 2此操作,則檢查結果是否相等的部分4。
expected = [call()]
assert client.isolate_endpoints.call_args_list == expected
驗證副作用:您的函式除了回傳值之外還有副作用。因此,您應該檢查這些是否正確發生。您希望該函式呼叫您之前注入isolate_endpoint的client模擬一次。因此,您正在檢查該方法是否在沒有引數的情況下被呼叫過一次。用于匹配一個不帶引數的call()方法呼叫。這[call()]意味著只有一次沒有引數的呼叫。然后你只需檢查斷言是否確實如此。
一個更簡潔的方法是這樣做:
client.isolate_endpoints.assert_called_once()
哪個做同樣的事情。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/504756.html
標籤:Python 单元测试 aws-lambda
