首页 > 解决方案 > 使用 pytest 在控制台中打印最快的测试

问题描述

我可以使用 打印最慢的测试--durations=1。但是我怎样才能打印最快?我认为答案与终端摘要有关。但我需要以某种方式测试持续时间。我在类似的问题中找到了这段代码,但它不起作用。

def pytest_terminal_summary(terminalreporter, exitstatus, config):
    for reps in terminalreporter.stats.values():
        for rep in reps:
            if rep.when == "call":
                print("duration reported after all tests passed:", rep.nodeid, rep.duration)

我收到一个错误AttributeError: 'WarningReport' object has no attribute 'when'

标签: pythonpytest

解决方案


我自己想通了:

def pytest_terminal_summary(terminalreporter, exitstatus, config):
    time_value = []
    for reps in terminalreporter.stats.values():
        for rep in reps:
            try:
                if rep.when == "call":
                    time_value.append((rep.nodeid, rep.duration))
            except AttributeError:
                pass
    print("Fastest test:", min(time_value, key=lambda x: x[1]))

输出:

Fastest test: ('tests/test_database.py::TestDatabase::test_method_5', 0.09348350000000005)


推荐阅读