Home > Back-end >  How to pass a list of fixtures to a test case in Pytest?
How to pass a list of fixtures to a test case in Pytest?

Time:10-27

I have a case where I need a list of fixtures (similar ones) inside a test case and perform same operation with those fixtures.

For ex:

def testcase(fixture1, fixture2, fixture3):
    # do some operation with fixture1
    # do the same operation with fixture2
    # do the same operation with fixture3

The thing is I have multiple such fixtures. Around 15 or so. I'm looking for a way where I can mention these fixtures in a list like fixtures_list = [fixture1, fixture2, fixture3, ...] and update the list whenever needed.

And use a for loop inside the test case to perform operations on with the fixture like

for fixture in fixtures_list:
    #do something with fixture

But I'm unable to do it as we must definitely pass the fixture to the test case.

Is there any way to overcome this?

CodePudding user response:

I was able to achieve this by creating another fixture and returning the fixtures inside that fixture.

def fixture_that_returns_other_fixtures(fix1, fix2, fix3):
    return fix1, fix2, fix3

and used fixture_that_returns_other_fixtures in all other tests wherever needed.

CodePudding user response:

From the pytest doc Here:

import pytest


class Fruit:
    def __init__(self, name):
        self.name = name

    def __eq__(self, other):
        return self.name == other.name


@pytest.fixture
def my_fruit():
    return Fruit("apple")


@pytest.fixture
def fruit_basket(my_fruit):
    return [Fruit("banana"), my_fruit]


def test_my_fruit_in_basket(my_fruit, fruit_basket):
    assert my_fruit in fruit_basket

Assuming this example and what you want, you can juste create a new fixture that takes your fixtures as parameters, and return them in a list.

Here is the same test, written with the appropriate solution:

@pytest.fixture
def all_fixtures(my_fruit, fruit_basket):
    return [my_fruit, fruit_basket]

def test_my_fruit_in_basket_bis(all_fixtures):
    assert all_fixtures[0] in all_fixtures[1]
  • Related