Browse Source

🎨 Auto format

pull/15447/head
pre-commit-ci-lite[bot] 2 months ago
committed by GitHub
parent
commit
9c554d54cd
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 5
      fastapi/cbx.py
  2. 37
      tests/test_cbx.py

5
fastapi/cbx.py

@ -57,8 +57,7 @@ class CBR(Generic[T]):
self.instance = self.cls(*args, **kwargs) self.instance = self.cls(*args, **kwargs)
for _name, endpoint in inspect.getmembers( for _name, endpoint in inspect.getmembers(
self.instance, lambda x: inspect.ismethod( self.instance, lambda x: inspect.ismethod(x) or inspect.isfunction(x)
x) or inspect.isfunction(x)
): ):
if cbx_router := endpoint.__annotations__.get("cbx_router"): if cbx_router := endpoint.__annotations__.get("cbx_router"):
for router in cbx_router: for router in cbx_router:
@ -100,7 +99,7 @@ class cbr(Generic[T]):
else: else:
endpoint.__annotations__.setdefault( endpoint.__annotations__.setdefault(
"cbx_router", "cbx_router",
[{"method": self.method, "path": self.path, "kwargs": self.kwargs}] [{"method": self.method, "path": self.path, "kwargs": self.kwargs}],
) )
return endpoint return endpoint

37
tests/test_cbx.py

@ -1,23 +1,21 @@
import logging
import asyncio import asyncio
from fastapi.cbx import cbv, cbr import logging
from fastapi import APIRouter, Cookie, Depends, FastAPI, HTTPException, Response, status
from fastapi.cbx import cbr, cbv
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from fastapi import APIRouter
from typing import Dict
from fastapi import FastAPI, APIRouter, Response, status, Cookie, Depends, HTTPException
from pydantic import BaseModel from pydantic import BaseModel
@cbv(router=APIRouter(prefix='/cbv')) @cbv(router=APIRouter(prefix="/cbv"))
class MyCBV: class MyCBV:
logger = logging.getLogger(__qualname__) logger = logging.getLogger(__qualname__)
class CBVModel(BaseModel): class CBVModel(BaseModel):
key: str = "cbv" key: str = "cbv"
value: str = "Class-based view for CRUD operations with singleton global dependency injection" value: str = "Class-based view for CRUD operations with singleton global dependency injection"
def __init__(self, **kwargs: Dict[str, str]): def __init__(self, **kwargs: dict[str, str]):
self.heavies = { self.heavies = {
"name": "fastapi-cbx", "name": "fastapi-cbx",
"description": "Minimal class-based routing extension for FastAPI", "description": "Minimal class-based routing extension for FastAPI",
@ -34,22 +32,23 @@ class MyCBV:
async def get(self, key: str) -> CBVModel: async def get(self, key: str) -> CBVModel:
self.logger.info(f"GET {key}") self.logger.info(f"GET {key}")
await asyncio.sleep(1) await asyncio.sleep(1)
return self.CBVModel(key=key, value=self.heavies.get(key, "One scenario, one route")) return self.CBVModel(
key=key, value=self.heavies.get(key, "One scenario, one route")
)
@cbr(router=APIRouter(prefix="/cbr")) @cbr(router=APIRouter(prefix="/cbr"))
class MyCBR: class MyCBR:
logger = logging.getLogger(__qualname__) logger = logging.getLogger(__qualname__)
class CBRModel(BaseModel): class CBRModel(BaseModel):
key: str = "CBR" key: str = "CBR"
value: str = "Class-based route for complex business logic with multiple endpoints and method-level dependencies" value: str = "Class-based route for complex business logic with multiple endpoints and method-level dependencies"
def __init__(self, **kwargs: Dict[str, str]): def __init__(self, **kwargs: dict[str, str]):
self.heavies = { self.heavies = {
"name": "fastapi-cbx", "name": "fastapi-cbx",
"description": "Minimal class-based routing extension for FastAPI" "description": "Minimal class-based routing extension for FastAPI",
} }
self.heavies.update(kwargs) self.heavies.update(kwargs)
@ -63,13 +62,16 @@ class MyCBR:
@cbr.get("/heavies", summary="Get heavies by key") @cbr.get("/heavies", summary="Get heavies by key")
async def get_heavies(self, key: str) -> CBRModel: async def get_heavies(self, key: str) -> CBRModel:
self.logger.info(f"GET {key}") self.logger.info(f"GET {key}")
return self.CBRModel(key=key, value=self.heavies.get(key, "One scenario, one route")) return self.CBRModel(
key=key, value=self.heavies.get(key, "One scenario, one route")
)
@staticmethod @staticmethod
def session(token: str = Cookie(default="", alias="token")) -> str: def session(token: str = Cookie(default="", alias="token")) -> str:
if token != "fastapi-cbx": if token != "fastapi-cbx":
raise HTTPException( raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token"
)
return token return token
@cbr.post("/heavies", summary="Set heavies") @cbr.post("/heavies", summary="Set heavies")
@ -106,6 +108,7 @@ client = TestClient(app)
# ==================== 100% Test Suite ==================== # ==================== 100% Test Suite ====================
def test_cbv(): def test_cbv():
asyncio.run(MyCBV.head(Response())) asyncio.run(MyCBV.head(Response()))
print(dir(MyCBV)) print(dir(MyCBV))
@ -118,15 +121,13 @@ def test_cbr():
print(dir(MyCBR)) print(dir(MyCBR))
response = client.get("/cbr/heavies?key=name") response = client.get("/cbr/heavies?key=name")
assert response.status_code == 200 assert response.status_code == 200
response = client.post( response = client.post("/cbr/heavies", json={"key": "test", "value": "test_value"})
"/cbr/heavies", json={"key": "test", "value": "test_value"})
assert response.status_code == 401 assert response.status_code == 401
assert response.json()["detail"] == "Invalid token" assert response.json()["detail"] == "Invalid token"
with TestClient(app, cookies={"token": "fastapi-cbx"}) as auth_client: with TestClient(app, cookies={"token": "fastapi-cbx"}) as auth_client:
response = auth_client.post( response = auth_client.post(
"/cbr/heavies", "/cbr/heavies", json={"key": "test", "value": "test"}
json={"key": "test", "value": "test"}
) )
assert response.status_code == 200 assert response.status_code == 200
response = client.delete("/cbr/heavies?name=test") response = client.delete("/cbr/heavies?name=test")

Loading…
Cancel
Save