Review of "Python Testing with pytest, Second Edition"
Even though I've been using pytest for years, being a testing enthusiast, I thought I'd read Brian Okken's book to see what I might be able to learn from it. I was pleased to discover not only several tidbits of the workings of pytest I hadn't known about, but also some testing strategy advice.
Here are a few examples of the former:
--fixturesargument. PyCharm can locate fixtures with Ctrl+Click but VS Code hasn't implemented that yet, so the command line option can be handy.
pytest.raises, the context manager you use when you expect code to raise an exception, has a
matchparameter to use a regular expression to check the exception message.
My typical workflows are to run the whole test suite from the command line but jump to an IDE when running individual tests. Brian's examples throughout the book show how versatile running tests from the command line can be, doing things like running subsets of tests and controlling the various output options.
For strategy, Brian provides a simple framework for figuring out what tests to write:
- Start with a non-trivial, "happy path" test case.
- Then look at test cases that represent
- interesting sets of input,
- interesting starting states,
- interesting end states, or
- all possible error states.
Other advice resonates with my own hard-won experience:
Ultimately Brian has done an impressive job giving value to both the beginner and more experienced user of pytest. The former will want to work through all the exercises and potentially leave some of the advanced techniques on their "mental bookshelf" until needed, while the latter can skim the exercises and basics. The conversational tone of book is also easy to read. After years of listening to Brian on the Python Bytes podcast, I was hearing the text in his own voice while I read.