Fixtures in pytest

Learn how to use fixtures from pytest for testing purposes.

Data parameters work well when we have the data we need to test, or we know how to build it easily, but in some cases, we need specific objects to be constructed for a test, or we find ourself writing or building the same objects repeatedly. To help with this, we can use fixtures.

Working with fixtures

Fixtures in pytest are functions or methods decorated with @pytest.fixture that provide reusable setup and teardown code for tests.

One of the great things about pytest is how it facilitates creating reusable features so that we can feed our tests with data or objects to test more effectively and without repetition.

Fixtures example

For example, we might want to create a MergeRequest object in a particular state and use that object in multiple tests. We define our object as a fixture by creating a function and applying the @pytest.fixture decorator. The tests that want to use that fixture will have to have a parameter with the same name as the function that's defined, and pytest will make sure that it's provided:

Get hands-on with 1200+ tech skills courses.