0
0
PyTesttesting~5 mins

Factory fixtures in PyTest

Choose your learning style9 modes available
Introduction

Factory fixtures help create test data easily and consistently. They make tests simpler and cleaner by reusing setup code.

When you need to create multiple test objects with similar properties.
When test data setup is complex and repeated in many tests.
When you want to avoid duplicating code for creating test data.
When you want to customize test data for different test cases easily.
When you want to keep tests clean and focused on behavior, not setup.
Syntax
PyTest
import pytest

@pytest.fixture
def factory_name():
    def _factory(**kwargs):
        # create and return test object using kwargs
        return SomeObject(**kwargs)
    return _factory

The fixture returns a function that creates objects when called.

You can pass different parameters to customize each test object.

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

@pytest.fixture
def user_factory():
    def _factory(name="John", age=30):
        return {"name": name, "age": age}
    return _factory
Test uses the factory to create a user with age 25 and checks the age.
PyTest
def test_user_age(user_factory):
    user = user_factory(age=25)
    assert user["age"] == 25
Sample Program

This test file defines a factory fixture to create product dictionaries. Two tests check default and custom product data.

PyTest
import pytest

@pytest.fixture
def product_factory():
    def _factory(name="Book", price=10.0):
        return {"name": name, "price": price}
    return _factory

def test_default_product(product_factory):
    product = product_factory()
    assert product["name"] == "Book"
    assert product["price"] == 10.0

def test_custom_product(product_factory):
    product = product_factory(name="Pen", price=2.5)
    assert product["name"] == "Pen"
    assert product["price"] == 2.5
OutputSuccess
Important Notes

Factory fixtures improve test readability and reduce duplication.

Use keyword arguments to customize objects easily.

Keep factory fixtures simple and focused on creating test data.

Summary

Factory fixtures return a function to create test objects.

They help reuse and customize test data setup.

Using them keeps tests clean and easy to maintain.