[Django]-Why does this Django test pass?

2πŸ‘

βœ…

I found that this issue has been fixed in Django 1.5. The testing email backend (locmem.py) now performs the same header sanitization as the standard backends.

https://code.djangoproject.com/ticket/18861

https://github.com/django/django/commit/8599f64e54adfb32ee6550ed7a6ec9944034d978

EDIT

I found a workaround for testing header validation in Django versions <1.5.

Use the get_connection method to load the console backend which performs the same validations as the production backend.

Thanks to Alexander Afanasiev for pointing me in the right direction.

connection = get_connection('django.core.mail.backends.console.EmailBackend')
send_mail('Subject\nhere',
          'Here is the message.',
          'from@example.com',
          ['to@example.com'],
          fail_silently=False,
          connection=connection)
πŸ‘€Alex

3πŸ‘

You’re not really testing anything. Testing would imply checking if the BadHeaderError has been raised or not. The test would fail if an assert test is false. You could do something like this –

def test_newline_causes_exception(self)
    error_occured = False
    try:
        send_mail('Header\nInjection', 'Here is the message.', 'from@example.com',
                  ['to@example.com'], fail_silently=False)
    except BadHeaderError:
        error_occured = True

    self.assertTrue(error_ocurred)

I haven’t tested it. But it should work.

PS: from django.core.mail import send_mail, BadHeaderError

Leave a comment