单独调用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('HeadernInjection', 'Here is the message.', 'from@example.com',
['to@example.com'], fail_silently=False)
EDIT:这个新的测试显示,当在测试中使用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('Subjectnhere', '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: 'Subjectnhere' != 'Subject here'
您实际上没有测试任何东西。测试意味着检查BadHeaderError
是否已经升高。如果断言测试为false,测试将失败。你可以这样做-
def test_newline_causes_exception(self)
error_occured = False
try:
send_mail('HeadernInjection', '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
我发现这个问题已经在Django 1.5中修复了。测试电子邮件后端(locmme .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('Subjectnhere',
'Here is the message.',
'from@example.com',
['to@example.com'],
fail_silently=False,
connection=connection)