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 = ... |
Get Python Testing with pytest 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.