test_get_db_function_scope.py 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. """Every ``get_db`` dependency is function-scoped (#3320).
  2. With the default request scope, ``get_db`` commits after the response has been
  3. sent, so a read straight after a write can miss it. FastAPI keys its dependency
  4. cache on the scope too: one route mixing both would get two sessions, and a
  5. request-scoped yield dependency cannot use a function-scoped one at all. So it
  6. is all of them or none.
  7. """
  8. from fastapi.routing import APIRoute, APIWebSocketRoute
  9. from backend.app.core.database import get_db
  10. from backend.app.main import app
  11. def _get_db_uses(dependant, path: str, found: list):
  12. for dep in dependant.dependencies:
  13. if dep.call is get_db:
  14. found.append((path, dep.computed_scope))
  15. _get_db_uses(dep, path, found)
  16. def test_every_get_db_dependency_is_function_scoped():
  17. found: list[tuple[str, str | None]] = []
  18. for route in app.routes:
  19. if isinstance(route, (APIRoute, APIWebSocketRoute)):
  20. _get_db_uses(route.dependant, route.path, found)
  21. assert len(found) > 100 # the walk reaches the routes at all
  22. request_scoped = sorted({path for path, scope in found if scope != "function"})
  23. assert request_scoped == [], 'use Depends(get_db, scope="function"):\n' + "\n".join(request_scoped)