关于python:如何使用pytest进行时间测试?

How to time tests with pytest?

本问题已经有最佳答案,请猛点这里访问。

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

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

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


您可以通过自动使用Fixture和pytest_runtest_makereport

将以下代码添加到根conftest.py中。 它将打印出每个测试的测试持续时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@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

希望对您有帮助!