Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Django email backend

In my settings.py, I put:

EMAIL_BACKEND = 'mailer.backend.DbBackend'

So even when importing from from django.core.mail import send_mail, the send_mail function still queues up the email in the database instead of sending it immediately.

It works just fine when actually running the website, but when testing the website, and accessing some webpages that trigger emails, emails are no longer queued anymore:

def test_something(self):
    ...
    # Check no emails are actually sent yet
    self.assertEquals(len(mail.outbox), 0) # test fails here -- 2 != 0

    # Check queued emails.
    messages = Message.objects.all()
    self.assertEquals(messages.count(), 2) # test would also fail here -- 0 != 2
    ...

How come it doesn't seem to be using the backend when it is testing? (importing send_mail from mailer itself gets the tests to pass, but I can't really change the imports of other mailing apps like django-templated-email)

like image 263
wrongusername Avatar asked Apr 24 '13 08:04

wrongusername


2 Answers

According to this question django overrides the setting.EMAIL_BACKEND when testing to 'django.core.mail.backends.locmem.EmailBackend'. It's also in the django docs here.

like image 161
Jacob Harding Avatar answered Sep 28 '22 11:09

Jacob Harding


If you really want have sending of emails (like default) via SMTP in django tests use the decorator:

from django.test.utils import override_settings    

@override_settings(EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend')
class TestEmailVerification(TestCase):
   ...
like image 42
andilabs Avatar answered Sep 28 '22 13:09

andilabs