Pytest:查找每个测试的开始和结束时间

Ram*_*hum 6 python testing pytest pytest-django

我有一个复杂的 Django-Pytest 测试套件,其中有许多在并行进程中运行的测试。我想查看每个测试开始和结束的确切时间点。我怎样才能从 Pytest 中获取这些信息?

hoe*_*ing 5

每个调用阶段的开始/停止时间戳存储在CallInfo对象中。但是,访问这些用于报告不是很方便,因此最好将两个时间戳都存储在报告对象中。将以下代码放入conftest.py项目/测试根目录中的文件中:

import pytest


@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()
    report.start = call.start
    report.stop = call.stop
Run Code Online (Sandbox Code Playgroud)

既然您已经通过开始/停止时间增强了每个报告,请按照您需要的方式处理它们,例如在测试执行后将它们打印在自定义部分中。使用以下方法增强您的conftest.py文件:

def pytest_terminal_summary(terminalreporter):
    terminalreporter.ensure_newline()
    terminalreporter.section('start/stop times', sep='-', bold=True)
    for stat in terminalreporter.stats.values():
        for report in stat:
            if report.when == 'call':
                start = datetime.fromtimestamp(report.start)
                stop = datetime.fromtimestamp(report.stop)
                terminalreporter.write_line(f'{report.nodeid:20}: {start:%Y-%m-%d %H:%M:%S} - {stop:%Y-%m-%d %H:%M:%S}')
Run Code Online (Sandbox Code Playgroud)

示例测试的测试执行

def test_spam():
    time.sleep(1)


def test_eggs():
    time.sleep(2)
Run Code Online (Sandbox Code Playgroud)

现在产生:

test_spam.py ..                                                         [100%]

------------------------------ start/stop times -------------------------------
test_spam.py::test_spam: 2020-04-26 13:29:05 - 2020-04-26 13:29:06
test_spam.py::test_eggs: 2020-04-26 13:29:06 - 2020-04-26 13:29:08
============================== 2 passed in 3.03s ==============================
Run Code Online (Sandbox Code Playgroud)

请注意,在上面的pytest_terminal_summaryhookimpl 示例中,我只打印了call阶段的时间(测试函数的执行时间)。如果您想查看或包含测试设置/拆卸阶段的时间戳,请分别terminalreporter.stats使用report.when == 'setup'/过滤报告对象report.when == 'teardown'