What's the purpose of fixtures decorator in pytest?

In pytest, I create fixtures using the @pytest.fixture decorator. But I must admit I use it without knowing why.

What’s the difference between, for example:

x = 3


def x():
    return 3


When you call a fixture in a test function you get the value returned or yielded by the fixture.

For example

def test_sum(x):
   assert 5 + x == 8

It will take x (the name of your fixture) and get the returned value (in your case is 3) and add it to 5.

Obviously fixtures like this one are not very useful, but imagine getting data from a json, or a db. You can have a fixture that return the json data in a cleaner way without rewriting code, with the added benefit that they can be called via a function parameter. as I showed in the code above.

There are additional benefits, one off the top of my head: you can parameterize a fixture to provide multiple examples, and then tests that use that fixture will run on all the possibilities.

1 Like

I didn’t know that. Thanks :slight_smile: