Ram Rachum
Ram Rachum

Reputation: 88708

pytest: printing from fixture

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?

Upvotes: 20

Views: 8645

Answers (3)

supamaze
supamaze

Reputation: 9513

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

pytest -s <path_to_file>

Upvotes: 18

Victor Gavro
Victor Gavro

Reputation: 1407

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))

Upvotes: 12

pfctdayelise
pfctdayelise

Reputation: 5285

I can see a print statement. But there are a couple of important things to note:

  • Because you have scope=session, this is only executed during the first test.
  • If the first test passes, nothing will be printed out. You can force the stdout to printed anyway (==not captured by pytest) by using the command-line option -s.

Upvotes: 1

Related Questions