Skip to content

Commit 32f31b7

Browse files
committed
Fix the pre-commit formatting hook
1 parent 7edd49b commit 32f31b7

File tree

10 files changed

+46
-44
lines changed

10 files changed

+46
-44
lines changed

cadwyn/_asts.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222

2323

2424
# A parent type of typing._GenericAlias
25-
_BaseGenericAlias = cast(type, type(List[int])).mro()[1] # noqa: UP006
25+
_BaseGenericAlias = cast("type", type(List[int])).mro()[1] # noqa: UP006
2626

2727
# type(list[int]) and type(List[int]) are different which is why we have to do this.
2828
# Please note that this problem is much wider than just lists which is why we use typing._BaseGenericAlias

cadwyn/applications.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -400,7 +400,7 @@ async def swagger_dashboard(self, req: Request) -> Response:
400400
init_oauth=self.swagger_ui_init_oauth,
401401
swagger_ui_parameters=self.swagger_ui_parameters,
402402
)
403-
return self._render_docs_dashboard(req, cast(str, self.docs_url))
403+
return self._render_docs_dashboard(req, cast("str", self.docs_url))
404404

405405
async def redoc_dashboard(self, req: Request) -> Response:
406406
version = req.query_params.get("version")
@@ -410,7 +410,7 @@ async def redoc_dashboard(self, req: Request) -> Response:
410410
openapi_url = root_path + f"{self.openapi_url}?version={version}"
411411
return get_redoc_html(openapi_url=openapi_url, title=f"{self.title} - ReDoc")
412412

413-
return self._render_docs_dashboard(req, docs_url=cast(str, self.redoc_url))
413+
return self._render_docs_dashboard(req, docs_url=cast("str", self.redoc_url))
414414

415415
def _extract_root_path(self, req: Request):
416416
return req.scope.get("root_path", "").rstrip("/")

cadwyn/changelogs.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ def _generate_changelog(versions: VersionBundle, router: _RootCadwynAPIRouter) -
9393
generator_from_newer_version,
9494
generator_from_older_version,
9595
schemas_from_older_version,
96-
cast(list[APIRoute], routes_from_newer_version),
96+
cast("list[APIRoute]", routes_from_newer_version),
9797
)
9898
if changelog_entry is not None: # pragma: no branch # This should never happen
9999
version_change_changelog.instructions.append(CadwynVersionChangeInstruction(changelog_entry))
@@ -321,18 +321,18 @@ def _convert_version_change_instruction_to_changelog_entry( # noqa: C901
321321
if isinstance(instruction, EndpointDidntExistInstruction):
322322
return CadwynEndpointWasAddedChangelogEntry(
323323
path=instruction.endpoint_path,
324-
methods=cast(Any, instruction.endpoint_methods),
324+
methods=cast("Any", instruction.endpoint_methods),
325325
)
326326
elif isinstance(instruction, EndpointExistedInstruction):
327327
return CadwynEndpointWasRemovedChangelogEntry(
328328
path=instruction.endpoint_path,
329-
methods=cast(Any, instruction.endpoint_methods),
329+
methods=cast("Any", instruction.endpoint_methods),
330330
)
331331
elif isinstance(instruction, EndpointHadInstruction):
332332
if instruction.attributes.include_in_schema is not Sentinel:
333333
return CadwynEndpointWasRemovedChangelogEntry(
334334
path=instruction.endpoint_path,
335-
methods=cast(Any, instruction.endpoint_methods),
335+
methods=cast("Any", instruction.endpoint_methods),
336336
)
337337

338338
renaming_map = {"operation_id": "operationId"}
@@ -379,7 +379,7 @@ def _convert_version_change_instruction_to_changelog_entry( # noqa: C901
379379
attribute_changes.append(CadwynEndpointAttributeChange(name="responses", new_value=changed_responses))
380380
return CadwynEndpointHadChangelogEntry(
381381
path=instruction.endpoint_path,
382-
methods=cast(Any, instruction.endpoint_methods),
382+
methods=cast("Any", instruction.endpoint_methods),
383383
changes=attribute_changes,
384384
)
385385

cadwyn/route_generation.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def generate_versioned_routers(
7878
webhooks: Union[_WR, None] = None,
7979
) -> GeneratedRouters[_R, _WR]:
8080
if webhooks is None:
81-
webhooks = cast(_WR, APIRouter())
81+
webhooks = cast("_WR", APIRouter())
8282
return _EndpointTransformer(router, versions, webhooks).transform()
8383

8484

@@ -167,7 +167,7 @@ def transform(self) -> GeneratedRouters[_R, _WR]:
167167

168168
# We know they are APIRoutes because of the check at the very beginning of the top loop.
169169
# I.e. Because head_route is an APIRoute, both routes are APIRoutes too
170-
older_route = cast(APIRoute, older_route)
170+
older_route = cast("APIRoute", older_route)
171171
# Wait.. Why do we need this code again?
172172
if older_route.body_field is not None and _route_has_a_simple_body_schema(older_route):
173173
if hasattr(older_route.body_field.type_, "__cadwyn_original_model__"):

cadwyn/schema_generation.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,7 @@ def _wrap_pydantic_model(model: type[_T_PYDANTIC_MODEL]) -> "_PydanticModelWrapp
263263
# For example, when "from __future__ import annotations" is used in the file with the schema
264264
if model is not BaseModel:
265265
model.model_rebuild(raise_errors=False)
266-
model = cast(type[_T_PYDANTIC_MODEL], model)
266+
model = cast("type[_T_PYDANTIC_MODEL]", model)
267267

268268
decorators = _get_model_decorators(model)
269269
validators = {}
@@ -343,7 +343,7 @@ def _rebuild_annotated(name: str):
343343
def _get_field_and_validator_names_from_model(cls: type) -> tuple[set[_FieldName], set[str]]:
344344
fields = cls.model_fields
345345
source = inspect.getsource(cls)
346-
cls_ast = cast(ast.ClassDef, ast.parse(textwrap.dedent(source)).body[0])
346+
cls_ast = cast("ast.ClassDef", ast.parse(textwrap.dedent(source)).body[0])
347347
validator_names = (
348348
_get_validator_info_or_none(node)
349349
for node in cls_ast.body
@@ -466,7 +466,7 @@ def generate_model_copy(self, generator: "SchemaGenerator") -> type[_T_PYDANTIC_
466466
fields = {name: field.generate_field_copy(generator) for name, field in self.fields.items()}
467467
model_copy = type(self.cls)(
468468
self.name,
469-
tuple(generator[cast(type[BaseModel], base)] for base in self.cls.__bases__),
469+
tuple(generator[cast("type[BaseModel]", base)] for base in self.cls.__bases__),
470470
self.other_attributes
471471
| per_field_validators
472472
| root_validators
@@ -776,7 +776,7 @@ def __getitem__(self, model: type[_T_ANY_MODEL], /) -> type[_T_ANY_MODEL]:
776776
wrapper = self._get_wrapper_for_model(model)
777777
model_copy = wrapper.generate_model_copy(self)
778778
self.concrete_models[model] = model_copy
779-
return cast(type[_T_ANY_MODEL], model_copy)
779+
return cast("type[_T_ANY_MODEL]", model_copy)
780780

781781
@overload
782782
def _get_wrapper_for_model(self, model: type[BaseModel]) -> "_PydanticModelWrapper[BaseModel]": ...
@@ -865,7 +865,7 @@ def _apply_alter_schema_instructions(
865865
elif isinstance(alter_schema_instruction, ValidatorExistedInstruction):
866866
validator_name = get_name_of_function_wrapped_in_pydantic_validator(alter_schema_instruction.validator)
867867
raw_validator = cast(
868-
pydantic._internal._decorators.PydanticDescriptorProxy, alter_schema_instruction.validator
868+
"pydantic._internal._decorators.PydanticDescriptorProxy", alter_schema_instruction.validator
869869
)
870870
schema_info.validators[validator_name] = _wrap_validator(
871871
raw_validator.wrapped,
@@ -1100,7 +1100,7 @@ def generate_model_copy(self, generator: "SchemaGenerator") -> type[_T_ENUM]:
11001100
for attr_name, attr in initialization_namespace.items():
11011101
enum_dict[attr_name] = attr
11021102
enum_dict["__doc__"] = self.cls.__doc__
1103-
model_copy = cast(type[_T_ENUM], type(self.name, self.cls.__bases__, enum_dict))
1103+
model_copy = cast("type[_T_ENUM]", type(self.name, self.cls.__bases__, enum_dict))
11041104
model_copy.__cadwyn_original_model__ = self.cls # pyright: ignore[reportAttributeAccessIssue]
11051105
return model_copy
11061106

cadwyn/structure/data.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ def decorator(transformer: Callable[[RequestInfo], None]) -> Any:
140140
if isinstance(schema_or_path, str):
141141
return _AlterRequestByPathInstruction(
142142
path=schema_or_path,
143-
methods=set(cast(list, methods_or_second_schema)),
143+
methods=set(cast("list", methods_or_second_schema)),
144144
transformer=transformer,
145145
)
146146
else:
@@ -214,7 +214,7 @@ def decorator(transformer: Callable[[ResponseInfo], None]) -> Any:
214214
# The validation above checks that methods is not None
215215
return _AlterResponseByPathInstruction(
216216
path=schema_or_path,
217-
methods=set(cast(list, methods_or_second_schema)),
217+
methods=set(cast("list", methods_or_second_schema)),
218218
transformer=transformer,
219219
migrate_http_errors=migrate_http_errors,
220220
)

cadwyn/structure/schemas.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ def existed_as(
246246
info: Union[FieldInfo, Any, None] = None,
247247
) -> FieldExistedAsInstruction:
248248
if info is None:
249-
info = cast(FieldInfo, Field())
249+
info = cast("FieldInfo", Field())
250250
info.annotation = type
251251
return FieldExistedAsInstruction(is_hidden_from_changelog=False, schema=self.schema, name=self.name, field=info)
252252

@@ -317,7 +317,7 @@ def field(self, name: str, /) -> AlterFieldInstructionFactory:
317317
def validator(
318318
self, func: "Union[Callable[..., Any], classmethod[Any, Any, Any], PydanticDescriptorProxy]", /
319319
) -> AlterValidatorInstructionFactory:
320-
func = cast(Union[Callable[..., Any], PydanticDescriptorProxy], unwrap_wrapped_function(func))
320+
func = cast("Union[Callable[..., Any], PydanticDescriptorProxy]", unwrap_wrapped_function(func))
321321

322322
if not isinstance(func, PydanticDescriptorProxy):
323323
if hasattr(func, "__self__"):

cadwyn/structure/versions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -620,7 +620,7 @@ async def _convert_endpoint_response_to_version( # noqa: C901
620620
detail = response_info.body
621621
if detail is None:
622622
detail = http.HTTPStatus(response_info.status_code).phrase
623-
raised_exception.detail = cast(str, detail)
623+
raised_exception.detail = cast("str", detail)
624624
raised_exception.headers = dict(response_info.headers)
625625
raised_exception.status_code = response_info.status_code
626626

tests/test_applications.py

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
import re
2-
from typing import Annotated, cast
2+
from typing import TYPE_CHECKING, Annotated, cast
33

44
import pytest
55
from fastapi import APIRouter, BackgroundTasks, Depends, FastAPI
6-
from fastapi.routing import APIRoute
76
from fastapi.testclient import TestClient
87
from pydantic import BaseModel
98

@@ -21,6 +20,9 @@
2120
v2022_01_02_router,
2221
)
2322

23+
if TYPE_CHECKING:
24+
from fastapi.routing import APIRoute
25+
2426

2527
def test__header_routing__invalid_version_format__error():
2628
main_app = Cadwyn(versions=VersionBundle(Version("2022-11-16")))
@@ -37,15 +39,15 @@ def test__header_routing__invalid_version_format__error():
3739

3840

3941
def test__header_routing_fastapi_init__openapi_passing_nulls__should_not_add_openapi_routes():
40-
assert [cast(APIRoute, r).path for r in Cadwyn(versions=VersionBundle(Version("2022-11-16"))).routes] == [
42+
assert [cast("APIRoute", r).path for r in Cadwyn(versions=VersionBundle(Version("2022-11-16"))).routes] == [
4143
"/docs/oauth2-redirect",
4244
"/changelog",
4345
"/openapi.json",
4446
"/docs",
4547
"/redoc",
4648
]
4749
assert [
48-
cast(APIRoute, r).path
50+
cast("APIRoute", r).path
4951
for r in Cadwyn(versions=VersionBundle(Version("2022-11-16")), docs_url=None, redoc_url=None).routes
5052
] == [
5153
"/changelog",
@@ -56,7 +58,7 @@ def test__header_routing_fastapi_init__openapi_passing_nulls__should_not_add_ope
5658

5759
def test__header_routing_fastapi_init__passing_null_to_oauth2__should_not_add_oauth2_redirect_route():
5860
app = Cadwyn(versions=VersionBundle(Version("2022-11-16")), swagger_ui_oauth2_redirect_url=None)
59-
assert [cast(APIRoute, r).path for r in app.routes] == [
61+
assert [cast("APIRoute", r).path for r in app.routes] == [
6062
"/changelog",
6163
"/openapi.json",
6264
"/docs",
@@ -165,7 +167,7 @@ def test__header_routing_fastapi_add_header_versioned_routers__apirouter_is_empt
165167
)
166168
assert len(app.router.versioned_routers) == 1
167169
assert len(app.router.versioned_routers["2022-11-16"].routes) == 1
168-
route = cast(APIRoute, app.router.versioned_routers["2022-11-16"].routes[0])
170+
route = cast("APIRoute", app.router.versioned_routers["2022-11-16"].routes[0])
169171
assert route.path == "/openapi.json"
170172

171173

@@ -385,9 +387,9 @@ def post_subscription(body: Subscription): # pragma: no cover
385387
assert "post-subscription" in openapi_dict["webhooks"], "'post-subscription' webhook is missing"
386388
assert "post" in openapi_dict["webhooks"]["post-subscription"], "POST method for 'post-subscription' is missing"
387389
assert "Subscription" in openapi_dict["components"]["schemas"], "'Subscription' component is missing"
388-
assert (
389-
"monthly_fee" in openapi_dict["components"]["schemas"]["Subscription"]["properties"]
390-
), "monthly_fee field is missing"
390+
assert "monthly_fee" in openapi_dict["components"]["schemas"]["Subscription"]["properties"], (
391+
"monthly_fee field is missing"
392+
)
391393

392394
resp = client.get("/openapi.json?version=2022-11-16")
393395
openapi_dict = resp.json()
@@ -397,9 +399,9 @@ def post_subscription(body: Subscription): # pragma: no cover
397399
assert "post-subscription" in openapi_dict["webhooks"], "'post-subscription' webhook is present"
398400
assert "post" in openapi_dict["webhooks"]["post-subscription"], "POST method for 'post-subscription' is missing"
399401
assert "Subscription" in openapi_dict["components"]["schemas"], "'Subscription' component is missing"
400-
assert (
401-
"monthly_fee" not in openapi_dict["components"]["schemas"]["Subscription"]["properties"]
402-
), "monthly_fee field is present yet it must be deleted"
402+
assert "monthly_fee" not in openapi_dict["components"]["schemas"]["Subscription"]["properties"], (
403+
"monthly_fee field is present yet it must be deleted"
404+
)
403405

404406

405407
def test__api_version_header_name_is_deprecated_and_translates_to_api_version_parameter_name():

tests/test_router_generation.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -99,8 +99,8 @@ def __call__(
9999
) -> tuple[list[APIRoute], list[APIRoute]]:
100100
app = self.create_versioned_app(*version_changes, router=router)
101101
return (
102-
cast(list[APIRoute], app.router.versioned_routers.get("2000-01-01", APIRouter()).routes),
103-
cast(list[APIRoute], app.router.versioned_routers.get("2001-01-01", APIRouter()).routes),
102+
cast("list[APIRoute]", app.router.versioned_routers.get("2000-01-01", APIRouter()).routes),
103+
cast("list[APIRoute]", app.router.versioned_routers.get("2001-01-01", APIRouter()).routes),
104104
)
105105

106106

@@ -730,8 +730,8 @@ async def test():
730730
app = create_versioned_app(version_change(schema(SchemaWithOneIntField).field("foo").had(type=list[str])))
731731
schemas = generate_versioned_models(app.versions)
732732

733-
routes_2000 = cast(list[APIRoute], app.router.versioned_routers["2000-01-01"].routes)
734-
routes_2001 = cast(list[APIRoute], app.router.versioned_routers["2001-01-01"].routes)
733+
routes_2000 = cast("list[APIRoute]", app.router.versioned_routers["2000-01-01"].routes)
734+
routes_2001 = cast("list[APIRoute]", app.router.versioned_routers["2001-01-01"].routes)
735735

736736
assert len(routes_2000) == len(routes_2001) == 2
737737

@@ -769,8 +769,8 @@ async def test(body: dict[str, list[SchemaWithOnePydanticField]]):
769769
app = create_versioned_app(version_change(schema(SchemaWithOneIntField).field("foo").had(type=list[str])))
770770
schemas = generate_versioned_models(app.versions)
771771

772-
routes_2000 = cast(list[APIRoute], app.router.versioned_routers["2000-01-01"].routes)
773-
routes_2001 = cast(list[APIRoute], app.router.versioned_routers["2001-01-01"].routes)
772+
routes_2000 = cast("list[APIRoute]", app.router.versioned_routers["2000-01-01"].routes)
773+
routes_2001 = cast("list[APIRoute]", app.router.versioned_routers["2001-01-01"].routes)
774774
assert len(routes_2000) == len(routes_2001) == 2
775775

776776
body_param_2000 = routes_2000[1].dependant.body_params[0]
@@ -802,8 +802,8 @@ async def test(body: ChildSchema):
802802

803803
app = create_versioned_app(version_change(schema(ParentSchema).field("foo").didnt_exist))
804804

805-
routes_2000 = cast(list[APIRoute], app.router.versioned_routers["2000-01-01"].routes)
806-
routes_2001 = cast(list[APIRoute], app.router.versioned_routers["2001-01-01"].routes)
805+
routes_2000 = cast("list[APIRoute]", app.router.versioned_routers["2000-01-01"].routes)
806+
routes_2001 = cast("list[APIRoute]", app.router.versioned_routers["2001-01-01"].routes)
807807
assert len(routes_2000) == len(routes_2001) == 2
808808

809809
body_param_2000 = routes_2000[1].dependant.body_params[0]
@@ -833,8 +833,8 @@ async def test3(body: UnversionedSchema3):
833833
app = create_versioned_app(version_change(schema(SchemaWithOneIntField).field("foo").had(type=list[str])))
834834
schemas = generate_versioned_models(app.versions)
835835

836-
routes_2000 = cast(list[APIRoute], app.router.versioned_routers["2000-01-01"].routes)
837-
routes_2001 = cast(list[APIRoute], app.router.versioned_routers["2001-01-01"].routes)
836+
routes_2000 = cast("list[APIRoute]", app.router.versioned_routers["2000-01-01"].routes)
837+
routes_2001 = cast("list[APIRoute]", app.router.versioned_routers["2001-01-01"].routes)
838838

839839
assert len(routes_2000) == len(routes_2001) == 4
840840
assert routes_2000[1].dependant.body_params[0].type_ is schemas["2000-01-01"][UnversionedSchema1]
@@ -1221,7 +1221,7 @@ async def test():
12211221

12221222
client_2000, *_ = create_versioned_clients().values()
12231223

1224-
dependant = cast(APIRoute, client_2000.app.router.versioned_routers["2000-01-01"].routes[-1]).dependant
1224+
dependant = cast("APIRoute", client_2000.app.router.versioned_routers["2000-01-01"].routes[-1]).dependant
12251225
assert dependant.dependencies[1].dependencies[0].security_requirements[0].security_scheme is auth_header_scheme
12261226
response = client_2000.get("/test")
12271227
assert response.status_code == expected_status_code

0 commit comments

Comments
 (0)