0
0
PyTesttesting~5 mins

Fixture factories in PyTest

Choose your learning style9 modes available
Introduction

Fixture factories help create reusable test data or objects with different settings easily. They make tests cleaner and avoid repeating code.

When you need similar test data but with small differences in each test.
When you want to create multiple objects with different properties for testing.
When you want to avoid repeating fixture code for similar setups.
When you want to customize test data dynamically inside tests.
When you want to keep your tests simple and readable by reusing setup logic.
Syntax
PyTest
import pytest

@pytest.fixture
def factory_name():
    def _factory(param1, param2):
        # create and return object using params
        return SomeObject(param1, param2)
    return _factory

The outer fixture returns an inner function (the factory) that creates objects.

You call the factory inside your test with different parameters to get different objects.

Examples
This fixture factory creates user dictionaries with given name and age.
PyTest
import pytest

@pytest.fixture
def user_factory():
    def _create_user(name, age):
        return {'name': name, 'age': age}
    return _create_user
Using the factory to create two different users inside one test.
PyTest
def test_users(user_factory):
    user1 = user_factory('Alice', 30)
    user2 = user_factory('Bob', 25)
    assert user1['name'] == 'Alice'
    assert user2['age'] == 25
Sample Program

This test uses a fixture factory to create products with different prices and checks their values.

PyTest
import pytest

@pytest.fixture
def product_factory():
    def _create_product(name, price):
        return {'name': name, 'price': price}
    return _create_product

def test_product_prices(product_factory):
    cheap = product_factory('Pen', 1.5)
    expensive = product_factory('Laptop', 1200)
    assert cheap['price'] < expensive['price']
    assert cheap['name'] == 'Pen'
    assert expensive['name'] == 'Laptop'
OutputSuccess
Important Notes

Fixture factories keep your tests flexible and avoid duplication.

Always return the inner factory function from the fixture.

You can add default values or optional parameters inside the factory function.

Summary

Fixture factories return a function to create test data with different inputs.

They help write cleaner and reusable test setups.

Use them when you need similar objects with small differences in tests.