0
0
PyTesttesting~15 mins

Parametrize with indirect fixtures in PyTest - Build an Automation Script

Choose your learning style9 modes available
Test login functionality with multiple user roles using indirect fixtures
Preconditions (3)
Step 1: Use pytest.mark.parametrize to pass different user roles to the 'user' fixture indirectly
Step 2: For each user role, call the login function with credentials from the fixture
Step 3: Verify that login returns success for valid users
✅ Expected Result: The test runs for each user role, login succeeds, and assertions pass for all cases
Automation Requirements - pytest
Assertions Needed:
Assert login function returns True for each user role
Best Practices:
Use pytest.mark.parametrize with indirect=True to pass parameters to fixtures
Keep test functions simple and focused
Use fixtures to manage setup and teardown
Automated Solution
PyTest
import pytest

# Simulated login function

def login(username, password):
    valid_users = {"admin": "adminpass", "guest": "guestpass", "user": "userpass"}
    return valid_users.get(username) == password

# Fixture that receives user role indirectly
@pytest.fixture
def user(request):
    role = request.param
    credentials = {
        "admin": ("admin", "adminpass"),
        "guest": ("guest", "guestpass"),
        "user": ("user", "userpass")
    }
    return credentials[role]

# Test function using indirect parametrize
@pytest.mark.parametrize("user", ["admin", "guest", "user"], indirect=True)
def test_login(user):
    username, password = user
    assert login(username, password) is True

This code defines a login function that checks if the username and password match known valid users.

The user fixture uses request.param to receive the user role indirectly from the test parameter. It returns the corresponding credentials tuple.

The test test_login uses pytest.mark.parametrize with indirect=True to pass the user roles to the user fixture. For each role, it gets credentials and asserts that login succeeds.

This approach keeps test data separate from setup logic and makes tests clear and reusable.

Common Mistakes - 3 Pitfalls
Not using indirect=true in parametrize when passing parameters to fixtures
Hardcoding credentials inside the test instead of using fixtures
Using mutable default arguments in fixtures
Bonus Challenge

Now add data-driven testing with 3 different sets of invalid credentials to verify login fails

Show Hint