我正在使用第三方库"mailjet";发送电子邮件。这是医生:https://dev.mailjet.com/email/guides/getting-started/#prerequisites
这是我想测试的send_email.py
中的方法:
from mailjet_rest import Client
def send_email(email_content):
client = Client(auth=(api_key, api_secret))
response = client.send.create(data=email_content)
if response.status_code != 200:
// raise the error
else:
print(response.status_code)
return response.status_code
...
我想模拟一下状态代码。这是我在test_send_email.py
:中尝试的
from unittest.mock import MagicMock, patch
import unittest
import send_email
class TestClass(unittest.TestCase):
@patch("send_email.Client")
def test_send_email(self, _mock):
email_content = {...}
_mock.return_value.status_code = 200
response = send_email(email_content)
// assert response == 200
当我运行测试时,它没有打印出状态代码,而是打印出:
<MagicMock name='Client().send.create().status_code' id='140640470579328'>
如何在测试中模拟status_code?提前感谢!!!!!
您将属性放错了位置。
您模拟客户端,这是正确的,并在其return_value中放入一些内容,这也是好的。
然而,线路
response = client.send.create(data=email_content)
应用于mock(客户端(的return_value、send属性及其create方法。
因此,您需要设置这个create方法的return_value.status_code。
class TestClass(unittest.TestCase):
@patch("send_email.Client")
def test_send_email(self, mock_client):
email_content = {...}
# this puts 200 in Client().status_code
# mock_client.return_value.status_code = 200
# that puts 200 in Client().send.create().status_code
mock_client.return_value.send.create.return_value.status_code = 20
response = send_email(email_content)
assert response == 200