覆盖pytest中的子装置

时间:2017-08-28 21:37:47

标签: python 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_service的{​​{1}},但实际情况是依赖链很长,我想重新使用所有的灯具,但有选择地在中间选择一些灯具来选择测试

我想做这样的事情(伪代码):

broken_resource

1 个答案:

答案 0 :(得分:3)

您可以在测试中使用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"
相关问题