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
CodeX
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:

More descriptive error messages, when pytest is involved

This output is definitely more helpful, but how does pytest make its asserts behave differently?!

Can we override a keyword in Python?

This question sent me into a rabbit hole, and helped me understand how pytest work a little bit better.

The only way for pytest to provide such verbose output is to override the assert keyword in Python and change its behaviour. However, after a quick search, you will find that there is no way to override any of the language keywords.

Other libraries or modules know that. Thus, unittest, for example, create its own methods instead of using the builtin assert keyword. Check the module’s assertEqual method below:

--

--

Tarek Amr
CodeX

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