【问题标题】:Testing Django email backend测试 Django 电子邮件后端
【发布时间】:2013-04-17 16:50:24
【问题描述】:

在我的 settings.py 中,我输入了:

EMAIL_BACKEND = 'mailer.backend.DbBackend'

因此,即使从from django.core.mail import send_mail 导入,send_mail 函数仍会将电子邮件排队到数据库中,而不是立即发送。

在实际运行网站时效果很好,但在测试网站时,以及访问一些触发电子邮件的网页时,电子邮件不再排队:

def test_something(self):
    ...
    # Check no emails are actually sent yet
    self.assertEquals(len(mail.outbox), 0) # test fails here -- 2 != 0

    # Check queued emails.
    messages = Message.objects.all()
    self.assertEquals(messages.count(), 2) # test would also fail here -- 0 != 2
    ...

为什么它在测试时似乎没有使用后端? (从mailer 导入send_mail 本身可以通过测试,但我无法真正更改其他邮件应用程序的导入,例如django-templated-email

【问题讨论】:

  • @AlexanderAfanasiev 是的,当使用runserver 运行网站时,我的后端工作正常;无论出于何种原因,它在进行单元测试时都不起作用。

标签: django unit-testing testing django-mailer


【解决方案1】:

据此question django 在测试'django.core.mail.backends.locmem.EmailBackend' 时会覆盖setting.EMAIL_BACKEND。它也在 django 文档here

【讨论】:

【解决方案2】:

要使用 django-mailer 正确测试电子邮件,您需要覆盖两个设置:

  1. 使用 django-mailer 后端进行测试
  2. 让 djano-mailer 后端使用测试后端

如果您没有设置 django-mailer 后端(编号 2),您的测试将尝试发送真实的电子邮件。

您还需要模拟运行 django-mailer 的 send_mail 管理命令,以便检查 mail.outbox 是否有正确的电子邮件。

以下是如何设置测试方法的示例:

from mailer.engine import send_all

@override_settings(EMAIL_BACKEND='mailer.backend.DbBackend')
@override_settings(MAILER_EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend')
def test_email(self):
    # Code that generates email goes here.

    send_all()  # Simulates running django-mailer's send_mail management command.

    # Code to check the email in mail.outbox goes here.

此策略使您的测试特定于您并不总是想要或需要的 django-mailer。我个人仅在测试 django-mailer 启用的特定功能时才使用此设置。否则,我使用 django 的默认测试电子邮件后端设置。

【讨论】:

    【解决方案3】:

    如果您真的想在 django 测试中通过 SMTP 发送电子邮件(如默认),请使用装饰器:

    from django.test.utils import override_settings    
    
    @override_settings(EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend')
    class TestEmailVerification(TestCase):
       ...
    

    【讨论】:

      【解决方案4】:

      尝试以下方法:

      django.core.mail.backends.console.EmailBackend
      

      【讨论】:

      • 与七年前的the accepted answer 中所述的django.core.mail.backends.locmem.EmailBackend 相比,这有什么好处?
      猜你喜欢
      • 2018-01-12
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      • 2020-11-13
      • 2012-11-10
      • 1970-01-01
      • 2012-11-30
      • 2018-10-19
      相关资源
      最近更新 更多