Skip to content

Commit

Permalink
fix: avoid conversion to bool in debug response (#2384)
Browse files Browse the repository at this point in the history
* fix: avoid conversion to bool

* refactor: compact instance retrieval

* test: add test for types not supporting bool
  • Loading branch information
geeshta authored Sep 29, 2023
1 parent 82aeb3d commit cf131a5
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
5 changes: 3 additions & 2 deletions litestar/middleware/exceptions/_debug_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,9 @@ def get_symbol_name(frame: FrameInfo) -> str:
locals_dict = frame.frame.f_locals
# this piece assumes that the code uses standard names "self" and "cls"
# in instance and class methods
instance_or_cls = locals_dict.get("self") or locals_dict.get("cls")
classname = f"{get_name(instance_or_cls)}." if instance_or_cls else ""
instance_or_cls = inst if (inst := locals_dict.get("self")) is not None else locals_dict.get("cls")

classname = f"{get_name(instance_or_cls)}." if instance_or_cls is not None else ""

return f"{classname}{frame.function}"

Expand Down
22 changes: 22 additions & 0 deletions tests/unit/test_middleware/test_exception_handler_middleware.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from inspect import getinnerframes
from typing import TYPE_CHECKING, Any, Callable, Optional

import pytest
Expand All @@ -10,6 +11,7 @@
from litestar.exceptions import HTTPException, InternalServerException, ValidationException
from litestar.logging.config import LoggingConfig, StructLoggingConfig
from litestar.middleware.exceptions import ExceptionHandlerMiddleware
from litestar.middleware.exceptions._debug_response import get_symbol_name
from litestar.middleware.exceptions.middleware import get_exception_handler
from litestar.status_codes import HTTP_400_BAD_REQUEST, HTTP_500_INTERNAL_SERVER_ERROR
from litestar.testing import TestClient, create_test_client
Expand Down Expand Up @@ -340,3 +342,23 @@ def handler() -> None:
assert caplog.records[0].message.startswith(
"exception raised on http connection to route /test\n\nTraceback (most recent call last):\n"
)


def test_get_symbol_name_where_type_doesnt_support_bool() -> None:
class Test:
def __bool__(self) -> bool:
raise TypeError("This type doesn't support bool")

def method(self) -> None:
raise RuntimeError("Oh no!")

exc = None

try:
Test().method()
except Exception as e:
exc = e

if exc is not None and exc.__traceback__ is not None:
frame = getinnerframes(exc.__traceback__, 2)[-1]
assert get_symbol_name(frame) == "Test.method"

0 comments on commit cf131a5

Please sign in to comment.