2016-08-21 33 views
2

比方說,我有一個參數化夾具這樣的:如何在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() 

我怎麼可以指定只接受SPECI的某些版本fied夾具?

回答

3

如果您要使用不同的參數不同的測試然後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() 
+0

'indirect = True'位似乎是pytest中記錄不完整的寶石之一!謝謝,這正是我需要的! –

2

我不認爲你可以配置它「只接收某些版本的」,但你可以明確地忽略了其中的一些:

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

謝謝。你知道如何爲* new *參數請求燈具嗎? – danijar

+0

@danijar你是什麼意思?如果您認爲應將此功能添加到軟件包中,請檢查其網站,以查看維護人員想要的這些建議。不過,我建議你想出一個更引人注目,更抽象的用例。 – jonrsharpe

+0

在上面的例子中,夾具是爲參數1,2和800定義的。但是在某些情況下,我想使用具有其他參數的夾具。我可以使用'pytest.skip()'來忽略參數(我假設在那行後面應該有一個'return'),但是我不能添加新的參數,例如5 – danijar