在参数化中传递最难的夹具 [英] Passing pytest fixture in parametrize

查看:0
本文介绍了在参数化中传递最难的夹具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过在@pyest.mark.parametrize中传递在conposest.py中定义的装置,我收到以下错误:

pytest --alist="0220,0221" test_1.py -v -s
NameError: name 'alist' is not defined

confest.py:

def pytest_addoption(parser):
    parser.addoption("--alist", action="store")

@pytest.fixture
def alist(request):
    return request.config.getoption("--alist").split(",")

test_1.py:

@pytest.mark.parametrize("channel", alist, scope="class")
class TestRaIntegrationReplay:

    def test_ra_start_time(self, channel):
        print(channel)

如果我将list作为装备传递给测试,则如下所示:

    def test_ra_start_time(self, alist):
        for channel in alist:
            print(channel)

它工作得很好,但不能通过传递到@pyest.mark.parametrize来工作

推荐答案

如评论中所述,您不能将装备直接传递给mark.parametrize装饰器,因为装饰器是在加载时计算的。
您可以通过实现pytest_generate_tests

在运行时进行参数化
import pytest

@pytest.hookimpl
def pytest_generate_tests(metafunc):
    if "alist" in metafunc.fixturenames:
        values = metafunc.config.option.alist
        if value is not None:
            metafunc.parametrize("alist", value.split(","))

def test_ra_start_time(alist):
    for channel in alist:
        print(channel)

def test_something_else():
    # will not be parametrized
    pass

参数化是基于测试函数中alist参数的存在进行的。要使参数化起作用,需要此参数(否则会因为缺少参数而出错)。

这篇关于在参数化中传递最难的夹具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆