Skip to content

Commit e5d8619

Browse files
committed
KIT-4553 Format all
1 parent 8f9d4f4 commit e5d8619

File tree

6 files changed

+101
-34
lines changed

6 files changed

+101
-34
lines changed

sag_py_web_common/__init__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
from .default_route import build_default_route # noqa: F401
2-
from .filtered_access_logger import FilteredAccessLoggerMiddleware # noqa: F401
3-
from .json_exception_handler import handle_unknown_exception, log_exception # noqa: F401
1+
from .default_route import build_default_route # noqa: F401
2+
from .filtered_access_logger import FilteredAccessLoggerMiddleware # noqa: F401
3+
from .json_exception_handler import handle_unknown_exception, log_exception # noqa: F401

sag_py_web_common/default_route.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22
from fastapi.responses import RedirectResponse
33

44

5-
def build_default_route(default_redirect_path: str = "/swagger", ingress_base_path: str = "") -> APIRouter:
5+
def build_default_route(
6+
default_redirect_path: str = "/swagger", ingress_base_path: str = ""
7+
) -> APIRouter:
68
"""Builds an api router for the default route / It can be used to redirect to a specific path.
79
810
Args:
@@ -18,6 +20,8 @@ def build_default_route(default_redirect_path: str = "/swagger", ingress_base_pa
1820
methods=["GET"],
1921
name="default",
2022
include_in_schema=False,
21-
endpoint=lambda _: RedirectResponse(url=f"{ingress_base_path}{default_redirect_path}"),
23+
endpoint=lambda _: RedirectResponse(
24+
url=f"{ingress_base_path}{default_redirect_path}"
25+
),
2226
)
2327
return default_route

sag_py_web_common/filtered_access_logger.py

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,12 @@
22
from typing import List, Optional, Union
33

44
from asgi_logger.middleware import AccessInfo, AccessLogAtoms, AccessLoggerMiddleware
5-
from asgiref.typing import ASGI3Application, ASGIReceiveCallable, ASGISendCallable, HTTPScope
5+
from asgiref.typing import (
6+
ASGI3Application,
7+
ASGIReceiveCallable,
8+
ASGISendCallable,
9+
HTTPScope,
10+
)
611

712

813
class FilteredAccessLoggerMiddleware(AccessLoggerMiddleware):
@@ -33,16 +38,27 @@ async def __call__(
3338
def log(self, scope: HTTPScope, info: AccessInfo) -> None:
3439
if self._should_log(scope):
3540
extra_args = {"execution_time": info["end_time"] - info["start_time"]}
36-
if info["response"].get("status") and str(info["response"]["status"])[0] == "2": # type: ignore
37-
self.logger.info(self.format, AccessLogAtoms(scope, info), extra=extra_args)
41+
if (
42+
info["response"].get("status")
43+
and str(info["response"]["status"])[0] == "2"
44+
): # type: ignore
45+
self.logger.info(
46+
self.format, AccessLogAtoms(scope, info), extra=extra_args
47+
)
3848
else:
39-
self.logger.warning(self.format, AccessLogAtoms(scope, info), extra=extra_args)
49+
self.logger.warning(
50+
self.format, AccessLogAtoms(scope, info), extra=extra_args
51+
)
4052

4153
def _should_log(self, scope: HTTPScope) -> bool:
4254
return (
4355
scope["type"] == "http"
44-
and not FilteredAccessLoggerMiddleware._is_excluded_via_path(scope, self.excluded_paths)
45-
and not FilteredAccessLoggerMiddleware._is_excluded_via_header(scope, self.exclude_header)
56+
and not FilteredAccessLoggerMiddleware._is_excluded_via_path(
57+
scope, self.excluded_paths
58+
)
59+
and not FilteredAccessLoggerMiddleware._is_excluded_via_header(
60+
scope, self.exclude_header
61+
)
4662
)
4763

4864
@staticmethod

sag_py_web_common/json_exception_handler.py

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,11 @@
88
from starlette.exceptions import HTTPException as StarletteHTTPException
99
from starlette.responses import Response
1010

11-
from sag_py_web_common.response_content import SimpleDetail, ValidationErrorDetail, ValidationErrorResponse
11+
from sag_py_web_common.response_content import (
12+
SimpleDetail,
13+
ValidationErrorDetail,
14+
ValidationErrorResponse,
15+
)
1216

1317
logger: Logger = logging.getLogger("http_error_logger")
1418

@@ -20,26 +24,35 @@ async def handle_unknown_exception(_: Any, exception: Exception) -> JSONResponse
2024
JSONResponse: A json response that contains the field 'detail' with the exception message.
2125
"""
2226
logger.error("An unknown Error!", exc_info=True, extra={"response_status": 500})
23-
return JSONResponse(status_code=500, content=SimpleDetail(detail=str(exception)).model_dump())
27+
return JSONResponse(
28+
status_code=500, content=SimpleDetail(detail=str(exception)).model_dump()
29+
)
2430

2531

2632
async def log_exception(_, exception: StarletteHTTPException) -> Response: # type: ignore
27-
logger.error("An HTTP Error! %s", exception.detail, extra={"response_status": exception.status_code})
33+
logger.error(
34+
"An HTTP Error! %s",
35+
exception.detail,
36+
extra={"response_status": exception.status_code},
37+
)
2838

2939
return await http_exception_handler(_, exception)
3040

3141

32-
async def handle_validation_exception(_: Any, exception: RequestValidationError) -> JSONResponse:
42+
async def handle_validation_exception(
43+
_: Any, exception: RequestValidationError
44+
) -> JSONResponse:
3345
errors = [
34-
ValidationErrorDetail(**{
35-
"loc": [str(loc) for loc in err["loc"]],
36-
"msg": err["msg"],
37-
"type": err["type"]
38-
})
46+
ValidationErrorDetail(
47+
**{
48+
"loc": [str(loc) for loc in err["loc"]],
49+
"msg": err["msg"],
50+
"type": err["type"],
51+
}
52+
)
3953
for err in exception.errors()
4054
]
4155
logger.error("Validation Error!", exc_info=True, extra={"response_status": 422})
4256
return JSONResponse(
43-
status_code=422,
44-
content=ValidationErrorResponse(detail=errors).model_dump()
57+
status_code=422, content=ValidationErrorResponse(detail=errors).model_dump()
4558
)

tests/test_filtered_access_logger.py

Lines changed: 34 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,9 @@ def test_middleware_logs_successfully(
5858

5959
middleware.log(scope, info) # type: ignore # pylint: disable=W0212:protected-access
6060

61-
logs_at_correct_log_level = [record for record in caplog.records if record.levelno == log_level]
61+
logs_at_correct_log_level = [
62+
record for record in caplog.records if record.levelno == log_level
63+
]
6264

6365
assert len(caplog.records) == 1
6466
assert len(logs_at_correct_log_level) == 1
@@ -84,7 +86,11 @@ def test_logs_can_be_ignored_via_path_and_header(
8486
excluded_paths = ["maintain/serviceStatus", "health/serviceStatus"]
8587
mock_app: ASGI3Application = lambda scope, receive, send: None # type: ignore # noqa: E731
8688
middleware = FilteredAccessLoggerMiddleware(
87-
app=mock_app, format=None, logger=None, excluded_paths=excluded_paths, exclude_header=exclude_header
89+
app=mock_app,
90+
format=None,
91+
logger=None,
92+
excluded_paths=excluded_paths,
93+
exclude_header=exclude_header,
8894
)
8995

9096
scope = {"type": "http", "path": path, "headers": ignored_headers}
@@ -122,8 +128,13 @@ def test_excluding_log_via_path_is_possible(path: str, pathIsIgnored: bool) -> N
122128
assert actual == pathIsIgnored
123129

124130

125-
@pytest.mark.parametrize("path,pathIsIgnored", [("/serviceStatus", False), ("/my/other/endpoint", False), ("/", False)])
126-
def test_not_configured_excluded_paths_does_not_cause_any_logs_to_be_excluded(path: str, pathIsIgnored: bool) -> None:
131+
@pytest.mark.parametrize(
132+
"path,pathIsIgnored",
133+
[("/serviceStatus", False), ("/my/other/endpoint", False), ("/", False)],
134+
)
135+
def test_not_configured_excluded_paths_does_not_cause_any_logs_to_be_excluded(
136+
path: str, pathIsIgnored: bool
137+
) -> None:
127138
excluded_paths = None
128139
scope = {"path": path}
129140

@@ -133,8 +144,13 @@ def test_not_configured_excluded_paths_does_not_cause_any_logs_to_be_excluded(pa
133144
assert actual == pathIsIgnored
134145

135146

136-
@pytest.mark.parametrize("path,pathIsIgnored", [("/serviceStatus", False), ("/my/other/endpoint", False), ("/", False)])
137-
def test_empty_excludes_paths_does_not_cause_any_logs_to_be_excluded(path: str, pathIsIgnored: bool) -> None:
147+
@pytest.mark.parametrize(
148+
"path,pathIsIgnored",
149+
[("/serviceStatus", False), ("/my/other/endpoint", False), ("/", False)],
150+
)
151+
def test_empty_excludes_paths_does_not_cause_any_logs_to_be_excluded(
152+
path: str, pathIsIgnored: bool
153+
) -> None:
138154
excluded_paths: List[str] = []
139155
scope = {"path": path}
140156

@@ -154,26 +170,34 @@ def test_empty_excludes_paths_does_not_cause_any_logs_to_be_excluded(path: str,
154170
([], False),
155171
],
156172
)
157-
def test_excluding_logs_via_header_is_possible(headers: list[tuple[bytes, bytes]], path_is_ignored: bool) -> None:
173+
def test_excluding_logs_via_header_is_possible(
174+
headers: list[tuple[bytes, bytes]], path_is_ignored: bool
175+
) -> None:
158176
exclude_header = "exclude-logging"
159177
scope = {
160178
"headers": headers,
161179
}
162180

163181
# pylint: disable=W0212:protected-access
164-
actual = FilteredAccessLoggerMiddleware._is_excluded_via_header(scope, exclude_header) # type: ignore
182+
actual = FilteredAccessLoggerMiddleware._is_excluded_via_header(
183+
scope, exclude_header
184+
) # type: ignore
165185

166186
assert actual == path_is_ignored
167187

168188

169-
@pytest.mark.parametrize("headers,path_is_ignored", [([(b"Exclude-Logging", b"")], False), ([], False)])
189+
@pytest.mark.parametrize(
190+
"headers,path_is_ignored", [([(b"Exclude-Logging", b"")], False), ([], False)]
191+
)
170192
def test_not_configured_exclude_header_does_not_cause_any_logs_to_be_excluded(
171193
headers: list[tuple[bytes, bytes]], path_is_ignored: bool
172194
) -> None:
173195
exclude_header = ""
174196
scope = {"headers": headers}
175197

176198
# pylint: disable=W0212:protected-access
177-
actual = FilteredAccessLoggerMiddleware._is_excluded_via_header(scope, exclude_header) # type: ignore
199+
actual = FilteredAccessLoggerMiddleware._is_excluded_via_header(
200+
scope, exclude_header
201+
) # type: ignore
178202

179203
assert actual == path_is_ignored

tests/test_json_exception_handler.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@
1414
@pytest.mark.asyncio
1515
async def test_handle_unknown_exception() -> None:
1616
# Act
17-
result: JSONResponse = await handle_unknown_exception("", Exception("error message"))
17+
result: JSONResponse = await handle_unknown_exception(
18+
"", Exception("error message")
19+
)
1820

1921
# Assert
2022
assert result.status_code == 500
@@ -24,7 +26,15 @@ async def test_handle_unknown_exception() -> None:
2426
@pytest.mark.asyncio
2527
async def test_validation_exception_handler() -> None:
2628
# Arrange
27-
exc = RequestValidationError([{"loc": ("body", "title"), "msg": "field required", "type": "value_error.missing"}])
29+
exc = RequestValidationError(
30+
[
31+
{
32+
"loc": ("body", "title"),
33+
"msg": "field required",
34+
"type": "value_error.missing",
35+
}
36+
]
37+
)
2838
request = Mock()
2939

3040
# Act

0 commit comments

Comments
 (0)