22
votes

I'm using py.test to run tests. I'm using it with pytest-xdist to run the tests in parallel. I want to see the output of print statements in my tests.

I have: Ubuntu 15.10, Python 2.7.10, pytest-2.9.1, pluggy-0.3.1.

Here's my test file:

def test_a():
    print 'test_a'


def test_b():
    print 'test_b'

When I run py.test, nothing is printed. That's expected: by default, py.test captures output.

When I run py.test -s, it prints test_a and test_b, as it should.

When I run py.test -s -n2, again nothing is printed. How can I get the print statements to work while using -n2?

I've already read pytest + xdist without capturing output and this bug report.

1
I found a workaround, although not a full solution. By redirecting stdout to stderr, the output of print statements is displayed. This can be accomplished with a single line of Python code: sys.stdout = sys.stderr. If placed in conftest.py, it applies to all tests.Steve Saporta
More complete answer in stackoverflow.com/q/27006884/151641, also check the GitHub issue linked there (github.com/pytest-dev/pytest/issues/680)mloskot

1 Answers

9
votes

I just see the explain about this issue in github https://github.com/pytest-dev/pytest/issues/1693

pytest-xdist use sys stdin/stdout to control execution, the only way to show print out should be std.err.

import sys
def test_a():
    print >> sys.stderr, 'test_a'


def test_b():
    print >> sys.stderr, 'test_b'

Not a good idea, but work.

Also you should note that the arg -s has no use if you use xdist plugin.


In python 3, I think logging.warning is a better choice, since that it is set up to write to stderr by default.

import logging
logging.basicConfig(format='%(message)s')

def test_a():
    logging.warning('test_a')


def test_b():
    logging.warning('test_b')

to see the log file, create a file called pytest.ini and add the below to it

log_cli = 1
log_cli_level = WARN
log_file = ./TestResults/test_log.log
log_file_level = WARN