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?
In most cases, you can send email using django. core. mail. send_mail() .
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.
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.
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'.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With