Skip to content

Commit

Permalink
Fix empty str(exception) when initialized with kwargs (#2181)
Browse files Browse the repository at this point in the history
Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
  • Loading branch information
BoWuGit and Kludex committed Jun 20, 2023
1 parent 8d7a1ca commit 2168e47
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
6 changes: 6 additions & 0 deletions starlette/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ def __init__(
self.detail = detail
self.headers = headers

def __str__(self) -> str:
return f"{self.status_code}: {self.detail}"

def __repr__(self) -> str:
class_name = self.__class__.__name__
return f"{class_name}(status_code={self.status_code!r}, detail={self.detail!r})"
Expand All @@ -28,6 +31,9 @@ def __init__(self, code: int, reason: typing.Optional[str] = None) -> None:
self.code = code
self.reason = reason or ""

def __str__(self) -> str:
return f"{self.code}: {self.reason}"

def __repr__(self) -> str:
class_name = self.__class__.__name__
return f"{class_name}(code={self.code!r}, reason={self.reason!r})"
Expand Down
11 changes: 11 additions & 0 deletions tests/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,12 @@ async def app(scope, receive, send):
assert response.text == ""


def test_http_str():
assert str(HTTPException(status_code=404)) == "404: Not Found"
assert str(HTTPException(404, "Not Found: foo")) == "404: Not Found: foo"
assert str(HTTPException(404, headers={"key": "value"})) == "404: Not Found"


def test_http_repr():
assert repr(HTTPException(404)) == (
"HTTPException(status_code=404, detail='Not Found')"
Expand All @@ -160,6 +166,11 @@ class CustomHTTPException(HTTPException):
)


def test_websocket_str():
assert str(WebSocketException(1008)) == "1008: "
assert str(WebSocketException(1008, "Policy Violation")) == "1008: Policy Violation"


def test_websocket_repr():
assert repr(WebSocketException(1008, reason="Policy Violation")) == (
"WebSocketException(code=1008, reason='Policy Violation')"
Expand Down

0 comments on commit 2168e47

Please sign in to comment.