使用参数初始化 pytest 夹具 [英] initing a pytest fixture with a parameter

查看:54
本文介绍了使用参数初始化 pytest 夹具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个夹具可以创建我在许多测试中使用的对象.
这个对象有一个属性 - priority (1 - 10)

I have a fixture that creates an object I use in many tests.
This Object has a property - priority (1 - 10)

现在有很多测试需要知道"对象的优先级(为了测试各种逻辑路径)

Now, there are a lot of tests that need to "know" the priority of the object (in order to test various logic paths)

所以我可以有 10 个不同的装置:

So I could have 10 different fixtures:

@pytest.fixture
def object_priority_1():
    return MyObj(priority=1)
@pytest.fixture
def object_priority_2():
    return MyObj(priority=2)
//....
@pytest.fixture
def object_priority_10():
    return MyObj(priority=10)

但它似乎不对......我确定有一种方法可以每次将外部参数传递给夹具 - 我只是找不到它

But it seems off... I'm sure there is a way to deliver an external param to a fixture each time - I just couldn't find it

澄清一下 - 我本来想要以下领域的东西:

To clarify - I would have wanted something in the area of:

@pytest.fixture
    def my_object(<priority as an external param>):
        return MyObj(priority)

然后测试将类似于:

def test_foo(my_object(1), my_object(6)):
//...

推荐答案

你可以:

@pytest.fixture
def my_object(priority):
    return MyObj(priority)    

def test_foo(my_object):
    obj_1 = my_object(1)
    assert something # 1
    obj_2 = my_object(2)
    assert something # 2

我有这个想法,然后我发现了这个问答:

I come with this idea, then I found this Q&A :

py.test:将参数传递给夹具函数

如果您的问题得到解决,我认为您的问题可能会考虑重复.

I think your question maybe consider a duplicate if your problem is solved.

这篇关于使用参数初始化 pytest 夹具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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