2017-06-21 29 views
1

我試圖測試一個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 

我希望測試沒有輸出傳遞。

+0

你能編輯你的帖子來告訴我們你到底在期待什麼嗎? – gkubed

+1

@gkubed編輯,謝謝! – happysachan

回答

2

發現從sendgrid-python的回購問題https://github.com/sendgrid/sendgrid-python/issues/293

去包裹呼叫的解決方法,因爲補丁似乎並不與SendGrid網頁API第3節進行工作,它看起來並不像他們將以支持它。

更新以下內容:

# api/utils.py 
def send_email(email, subject, html): 
    msg = create_email(email, subject, html) 
    request_body = msg.get() 
    response = _send_email(request_body) 
    print(response.status_code) 
    print(response.body) 
    print(response.headers) 


def _send_email(request_body): 
    """Wrapping the SendGrid mail sending method in order to patch it 
    while testing. https://github.com/sendgrid/sendgrid- 
    python/issues/293""" 
    response = sg.client.mail.send.post(request_body=request_body) 
    return response 

# api/utils_test.py 
@patch('api.Login.utils._send_email') 
def test_send_email(mock_mail_send): 
    send_email(email, subject, html) 
    assert mock_mail_send.called 
0

不是在Python端,而是在SendGrid端,您是否嘗試過使用sandbox mode

+1

我還沒有,但我認爲我遇到的問題是該方法沒有被修補。我懷疑這是我在@patch中描述路徑的方式 – happysachan

0

另一種選擇是結合使用Prism我們Open API definition。這將創建SendGrid API的本地模擬版本,以便您可以針對我們的任何端點進行測試。

然後,您可以從命令行運行prism run --mock --list --spec https://raw.githubusercontent.com/sendgrid/sendgrid-oai/master/oai_stoplight.json。請致電this example