简体   繁体   English

python 如何模拟 3rd 方库响应

[英]python how to mock 3rd party library response

I'm using a 3rd party library "mailjet" to send email.我正在使用第 3 方库“mailjet”发送 email。 Here's the doc: https://dev.mailjet.com/email/guides/getting-started/#prerequisites这是文档: https://dev.mailjet.com/email/guides/getting-started/#prerequisites

This is the method in send_email.py that I want to test:这是我要测试的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
...

I wanted to mock the status code.我想模拟状态码。 This is what I tried in test_send_email.py :这是我在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

When I run the test, it didn't print out the status code, it prints:当我运行测试时,它没有打印出状态码,它打印:

<MagicMock name='Client().send.create().status_code' id='140640470579328'>

How can I mock the status_code in the test?如何在测试中模拟 status_code? Thanks in advance!!!!!提前致谢!!!!!

You are putting the attribute in the wrong place.您将属性放在错误的位置。

You mock the Client, which is correct, and put something in its return_value, which is also good.你模拟客户端,这是正确的,并在它的 return_value 中放入一些东西,这也很好。

However, the line然而,线

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

applies on the return_value of your mock (client), the send attribute and its create method.适用于您的模拟(客户端)的 return_value、发送属性及其创建方法。

So what you need is to set the return_value.status_code of this create method.所以你需要设置这个create方法的return_value.status_code。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM