【pytest】 用例运行时间统计

  1. 使用 --duration 参数:

pytest 提供了一个 --duration 参数,它可以在测试运行后显示最慢的 N 个测试用例的运行时间。例如,要显示最慢的 10 个测试用例的运行时间,你可以使用以下命令:

 
pytest --duration=10

 

  1. 使用 pytest-benchmark 插件:

虽然 pytest-benchmark 主要用于基准测试,但它也可以用来跟踪测试用例的运行时间。你可以使用它来获取更详细的性能数据。

首先,你需要安装插件:

bash复制代码
pip install pytest-benchmark

然后,在测试文件或命令行中使用它。但是请注意,这个插件主要是用于基准测试,而不仅仅是显示运行时间。
3. 使用 pytest 钩子:

你可以使用 pytest 的钩子(如 pytest_runtest_logreport)来跟踪每个测试用例的运行时间。你可以创建一个自定义的 pytest 插件或使用 conftest.py 文件来实现这一点。

以下是一个简单的示例,使用 conftest.py 来记录每个测试用例的运行时间:

# conftest.py  
import pytest  
import time  
  
class TestTimer:  
    def __init__(self):  
        self.start_time = None  
  
    def start(self):  
        self.start_time = time.time()  
  
    def stop(self):  
        return time.time() - self.start_time  
  
def pytest_runtest_setup(item):  
    item.user_properties.setdefault("timer", TestTimer()).start()  
  
def pytest_runtest_logreport(report):  
    if report.when == "call" and report.passed:  
        duration = report.item.user_properties["timer"].stop()  
        print(f"Test {report.nodeid} took {duration:.2f} seconds to run.")

在这个示例中,我们创建了一个 TestTimer 类来跟踪每个测试用例的开始和结束时间。然后,在 pytest_runtest_setup 钩子中,我们为每个测试用例启动一个计时器。在 pytest_runtest_logreport 钩子中,我们停止计时器并打印出每个成功通过的测试用例的运行时间。
4. 使用 pytest 插件和报告生成器:

还有其他一些 pytest 插件(如 pytest-htmlpytest-json-report 等)可以生成详细的测试报告,其中包括每个测试用例的运行时间。这些插件通常提供更丰富的功能和更好的可读性。

posted on 2024-06-21 11:02  彩屏黑白  阅读(56)  评论(0编辑  收藏  举报

导航