Test: Add coverage for BackgroundTasks collection and pragma for unreachable code

This commit is contained in:
kumarvishwajeettrivedi 2025-11-23 00:08:20 +05:30
parent 258ee6eec7
commit 3a84d397fb
2 changed files with 27 additions and 1 deletions

View File

@ -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)

View File

@ -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