Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print output when using pytest with xdist

Tags:

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.

like image 879
Steve Saporta Avatar asked Apr 19 '16 18:04

Steve Saporta


People also ask

How do I check my pytest output?

If you want to be able to see that output even if the test does not fail, then you'll want to run your pytest test with a special flag. That special flag is the -s flag. Alternatively, you could also use the --show-capture flag, which makes things a little more clear but also is a little bit longer.

What is pytest-Xdist?

The pytest-xdist plugin extends pytest with new test execution modes, the most used being distributing tests across multiple CPUs to speed up test execution: pytest -n auto.

Where does pytest print to?

By default, pytest captures the output to sys. stdout/stderr and redirects it to a temporary file.

How do you achieve parallel execution in pytest?

To overcome this, pytest provides us with an option to run tests in parallel. For this, we need to first install the pytest-xdist plugin. -n <num> runs the tests by using multiple workers, here it is 3. We will not be having much time difference when there is only a few tests to run.


1 Answers

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  
like image 68
Vi.Ci Avatar answered Oct 05 '22 00:10

Vi.Ci