Skip to content

Commit f48c012

Browse files
committed
custom dependency test example
1 parent 35cc26b commit f48c012

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

tests/fixtures/views.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ class Config:
2323
arbitrary_types_allowed = True
2424

2525

26-
def common_handler(view: ViewBase, dto: BaseModel) -> Dict:
26+
def common_handler(view: ViewBase, dto: SessionDependency) -> Dict:
2727
return {"session": dto.session}
2828

2929

tests/test_api/test_routers.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from typing import Dict, Optional
22

3-
from fastapi import APIRouter, Depends, FastAPI, Header, status
3+
from fastapi import APIRouter, Depends, FastAPI, Header, Path, status
44
from httpx import AsyncClient
55
from pydantic import BaseModel
66
from pytest import mark # noqa
@@ -17,7 +17,7 @@
1717
)
1818
from fastapi_jsonapi.views.view_base import ViewBase
1919
from tests.fixtures.db_connection import async_session_dependency
20-
from tests.fixtures.views import SessionDependency, common_handler
20+
from tests.fixtures.views import SessionDependency
2121
from tests.misc.utils import fake
2222
from tests.models import User
2323
from tests.schemas import (
@@ -131,12 +131,23 @@ async def check_that_user_is_admin(x_auth: Annotated[str, Header()]):
131131
class AdminOnlyPermission(BaseModel):
132132
is_admin: Optional[bool] = Depends(check_that_user_is_admin)
133133

134+
def get_path_obj_id(obj_id: int = Path(default=...)):
135+
return obj_id
136+
137+
class DetailGenericDependency(SessionDependency):
138+
custom_name_obj_id: int = Depends(get_path_obj_id)
139+
140+
def all_handler(view: ViewBase, dto: DetailGenericDependency) -> Dict:
141+
# test inside handler
142+
assert dto.custom_name_obj_id == int(view.request.path_params["obj_id"])
143+
return {"session": dto.session}
144+
134145
class DependencyInjectionDetailView(DetailViewBaseGeneric):
135146
method_dependencies: Dict[HTTPMethod, HTTPMethodConfig] = {
136147
HTTPMethod.GET: HTTPMethodConfig(dependencies=AdminOnlyPermission),
137148
HTTPMethod.ALL: HTTPMethodConfig(
138-
dependencies=SessionDependency,
139-
prepare_data_layer_kwargs=common_handler,
149+
dependencies=DetailGenericDependency,
150+
prepare_data_layer_kwargs=all_handler,
140151
),
141152
}
142153

0 commit comments

Comments
 (0)