[Django]-How to test that my Django email view can catch a BadHeaderError?

2👍

This snippet is from Django’s own tests; this is how they test that this error is raised

def test_header_injection(self):
    email = EmailMessage('Subject\nInjection Test', 'Content', 'from@example.com', ['to@example.com'])
    self.assertRaises(BadHeaderError, email.message)

1👍

Use a mocker on the mail_admins function to raise the BadHeaderError when called. it would be something like this:

from mocker import Mocker, KWARGS

mocker = Mocker()
raise_error = mocker.replace('COMPLETE_PATH_TO_mail_admins_FUNCTION')  
#  i.e django.contrib.emails.mail_admins

raise_error(KWARGS)
mocker.raise(BadHeaderException)

haven’t test this yet but it should help you out 🙂

👤Hassek

Leave a comment