【发布时间】:2019-10-18 15:44:30
【问题描述】:
我正在为一个使用django-post_office 包来实现其大部分电子邮件功能的应用程序编写测试。
默认的django.core.mail 库包含大量有用的工具,用于测试是否真的有电子邮件正在发送。 (在测试期间没有实际发送任何内容)
class TestFunctionThatSendsEmail(Testcase):
@override_settings(
EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend'
)
def test_function_sends_email(self):
self.assertEqual(len(outbox), 0)
run_function_that_calls_email()
self.assertEqual(len(outbox), 1)
...
# other tests
但是,我们函数中的电子邮件是使用 django-post_office mail.send() 函数发送的
# priority now to make sure that they are being sent right away
mail.send(
sender=sender,
recipients=to,
context=context,
template=template_name,
priority='now',
)
这会导致上述测试失败,因为某些原因电子邮件没有最终进入发件箱。
奇怪的是,如果我将 EMAIL_BACKEND 更改为 django.core.mail.backends.console.EmailBackend,电子邮件会显示在我的终端中,因此它正在监听 EMAIL_BACKEND 设置。
我尝试在django-post_office github 中寻找替代方法/功能来测试此功能,但我只能找到检查电子邮件是否保存到数据库并验证其状态的建议。 (我做过并且工作过)但是 django 似乎无法检测到任何实际发送的电子邮件这一事实让我有点紧张。
有没有人知道让django-post_office 发送的电子邮件出现在发件箱中的方法,或者,如果不可能,有一种方法可以确保它们确实被发送? (除了检查数据库)
【问题讨论】:
-
你找到答案了吗?我有同样的问题。
-
不幸的是我没有。我最终模拟了我们的“send_email”函数(它本身包含对 post_office_mail.send() 函数的调用)并验证调用是用正确的参数进行的——因此隐含地相信邮局包可以正常工作。
-
另一种选择是从
Email模型中获取email对象,并测试self.assertEqual(email.status, STATUS.sent)。这至少告诉您self.email_message()在dispatch()下返回。
标签: python django django-email django-postoffice