Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add wrapper for app lifespan #899

Merged
merged 1 commit into from
Oct 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions fastapi_pagination/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

import inspect
import warnings
from contextlib import ExitStack, contextmanager, suppress
from contextlib import ExitStack, asynccontextmanager, contextmanager, suppress
from contextvars import ContextVar
from typing import (
Any,
Expand Down Expand Up @@ -365,8 +365,15 @@ def _add_pagination(parent: ParentT) -> None:
def add_pagination(parent: ParentT) -> ParentT:
_add_pagination(parent)

@parent.on_event("startup")
def on_startup() -> None:
router = parent.router if isinstance(parent, FastAPI) else parent
_original_lifespan_context = router.lifespan_context

@asynccontextmanager
async def lifespan(app: Any) -> AsyncIterator[Any]:
_add_pagination(parent)

async with _original_lifespan_context(app) as maybe_state:
yield maybe_state

router.lifespan_context = lifespan
return parent
33 changes: 32 additions & 1 deletion tests/test_api.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from typing import Any, Generic, Sequence, TypeVar
from contextlib import asynccontextmanager
from typing import Any, AsyncIterator, Generic, Sequence, TypeVar

from fastapi import Depends, FastAPI, Request, Response, status
from fastapi.routing import APIRouter
from fastapi.testclient import TestClient
from pydantic import Field
from pytest import fixture

try:
from pydantic.generics import GenericModel
Expand Down Expand Up @@ -252,3 +254,32 @@ async def route():

rsp = client.get("/", params={"page": -1})
assert rsp.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY


class TestLifespan:
@fixture(scope="class")
def app(self):
@asynccontextmanager
async def lifespan(_: Any) -> AsyncIterator[None]:
app.state.called = True
yield

app = FastAPI(lifespan=lifespan)

@app.get(
"/",
response_model=Page[int],
)
async def route():
return paginate([])

add_pagination(app)
app.state.called = False

return app

async def test_lifespan_wrap(self, app, client):
rsp = await client.get("/")
assert rsp.status_code == status.HTTP_200_OK

assert app.state.called, "original lifespan not called"