python 如何模拟第 3 方库响应

python how to mock 3rd party library response

我正在使用第 3 方库“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?提前致谢!!!!!

您将属性放在错误的位置。

你mock了Client,这是对的,在它的return_value里放点东西也不错

但是,行

response = client.send.create(data=email_content)

适用于您的模拟(客户端)的 return_value、发送属性及其创建方法。

所以你需要设置这个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