Python Power Assertions with Nimoy

Noam Tenne
2 min readJun 29, 2021

TLDR: Python just got power assertions!

In previous posts, I’ve showcased my mission to make Python testing better with Nimoy, a Python DSL modelled after Spock.

In the past few months I’ve been working on a killer feature, which I believe is a first in the Python ecosystem — Power Assertions. This is modelled after a feature of Groovy which goes by the same name.

Why Are Power Assertions Important?

Assertions are a key part of testing. Every test boils down to this binary statement — “is this expectation true of false?”. This is true whether you use your language’s built in assert keyword or a more advanced assertion method offered by your testing framework.

When an assertion fails, the output is binary as well — “Expected x, but got y”, or in other words “x is not y”.

If you’re lucky, your testing framework will delegate this comparison to a library like Hamcrest which gives you a more verbose breakdown, and answers the question “What exactly is the difference between x and y?

While this comparison is extremely helpful, it still focuses on the difference between the values.

We need to keep in mind that a given state is normally an outcome of a series of states, that is, one outcome is a result of multiple conditions and causes.

This is where the “power” in power assertions really shows.

Python Power Assertions

With power assertions, a setup and assertion like:

Will output a report like:

Note how the assertion report outputs the value of the expression at every stage, from the string value of the class, to the result of accessing key ‘d’ in the map and finally the comparison which results in “false”.

The feature of power assertions is now in beta, and merged into version 1.1.1 of Nimoy.

One Thing To Note

Boolean expressions with side effects are affected by this feature. This is because report mechanism stores the references to instances, not the values.

--

--