brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python pytest's capsys lets a test check what your code printed

Python
~/tips/tip-python-pytest-capsys

def greet(name):

Assert on stdout and stderr output of a function inside a pytest test.

For command line tools, what gets printed is the result. pytest’s capsys fixture captures it so a test can check it.

def greet(name):
    print(f"hello {name}")

def test_greet(capsys):
    greet("ann")
    out, err = capsys.readouterr()
    assert out == "hello ann\n"
    assert err == ""

readouterr() returns everything written to stdout and stderr since the test started, or since the last call, and then empties the buffer. So you can call a function, check its output, call another one and check again without the first output getting in the way.

I find it useful for testing that warnings go to stderr and data goes to stdout, because a script that mixes the two breaks pipes. Checking err being empty catches that.

Note the newline at the end of the expected string. print adds one, and forgetting it is the most common reason this kind of assert fails. For longer output I’d check with in instead of an exact match.

It captures at the Python level, so output from a subprocess or a C library that writes straight to the file descriptor doesn’t show up. Use the capfd fixture for that, which works the same way but captures one level lower.

Further reading: pytest: capturing output

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link