|
| 1 | +from functools import partial |
| 2 | +from typing import Iterator |
| 3 | + |
| 4 | +from fastapi import Depends, FastAPI |
| 5 | +from pytest import fixture, mark |
| 6 | +from sqlmodel import Field, Session, SQLModel, create_engine, select |
| 7 | + |
| 8 | +from fastapi_pagination import LimitOffsetPage, Page, add_pagination |
| 9 | +from fastapi_pagination.ext.sqlmodel import paginate |
| 10 | + |
| 11 | +from ..base import BasePaginationTestCase, SafeTestClient, UserOut |
| 12 | +from ..utils import faker |
| 13 | + |
| 14 | + |
| 15 | +@fixture(scope="session") |
| 16 | +def engine(database_url): |
| 17 | + if database_url.startswith("sqlite"): |
| 18 | + connect_args = {"check_same_thread": False} |
| 19 | + else: |
| 20 | + connect_args = {} |
| 21 | + |
| 22 | + return create_engine(database_url, connect_args=connect_args) |
| 23 | + |
| 24 | + |
| 25 | +@fixture(scope="session") |
| 26 | +def SessionLocal(engine): |
| 27 | + return partial(Session, engine) |
| 28 | + |
| 29 | + |
| 30 | +@fixture(scope="session") |
| 31 | +def User(): |
| 32 | + class User(SQLModel, table=True): |
| 33 | + id: int = Field(primary_key=True) |
| 34 | + name: str |
| 35 | + |
| 36 | + return User |
| 37 | + |
| 38 | + |
| 39 | +@fixture( |
| 40 | + scope="session", |
| 41 | + params=[True, False], |
| 42 | + ids=["model", "query"], |
| 43 | +) |
| 44 | +def query(request, User): |
| 45 | + if request.param: |
| 46 | + return User |
| 47 | + else: |
| 48 | + return select(User) |
| 49 | + |
| 50 | + |
| 51 | +@fixture(scope="session") |
| 52 | +def app(query, engine, User, SessionLocal): |
| 53 | + app = FastAPI() |
| 54 | + |
| 55 | + @app.on_event("startup") |
| 56 | + def on_startup(): |
| 57 | + SQLModel.metadata.create_all(engine) |
| 58 | + |
| 59 | + with SessionLocal() as session: |
| 60 | + session.add_all([User(name=faker.name()) for _ in range(100)]) |
| 61 | + |
| 62 | + def get_db() -> Iterator[Session]: |
| 63 | + with SessionLocal() as db: |
| 64 | + yield db |
| 65 | + |
| 66 | + @app.get("/default", response_model=Page[UserOut]) |
| 67 | + @app.get("/limit-offset", response_model=LimitOffsetPage[UserOut]) |
| 68 | + def route(db: Session = Depends(get_db)): |
| 69 | + return paginate(db, query) |
| 70 | + |
| 71 | + add_pagination(app) |
| 72 | + return app |
| 73 | + |
| 74 | + |
| 75 | +@mark.future_sqlalchemy |
| 76 | +class TestSQLModel(BasePaginationTestCase): |
| 77 | + @fixture(scope="session") |
| 78 | + def client(self, app): |
| 79 | + with SafeTestClient(app) as c: |
| 80 | + yield c |
| 81 | + |
| 82 | + @fixture(scope="session") |
| 83 | + def entities(self, SessionLocal, User): |
| 84 | + with SessionLocal() as session: |
| 85 | + return session.exec(select(User)).unique().all() |
0 commit comments