Pytest stdout/stderr capture
Pytest captures stdout/stderr and sets stdin to os.devnull. When a test involves the use of Python subprocess, the “capfd” Pytest fixture is required to capture the subprocess output. “capsys” fixture only captures native Python prints, without capturing subprocess output. This is also true when testing a Python script intended to be used from the command line.
import subprocess
import sys
def test_script(capfd):
"""test that a particular message is printed to terminal"""
ret = subprocess.run([sys.executable, "-m", "mymod"], text=True)
assert ret.returncode == 0
cap = capfd.readouterr()
assert cap.out.strip() == "success"
assert cap.err.strip() == ""