Using fixtures inside test function

Viewed 403

I am using multiple fixtures inside a use fixture decorator as below:

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

Fixtures file:

@pytest.fixture
def fixture1:

@pytest.fixture
def fixture2:

The problem is that I need these two fixtures to be triggered at a specific line in my code snippet, but these two fixtures triggers simultaneously.

How can this be achieved?

1 Answers

The fixtures are not triggers simultaneously, but both are triggered before the test when you use them as arguments, which is the expected behavior. You can also see it in the error message if you try to call the fixture from the test

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.

If all your tests require the fixtures in test run time don't use regular functions and not fixtures. If this usecase is unique you can add another function that can be called from the fixture and from the tests

def fixture1_implementation():
    ...


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


def test_me():
    fixture1_implementation()

# or

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