Merge pull request #39 from matusf/29-add-raise_for_status
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add `raise_for_status()` to API
authored by Tom Christie · committed by GitHub · parents 8a227c1, c628eb0 · Browse files · 4 files·+61 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+61 added−1 removed
- tests:+29 added−0 removed
- other:+32 added−1 removed
Provenance
- Commit
5c1cb30- Tree
7190470- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent 1
8a227c1- Parent 2
c628eb0
4 files changed+61 added−1 removed
modified:httpcore/exceptions.py+6 added
32 unmodified lines33 34 # HTTP exceptions...35 36 37+class HttpError(Exception):38+ """39+ An Http error occurred.40+ """41+42+43 class ProtocolError(Exception):44 """45 Malformed HTTP.46 """76 unmodified linesmodified:httpcore/models.py+26 added-1 removed
12 unmodified lines13 Decoder,14 IdentityDecoder,15 MultiDecoder,16 )17-from .exceptions import InvalidURL, ResponseClosed, ResponseNotRead, StreamConsumed17+from .exceptions import (18+ HttpError,19+ InvalidURL,20+ ResponseClosed,21+ ResponseNotRead,22+ StreamConsumed,23+)24 from .utils import (25 get_reason_phrase,26 is_known_encoding,27 normalize_header_key,604 unmodified lines632 633 def __repr__(self) -> str:634 class_name = self.__class__.__name__635 return f"<{class_name}(status_code={self.status_code})>"636+637+ def raise_for_status(self) -> None:638+ """639+ Raise the `HttpError` if one occurred.640+ """641+ message = (642+ "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"643+ "For more information check: https://httpstatuses.com/{0.status_code}"644+ )645+646+ if 400 <= self.status_code < 500:647+ message = message.format(self, error_type="Client Error")648+ elif 500 <= self.status_code < 600:649+ message = message.format(self, error_type="Server Error")650+ else:651+ message = ""652+653+ if message:654+ raise HttpError(message)modified:tests/conftest.py+14 added
7 unmodified lines8 async def app(scope, receive, send):9 assert scope["type"] == "http"10 if scope["path"] == "/slow_response":11 await slow_response(scope, receive, send)12+ elif scope["path"].startswith("/status"):13+ await status_code(scope, receive, send)14 else:15 await hello_world(scope, receive, send)16 17 19 unmodified lines37 )38 await send({"type": "http.response.body", "body": b"Hello, world!"})39 40 41+async def status_code(scope, receive, send):42+ status_code = int(scope["path"].replace("/status/", ""))43+ await send(44+ {45+ "type": "http.response.start",46+ "status": status_code,47+ "headers": [[b"content-type", b"text/plain"]],48+ }49+ )50+ await send({"type": "http.response.body", "body": b"Hello, world!"})51+52+53 @pytest.fixture54 async def server():55 config = Config(app=app, lifespan="off")56 server = Server(config=config)8 unmodified linesmodified:tests/test_client.py+15 added
48 unmodified lines49 response = await client.request(50 "POST", "http://127.0.0.1:8000/", content=hello_world()51 )52 assert response.status_code == 20053+54+55+@pytest.mark.asyncio56+async def test_raise_for_status(server):57+ async with httpcore.Client() as client:58+ for status_code in (200, 400, 404, 500, 505):59+ response = await client.request(60+ "GET", f"http://127.0.0.1:8000/status/{status_code}"61+ )62+63+ if 400 <= status_code < 600:64+ with pytest.raises(httpcore.exceptions.HttpError):65+ response.raise_for_status()66+ else:67+ assert response.raise_for_status() is None