Django的send_email()在测试时不会引发BadHeaderError

时间:2015-11-12 21:24:37

标签: python django email

我正在为联系电子邮件视图编写一些测试,我发现当我使用虚假电子邮件设置(EMAIL_HOST_USER和EMAIL_HOST_PASSWORD)时,不会引发BadHeaderError。在生产中它按预期工作,当我正确配置电子邮件并在我使用假电子邮件时引发异常时成功。无论我使用哪种电子邮件设置,测试总是成功的。

我尝试使用DEBUG = False来运行测试,但获得了相同的输出。我不知道可能导致这种行为的原因。

这是我正在测试的视图(我在这里简化了,其余代码只是获取POST数据并验证它,它按预期工作):

# home.views.py

def contact(request):
    success = False
    error = ''
    try:
        email_message = (
        "MESSAGE SENT BY: " +
        contact_email + " (" +
        contact_name + ")"
        "\n_______________________________"
        "_________________________________"
        "__\n\n\n" +
        contact_message
        )
        send_mail(
            contact_subject,
            email_message,
            settings.DEFAULT_FROM_EMAIL,
           [settings.DEFAULT_FROM_EMAIL]
        )
        success = True
    except BadHeaderError:
        error = (
            "Invalid header found."
        )
    except smtplib.SMTPException:
        error = (
             "A connection error occurred and "
             "your message has not been sent."
        )
    response = {'success': success, 'error': error}
    return HttpResponse(json.dumps(response),
                        content_type='application/json')

更新 - 这些测试最终按预期工作,感谢@mata评论和我自己对模拟库的研究:

class ContactTestCase(TestCase):

    def setUp(self):
        self.client = Client()

    def test_contact_ok(self):
        response = self.client.post(
            reverse("home:contact"),
            {
                'contactName': 'John Snow',
                'contactEmail': 'johnsnow@winterfell.com',
                'contactSubject': 'Winter is coming',
                'contactMessage': 'Hello',
                'contactCaptcha': settings.GOOGLE_RECAPTCHA_TEST_KEY
            }
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            json.loads(response.content.decode('utf-8'))['success'], True
        )
        self.assertEqual(
            json.loads(response.content.decode('utf-8'))['error'], ''
        )

    @mock.patch("home.views.send_mail")
    def test_contact_ko_bad_header(self, send_mail_mock):
        send_mail_mock.side_effect = BadHeaderError()
        response = self.client.post(
            reverse("home:contact"),
            {
                'contactName': 'John Snow',
                'contactEmail': 'johnsnow@winterfell.com',
                'contactSubject': 'Winter is coming',
                'contactMessage': 'Hello',
                'contactCaptcha': settings.GOOGLE_RECAPTCHA_TEST_KEY
            }
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            json.loads(response.content.decode('utf-8'))['success'], False
        )
        self.assertEqual(
            json.loads(response.content.decode('utf-8'))['error'],
            'Invalid header found.'
        )

    @mock.patch("home.views.send_mail")
    def test_contact_ko_smtp_error(self, send_mail_mock):
        send_mail_mock.side_effect = smtplib.SMTPException()
        response = self.client.post(
            reverse("home:contact"),
            {
                'contactName': 'John Snow',
                'contactEmail': 'johnsnow@winterfell.com',
                'contactSubject': 'Winter is coming',
                'contactMessage': 'Hello',
                'contactCaptcha': settings.GOOGLE_RECAPTCHA_TEST_KEY
            }
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            json.loads(response.content.decode('utf-8'))['success'], False
        )
        self.assertEqual(
            json.loads(response.content.decode('utf-8'))['error'],
            'A connection error occurred and your message has not been sent.'
        )

1 个答案:

答案 0 :(得分:2)

在测试会话期间,测试运行sets up一个本地内存后端(通过调用django.test.utils.setup_test_environment()),它只会将已发送的邮件附加到mail.outbox而不是真正发送它们,因此更改您的电子邮件用户和密码设置不会产生影响。

此外,无效的用户和密码设置不应生成BadHeaderError,仅在标题包含换行符或回车符时使用。