Browse Source

test: replace synthetic private-helper coverage with real startup lifecycle scenario

Made-with: Cursor
pull/15097/head
essentiaMarco 4 months ago
parent
commit
e0fe1666a8
  1. 36
      tests/test_dependency_lifespan_scope.py

36
tests/test_dependency_lifespan_scope.py

@ -4,7 +4,7 @@ from contextlib import asynccontextmanager
from typing import Annotated from typing import Annotated
import pytest import pytest
from fastapi import APIRouter, Depends, FastAPI from fastapi import Depends, FastAPI
from fastapi.exceptions import DependencyScopeError from fastapi.exceptions import DependencyScopeError
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from starlette.requests import Request from starlette.requests import Request
@ -103,22 +103,30 @@ def test_lifespan_dependency_same_instance_across_requests() -> None:
assert len(instances) == 1 assert len(instances) == 1
def test_collect_lifespan_dependants_route_level_scope() -> None: def test_lifespan_dependency_decorator_level_dependencies_runs_at_startup() -> None:
"""Covers _collect_lifespan_dependants when route's flat dependant has computed_scope lifespan.""" """Lifespan deps declared in decorator-level dependencies are initialized once at startup."""
from fastapi.routing import _collect_lifespan_dependants events: list[str] = []
router = APIRouter() def lifespan_dep() -> str:
events.append("start")
yield "ok"
events.append("stop")
app = FastAPI()
@router.get("/") @app.get("/", dependencies=[Depends(lifespan_dep, scope="lifespan")])
def root() -> dict[str, str]: def root() -> dict[str, str]:
return {"ok": "yes"} # pragma: no cover - route not requested in this test return {"ok": "yes"}
route = next(r for r in router.routes if hasattr(r, "dependant")) assert events == []
# Simulate route-level lifespan scope so the flat.computed_scope == "lifespan" branch is hit with TestClient(app) as client:
route.dependant.scope = "lifespan" assert events == ["start"]
result = _collect_lifespan_dependants(router) r1 = client.get("/")
assert len(result) == 1 r2 = client.get("/")
assert result[0].computed_scope == "lifespan" assert r1.status_code == 200
assert r2.status_code == 200
assert events == ["start"]
assert events == ["start", "stop"]
def test_lifespan_dependency_synthetic_request_receive_send() -> None: def test_lifespan_dependency_synthetic_request_receive_send() -> None:

Loading…
Cancel
Save