首页 > 解决方案 > 在测试功能中使用夹具

问题描述

我在使用夹具装饰器中使用多个夹具,如下所示:

@pytest.mark.usefixtures(fixture1, fixture2)
def test_me:

夹具文件:

@pytest.fixture
def fixture1:

@pytest.fixture
def fixture2:

问题是我需要在我的代码片段中的特定行触发这两个夹具,但这两个夹具同时触发。

如何做到这一点?

标签: pythonpytest

解决方案


fixtures 不是同时触发的,但是当您将它们用作参数时,它们都会在测试之前触发,这是预期的行为。如果您尝试从测试中调用夹具,您也可以在错误消息中看到它

def test_me():
    fixture1()

直接调用夹具“fixture1”。Fixtures 不是直接调用的,而是在测试函数请求它们作为参数时自动创建的。

如果您的所有测试都需要在测试运行时使用固定装置,请不要使用常规功能而不是固定装置。如果此用例是唯一的,您可以添加另一个可以从夹具和测试中调用的函数

def fixture1_implementation():
    ...


@pytest.fixture
def fixture1():
    fixture1_implementation()


def test_me():
    fixture1_implementation()

# or

@pytest.mark.usefixtures('fixture1')
def test_example():
    ...

推荐阅读