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

How to use override parameters of a fixture in Pytest?

假设我有一个这样的参数化夹具:

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

当我在测试函数中使用夹具作为参数时,Pytest 使用所有三个版本运行测试:

def test_resource(resource):  # Runs for capacities 1, 2, and 800.
    assert resource.is_okay()

但是,对于某些测试,我想更改构建夹具的参数:

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

如何指定只接收特定版本的指定夹具?

我不认为你可以配置它"to only receive certain versions",但你可以明确地忽略其中的一些:

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()

如果您想对不同的测试使用不同的参数集,那么 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()