1

I developed a FastAPI app with WebSockets and I'm trying to test it. I need async tests in order to check data in the database during tests. My setup looks like this: I have a fixture that generates a database session:

@pytest_asyncio.fixture(scope="session")
async def async_engine() -> AsyncEngine:
    yield create_async_engine(settings.TEST_DATABASE_URL)

@pytest_asyncio.fixture(scope="function")
async def session(async_engine):
    AsyncSessionLocal = sessionmaker(
        bind=async_engine, autoflush=False, expire_on_commit=False, future=True, class_=AsyncSession
    )
    yield AsyncSessionLocal()

Then I have a fixture to create a client:

@pytest_asyncio.fixture(scope="function")
async def client(session):
    app.dependency_overrides[get_db_session] = lambda: session
    async with AsyncClient(transport=ASGIWebSocketTransport(app), base_url="http://test") as client:
        yield client

The transport=ASGIWebSocketTransport(app) part is from httpx-ws library, httpx itself does not support websockets.

The tests looks like this:

@pytest.mark.asyncio
async def test_http(session, client):
    r = await client.get('/test/')

@pytest.mark.asyncio
async def test_ws(session, client):
    async with aconnect_ws("/ws/", client) as ws:
        await ws.send_json({})

test_http works as expected. However, test_ws does not: all sql queries in /ws/ endpoint hang forever. When engine is created with echo=True I see my sql statement in logs like sqlalchemy.engine.Engine SELECT test.id FROM test and then nothing. I've tried looking into pg_stat_activity, pg_locks and pg_blocking_pids(pid) with no success.

At this point I'm stuck: I've read through httpx-ws code and couldn't find any potential problems. What else can I do to figure out why database connection hangs in my case?

Artem Shalagin
  • 137
  • 1
  • 8

0 Answers0