Good morning,
I am trying to test a Celery Task by raising an SMTPException when sending an email.
Say I have the following code:
located in: my_app.mailer.tasks
from django.core.mail import EmailMultiAlternatives
@app.task(bind=True )
def send_mail(self):
subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
try:
msg.send(fail_silently=False)
except SMTPException as exc:
print('Exception ', exc)
and I run the following test:
class SendMailTest(TestCase):
@patch('my_app.mailer.tasks.EmailMultiAlternatives.send')
def test_task_state(self, mock_send):
mock_send.side_effect = SMTPException()
task = send_mail.delay()
results = task.get()
self.assertEqual(task.state, 'SUCCESS')
The email is sent without error.
However, if I turn the task into a standard function and then run the following test against it:
now located in: my_app.mailer.views
class SendMailTest(TestCase):
@patch('myapp.mailer.views.EmailMultiAlternatives.send')
def test_task_state(self, mock_send):
mock_send.side_effect = SMTPException()
send_mail(fail_silently=False)
The string ‘Exception’ is displayed, but there is no exc information as to what caused the exception.
Please, what am I doing wrong?