在测试函数中使用 fixtures

Using fixtures inside test function

我在 use fixture 装饰器中使用了多个 fixture,如下所示:

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

夹具文件:

@pytest.fixture
def fixture1:

@pytest.fixture
def fixture2:

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

如何实现?

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

def test_me():
    fixture1()

Fixture "fixture1" called directly. Fixtures are not meant to be called directly, but are created automatically when test functions request them as parameters.

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

def fixture1_implementation():
    ...


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


def test_me():
    fixture1_implementation()

# or

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