Skip to Main Content
Python Testing with pytest
book

Python Testing with pytest

by Brian Okken
February 2022
Intermediate to advanced content levelIntermediate to advanced
274 pages
6h 28m
English
Pragmatic Bookshelf
Content preview from Python Testing with pytest

Using monkeypatch

During the previous discussion of capsys, we used this code to test the output of the Cards project:

 import​ ​cards
 
 
 def​ ​test_version_v2​(capsys):
  cards.cli.version()
  output = capsys.readouterr().out.rstrip()
 assert​ output == cards.__version__

That made a decent example of how to use capsys, but it’s still not how I prefer to test the CLI. The Cards application uses a library called Typer[16] that includes a runner feature that allows us to test more of our code, makes it look more like a command-line test, remains in process, and provides us with output hooks. It’s used like this:

 from​ ​typer.testing​ ​import​ CliRunner
 
 
 def​ ​test_version_v3​():
  runner = ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python Testing with pytest

Python Testing with pytest

Brian Okken

Publisher Resources

ISBN: 9781680509427Errata Page