Skip to content

Commit 8f90e8d

Browse files
committed
Added tests.
Signed-off-by: Pavel Kirilin <win10@list.ru>
1 parent 27f2e1c commit 8f90e8d

File tree

4 files changed

+549
-12
lines changed

4 files changed

+549
-12
lines changed

aiohttp_deps/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,14 @@
33

44
from aiohttp_deps.initializer import init
55
from aiohttp_deps.router import Router
6+
from aiohttp_deps.swagger import extra_openapi, setup_swagger
67
from aiohttp_deps.utils import Form, Header, Json, Path, Query
78
from aiohttp_deps.view import View
89

910
__all__ = [
1011
"init",
12+
"setup_swagger",
13+
"extra_openapi",
1114
"Header",
1215
"Depends",
1316
"Router",

aiohttp_deps/swagger.py

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from taskiq_dependencies import DependencyGraph
1010

1111
from aiohttp_deps.initializer import InjectableFuncHandler, InjectableViewHandler
12-
from aiohttp_deps.utils import Header, Json, Path, Query
12+
from aiohttp_deps.utils import Form, Header, Json, Path, Query
1313

1414
REF_TEMPLATE = "#/components/schemas/{model}"
1515
SCHEMA_KEY = "openapi_schema"
@@ -64,7 +64,7 @@ async def swagger_handler(_: web.Request) -> web.Response:
6464
def _is_optional(annotation: Optional[inspect.Parameter]) -> bool:
6565
# If it's an empty annotation,
6666
# we guess that the value can be optional.
67-
if annotation is None or annotation == annotation.empty:
67+
if annotation is None or annotation.annotation == annotation.empty:
6868
return True
6969

7070
origin = getattr(annotation.annotation, "__origin__", None)
@@ -91,11 +91,14 @@ def _add_route_def( # noqa: C901
9191
"responses": {},
9292
"parameters": [],
9393
}
94-
if route.resource is None:
94+
if route.resource is None: # pragma: no cover
9595
return
9696

9797
for dependency in graph.ordered_deps:
98-
if isinstance(dependency.dependency, Json):
98+
if isinstance(dependency.dependency, (Json, Form)):
99+
content_type = "application/json"
100+
if isinstance(dependency.dependency, Form):
101+
content_type = "application/x-www-form-urlencoded"
99102
if (
100103
dependency.signature
101104
and dependency.signature.annotation != inspect.Parameter.empty
@@ -105,15 +108,19 @@ def _add_route_def( # noqa: C901
105108
ref_template=REF_TEMPLATE,
106109
)
107110
openapi_schema["components"]["schemas"].update(
108-
input_schema.pop("definitions"),
111+
input_schema.pop("definitions", {}),
109112
)
110113
route_info["requestBody"] = {
111-
"content": {"applicaiton/json": {"schema": input_schema}},
114+
"content": {content_type: {"schema": input_schema}},
115+
}
116+
else:
117+
route_info["requestBody"] = {
118+
"content": {content_type: {}},
112119
}
113120
elif isinstance(dependency.dependency, Query):
114121
route_info["parameters"].append(
115122
{
116-
"name": dependency.param_name,
123+
"name": dependency.dependency.alias or dependency.param_name,
117124
"in": "query",
118125
"description": dependency.dependency.description,
119126
"required": not _is_optional(dependency.signature),
@@ -122,7 +129,7 @@ def _add_route_def( # noqa: C901
122129
elif isinstance(dependency.dependency, Header):
123130
route_info["parameters"].append(
124131
{
125-
"name": dependency.param_name,
132+
"name": dependency.dependency.alias or dependency.param_name,
126133
"in": "header",
127134
"description": dependency.dependency.description,
128135
"required": not _is_optional(dependency.signature),
@@ -131,7 +138,7 @@ def _add_route_def( # noqa: C901
131138
elif isinstance(dependency.dependency, Path):
132139
route_info["parameters"].append(
133140
{
134-
"name": dependency.param_name,
141+
"name": dependency.dependency.alias or dependency.param_name,
135142
"in": "path",
136143
"description": dependency.dependency.description,
137144
"required": not _is_optional(dependency.signature),
@@ -189,7 +196,7 @@ async def event_handler(app: web.Application) -> None:
189196
"paths": defaultdict(dict),
190197
}
191198
for route in app.router.routes():
192-
if route.resource is None:
199+
if route.resource is None: # pragma: no cover
193200
continue
194201
if hide_heads and route.method == "HEAD":
195202
continue
@@ -207,7 +214,7 @@ async def event_handler(app: web.Application) -> None:
207214
route._handler.graph,
208215
extra_openapi=extra_openapi,
209216
)
210-
except Exception as exc:
217+
except Exception as exc: # pragma: no cover
211218
logger.warn(
212219
"Cannot add route info: %s",
213220
exc,
@@ -232,7 +239,7 @@ async def event_handler(app: web.Application) -> None:
232239
graph,
233240
extra_openapi=extra_openapi,
234241
)
235-
except Exception as exc:
242+
except Exception as exc: # pragma: no cover
236243
logger.warn(
237244
"Cannot add route info: %s",
238245
exc,

tests/test_isoptional.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import inspect
2+
import sys
3+
from typing import Optional, Union
4+
5+
import pytest
6+
7+
from aiohttp_deps.swagger import _is_optional
8+
9+
10+
def test_optional():
11+
def tfunc(param: Optional[int]):
12+
"""Nothing."""
13+
14+
param = inspect.signature(tfunc).parameters["param"]
15+
16+
assert _is_optional(param)
17+
18+
19+
def test_untyped():
20+
def tfunc(param):
21+
"""Nothing."""
22+
23+
param = inspect.signature(tfunc).parameters["param"]
24+
25+
assert _is_optional(param)
26+
27+
28+
def test_unioned_optional():
29+
def tfunc(param: Union[int, None]):
30+
"""Nothing."""
31+
32+
param = inspect.signature(tfunc).parameters["param"]
33+
34+
assert _is_optional(param)
35+
36+
37+
def test_unioned_optional():
38+
def tfunc(param: Union[int, str]):
39+
"""Nothing."""
40+
41+
param = inspect.signature(tfunc).parameters["param"]
42+
43+
assert not _is_optional(param)
44+
45+
46+
@pytest.mark.skipif(sys.version_info < (3, 10), reason="requires python3.10 or higher")
47+
def test_new_type_style():
48+
def tfunc(param: int | None):
49+
"""Nothing."""
50+
51+
param = inspect.signature(tfunc).parameters["param"]
52+
53+
assert _is_optional(param)

0 commit comments

Comments
 (0)