如何在一次pytest-xdist运行中从参数化测试函数收集值

问题描述

我使用pytest-xdist运行一个参数化的测试函数,该函数具有我感兴趣的变量。我想将变量的值存储在单独的对象中,并在以后使用该对象编写测试报告。

我尝试使用一个会话范围固定装置,该装置应该在所有测试完成并且结果对象变得可用之后立即运行一次。乍一看,它确实运行良好,但我发现pytest-xdist does not have内置支持,可确保一次会话范围内的夹具仅执行一次。这意味着我的存储对象很可能是从头开始重写了N次,其中N是共享我的测试的许多pytest-xdist工作者。这不是可取的行为。

简短的片段说明问题

# test_x.py

import pytest
from typing import Tuple
from typing import List

@pytest.mark.parametrize('x',list(range(4)))
def test_x(x):
    result = (str(x),x ** 2)  # <-- here I have a dummy result,say a tuple

def write_report(results: List[Tuple[str,int]]):
    # here I would like to have ALL the results that is `results` expected to be:
    # [('0',0),('1',1),('2',4),('3',9)]
    # considering the fact test_x was paralleled by pytest-xdist to N > 1 workers.
    ...

我用pytest -n auto test_x.py

运行它

在这种顺序的多处理测试调用中,还有另一种方法来收集所有result值吗?我将不胜感激。

Edited

昨天我发现了一个很有前途的package pytest_harvest,但是还没有实现。只要不涉及pytest-xdist,一切都会顺利进行。出色的results_bag固定装置可以按预期的方式工作,将需要的值存储起来,并在所有结果停止时将其返回到会话结果挂钩pytest_sessionfinish中。但是,当您添加xdist worker时,突然没有会话结果(尽管它确实返回一个空字典)。

# conftest.py
from pytest_harvest import is_main_process
from pytest_harvest import get_session_results_dct

def pytest_sessionfinish(session):
    dct = get_session_results_dct(session)
    if is_main_process(session):
        print(dct) # prints an empty OrderedDict...

# test_parallel.py
import pytest

@pytest.mark.parametrize('x',list(range(3)))
def test_parallel(x,results_bag):
    results_bag.x = x

pytest -sv test_parallel.py->确定

pytest -sv -n auto test_parallel.py->一个空的OrderedDict

有人在想如何使它像样地工作吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)