Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test alternative body content in EmailMultiAlternatives object using django test system?

I have EmailMultiAlternatives object with text and html content in my view:

email = EmailMultiAlternatives(subject=subject, body=message, from_email=sender, to=recipient)
email.attach_alternative(messageHTML, 'text/html')

When I test the content of message body attribute contains the text version and I don't know how to assert html content:

self.assertHTMLEqual(mail.outbox[0].body, message) # This test passes
self.assertHTMLEqual(mail.outbox[0].<???>, messageHTML) # But here I don't know what to do
like image 675
Alexander Shpindler Avatar asked Mar 16 '18 19:03

Alexander Shpindler


Video Answer


1 Answers

When you write - mail.outbox[0], an email object is returned to you which is an instance of EmailMultiAlternatives class. It has an attribute called alternatives which is a list of alternative contents.

Since you attached only 1 alternative content, you can fetch it like this:

mail.outbox[0].alternatives[0]

# above will return the following tuple:

('<html>...</html>', 'text/html')

# \______________/    \_______/
#        |                |
#   HTML content        mimetype 

To test the message, you can do this:

self.assertHTMLEqual(mail.outbox[0].alternatives[0][0], messageHTML)
like image 174
xyres Avatar answered Sep 19 '22 03:09

xyres