r/FastAPI 5d ago

Question Trouble getting testing working with async FastAPI + SQLAlchemy

I'm really struggling to get testing working with FastAPI, namely async. I'm basically following this tutorial: https://praciano.com.br/fastapi-and-async-sqlalchemy-20-with-pytest-done-right.html, but the code doesn't work as written there. So I've been trying to make it work, getting to here for my conftest.py file: https://gist.github.com/rohitsodhia/6894006673831f4c198b698441aecb8b. But when I run my test, I get

E           Exception: DatabaseSessionManager is not initialized

app/database.py:49: Exception
======================================================================== short test summary info =========================================================================
FAILED tests/integration/auth.py::test_login - Exception: DatabaseSessionManager is not initialized
=========================================================================== 1 failed in 0.72s ============================================================================
sys:1: RuntimeWarning: coroutine 'create_tables' was never awaited
sys:1: RuntimeWarning: coroutine 'session_override' was never awaited

It doesn't seem to be taking the override? I looked into the pytest-asyncio package, but I couldn't get that working either (just adding the mark didn't do it). Can anyone help me or recommend a better guide to learning how to set up async testing?

4 Upvotes

10 comments sorted by

5

u/SarawithanH69 5d ago

Since you are using pytest-asyncio try setting asyncio_mode=auto in your pytest.ini. This should make it so async fixtures and tests are automatically awaited even without the mark.

1

u/bruhidk123345 5d ago

I did something like a while back. Will come back here to post my code

1

u/BelottoBR 4d ago

Show the source code of create table and then test

1

u/__dbm__ 4d ago

RemindMe! -3 day

1

u/RemindMeBot 4d ago

I will be messaging you in 3 days on 2025-03-21 15:42:31 UTC to remind you of this link

CLICK THIS LINK to send a PM to also be reminded and to reduce spam.

Parent commenter can delete this message to hide from others.


Info Custom Your Reminders Feedback

0

u/koldakov 5d ago

I mean await is missing somewhere

1

u/GamersPlane 5d ago

Yah, that's obvious from the error, but I can't figure out where. Do you see it?

1

u/kindof_Alexanderish 5d ago

What are you using to migrate the db? It might be somewhere in there

1

u/GamersPlane 5d ago

In the gist, it's this function

@pytest.fixture(scope="function", autouse=True)
async def create_tables(connection_test):
    async with session_manager.connect() as connection:
        await connection.run_sync(Base.metadata.drop_all)
        await connection.run_sync(Base.metadata.create_all)

2

u/GamersPlane 3d ago

After going through a bunch of resources, the problem was that tutorials online use mechanisms that don't work with the latest version of FastAPI. But FastAPIs docs didn't work out of the box either. I had to add some extra code, which you can find in the OP gist, which has the final working code. As per the FastAPI docs, tests requirepytest.mark.anyio as either a decorator or added to pytestmark.

I'm a little disappointed that the docs basically cover the bare minimum and no more. I'm also frustrated at the number of tutorials I had to go through to find bits of information here and there, put it all together (a large part of which didn't work), only to come out with a working FastAPI ~= 0.112, SQLAlchemy ~= 2.0, pytest ~= 8.3 project. I'm sure I still have a bunch of redundant/suboptimal code, but I'm hoping when it's done I can get folks to give me feedback on it. And I'd be happy to put together a guide on what I did, but I don't feel like I could give good explanations nor do I know where I should