Using capsys

The capsys builtin fixture provides two bits of functionality: it allows you to retrieve stdout and stderr from some code, and it disables output capture temporarily. Let’s take a look at retrieving stdout and stderr.

Suppose you have a function to print a greeting to stdout:

 def​ greeting(name):
 print​(​'Hi, {}'​.format(name))

You can’t test it by checking the return value. You have to test stdout somehow. You can test the output by using capsys:

 def​ test_greeting(capsys):
  greeting(​'Earthling'​)
  out, err = capsys.readouterr()
 assert​ out == ​'Hi, Earthling​​\n​​'
 assert​ err == ​''
 
  greeting(​'Brian'​)
  greeting(​'Nerd'​)
  out, err = capsys.readouterr()
 

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.