由于主题中的换行符,独立调用send_mail函数将导致BadHeaderError异常。为什么这个Django测试通过?
我希望这个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.', '[email protected]',
['[email protected]'], 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.',
'[email protected]', ['[email protected]'], fail_silently=False)
except BadHeaderError:
raise Exception
self.assertEqual(len(outbox), 1)
self.assertEqual(outbox[0].subject, 'Subject here')
结果:
AssertionError: 'Subject\nhere' != 'Subject here'
它会在django shell中抛出异常吗? – alecxe 2013-03-19 21:46:57
@AlexanderAfanasiev是的。 – Alex 2013-03-19 21:47:39
Django在测试阶段替换正常的电子邮件后端和测试。这可能是一个原因。请检查django.core.mail.outbox中是否存在错误,或换句话说,是否实际发送了消息。请参阅https://docs.djangoproject.com/en/1.3/topics/testing/#e-mail-services。 – alecxe 2013-03-19 21:57:40