|
7 | 7 | import httpx |
8 | 8 | import pytest |
9 | 9 | import uvicorn |
10 | | -from fastapi import APIRouter, FastAPI |
| 10 | +from fastapi import APIRouter, BackgroundTasks, FastAPI |
11 | 11 | from pytest_simcore.helpers.logging_tools import log_context |
12 | 12 | from servicelib.fastapi.cancellation_middleware import CancellationMiddleware |
13 | 13 | from servicelib.utils import unused_port |
@@ -43,6 +43,24 @@ async def sleep(sleep_time: float) -> dict[str, str]: |
43 | 43 | finally: |
44 | 44 | server_done_event.set() |
45 | 45 |
|
| 46 | + async def _sleep_in_the_back(sleep_time: float) -> None: |
| 47 | + with log_context(logging.INFO, msg="sleeper in the back") as ctx: |
| 48 | + try: |
| 49 | + await asyncio.sleep(sleep_time) |
| 50 | + except asyncio.CancelledError: |
| 51 | + ctx.logger.info("sleeper in the back cancelled!") |
| 52 | + await server_cancelled_mock() |
| 53 | + finally: |
| 54 | + server_done_event.set() |
| 55 | + |
| 56 | + @router.get("/sleep-with-background-task") |
| 57 | + async def sleep_with_background_task( |
| 58 | + sleep_time: float, background_tasks: BackgroundTasks |
| 59 | + ) -> dict[str, str]: |
| 60 | + with log_context(logging.INFO, msg="sleeper with background task"): |
| 61 | + background_tasks.add_task(_sleep_in_the_back, sleep_time) |
| 62 | + return {"message": "Sleeping in the back"} |
| 63 | + |
46 | 64 | return router |
47 | 65 |
|
48 | 66 |
|
@@ -112,4 +130,17 @@ async def test_server_cancels_when_client_disconnects( |
112 | 130 | async with asyncio.timeout(5): |
113 | 131 | await server_done_event.wait() |
114 | 132 | server_cancelled_mock.assert_called_once() |
115 | | - ctx.logger.info("done testing") |
| 133 | + server_cancelled_mock.reset_mock() |
| 134 | + server_done_event.clear() |
| 135 | + |
| 136 | + # NOTE: shows that FastAPI BackgroundTasks get cancelled too! |
| 137 | + # check background tasks get cancelled as well sadly |
| 138 | + with log_context(logging.INFO, msg="client calling endpoint for cancellation"): |
| 139 | + response = await client.get( |
| 140 | + "/sleep-with-background-task", |
| 141 | + params={"sleep_time": 2}, |
| 142 | + ) |
| 143 | + assert response.status_code == 200 |
| 144 | + async with asyncio.timeout(5): |
| 145 | + await server_done_event.wait() |
| 146 | + server_cancelled_mock.assert_called_once() |
0 commit comments