I'm upgrading from version 1 of the Python library to the latest version. In my tests, I was previously able to mock the library call to send the email but the mock isn't working with the latest version.
With v1, I had this in my code:
SG = sendgrid.SendGridClient(SG_KEY)
SG.send(message)
and in my tests I added this decorator to mock the send call:
@mock.patch("tasks.SG.send", autospec=True) # tasks is my module
With v3, I'm trying more or less the same thing:
SG = sendgrid.SendGridAPIClient(apikey=SG_KEY)
SG.client.mail.send.post(request_body=data)
with this decorator:
@mock.patch("tasks.SG.client.mail.send.post", autospec=True)
But the mock doesn't work. The call to the post method happens instead of being mocked.
Has anyone been able to get this kind of mock to work?
Hello @jeffoneill,
We now mock our tests using Prism. To have Prism auto-start, please see: https://github.com/sendgrid/sendgrid-python/blob/master/test/test_sendgrid.py#L18
I hope that helps. Thanks!
With Best Regards,
Elmer
Elmer, thanks for the suggestion. I don't want to install another package just for one mock. :) For a quick fix, I'm just wrapping the call like this:
def _send_emails_sendgrid(data):
response = SG.client.mail.send.post(request_body=data)
And I mock my function with this decorator:
@mock.patch("my_module._send_emails_sendgrid", autospec=True)
Thanks for sharing that with us!
If you don't mind, please fill out this form and we will send you some swag :)
I have the same problem and asked on Stack Overflow https://stackoverflow.com/questions/44684016/how-to-mock-a-sendgrid-web-api-v-3-method-in-python will use this solution for now, thanks!
Most helpful comment
Elmer, thanks for the suggestion. I don't want to install another package just for one mock. :) For a quick fix, I'm just wrapping the call like this:
And I mock my function with this decorator: