Python 如何使用pytest对测试计时?

Python 如何使用pytest对测试计时?,python,testing,automated-tests,pytest,Python,Testing,Automated Tests,Pytest,如何显示pytest执行的每个测试所花费的时间 我已经研究了pytest timeout、pytest timeit和pytest基准测试。pytest基准是最接近的,但需要手动包装每个测试 最迫切的需要是弄清楚为什么在Py3.x下进行测试所需的时间几乎是Py2.7的两倍。正如pytest所标识的那样,在我想要测试的包中有231个顶级测试,所以包装所有这些测试并不简单 您可以通过自动使用fixture和pytest\u runtest\u makereport来实现这一点 将以下代码添加到根co

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

我已经研究了pytest timeout、pytest timeit和pytest基准测试。pytest基准是最接近的,但需要手动包装每个测试


最迫切的需要是弄清楚为什么在Py3.x下进行测试所需的时间几乎是Py2.7的两倍。正如pytest所标识的那样,在我想要测试的包中有231个顶级测试,所以包装所有这些测试并不简单

您可以通过自动使用fixture和pytest\u runtest\u makereport来实现这一点

将以下代码添加到根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

希望它能帮助你

您可以通过自动使用fixture和pytest\u runtest\u makereport来实现这一点

将以下代码添加到根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

希望它能帮助你

这是一个很好的回答,很有教育意义。然而,我认为在其他人提到的问题中提供了更好的答案:持续时间=0。这是一个很好的回答,非常有教育意义。然而,我认为在其他人提到的问题中提供了更好的答案:持续时间=0。