我正在嘗試模擬一個呼叫 sendgrid API 的函式。我想模擬 API 庫,但不知道哪里出錯了。
呼叫 API 的函式:
def mailing_list_signup(data: dict):
email_address = data["email"]
name = data["contact_name"]
API_KEY = settings.SENDGRID_API_KEY
sg = SendGridAPIClient(API_KEY)
# https://docs.sendgrid.com/api-reference/contacts/add-or-update-a-contact
data = {
"contacts": [
{
"email": email_address,
"name": name,
}
]
}
response = sg.client.marketing.contacts.put(request_body=data)
return response
我的壞測驗:
@dataclass
class APIResponse:
status_code: int = 202
body: bytes = b"example"
@override_settings(SENDGRID_API_KEY='123')
def test_mailing_list_signup():
response = APIResponse()
with mock.patch("myapp.apps.base.business.SendGridAPIClient") as sendgridAPI:
sendgridAPI.client.marketing.contacts.put.return_value = response
data = {
"email": "[email protected]",
"contact_name": None,
}
result = mailing_list_signup(data)
assert result == response
Pytest 告訴我測驗失敗并顯示以下訊息:
FAILED myapp/apps/base/tests/test_business.py::test_mailing_list_signup - AssertionError: assert <MagicMock name='SendGridAPIClient().client.marketing.contacts.put()' id='4622453344'> == APIClient(status_code=202, body=b'example')
uj5u.com熱心網友回復:
因為一個可呼叫的回傳值正在被模擬,所以回傳值應該設定在可呼叫而不是屬性上。
更改
sendgridAPI.client.marketing.contacts.put.return_value = response
為
sendgridAPI.client.marketing.contacts.put().return_value = response
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/443505.html
