Skip to content

Extending Fixtures and Renaming Fixtures

Extending Fixtures

Fixtures can use other fixtures. This allows you to build modular chains of dependencies.

Important Rule: A fixture can only request other fixtures that have the same or wider scope.

  • ✅ A function scoped fixture can request a session scoped fixture.
  • ❌ A session scoped fixture cannot request a function scoped fixture.
python
@pytest.fixture(scope="session")
def db_engine():
    return create_engine()

@pytest.fixture(scope="function")
def db_session(db_engine):
    # Depending on the wider scoped 'db_engine'
    session = db_engine.connect()
    yield session
    session.close()

Renaming Fixtures

If a fixture name is too long or conflicts with a variable name, you can assign it a specific name using the name argument.

python
@pytest.fixture(name="user")
def create_complex_user_object_helper():
    return "UserObject"

def test_user_login(user):
    # We access the fixture using the alias "user"
    assert user == "UserObject"