pytest-xdist启动测试开3个进程但这会导致pytest_terminal_summary也执行3次我希望pytest_terminal_summary只执行以后一次就行
您可以使用pytest hook机制来实现这个目标。您可以在conftest.py文件中定义pytest_terminal_summary hook,并在其中记录已经执行的次数。然后,您可以使用pytest_configure hook来检查当前是否在xdist运行模式下,并根据情况禁用pytest_terminal_summary hook。
以下是示例代码:
# conftest.py
import pytest
def pytest_terminal_summary(terminalreporter):
terminalreporter._num_summary_calls += 1
@pytest.hookimpl(tryfirst=True)
def pytest_configure(config):
if config.pluginmanager.hasplugin('xdist'):
if config.workerinput['workerid'] == 'gw0': # only run on the first worker
config.pluginmanager.register(XdistSummaryPlugin(config), 'xdist-summary')
class XdistSummaryPlugin:
def __init__(self, config):
self.config = config
self.num_summary_calls = 0
def pytest_terminal_summary(self, terminalreporter):
self.num_summary_calls += 1
if self.num_summary_calls == self.config.workercount:
# do whatever you want to do in the final summary here
terminalreporter.write_line("Final summary")
在这个例子中,我们定义了一个名为XdistSummaryPlugin的插件,它在第一个worker进程上注册了pytest_terminal_summary hook。在每个worker进程上,pytest_terminal_summary hook会被调用,并记录已经执行的次数。在最后一个worker进程上,我们可以执行任何需要在最终总结中执行的操作,然后使用terminalreporter.write_line输出最终总结。
请注意,我们使用了pytest.hookimpl(tryfirst=True)来确保我们的hook先于其他插件运行。这样,我们可以确保我们的hook在其他插件之前运行,并记录正确的执行次数。
原文地址: https://www.cveoy.top/t/topic/bIP1 著作权归作者所有。请勿转载和采集!