Is there any way to use the same fixture multiple times in a function with pytest?

1.5k Views Asked by At

Like this

@pytest.fixture
def myfixture():
   # creates a complex object

def test_compare(myfixture,myfixture):
   #compares

Is there a way to know which fixture am I working on? The generated objects are different

Thanks

2

There are 2 best solutions below

0
Chanda Korat On

Why you want to compare objects returned by fixture? Fixtures are not meant to be so.

As per the documentation,

The purpose of test fixtures is to provide a fixed baseline upon which tests can reliably and repeatedly execute.

If you want to compare returned objects, just make it as a function, not as a fixture.Like.

def myfixture():
   # creates a complex object

def test_compare():
   a=myfixture()
   b=myfixture()
   #compare a and b
0
Sardorbek Imomaliev On

You are looking for factory pattern https://docs.pytest.org/en/latest/fixture.html#factories-as-fixtures

Here is SO question about advantages of fixture factories Why would a pytest factory as fixture be used over a factory function?

Answering your question

@pytest.fixture
def myfixture():
   def _make_fixture():
       # creates a complex object
   return _make_fixture

def test_compare(myfixture):
    data1 = myfixture()
    data2 = myfixture()
    #compares