Skip to content

Commit 31da515

Browse files
committed
test complete
1 parent c574abc commit 31da515

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

packages/service-library/tests/fastapi/test_cancellation_middleware.py

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import httpx
88
import pytest
99
import uvicorn
10-
from fastapi import APIRouter, FastAPI
10+
from fastapi import APIRouter, BackgroundTasks, FastAPI
1111
from pytest_simcore.helpers.logging_tools import log_context
1212
from servicelib.fastapi.cancellation_middleware import CancellationMiddleware
1313
from servicelib.utils import unused_port
@@ -43,6 +43,24 @@ async def sleep(sleep_time: float) -> dict[str, str]:
4343
finally:
4444
server_done_event.set()
4545

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+
4664
return router
4765

4866

@@ -112,4 +130,17 @@ async def test_server_cancels_when_client_disconnects(
112130
async with asyncio.timeout(5):
113131
await server_done_event.wait()
114132
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

Comments
 (0)