Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest: printing from fixture

Tags:

python

pytest

I'm writing tests using Pytest. I have a fixture like this:

@pytest.yield_fixture(autouse=True, scope='session')
def manage_tests():
    print("Do stuff...")
    do_stuff()
    yield

I put a print statement there so I could see it in the console when I'm running the tests, for better visibility into what the program is doing. But I don't see that text in the console, I'm guessing pytest swallows it. Is there any way to print from a fixture?

like image 817
Ram Rachum Avatar asked Jan 16 '16 11:01

Ram Rachum


People also ask

Can you print in pytest?

Allows to print extra content onto the PyTest reporting. This can be used for example to report sub-steps for long running tests, or to print debug information in your tests when you cannot debug the code.

How do I call a pytest fixture?

To access the fixture function, the tests have to mention the fixture name as input parameter. Pytest while the test is getting executed, will see the fixture name as input parameter. It then executes the fixture function and the returned value is stored to the input parameter, which can be used by the test.

What is pytest fixture ()?

What Are Pytest Fixtures? Pytest fixtures are functions that can be used to manage our apps states and dependencies. Most importantly, they can provide data for testing and a wide range of value types when explicitly called by our testing software. You can use the mock data that fixtures create across multiple tests.


2 Answers

Pytest doesn't not swallow the output, it's just not shown by default. To see output in console, try running test with -s option, like:

pytest -s <path_to_file>
like image 146
supamaze Avatar answered Sep 25 '22 07:09

supamaze


with pytest 3 use this fixture:

@pytest.fixture()
def tprint(request, capsys):
    """Fixture for printing info after test, not supressed by pytest stdout/stderr capture"""
    lines = []
    yield lines.append

    with capsys.disabled():
        for line in lines:
            sys.stdout.write('\n{}'.format(line))
like image 26
Victor Gavro Avatar answered Sep 25 '22 07:09

Victor Gavro