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たかどうかを確認することを意味します。アサート テストが false の場合、テストは失敗します。あなたはこのようなことをすることができます -

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 に答える