问题描述
单独调用send_mail函数将导致由于主题中的换行符引起的BadHeaderError异常。
Calling the send_mail function independently will cause a BadHeaderError exception due to the newline in the subject.
我预计这个test_newline_causes_exception也会失败,但是没有。这是在Django 1.3中。任何想法?
I expect this test_newline_causes_exception to fail as well, but it does not. This is in Django 1.3. Any ideas?
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)。
This new test shows that the header checking code (django.core.mail.message.forbid_multi_line_headers) is not called when send_mail is used in tests.
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 1.5中已经解决了这个问题。测试电子邮件后端(locmem.py)现在执行与标准后端相同的头清理。
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.
编辑
我发现在Django版本
I found a workaround for testing header validation in Django versions <1.5.
使用get_connection方法加载与生产后端执行相同验证的控制台后端。
Use the get_connection method to load the console backend which performs the same validations as the production backend.
感谢Alexander Afanasiev指出我的方向正确。
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.',
'[email protected]',
['[email protected]'],
fail_silently=False,
connection=connection)
这篇关于为什么Django测试通过?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!