Pytest print to stdout despite of output capturing

Question:

I am aware that PyTest captures the output (stdout, stderr, …) for the tests it executes, and that is an awesome feature I want to keep. However, there is some content that I wish to print to the console immediately from my within conftest.py file, as general information to the person watching the test execution from their terminal. Using a print statement there does not work, as the output of the conftest.py file seems to also be captured, and is only shown if an error happens while executing that file.

Is there a way for me to explicitly bypass this "PyTest output capturing" for a single print statement?

Asked By: Erik Brendel

||

Answers:

On Unix you could open the controlling terminal and print to it directly:

import os

termfd = open(os.ctermid(), "w")
termfd.write("hello")
termfd.close()
Answered By: dan

At the bottom of the documentation linked by OP, there is this example:

def test_disabling_capturing(capsys):
    print("this output is captured")
    with capsys.disabled():
        print("output not captured, going directly to sys.stdout")
    print("this output is also captured")

The content written to sys.stdout in the with capsys.disabled() context will show up (not prettily) in the pytest results.

Answered By: Ian

To extend on Ian’s answer: capsys is a function-scoped fixture, meaning it can be used tests, and other function-scoped fixtures, but not higher scoped fixtures, such as a session-scoped.

@pytest.fixture(scope="session")
def my_fxture(capsys):
    with capsys.disabled():
        ("YOLO")

The above will result in the following error:

ScopeMismatch: You tried to access the 'function' scoped fixture 'capsys' with a 'session' scoped request object, involved factories

To get around this, you currently need this hack:

@pytest.fixture(scope="session")
def session_setup_teardown(request):
    capmanager = request.config.pluginmanager.getplugin("capturemanager")
    with capmanager.global_and_fixture_disabled():
        print("YOLO")
Answered By: andyhasit
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.