python - 如何访问pytest中的整体运行时?

标签 python testing pytest

运行测试后在pytest中有概览:

============= 7 在 1.11 秒内通过 ============

我喜欢访问 pytest 结束时的时间(这里是 1.11)。

我在这里找到了一些有用的信息:

How can I access the overall test result of a pytest test run during runtime?

但与整体测试运行时间不符。

我尝试使用 def pytest_sessionfinish(session, exitstatus)

我没有在那里找到总持续时间。

看起来该值在 RunResult 对象中。 https://docs.pytest.org/en/latest/_modules/_pytest/pytester.html#RunResult

如何访问?

最佳答案

您可以在TerminalReporter 插件实例中访问执行开始时间戳,然后自己计算执行时间(这也是pytest 本身所做的)。示例:

# conftest.py

import time

def pytest_sessionfinish(session, exitstatus):
    reporter = session.config.pluginmanager.get_plugin('terminalreporter')
    duration = time.time() - reporter._sessionstarttime
    reporter.write_sep('=', 'duration: {} seconds'.format(duration), yellow=True, bold=True)

更新

looki 所述在注释中,当运行使用 pytest-xdist 分发的测试时,这不会返回总体执行时间,因为每个进程都成为它自己的 session 实例。切换到 pytest_unconfigure hook(实现方式差不多):

def pytest_unconfigure(config):
    reporter = config.pluginmanager.get_plugin('terminalreporter')
    duration = time.time() - reporter._sessionstarttime
    reporter.write_sep('=', 'duration: {} seconds'.format(duration), yellow=True, bold=True)

关于python - 如何访问pytest中的整体运行时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56271207/

相关文章:

python - 如何用非数字列的模式替换空值?

Python 3 C扩展导入时出现段错误

macos - 由于环境错误 : [Errno 13] Pip install Pytest,无法安装软件包

python - TypeError:不能理解的数据类型opencv python

python - 创建表时修改DEFAULT子句

Java JUnit 测试

ruby - 在 RSpec 中期待 Lambda

ios - XC 测试框架 iOS(XCode 6.1) 测试 session 退出 (80) 未 checkin

automated-tests - 剧作家派森. - 如何检查元素是否隐藏

python - 将 pytest 工作目录更改为测试用例目录