From 3a84d397fb9807f099c5ed7a6840ad512f8959c4 Mon Sep 17 00:00:00 2001 From: kumarvishwajeettrivedi Date: Sun, 23 Nov 2025 00:08:20 +0530 Subject: [PATCH] Test: Add coverage for BackgroundTasks collection and pragma for unreachable code --- fastapi/routing.py | 2 +- tests/test_issue_11215_coverage.py | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 tests/test_issue_11215_coverage.py diff --git a/fastapi/routing.py b/fastapi/routing.py index 012a79b4c..9d6759ba4 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -412,7 +412,7 @@ def get_request_handler( # solved_result.background_tasks is always BackgroundTasks (from dependencies/utils.py) if isinstance(solved_result.background_tasks, BackgroundTasks): combined_tasks.tasks.extend(solved_result.background_tasks.tasks) - elif isinstance(solved_result.background_tasks, BackgroundTask): + elif isinstance(solved_result.background_tasks, BackgroundTask): # pragma: no cover # Should not happen for BackgroundTasks dependency but safe to handle combined_tasks.tasks.append(solved_result.background_tasks) diff --git a/tests/test_issue_11215_coverage.py b/tests/test_issue_11215_coverage.py new file mode 100644 index 000000000..a1134aecf --- /dev/null +++ b/tests/test_issue_11215_coverage.py @@ -0,0 +1,26 @@ +from fastapi import BackgroundTasks, FastAPI +from fastapi.testclient import TestClient +from starlette.background import BackgroundTasks as StarletteBackgroundTasks +from starlette.responses import Response + +app = FastAPI() + +@app.get("/") +def endpoint(tasks: BackgroundTasks): + tasks.add_task(lambda: print("Dependency task")) + + response_tasks = StarletteBackgroundTasks() + response_tasks.add_task(lambda: print("Response task")) + + return Response( + content="Custom response", + background=response_tasks, + ) + +client = TestClient(app) + +def test_issue_11215_response_background_tasks_collection(capsys): + client.get("/") + captured = capsys.readouterr() + assert "Dependency task" in captured.out + assert "Response task" in captured.out