python - 如何测试 Django 电子邮件的内容?

标签 python django email

我是 Django 的新手,我正在尝试使用 unittest 检查出站电子邮件中是否有一些文本:

class test_send_daily_email(TestCase):
    def test_success(self):
        self.assertIn(mail.outbox[0].body, "My email's contents")

但是,我遇到了 mail.outbox[0].body 的问题。它将输出 \nMy email's contents\n 并且不会匹配测试文本。

我尝试了几种不同的修复方法,但都没有成功:

  • str(mail.outbox[0].body).rstrip() - 返回一个相同的字符串
  • str(mail.outbox[0].body).decode('utf-8') - 无属性解码

抱歉,我知道这一定是一项微不足道的任务。在 Rails 中,我会使用像 Nokogiri 这样的东西来解析文本。在 Django 中解析这个的正确方法是什么?我无法在 the documentation 中找到这方面的说明.

最佳答案

这取决于您邮件的实际内容(纯文本或 html),但简单的方法是也对您要测试的字符串进行编码。

# if you are testing HTML content
self.assertTextInHTML("My email's contents", mail.outbox[0].body)

# the string may need escaping the same way django escapes
from django.utils.html import escape
self.assertIn(escape("My email's contents"), mail.outbox[0].body)

关于python - 如何测试 Django 电子邮件的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47089450/

相关文章:

python - 验证电子邮件未在 ubuntu 的本地服务器中使用 smtp 发送到电子邮件地址

c# - 从 C# 启动电子邮件应用程序 (MAPI)(带附件)

python - Python 中条件运算符的推荐编码风格是什么?

Django/HTTP - 使用 POST 请求发送查询字符串 - 不推荐吗?

python - Django 500 服务器错误仅出现在一个 URL 中

python - 替代支持 Python 3 的 S3 绑定(bind)

android - 使用 JavaMail API 在 Android 中发送电子邮件

python - 使用 python 2.7 for windows 执行 sh 文件

Python - 以深度优先顺序使用生成器迭代树

python - 使用 Delaunay 三角剖分进行插值