|
| 1 | +# pylint: disable=redefined-outer-name |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import logging |
| 5 | +from collections.abc import Iterator |
| 6 | +from threading import Thread |
| 7 | +from unittest.mock import AsyncMock |
| 8 | + |
| 9 | +import httpx |
| 10 | +import pytest |
| 11 | +import uvicorn |
| 12 | +from fastapi import APIRouter, BackgroundTasks, FastAPI |
| 13 | +from pytest_simcore.helpers.logging_tools import log_context |
| 14 | +from servicelib.fastapi.cancellation_middleware import RequestCancellationMiddleware |
| 15 | +from servicelib.utils import unused_port |
| 16 | +from yarl import URL |
| 17 | + |
| 18 | + |
| 19 | +@pytest.fixture |
| 20 | +def server_done_event() -> asyncio.Event: |
| 21 | + return asyncio.Event() |
| 22 | + |
| 23 | + |
| 24 | +@pytest.fixture |
| 25 | +def server_cancelled_mock() -> AsyncMock: |
| 26 | + return AsyncMock() |
| 27 | + |
| 28 | + |
| 29 | +@pytest.fixture |
| 30 | +def fastapi_router( |
| 31 | + server_done_event: asyncio.Event, server_cancelled_mock: AsyncMock |
| 32 | +) -> APIRouter: |
| 33 | + router = APIRouter() |
| 34 | + |
| 35 | + @router.get("/sleep") |
| 36 | + async def sleep(sleep_time: float) -> dict[str, str]: |
| 37 | + with log_context(logging.INFO, msg="sleeper") as ctx: |
| 38 | + try: |
| 39 | + await asyncio.sleep(sleep_time) |
| 40 | + return {"message": f"Slept for {sleep_time} seconds"} |
| 41 | + except asyncio.CancelledError: |
| 42 | + ctx.logger.info("sleeper cancelled!") |
| 43 | + await server_cancelled_mock() |
| 44 | + return {"message": "Cancelled"} |
| 45 | + finally: |
| 46 | + server_done_event.set() |
| 47 | + |
| 48 | + async def _sleep_in_the_back(sleep_time: float) -> None: |
| 49 | + with log_context(logging.INFO, msg="sleeper in the back") as ctx: |
| 50 | + try: |
| 51 | + await asyncio.sleep(sleep_time) |
| 52 | + except asyncio.CancelledError: |
| 53 | + ctx.logger.info("sleeper in the back cancelled!") |
| 54 | + await server_cancelled_mock() |
| 55 | + finally: |
| 56 | + server_done_event.set() |
| 57 | + |
| 58 | + @router.get("/sleep-with-background-task") |
| 59 | + async def sleep_with_background_task( |
| 60 | + sleep_time: float, background_tasks: BackgroundTasks |
| 61 | + ) -> dict[str, str]: |
| 62 | + with log_context(logging.INFO, msg="sleeper with background task"): |
| 63 | + background_tasks.add_task(_sleep_in_the_back, sleep_time) |
| 64 | + return {"message": "Sleeping in the back"} |
| 65 | + |
| 66 | + return router |
| 67 | + |
| 68 | + |
| 69 | +@pytest.fixture |
| 70 | +def fastapi_app(fastapi_router: APIRouter) -> FastAPI: |
| 71 | + app = FastAPI() |
| 72 | + app.include_router(fastapi_router) |
| 73 | + app.add_middleware(RequestCancellationMiddleware) |
| 74 | + return app |
| 75 | + |
| 76 | + |
| 77 | +@pytest.fixture |
| 78 | +def uvicorn_server(fastapi_app: FastAPI) -> Iterator[URL]: |
| 79 | + random_port = unused_port() |
| 80 | + with log_context( |
| 81 | + logging.INFO, |
| 82 | + msg=f"with uvicorn server on 127.0.0.1:{random_port}", |
| 83 | + ) as ctx: |
| 84 | + config = uvicorn.Config( |
| 85 | + fastapi_app, |
| 86 | + host="127.0.0.1", |
| 87 | + port=random_port, |
| 88 | + log_level="error", |
| 89 | + ) |
| 90 | + server = uvicorn.Server(config) |
| 91 | + |
| 92 | + thread = Thread(target=server.run) |
| 93 | + thread.daemon = True |
| 94 | + thread.start() |
| 95 | + |
| 96 | + ctx.logger.info( |
| 97 | + "server ready at: %s", |
| 98 | + f"http://127.0.0.1:{random_port}", |
| 99 | + ) |
| 100 | + |
| 101 | + yield URL(f"http://127.0.0.1:{random_port}") |
| 102 | + |
| 103 | + server.should_exit = True |
| 104 | + thread.join(timeout=10) |
| 105 | + |
| 106 | + |
| 107 | +async def test_server_cancels_when_client_disconnects( |
| 108 | + uvicorn_server: URL, |
| 109 | + server_done_event: asyncio.Event, |
| 110 | + server_cancelled_mock: AsyncMock, |
| 111 | +): |
| 112 | + async with httpx.AsyncClient(base_url=f"{uvicorn_server}") as client: |
| 113 | + # check standard call still complete as expected |
| 114 | + with log_context(logging.INFO, msg="client calling endpoint"): |
| 115 | + response = await client.get("/sleep", params={"sleep_time": 0.1}) |
| 116 | + assert response.status_code == 200 |
| 117 | + assert response.json() == {"message": "Slept for 0.1 seconds"} |
| 118 | + async with asyncio.timeout(10): |
| 119 | + await server_done_event.wait() |
| 120 | + server_done_event.clear() |
| 121 | + |
| 122 | + # check slow call get cancelled |
| 123 | + with log_context( |
| 124 | + logging.INFO, msg="client calling endpoint for cancellation" |
| 125 | + ) as ctx: |
| 126 | + with pytest.raises(httpx.ReadTimeout): |
| 127 | + response = await client.get( |
| 128 | + "/sleep", params={"sleep_time": 10}, timeout=0.1 |
| 129 | + ) |
| 130 | + ctx.logger.info("client disconnected from server") |
| 131 | + |
| 132 | + async with asyncio.timeout(5): |
| 133 | + await server_done_event.wait() |
| 134 | + server_cancelled_mock.assert_called_once() |
| 135 | + server_cancelled_mock.reset_mock() |
| 136 | + server_done_event.clear() |
| 137 | + |
| 138 | + # NOTE: shows that FastAPI BackgroundTasks get cancelled too! |
| 139 | + # check background tasks get cancelled as well sadly |
| 140 | + with log_context(logging.INFO, msg="client calling endpoint for cancellation"): |
| 141 | + response = await client.get( |
| 142 | + "/sleep-with-background-task", |
| 143 | + params={"sleep_time": 2}, |
| 144 | + ) |
| 145 | + assert response.status_code == 200 |
| 146 | + async with asyncio.timeout(5): |
| 147 | + await server_done_event.wait() |
| 148 | + server_cancelled_mock.assert_called_once() |
0 commit comments