Tree in Africa
Photo by Damian Patkowski on Unsplash

Pytest’s assert is not what you think it is

What is AST? And how pytest hacks it to give you a better UX?

Tarek Amr
Published in
6 min readJun 19, 2022

--

In Python, like many other languages, there is a statement that checks a given condition, and raises an AssertionError if this condition is False, otherwise, it does nothing if the given condition is True. That’s basically what assert does.

Python’s assert statement

This makes assert a good candidate for unit tests. In the end of the day, you are testing a certain condition, and want your test to fail if that condition fails.

Nevertheless, there is one small problem here. The AssertionError gives you minimal information. Check the following code; it tells you the two lists are not equal, but doesn’t really tell you which elements of the two lists are different:

Assert errors ain’t very descriptive

Compare that to Pytest’s output, when the same assert statement is used:

--

--

Tarek Amr
Writer for

I write about what machines can learn from data, what humans can learn from machines, and what businesses can learn from all three.