Skip to content

When using ContextVars for db dependency injection all related tests are failing. #95

@madeinoz67

Description

@madeinoz67

Describe the bug
When using dependency injection instead of passing the db dependency down through all the layers, a ContextVars is being used. Passing the db sessions via ContextVar over function parameters is working with no problems with the application and results in a cleaner solution.

However with testing, a context is setup in a fixture and is not being propagated to the underlying test, resulting in the underlying function not finding the required context and failing.

This issue is documented pytest-dev/pytest-asyncio#127 and a PR pytest-dev/pytest-asyncio#161

Expected behaviour
the test fixture should be propagating the ContextVar down to the test function so it available to the function under test

Screenshots

LookupError: <ContextVar name='db_session_context' at 0x1120f29a0>
tests/test_services/test_part_service.py:23: in test_part_get
    item: PartModel = await part_service.create_part(obj_in)  # noqa:
app/services/part_service.py:103: in create_part
    db_session: AsyncSession = db_session_context.get()
E   LookupError: <ContextVar name='db_session_context' at 0x1120f29a0>

--------------------------------- Captured Log ---------------------------------

--------------------------------- Captured Out ---------------------------------


--------------------------------- Captured Err ---------------------------------
INFO  [alembic.env] DETECTED aiosqlite driver, stripping from DATABASE_URL for migration
INFO  [alembic.env] Database URL: sqlite:///./tests/files/test.db
INFO  [alembic.env] Running migrations online
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.runtime.migration] Running upgrade  -> 9905971ce75e, Adds Parts Table
INFO  [alembic.env] DETECTED aiosqlite driver, stripping from DATABASE_URL for migration
INFO  [alembic.env] Database URL: sqlite:///./tests/files/test.db
INFO  [alembic.env] Running migrations online
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.runtime.migration] Running downgrade 9905971ce75e -> , Adds Parts Table

Additional context
Should be resolved by this PR pytest-dev/pytest-asyncio#161

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: blockedSomething is blocking thistype: bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions