0
0
PyTesttesting~15 mins

Fixture factories in PyTest - Build an Automation Script

Choose your learning style9 modes available
Automate user creation using fixture factory
Preconditions (2)
Step 1: Use the fixture factory to create a user with default attributes
Step 2: Use the fixture factory to create a user with a custom username 'testuser'
Step 3: Verify that the created user objects have the expected attributes
✅ Expected Result: The test should pass confirming that the fixture factory creates user objects correctly with default and custom attributes
Automation Requirements - pytest
Assertions Needed:
Assert default user has username 'defaultuser'
Assert custom user has username 'testuser'
Best Practices:
Use fixture factory pattern to generate test data
Keep fixtures modular and reusable
Use assert statements for validation
Avoid hardcoding test data inside tests
Automated Solution
PyTest
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.

Common Mistakes - 3 Pitfalls
Defining fixture that returns a fixed user object instead of a factory function
Hardcoding user data inside the test instead of using the fixture factory
Not using assert statements to verify user attributes
Bonus Challenge

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

Show Hint