Automate user creation using factory fixture
Preconditions (2)
✅ Expected Result: The test should create a User instance using the factory fixture and assert that the username, email, and is_active fields have the expected default values.
Jump into concepts and practice - no test required
import pytest import factory # Simulated User model for testing class User: def __init__(self, username, email, is_active=True): self.username = username self.email = email self.is_active = is_active # Factory class for User class UserFactory(factory.Factory): class Meta: model = User username = "testuser" email = "testuser@example.com" is_active = True @pytest.fixture def user_factory(): return UserFactory def test_create_user_with_factory(user_factory): user = user_factory() assert user.username == "testuser", f"Expected username 'testuser', got {user.username}" assert user.email == "testuser@example.com", f"Expected email 'testuser@example.com', got {user.email}" assert user.is_active is True, f"Expected is_active True, got {user.is_active}"
This test uses factory_boy to create a UserFactory that generates User instances with default values.
The user_factory pytest fixture returns the factory class, so the test can call it to create a user.
The test test_create_user_with_factory calls the factory to create a user and then asserts the username, email, and is_active fields match the expected defaults.
Assertions include messages to help understand failures.
This approach keeps test data creation clean and reusable.
Now add data-driven testing with 3 different user inputs using the factory fixture
@pytest.fixture
def number_factory():
def create_number(x):
return x * 2
return create_number
def test_double(number_factory):
result = number_factory(5)
assert result == 10
print(result)@pytest.fixture
def item_factory():
def create_item(name, price):
return {'name': name, 'price': price}
return create_item
def test_item(item_factory):
item = item_factory('Book')
assert item['price'] == 10