Chapter 6. Testing with pytest

If you think back to when you wrote your first programs, you may recall a common experience: you had an idea for how a program could help with a real-life task and spent a sizable amount of time coding it from top to bottom, only to be confronted with screens full of disheartening error messages when you finally ran it. Or, worse, it gave you results that were subtly wrong.

There are a few lessons we’ve all learned from experiences like this. One is to start simple and keep it simple as you iterate on the program. Another lesson is to test early and repeatedly. Initially, this may just mean to run the program manually and validate that it does what it should. Later on, if you break the program into smaller parts, you can test those parts in isolation and automatically. As a side effect, the program gets easier to read and work on, too.

In this chapter, I’ll talk about how testing can help you produce value early and consistently. Good tests amount to an executable specification of the code you own. They set you free from institutional knowledge in a team or company, and they speed up your development by giving you immediate feedback on changes.

The third-party testing framework pytest has become somewhat of a de facto standard in the Python world. Tests written with pytest are simple and readable: you write most tests as if there was no framework, using basic language primitives like functions and assertions. Despite its simplicity, the framework ...

Get Hypermodern Python Tooling now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.