Skip to content

Session not committed in tests #8

@a-babarytskyi

Description

@a-babarytskyi

It is not an issue, but rather an important notice, that if you have a middleware, that accesses database for any purpose, and does it not through dependencies injection (as it is done in views), then overriding dependencies in app.dependency obviously will not affect middleware and it will not see any data in database, since it is never committed throughout the tests. If you need data to be actually committed and not just flushed, to be accessible in different sessions, then you would need something like this for session generation:

@pytest.fixture(scope='session')
async def session_generator() -> AsyncGenerator:
    async_engine = create_async_engine(
        settings.TEST_DB_URL,
        pool_pre_ping=True,
        echo=settings.ECHO_SQL
    )

    AsyncSessionLocal = async_sessionmaker(
            autocommit=False,
            autoflush=False,
            bind=async_engine,
            future=True,
        )
    
    def test_get_session() -> Generator:
        try:
            yield AsyncSessionLocal
        except SQLAlchemyError:
            pass

    app.dependency_overrides[get_session] = test_get_session

    yield AsyncSessionLocal

And test case would start like this

@pytest.mark.anyio
async def test_create_account( session_generator: AsyncSession):

    async with session_generator.begin() as session:
        await Account.get_or_create()....

Again this is not an issue, but rather a different approach, especially if you rely on some auth middleware. Also it is possible potentially to replace such middleware with Global dependency, but for redirections to auth app you will need to do some dirty stuff with exceptions, etc...

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions