How to test content of a Django email?

Viewed 1199

I'm new to Django and am trying to use unittest to check if there's some text in an outbound email:

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

However, I'm having an issue with mail.outbox[0].body. It will output \nMy email&#39s contents\n and won't match the test text.

I've attempted a few different fixes with no luck:

  • str(mail.outbox[0].body).rstrip() - returns an idential string
  • str(mail.outbox[0].body).decode('utf-8') - no attribute decode

Apologies, I know this must be a trivial task. In Rails I would use something like Nokogiri to parse the text. What's the right way to parse this in Django? I wasn't able to find instructions on this in the documentation.

1 Answers

It depends on the actual content of your mail (plain or html) but the easy way is to also encode the string you are testing against.

# 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)
Related