2017-08-28 16 views
0

我使用pytest與一些複雜的依賴注入裝置。我有固定裝置在長鏈中使用其他裝置。我希望能夠在鏈條中間修改一些固定裝置以進行特定的測試。覆蓋pytest中的子裝置

鑑於這些(簡體)燈具:

@pytest.fixture 
def cache(): 
    return Cache() 

# Use cache fixture in a new fixture. 
@pytest.fixture 
def resource(cache): 
    return Resource(cache=cache, working=True) 

# Use resource fixture in a new fixture. 
@pytest.fixture 
def service(resource): 
    return Service(resource=resource) 

和一些測試:

def test_service_when_resource_working(service): 
    assert service.status == "good" 

def test_service_when_resource_broken(service): 
    assert service.status == "bad" 

我如何可以覆蓋resource夾具,這樣是這樣的:

@pytest.fixture 
def broken_resource(cache): 
    return Resource(cache=cache, working=False) 

。 ..但僅限於test_service_when_resource_broken測試用例?我可以創建一個使用broken_resourcebroken_service,但實際情況是依賴鏈很長,我想重新使用所有的燈具,但在選擇的測試中選擇性地更改其中的一些。

我想要做這樣的事情(僞):

@pytest.override_fixture('resource', 'broken_resource') 
def test_service_when_resource_broken(service): 
    # service should have been instantiated with broken_resource instead of resource. 
    assert service.status == "bad" 

回答

2

您可以使用您的測試markers達到你期待什麼。 基本上,你需要標記你需要不同行爲的測試。在fixture方法中,從請求的測試上下文和進程中查找該標記。

這裏是你如何做到這一點。

@pytest.fixture 
def cache(): 
    return Cache() 

# Use cache fixture in a new fixture. 


@pytest.fixture 
def resource(request, cache): 
    working = True 
    marker = request.node.get_marker("broken") 
    if marker: 
     working = False 

    return Resource(cache=cache, working=working) 


# Use resource fixture in a new fixture. 
@pytest.fixture 
def service(resource): 
    return Service(resource=resource) 


def test_service_when_resource_working(service): 
    assert service.status == "good" 


@pytest.mark.broken 
def test_service_when_resource_broken(service): 
    assert service.status == "bad" 
+0

完美。謝謝! –

+0

很高興,它有幫助,請您將答案標記爲已接受。 – Sanju