‹ Kinyanjui Wangonya

Tags / pytest


It’s good practice to, as much as possible, write tests for your code. If you’re working with Python, pytest makes the process of writing and running tests much smoother. I wrote a few posts some time back on getting started with testing with pytest, so if you’re completely new to it, you might want to take a look at them:

For testing CLI apps, Click provides a convenient module: click.testing which has some useful functions (notably CliRunner()) to help us invoke commands and check their behavior.

We’ll go ahead and test each part of our app - creating, reading, updating and deleting.

You might need to capture print statements in your tests while debugging. This might be just to help you debug, or for some other reason. I mostly do this kind of thing when testing for database connections where, in addition to other tests, I want to make sure I see that “Database connection successful” message.

First time I had someone review my pull requests, she was pretty strict on tests. I couldn’t merge if the tests were failing, of course. But I also couldn’t merge if coverage had decreased. TDD was still new to me so maintaining coverage was a challenge since I was only testing the bare minimum I could. I had to find out how to make my tests more robust and ensure as much of my code was tested as possible. One area that I wasn’t really sure how to test was the custom exceptions I had written.

Test-Driven Development is great. If you’re a Pythonista, it gets even better with pytest - a framework that makes building simple and scalable tests easy.

In this series, I’ll be exploring the cool features that pytest offers to help make testing Python code a breeze.

« Older posts Newer posts »