pytest:从夹具打印

问题描述 投票:0回答:3

我正在使用 Pytest 编写测试。我有一个这样的装置:

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

我在那里放置了一条打印语句,以便在运行测试时可以在控制台中看到它,以便更好地了解程序正在做什么。但我在控制台中没有看到该文本,我猜 pytest 吞下了它。有没有办法从固定装置打印?

python pytest
3个回答
18
投票

Pytest 不会吞掉输出,只是默认情况下不显示。要在控制台中查看输出,请尝试使用

-s
选项运行测试,例如:

pytest -s <path_to_file>

11
投票

在 pytest 3 中使用此夹具:

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

1
投票

我可以看到打印语句。但有一些重要的事情需要注意:

  • 因为你有
    scope=session
    ,所以这只在第一次测试时执行。
  • 如果第一个测试通过,则不会打印任何内容。您可以使用命令行选项 -s 强制打印标准输出(==不被 pytest 捕获)。
© www.soinside.com 2019 - 2024. All rights reserved.