Testing EmailMultiAlternatives email

So, my app renders an email using EmailMultiAlternatives, and I want to test email body. I am using the following script to access the email’s body;


I am able to print the email using print(mail.outbox[0].alternatives[0][0])

Here is your code: 7997644198

But, when I try to test the body of the email using;

self.assertContains(mail.outbox[0].alternatives[0][0], escape('Here is your code:'))

I get an error, AttributeError: ‘SafeString’ object has no attribute ‘status_code’

Please, what am I doing wrong?

Keep in mind that when you print an object, you’re not necessarily looking at the object. You’re looking at a representation of the object that the __str__ method on that class generates.

If you want to examine that object to understand its structure and contents, you can either use the python debugger or the Django shell. (You can also look at the source code for it to understand how it’s defined and what the __str__ method is doing.)

You can possibly take the shortcut by setting up your test to test the string formatted version by wrapping that object in the str function (e.g. str(mail.outbox[0].alternatives[0][0])), however, I’m not entirely sure that that’s going to test what you’re really trying to validate here. That’s something you’re going to need to decide.

Thanks Ken.

Actually, if I had read the error properly, I would have understood that assertContains is asking for a status_code which is part of a normal response and certainly not part of an email.

Using assertIn worked.

self.assertIn('Here is your code:', mail.outbox[0].alternatives[0][0])
1 Like