0
0
PyTesttesting~15 mins

Factory fixtures in PyTest - Build an Automation Script

Choose your learning style9 modes available
Automate user creation using factory fixture
Preconditions (2)
Step 1: Create a factory fixture that generates User instances with default values
Step 2: Use the factory fixture to create a user in the test
Step 3: Verify the created user has the expected default username and email
Step 4: Verify the user is active by default
✅ 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.
Automation Requirements - pytest
Assertions Needed:
Assert the username equals the default username from the factory
Assert the email equals the default email from the factory
Assert is_active is True
Best Practices:
Use pytest fixtures to define the factory
Use factory_boy for factory implementation
Keep test isolated and independent
Use clear and descriptive assertion messages
Automated Solution
PyTest
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.

Common Mistakes - 4 Pitfalls
Not using a fixture for the factory and creating factory instances directly in the test
{'mistake': 'Hardcoding user data in the test instead of using factory defaults', 'why_bad': 'Leads to duplication and brittle tests if defaults change.', 'correct_approach': "Use the factory's default attributes and assert against them."}
Not asserting all important fields like is_active
Using print statements instead of assertions
Bonus Challenge

Now add data-driven testing with 3 different user inputs using the factory fixture

Show Hint