我是 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/