Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django tests for sending email

Tags:

django

I need to test that mail is sent from a Django 1.8 application; the documentation is clear on how to do this, e.g.

https://docs.djangoproject.com/en/stable/topics/testing/tools/#email-services

Here's some code which should therefore suffice:

from myapp.utils.mailutils import mail as mymail
from django.core import mail

def testThisFails(self):
    user = User.objects.filter(id=1).__getitem__(0)
    mymail(user,'Test Message','Test message content, please ignore...')
    self.assertEquals(len(mail.outbox), 1)
    self.assertEquals(mail.outbox[0].subject, 'Test Message')

...obviously, I have proper tests as well. Anyway, I get nothing but this:

self.assertEquals(len(mail.outbox), 1)
AssertionError: 0 != 1

Here's a similar question mentioning that the locmail backend needs to be used:

Django 1.3: Outbox empty during tests

So, I added this to settings.py:

TESTING = len(sys.argv) > 1 and sys.argv[1] == 'test'
if TESTING:
    EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'

...with no luck. Even omitting the if TESTING doesn't address the issue. Is there any means by which I can get my tests to use this backend directly?

like image 399
knirirr Avatar asked Sep 14 '16 14:09

knirirr


People also ask

How do I send an email using Django?

In most cases, you can send email using django. core. mail. send_mail() .

How do I know if my email is sent Django?

outbox when send_mail is called in another function. @pymarco If you import mail from core, mail. outbox[0]. body will show you the email sent even if the send_mail is performed elsewhere.

How does Django verify email?

First we need to configure the email host server in the settings.py for confirmation mail. Add the below configuration in the settings.py file. We used the email-id along with the password and gmail SMTP host server. You can use the other SMTP server as well.

How do I send and receive emails in Django?

Use the get_new_mail method to collect new messages from the server. Go to Django Admin, then to 'Mailboxes' page, check all the mailboxes you need to receive emails from. At the top of the list with mailboxes, choose the action selector 'Get new mail' and click 'Go'.


1 Answers

Use self.settings context manager for overriding settings

def testThisFails(self):
    # do first here
    user = User.objects.filter(id=1).__getitem__(0)
    with self.settings(EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend'):
        mymail(user,'Test Message','Test message content, please ignore...')
        self.assertEquals(len(mail.outbox), 1)
        self.assertEquals(mail.outbox[0].subject, 'Test Message')

Also use first or get instead of __getitem__. Which is magic method for doing [0] call

user = User.objects.filter(id=1).first()
like image 74
Sardorbek Imomaliev Avatar answered Oct 19 '22 21:10

Sardorbek Imomaliev