1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] I'm trying to test my streaming endpoint with pytest but it just gets frozen

Discussão em 'Python' iniciado por Stack, Setembro 7, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to test one of my endpoints for my log application (I'm using FastAPI, MongoDB and Beanie), which opens a stream in which you recieve all existing logs and all the new logs that appear, however, i don't want my test to keep it opened forever, as I want pytest to end, so I made it like this:

    async def test_stream_logs_direct_agent(init_db, client):
    await Log(
    client="test",
    dt=datetime.now(timezone.utc),
    content="Content123",
    ).insert()

    async with client.stream(
    "GET",
    "/api/stream-logs",
    params={"client_name": "test"},
    headers={"Accept": "text/event-stream"},
    ) as resp:
    line = await asyncio.wait_for(resp.aiter_lines().__anext__(), timeout=3)
    print(line)
    assert "Content123" in line
    await resp.aclose()


    However, the test gets stuck and I have to abort pytest manually. I don't know what to do, the line gets sent as I added print(line) in order to be able to see through the console if it was arriving good, and it shows once I abort pytest, however, the test runs infinitely and I don't know what to do.

    My endpoint only does a StreamingResponse, calling the stream_logs function, which is this one:

    async def stream_logs(client_name: str):
    db = MongoDB.database["logs"]
    query = {"client_name": client_name}
    cursor = db.find(query)

    async for doc in cursor:
    dt = doc.get("dt")
    content = doc.get("message", "")
    dtc = dt.strftime("%d %b %Y %H:%M:%S")
    yield f"data: [{dtc}] {content}\n\n"

    pipeline = [
    {"$match": {"operationType": "insert", "fullDocument.client_name": client_name}},
    ]
    async with db.watch(pipeline) as change_stream:
    async for change in change_stream:
    full = change.get("fullDocument", {})
    dt = full.get("dt")
    content = full.get("message", "")
    dtc = dt.strftime("%d %b %Y %H:%M:%S")
    yield f"data: [{dtc}] {content}\n\n"


    Any tips?

    I have tried to use break in the test, adding variables to exit, etc, but nothing works, the test gets stuck infinitely.

    Continue reading...

Compartilhe esta Página