我試圖測試一個SendGrid方法在不發送電子郵件的情況下被調用。當我運行我的測試時,該方法未修補,而是運行發送電子郵件的原始方法。我不知道爲什麼我的修補程序無法正常工作。此問題與How to mock a SendGrid method in Python類似,但使用不同版本的SendGrid。如何在python中模擬sendgrid web api v.3方法
# api/Login/utils_test.py
from .utils import send_email
from unittest.mock import patch
@patch('api.Login.utils.sg.client.mail.send.post')
def test_send_email(mock_mail_send):
send_email(email, subject, html)
assert mock_mail_send.called
# api/Login/utils.py
from api import sg
def send_email(email, subject, html):
msg = create_email(email, subject, html)
request_body = msg.get()
response = sg.client.mail.send.post(request_body=request_body)
# api/__init__.py
from server import sg
# server.py
import sendgrid
import os
sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
目前,當我從API目錄內運行pytest Login/utils_test.py
,我得到一個AssertionError:
assert False
+ where False = <MagicMock name='post' id='4370000808'>.called
我希望測試沒有輸出傳遞。
你能編輯你的帖子來告訴我們你到底在期待什麼嗎? – gkubed
@gkubed編輯,謝謝! – happysachan