-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathtest_routers.py
More file actions
222 lines (188 loc) · 7.73 KB
/
test_routers.py
File metadata and controls
222 lines (188 loc) · 7.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
from typing import ClassVar, Dict, Optional
from fastapi import APIRouter, Depends, FastAPI, Header, Path, status
from httpx import AsyncClient
from pydantic import BaseModel
from pytest import mark # noqa
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from typing_extensions import Annotated
from fastapi_jsonapi import RoutersJSONAPI, init
from fastapi_jsonapi.exceptions import Forbidden, InternalServerError
from fastapi_jsonapi.misc.sqla.generics.base import DetailViewBaseGeneric, ListViewBaseGeneric
from fastapi_jsonapi.views.utils import (
HTTPMethod,
HTTPMethodConfig,
)
from fastapi_jsonapi.views.view_base import ViewBase
from tests.fixtures.db_connection import async_session_dependency
from tests.fixtures.views import SessionDependency
from tests.misc.utils import fake
from tests.models import User
from tests.schemas import (
UserAttributesBaseSchema,
UserInSchema,
UserPatchSchema,
UserSchema,
)
pytestmark = mark.asyncio
def build_app(detail_view, resource_type: str) -> FastAPI:
app = FastAPI(
title="FastAPI and SQLAlchemy",
debug=True,
openapi_url="/openapi.json",
docs_url="/docs",
)
router: APIRouter = APIRouter()
RoutersJSONAPI(
router=router,
path="/users",
tags=["User"],
class_detail=detail_view,
class_list=ListViewBaseGeneric,
schema=UserSchema,
resource_type=resource_type,
schema_in_patch=UserPatchSchema,
schema_in_post=UserInSchema,
model=User,
)
app.include_router(router, prefix="")
init(app)
return app
async def test_dependency_handler_call():
def one() -> int:
return 1
def two() -> int:
return 2
class CustomDependencies(BaseModel):
dependency_1: int = Depends(one)
dependency_2: int = Depends(two)
async def dependencies_handler(view_base: ViewBase, dto: CustomDependencies) -> Optional[Dict]:
raise InternalServerError(
detail="hi",
errors=[
InternalServerError(
title="Check that dependency successfully passed",
detail=dto.dict(),
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
),
InternalServerError(
title="Check caller class",
detail=view_base.__class__.__name__,
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
),
],
)
class DependencyInjectionDetailView(DetailViewBaseGeneric):
method_dependencies: ClassVar[Dict[HTTPMethod, HTTPMethodConfig]] = {
HTTPMethod.GET: HTTPMethodConfig(
dependencies=CustomDependencies,
prepare_data_layer_kwargs=dependencies_handler,
),
}
app = build_app(DependencyInjectionDetailView, resource_type="test_dependency_handler_call")
async with AsyncClient(app=app, base_url="http://test") as client:
res = await client.get("/users/1/")
assert res.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR, res.text
assert res.json() == {
"errors": [
{
"detail": "hi",
"meta": [
{
"detail": {"dependency_1": 1, "dependency_2": 2},
"source": {"pointer": ""},
"status_code": status.HTTP_500_INTERNAL_SERVER_ERROR,
"title": "Check that dependency successfully passed",
},
{
"detail": DependencyInjectionDetailView.__name__,
"source": {"pointer": ""},
"status_code": status.HTTP_500_INTERNAL_SERVER_ERROR,
"title": "Check caller class",
},
],
"status_code": status.HTTP_500_INTERNAL_SERVER_ERROR,
},
],
}
async def test_dependencies_as_permissions(user_1: User):
async def check_that_user_is_admin(x_auth: Annotated[str, Header()]):
if x_auth != "admin":
raise Forbidden(detail="Only admin user have permissions to this endpoint")
class AdminOnlyPermission(BaseModel):
is_admin: Optional[bool] = Depends(check_that_user_is_admin)
def get_path_obj_id(obj_id: int = Path(default=...)):
return obj_id
class DetailGenericDependency(SessionDependency):
custom_name_obj_id: int = Depends(get_path_obj_id)
def all_handler(view: ViewBase, dto: DetailGenericDependency) -> Dict:
# test inside handler
assert dto.custom_name_obj_id == int(view.request.path_params["obj_id"])
return {"session": dto.session}
class DependencyInjectionDetailView(DetailViewBaseGeneric):
method_dependencies: ClassVar[Dict[HTTPMethod, HTTPMethodConfig]] = {
HTTPMethod.GET: HTTPMethodConfig(dependencies=AdminOnlyPermission),
HTTPMethod.ALL: HTTPMethodConfig(
dependencies=DetailGenericDependency,
prepare_data_layer_kwargs=all_handler,
),
}
resource_type = fake.word()
app = build_app(DependencyInjectionDetailView, resource_type=resource_type)
async with AsyncClient(app=app, base_url="http://test") as client:
res = await client.get(f"/users/{user_1.id}/", headers={"X-AUTH": "not_admin"})
assert res.status_code == status.HTTP_403_FORBIDDEN, res.text
assert res.json() == {
"errors": [
{
"detail": "Only admin user have permissions to this endpoint",
"source": {"pointer": ""},
"status_code": status.HTTP_403_FORBIDDEN,
"title": "Forbidden",
},
],
}
res = await client.get(f"/users/{user_1.id}/", headers={"X-AUTH": "admin"})
assert res.json() == {
"data": {
"attributes": UserAttributesBaseSchema.from_orm(user_1).dict(),
"id": str(user_1.id),
"type": resource_type,
},
"jsonapi": {"version": "1.0"},
"meta": None,
}
async def test_manipulate_data_layer_kwargs(
user_1: User,
):
class GetDetailDependencies(BaseModel):
session: AsyncSession = Depends(async_session_dependency)
class Config:
arbitrary_types_allowed = True
async def set_session_and_ignore_user_1(view_base: ViewBase, dto: GetDetailDependencies) -> Dict:
query = select(User).where(User.id != user_1.id)
return {
"session": dto.session,
"query": query,
}
class DependencyInjectionDetailView(DetailViewBaseGeneric):
method_dependencies: ClassVar[Dict[HTTPMethod, HTTPMethodConfig]] = {
HTTPMethod.GET: HTTPMethodConfig(
dependencies=GetDetailDependencies,
prepare_data_layer_kwargs=set_session_and_ignore_user_1,
),
}
app = build_app(DependencyInjectionDetailView, resource_type="test_manipulate_data_layer_kwargs")
async with AsyncClient(app=app, base_url="http://test") as client:
res = await client.get(f"/users/{user_1.id}/")
assert res.status_code == status.HTTP_404_NOT_FOUND, res.text
assert res.json() == {
"errors": [
{
"detail": f"Resource User `{user_1.id}` not found",
"meta": {"parameter": "id"},
"status_code": status.HTTP_404_NOT_FOUND,
"title": "Resource not found.",
},
],
}