pytest:从夹具打印

Ram*_*hum 5 python pytest

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

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

我在此处放置了一条打印语句,以便在运行测试时可以在控制台中看到它,以更好地了解程序的运行情况。但是我在控制台中看不到该文本,我猜想pytest会吞下它。有什么办法可以从固定装置打印?

Vic*_*vro 7

与 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))
Run Code Online (Sandbox Code Playgroud)


sup*_*aze 5

Pytest不会吞下输出,默认情况下不会显示。要在控制台中查看输出,请尝试运行带有-s选项的测试,例如:

pytest -s <path_to_file>
Run Code Online (Sandbox Code Playgroud)


pfc*_*ise 1

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

  • 因为你有scope=session,所以这仅在第一次测试期间执行。
  • 如果第一个测试通过,则不会打印任何内容。您可以使用命令行选项 -s 强制打印标准输出(==不被 pytest 捕获