django之为什么这个 Django 测试通过了
yyy_WW
阅读:23
2025-04-02 23:11:03
评论:0
单独调用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 时,不会调用 header 检查代码 (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'
请您参考如下方法:
您实际上并没有在测试任何东西。测试意味着检查 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
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。