【问题标题】:Django Test framework with file based Email backend server带有基于文件的电子邮件后端服务器的 Django 测试框架
【发布时间】:2012-11-30 16:46:32
【问题描述】:

我已经在 Django 框架中制定了测试用例。

用例: 我正在使用 API 通过向他们发送电子邮件来注册用户,当他们点击电子邮件中提供的链接时,他们的帐户就会被激活。

在我的 settings.py 中我正在使用

EMAIL_FILE_PATH  ='django.core.mail.backends.filebased.EmailBackend'

指向本地目录。

当从 Eclipse 运行 PyUnit 测试用例时,一切工作文件。为发送的每封电子邮件生成文本文件

但是,当我使用时

python ./manage.py test <component_name>

文件不会生成。

任何见解当我使用 ./manage.py 执行测试用例和使用 pyUnit 时有什么区别?

【问题讨论】:

  • 当您使用 manage.py 测试时,所有电子邮件功能都被重定向到虚拟发件箱,这意味着什么都做不了,无论您的电子邮件后端设置在 settings.py 中是什么。他们假设您不想在测试时发送真实的电子邮件或在真实环境中创建文件。

标签: python django unit-testing automated-tests functional-testing


【解决方案1】:

如果您想使用特定的电子邮件后端,可以在 Django 中覆盖此方面。

在 django.test.utils 中,当 Django 设置测试环境时,Django 会将电子邮件后端更改为 Django 测试文档中提到的 locmem:

def setup_test_environment():
...
    mail.original_email_backend = settings.EMAIL_BACKEND
    settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'

因此,如果您想为测试启用发送电子邮件,您只需将设置更改为您想要的。

from django.test.utils import override_settings

@override_settings(EMAIL_BACKEND='django.core.mail.backends.filebased.EmailBackend')
class MyTest(TestCase):
    # your test case

【讨论】:

    【解决方案2】:

    简单的答案:

    如果不设计自己的电子邮件系统,就无法做到这一点,但这可能很愚蠢。我建议做其他事情来验证代码是否成功,而无需发送电子邮件。比如,运行代码,假设用户单击链接并创建 RequestFactory 以获取/发布链接以运行与其关联的视图代码。

    来自Django Testing Application

    电子邮件服务

    "If any of your Django views send email using Django's email functionality,
    you probably don't want to send email each time you run a test using that
    view. For this reason, Django's test runner automatically redirects all
    Django-sent email to a dummy outbox. This lets you test every aspect of
    sending email -- from the number of messages sent to the contents of each
    message -- without actually sending the messages."
    

    【讨论】:

      猜你喜欢
      • 2013-04-17
      • 2017-12-15
      • 1970-01-01
      • 1970-01-01
      • 2012-05-24
      • 2019-10-28
      • 2011-06-06
      • 2018-01-12
      • 1970-01-01
      相关资源
      最近更新 更多