]> git.ipfire.org Git - thirdparty/httpx.git/commitdiff
Add response.reason
authorTom Christie <tom@tomchristie.com>
Thu, 18 Apr 2019 10:41:13 +0000 (11:41 +0100)
committerTom Christie <tom@tomchristie.com>
Thu, 18 Apr 2019 10:41:13 +0000 (11:41 +0100)
httpcore/connections.py
httpcore/datastructures.py
tests/test_responses.py

index 205482e8a697c00e72c5836177c987561582f0bf..16f91408a32fca23615eb0c4b0a29ad927f0a093 100644 (file)
@@ -68,11 +68,12 @@ class Connection:
         if isinstance(event, h11.InformationalResponse):
             event = await self._receive_event()
         assert isinstance(event, h11.Response)
+        reason = event.reason.decode('latin1')
         status_code = event.status_code
         headers = event.headers
         body = self._body_iter()
         return Response(
-            status_code=status_code, headers=headers, body=body, on_close=self._release
+            status_code=status_code, reason=reason, headers=headers, body=body, on_close=self._release
         )
 
     async def _body_iter(self) -> typing.AsyncIterator[bytes]:
index 5f84b4669e93edac0912f30ac2687ca6bdc2acb0..49f85bdc96fc7ef546c060404bf9d10efd8a1c95 100644 (file)
@@ -1,3 +1,4 @@
+import http
 import typing
 from urllib.parse import urlsplit
 
@@ -122,11 +123,19 @@ class Response:
         self,
         status_code: int,
         *,
+        reason: typing.Optional[str] = None,
         headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),
         body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",
         on_close: typing.Callable = None,
     ):
         self.status_code = status_code
+        if not reason:
+            try:
+                self.reason = http.HTTPStatus(status_code).phrase
+            except ValueError as exc:
+                self.reason = ""
+        else:
+            self.reason = reason
         self.headers = list(headers)
         self.on_close = on_close
         self.is_closed = False
index ae754b404a1126690ce74720b2053ca87a93867c..3efef890b7a88ec97b593953ad9019d4a8a3363f 100644 (file)
@@ -24,6 +24,7 @@ http = MockHTTP()
 async def test_request():
     response = await http.request("GET", "http://example.com")
     assert response.status_code == 200
+    assert response.reason == "OK"
     assert response.body == b"Hello, world!"
     assert response.is_closed
 
@@ -112,3 +113,9 @@ async def test_cannot_read_after_response_closed():
 
     with pytest.raises(httpcore.ResponseClosed):
         await response.read()
+
+
+def test_unknown_status_code():
+    response = httpcore.Response(600)
+    assert response.status_code == 600
+    assert response.reason == ""