如何使用pytest进行时间测试?

Ree*_*ece 1 python testing automated-tests pytest

如何显示 pytest 执行的每个测试所花费的时间?

我调查了 pytest-timeout、pytest-timeit 和 pytest-benchmark。pytest-benchmark 最接近,但需要手动包装每个测试。

最迫切的需要是弄清楚为什么在 Py 3.x 下进行测试所需的时间几乎是 Py 2.7 的两倍。我要测试的包中有 231 个顶级测试(由 pytest 确定),因此包装所有这些并非易事。

Cha*_*rat 5

您可以通过自动使用夹具和 pytest_runtest_makereport

将以下代码添加到您的 root conftest.py。它会打印出每次测试的测试持续时间。

@pytest.fixture(scope='function', autouse=True)
def testcase_result(request):
    print("Test '{}' STARTED".format(request.node.nodeid))
    def fin():
        print("Test '{}' COMPLETED".format(request.node.nodeid))
        print("Test '{}' DURATION={}".format(request.node.nodeid,request.node.rep_call.duration))
    request.addfinalizer(fin)


@pytest.mark.tryfirst
def pytest_runtest_makereport(item, call, __multicall__):
    rep = __multicall__.execute()
    setattr(item, "rep_" + rep.when, rep)
    return rep
Run Code Online (Sandbox Code Playgroud)

希望对你有帮助!

  • 这是一个很好的回应,非常有教育意义。但是,我认为在其他人引用的问题中提供了更好的答案:--durations=0 (/sf/ask/1951908311/ -tests-with-py-test)。 (3认同)