Automate user creation using fixture factory
Preconditions (2)
✅ Expected Result: The test should pass confirming that the fixture factory creates user objects correctly with default and custom attributes
import pytest class User: def __init__(self, username, email): self.username = username self.email = email @pytest.fixture def user_factory(): def create_user(username='defaultuser', email='default@example.com'): return User(username, email) return create_user def test_user_creation(user_factory): default_user = user_factory() assert default_user.username == 'defaultuser' assert default_user.email == 'default@example.com' custom_user = user_factory(username='testuser', email='testuser@example.com') assert custom_user.username == 'testuser' assert custom_user.email == 'testuser@example.com'
This test uses a fixture factory user_factory that returns a function to create User objects with default or custom attributes.
The test test_user_creation calls the factory twice: once with defaults and once with custom username and email.
Assertions check that the created users have the expected usernames and emails.
This pattern keeps test data creation flexible and reusable.
Now add data-driven testing with 3 different user inputs using the fixture factory
@pytest.fixture
def user_factory():
def create_user(name):
return {'name': name, 'active': True}
return create_user
def test_user_active(user_factory):
user = user_factory('Alice')
assert user['active'] is True
@pytest.fixture
def product_factory():
def create_product(name, price):
return {'name': name, 'price': price}
return create_product
def test_product(product_factory):
product = product_factory('Book')
assert product['price'] > 0
Pass the test and this pattern moves unknown