]> git.ipfire.org Git - thirdparty/starlette.git/commitdiff
Fix empty str(exception) when initialized with kwargs (#2181)
authorbowugit <wubo616@gmail.com>
Tue, 20 Jun 2023 18:35:45 +0000 (02:35 +0800)
committerGitHub <noreply@github.com>
Tue, 20 Jun 2023 18:35:45 +0000 (18:35 +0000)
Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
starlette/exceptions.py
tests/test_exceptions.py

index 87da735915de4752dc40346b11d2b25394a5bb77..cc08ed909d5dd696c12f323b1800488050d21445 100644 (file)
@@ -18,6 +18,9 @@ class HTTPException(Exception):
         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})"
@@ -28,6 +31,9 @@ class WebSocketException(Exception):
         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})"
index 2f2b89167337c9d394bf2a5df3b25938347a60a4..735f2401ed41fe7a783232b34b0744f5c82d4f9d 100644 (file)
@@ -144,6 +144,12 @@ def test_force_500_response(test_client_factory):
     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')"
@@ -160,6 +166,11 @@ def test_http_repr():
     )
 
 
+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')"