Home Ask Login Register

Developers Planet

Your answer is one click away!

emf 2 weeks ago

Python pytest: capturing stdout always fails

I'm trying to capture output from stdout / print statements in pytest (Python version 3.6).

This always fails:

message = 'The meaning of life is not actually 42\n'

def print_greeting():
    """print 42 to stdout"""

    # write to stdout
    sys.stdout.write(message)           # this fails

    # print to stdout
    print('Message again: ', message)   # this fails too


def test_printgreeting(capsys):
    """assert '42' was printed to stdout"""

    # capture stdout / stderr
    out, err = capsys.readouterr()
    print_greeting()

    # 42 should be in stdout from sys.stdout.write
    assert '42' in out

Results from pytest:

========================================================= test session starts ==========================================================

collected 1 item

test.py
The meaning of life is not actually 42
F

=============================================================== FAILURES ===============================================================
__________________________________________________________ test_printgreeting __________________________________________________________
test.py:42: in test_printgreeting
    assert '42' in out
E   AssertionError: assert '42' in ''
======================================================= 1 failed in 0.03 seconds =======================================================

Why is this not captured?

Answers


Phydeaux 2 weeks ago

You need to call readouterr after you print:

def test_printgreeting(capsys):
    """assert '42' was printed to stdout"""

    # capture stdout / stderr
    print_greeting()
    out, err = capsys.readouterr()

    # 42 should be in stdout from sys.stdout.write
    assert '42' in out

Post Status

Asked in 2 weeks ago
Viewed 2,642 times
Voted 11
Answered 1 times

Search




Leave an answer


Quote of the day: live life