Home > Enterprise >  mock django.core.mail.send_mail in another function
mock django.core.mail.send_mail in another function

Time:02-05

I want to mock django's send_mail() so that it throws an Exception. My approach is as below, but mails are still being sent, and no Exceptions being thrown. It works if I call send_mail() directly within the context manager, but not if I call a function that imports and then uses send_mail()

# test.py

import handle_alerts
from unittest import mock

class MailTest(TestCase):
  def test_handle_alerts(self):
     with mock.patch("django.core.mail.send_mail") as mocked_mail:
        mocked_mail.side_effect = Exception("OH NOES")

        handle_alerts()  # ends up using send_mail
# handle_alerts.py

from django.core.mail import send_mail

def handle_alerts():
  send_mail(....)  # valid call goes here

CodePudding user response:

You should mock function use, not function declaration.

class MailTest(TestCase):
    def test_handle_alerts(self):
        with mock.patch("handle_alerts.send_mail") as mocked_mail:
            mocked_mail.side_effect = Exception("OH NOES")

            handle_alerts()
  •  Tags:  
  • Related