Handle h11.Connection.next_event() RemoteProtocolError (#524)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
raise (new) ConnectionClosed exception if this occurs when socket is closed, otherwise reuse ProtocolError exception. Add test case for ConnectionClosed behavior. Resolves #96
authored by toppk · committed by Florimond Manca · parent 926d6cd · Browse files · 4 files·+42 added−2 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+42 added−2 removed
- tests:+24 added−1 removed
- other:+18 added−1 removed
Provenance
- Commit
f06ca87- Tree
bed9123- Author
toppk <toppk@bllue.org>- Committer
Florimond Manca <florimond.manca@gmail.com>- Parent
926d6cd
4 files changed+42 added−2 removed
modified:httpx/dispatch/http11.py+12 added-1 removed
2 unmodified lines3 import h114 5 from ..concurrency.base import BaseSocketStream, ConcurrencyBackend, TimeoutFlag6 from ..config import TimeoutConfig, TimeoutTypes7+from ..exceptions import ConnectionClosed, ProtocolError8 from ..models import AsyncRequest, AsyncResponse9 from ..utils import get_logger10 11 H11Event = typing.Union[149 unmodified lines161 """162 Read a single `h11` event, reading more data from the network if needed.163 """164 while True:165+ try:164- event = self.h11_state.next_event()166+ event = self.h11_state.next_event()167+ except h11.RemoteProtocolError as e:168+ logger.debug(169+ "h11.RemoteProtocolError exception "170+ + f"their_state={self.h11_state.their_state} "171+ + f"error_status_hint={e.error_status_hint}"172+ )173+ if self.stream.is_connection_dropped():174+ raise ConnectionClosed(e)175+ raise ProtocolError(e)176 177 if isinstance(event, h11.Data):178 logger.trace(f"receive_event event=Data(<{len(event.data)} bytes>)")179 else:40 unmodified linesmodified:httpx/exceptions.py+6 added
148 unmodified lines149 URL was missing a hostname, or was not one of HTTP/HTTPS.150 """151 152 153+class ConnectionClosed(HTTPError):154+ """155+ Expected more data from peer, but connection was closed.156+ """157+158+159 class CookieConflict(HTTPError):160 """161 Attempted to lookup a cookie by name, but multiple cookies existed.162 """modified:tests/dispatch/test_connections.py+12 added-1 removed
1-from httpx import HTTPConnection1+import pytest2 3+from httpx import HTTPConnection, exceptions4 5+6 async def test_get(server, backend):7 async with HTTPConnection(origin=server.url, backend=backend) as conn:8 response = await conn.request("GET", server.url)9 await response.read()6 unmodified lines16 response = await conn.request("GET", server.url, data=b"Hello, world!")17 assert response.status_code == 20018 19 20+async def test_premature_close(server, backend):21+ with pytest.raises(exceptions.ConnectionClosed):22+ async with HTTPConnection(origin=server.url, backend=backend) as conn:23+ response = await conn.request(24+ "GET", server.url.copy_with(path="/premature_close")25+ )26+ await response.read()27+28+29 async def test_https_get_with_ssl_defaults(https_server, ca_cert_pem_file, backend):30 """31 An HTTPS request, with default SSL configuration set on the client.32 """18 unmodified linesmodified:tests/conftest.py+12 added
61 unmodified lines62 async def app(scope, receive, send):63 assert scope["type"] == "http"64 if scope["path"].startswith("/slow_response"):65 await slow_response(scope, receive, send)66+ elif scope["path"].startswith("/premature_close"):67+ await premature_close(scope, receive, send)68 elif scope["path"].startswith("/status"):69 await status_code(scope, receive, send)70 elif scope["path"].startswith("/echo_body"):71 await echo_body(scope, receive, send)32 unmodified lines104 )105 await send({"type": "http.response.body", "body": b"Hello, world!"})106 107 108+async def premature_close(scope, receive, send):109+ await send(110+ {111+ "type": "http.response.start",112+ "status": 200,113+ "headers": [[b"content-type", b"text/plain"]],114+ }115+ )116+117+118 async def status_code(scope, receive, send):119 status_code = int(scope["path"].replace("/status/", ""))120 await send(121 {219 unmodified lines