Introduction to Pytest Fixtures

Overview of pytest fixtures

A really useful feature of pytest is fixtures. Fixtures allow us to create reusable code that can be used across multiple tests.

A fixture is a function that returns an object that will be used in our tests. They can be used to set up preconditions or data for a test or to clean up after a test. Pytest fixtures are used to make testing code easier and more efficient. They can be used to create test data, set up database connections, and more.

Fixtures can provide their values to test functions using return or yield statements. If we have teardown code in the fixture, it is important to use the yield statement instead of return in the fixture definition because this allows the teardown code to be executed after the test has been completed.

Note: We cannot have multiple yield statements in a single fixture.

Configuration file

In pytest, conftest.py is a special file that allows us to define fixtures, hooks, and plugins that can be shared across multiple test files in a directory or its subdirectories. In a conftest.py file, we can define fixtures that can be used by tests in the same directory and its subdirectories. This helps avoid the duplication of code and ensures a consistent setup and teardown of resources for all tests that use the fixture.

Fixtures defined in a conftest.py file can be used by any test without importing them. Pytest discovers them automatically. We’ll learn about pytest discovery and test organization in upcoming lessons.

These fixtures are defined using the @pytest.fixture decorator. An example is given below:

Get hands-on with 1200+ tech skills courses.