微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在一次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 举报,一经查实,本站将立刻删除。