0

I am writing some tests for a contact-email view and I find that BadHeaderError is not raised when I use fake email settings (EMAIL_HOST_USER and EMAIL_HOST_PASSWORD). In production it works as expected, being successful when I configure email properly and raising the exception when I use a fake email. Tests are always successful, no matter what email settings I use.

I have tried to use DEBUG=False to run the tests but got the same output. I have no idea about what could be causing this behaviour.

This is the view I am testing (I have it simplified here, the rest of the code is just about getting POST data and validating it, which work as expected):

# home.views.py

def contact(request):
    success = False
    error = ''
    try:
        email_message = (
        "MESSAGE SENT BY: " +
        contact_email + " (" +
        contact_name + ")"
        "\n_______________________________"
        "_________________________________"
        "__\n\n\n" +
        contact_message
        )
        send_mail(
            contact_subject,
            email_message,
            settings.DEFAULT_FROM_EMAIL,
           [settings.DEFAULT_FROM_EMAIL]
        )
        success = True
    except BadHeaderError:
        error = (
            "Invalid header found."
        )
    except smtplib.SMTPException:
        error = (
             "A connection error occurred and "
             "your message has not been sent."
        )
    response = {'success': success, 'error': error}
    return HttpResponse(json.dumps(response),
                        content_type='application/json')

UPDATE - These are the tests finally working as expected, thanks to @mata comments and my own research with the mock library:

class ContactTestCase(TestCase):

    def setUp(self):
        self.client = Client()

    def test_contact_ok(self):
        response = self.client.post(
            reverse("home:contact"),
            {
                'contactName': 'John Snow',
                'contactEmail': '[email protected]',
                'contactSubject': 'Winter is coming',
                'contactMessage': 'Hello',
                'contactCaptcha': settings.GOOGLE_RECAPTCHA_TEST_KEY
            }
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            json.loads(response.content.decode('utf-8'))['success'], True
        )
        self.assertEqual(
            json.loads(response.content.decode('utf-8'))['error'], ''
        )

    @mock.patch("home.views.send_mail")
    def test_contact_ko_bad_header(self, send_mail_mock):
        send_mail_mock.side_effect = BadHeaderError()
        response = self.client.post(
            reverse("home:contact"),
            {
                'contactName': 'John Snow',
                'contactEmail': '[email protected]',
                'contactSubject': 'Winter is coming',
                'contactMessage': 'Hello',
                'contactCaptcha': settings.GOOGLE_RECAPTCHA_TEST_KEY
            }
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            json.loads(response.content.decode('utf-8'))['success'], False
        )
        self.assertEqual(
            json.loads(response.content.decode('utf-8'))['error'],
            'Invalid header found.'
        )

    @mock.patch("home.views.send_mail")
    def test_contact_ko_smtp_error(self, send_mail_mock):
        send_mail_mock.side_effect = smtplib.SMTPException()
        response = self.client.post(
            reverse("home:contact"),
            {
                'contactName': 'John Snow',
                'contactEmail': '[email protected]',
                'contactSubject': 'Winter is coming',
                'contactMessage': 'Hello',
                'contactCaptcha': settings.GOOGLE_RECAPTCHA_TEST_KEY
            }
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            json.loads(response.content.decode('utf-8'))['success'], False
        )
        self.assertEqual(
            json.loads(response.content.decode('utf-8'))['error'],
            'A connection error occurred and your message has not been sent.'
        )

1 Answer 1

2

During a test session the test runner sets up a local memory backend (by calling django.test.utils.setup_test_environment()), which will simply append sent mails to mail.outbox instead of really sending them, therefore changing your email user and password settings won't have an effect.

Also, invalid user and password settings shouldn't generate a BadHeaderError, that's only used when a header contains newline or carriage return characters.

3
  • So is there a way to test if emails are really going to be sent? I am thinking of using mocks to fake that behaviour, raising different exceptions. Thanks also for the BadHeaderError comment, I guess I should be also catching smtplib.SMTPException for general fails. Nov 12, 2015 at 23:06
  • That sounds like you want to test the email backend, not the view. django.mail.get_connection(backend='django.core.mail.backends.EmailBackend') would give you a connection explicitly using the smtp backend, which you then can use in a testcase as the connection argument to send_message.
    – mata
    Nov 12, 2015 at 23:26
  • I got it finally working as I wanted, isolating my view and replacing send_mail() behaviour with mocks. I have updated the tests in the question with the right ones, in case you (or anyone) are interested in my approach. Thank you for the help, I was really frustrated before knowing send_mail() had a different behaviour in tests. Nov 15, 2015 at 16:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.