ambient-digital

Web development, technology, agility, creativity, UX and a healthy working environment  — We write about all the exciting things we do at work. https://ambient-innovation.com

Better unit-tests for your emails with Django 5.2

How a novel helper will increase your code quality

Ronny Vedrilla
ambient-digital
Published in
2 min readFeb 5, 2025

--

Motivation

Unit-testing emails has always been a second-class citizen in my experience. They feel like an external API — which they are — and it’s kind of clunky to get the content of the low-level email object and to put it into a proper test.

You’ll face this problem on steroids if you add HTML content (or any other content type than plain-text). You have to navigate through an undocumented multi-level dictionary to get to the relevant content.

This was one of the main drivers why I’ve created django-pony-express back in the day: Easen the pain of creating and testing emails. Since they are an integral part of the business logic, it’s careless at best to not write test for this feature.

Photo by Hunter Haley on Unsplash

Help is on the way

If you check the release notes of upcoming Django 5.2, you’ll see a neat helper called “body_contains()” which lives in the EmailMultiAlternatives class. With this helper, it’s really easy to get text-based content from your email object and write tests for it.

The great part is that it will assert ALL text-based content, meaning it’ll check plain-text, HTML, and, in theory, any other text content you might have.

Here’s a neat example from the docs:

Example from the official Django docs

Personal note

I will add this helper to the django-pony-express package once 5.2 has been officially released.

Secondly, I’m proud to say that this was my first Django core contribution. I’m even happier since it was (kind of) a new feature, which are extra-hard to sell to all those girls and guys who do an amazing job keeping the lights on at Django. ❤️

--

--

ambient-digital
ambient-digital

Published in ambient-digital

Web development, technology, agility, creativity, UX and a healthy working environment  — We write about all the exciting things we do at work. https://ambient-innovation.com

Ronny Vedrilla
Ronny Vedrilla

Written by Ronny Vedrilla

IT architect at Ambient in Cologne, Germany.

No responses yet