如何在Pytest中使用fixture的覆盖参数?

5

假设我有一个类似这样的参数化fixture:

@pytest.fixture(params=[1, 2, 800]):
def resource(request):
    return Resource(capacity=request.param)

当我在测试函数中使用fixture作为参数时,Pytest会运行带有所有三个版本的测试:
def test_resource(resource):  # Runs for capacities 1, 2, and 800.
    assert resource.is_okay()

然而,对于一些测试,我希望更改构建 fixture 的参数:

def test_worker(resource, worker):  # Please run this for capacities 1 and 5.
    worker.use(resource)
    assert worker.is_okay()

我该如何指定只接收指定夹具的特定版本?
2个回答

6
如果您想为不同的测试使用不同的参数集,则pytest.mark.parametrize会很有帮助。
@pytest.mark.parametrize("resource", [1, 2, 800], indirect=True)
def test_resource(resource):
    assert resource.is_okay()

@pytest.mark.parametrize("resource", [1, 5], indirect=True)
def test_resource_other(resource):
    assert resource.is_okay()

3
“indirect=True”这个参数似乎是pytest中文件文档不够清晰的一个亮点!谢谢,这正是我所需要的! - radu.ciorba

3

我认为您无法配置它 “仅接收某些版本”,但是您可以明确地忽略其中的一些版本:

def test_worker(resource, worker):
    if resource.capacity == 800:
        pytest.skip("reason why that value won't work")
    worker.use(resource)
    assert worker.is_okay()

谢谢。你知道如何请求参数的装置吗? - danijar
@danijar 您的意思是什么?如果您认为应该将此功能添加到软件包中,请查看其网站以了解维护者希望这些类型的建议放在何处。不过,我建议您提出更具有说服力和少一些抽象的用例。 - jonrsharpe
1
在上面的示例中,fixture 被定义为参数 1、2 和 800。但在某些情况下,我想使用其他参数的 fixture。就像你展示的那样,我可以使用 pytest.skip() 忽略参数(我假设该行后应该有一个 return),但我无法添加新的参数,比如 5。 - danijar
在这种情况下,您可以将其添加到fixture中,并使用相同的方法跳过您不想要的内容。再次强调,更具体的示例可能会有所帮助;您为什么要以这种方式进行参数化?您是否阅读了例如http://doc.pytest.org/en/latest/skipping.html? - jonrsharpe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接