3

单独调用 send_mail 函数会由于主题中的换行而导致 BadHeaderError 异常。

我希望这个 test_newline_causes_exception 也会失败,但事实并非如此。这是在 Django 1.3 中。有任何想法吗?

from django.core.mail import send_mail
from django.utils import unittest

class EmailTestCase(unittest.TestCase):

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

编辑:这个新测试表明,在测试中使用 send_mail 时,不会调用标头检查代码 (django.core.mail.message.forbid_multi_line_headers)。

from django.core.mail import send_mail, BadHeaderError, outbox
from django.utils import unittest

class EmailTestCase(unittest.TestCase):

    def test_newline_in_subject_should_raise_exception(self):

        try:
            send_mail('Subject\nhere', 'Here is the message.',
                      'from@example.com', ['to@example.com'], fail_silently=False)
        except BadHeaderError:
            raise Exception

        self.assertEqual(len(outbox), 1)

        self.assertEqual(outbox[0].subject, 'Subject here')

结果:

AssertionError: 'Subject\nhere' != 'Subject here'
4

2 回答 2

2

你并没有真正测试任何东西。测试意味着检查是否BadHeaderError已经提出。如果断言测试为假,则测试将失败。你可以做这样的事情 -

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)

我没有测试过。但它应该工作。

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

于 2013-03-19T22:10:26.960 回答
2

我发现这个问题已经在 Django 1.5 中得到修复。测试电子邮件后端 (locmem.py) 现在执行与标准后端相同的标头清理。

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

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

编辑

我找到了一种在 Django 版本 <1.5 中测试标头验证的解决方法。

使用 get_connection 方法加载控制台后端,该后端执行与生产后端相同的验证。

感谢 Alexander Afanasiev 为我指明了正确的方向。

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)
于 2013-03-20T01:50:32.013 回答