Refactor to request = Client.send(request)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by Tom Christie · parent 25c652a · Browse files · 11 files·+273 added−222 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+273 added−222 removed
- tests:+117 added−124 removed
- other:+156 added−98 removed
Provenance
- Commit
be77498- Tree
d60d623- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
25c652a
11 files changed+273 added−222 removed
modified:httpcore/__init__.py+2 added-1 removed
1 from .config import PoolLimits, SSLConfig, TimeoutConfig2+from .connections import Connection2-from .datastructures import URL, Request, Response3+from .datastructures import URL, Origin, Request, Response4 from .exceptions import (5 BadResponse,6 ConnectTimeout,7 PoolTimeout,8 unmodified linesmodified:httpcore/config.py+2 added
1+import asyncio2+import os3 import ssl4 import typing5 6 import certifi166 unmodified linesmodified:httpcore/connections.py+88 added-48 removed
1 import asyncio2-import ssl2 import typing3 4 import h115 7-from .config import TimeoutConfig8-from .datastructures import Request, Response6+from .config import DEFAULT_SSL_CONFIG, DEFAULT_TIMEOUT_CONFIG, SSLConfig, TimeoutConfig7+from .datastructures import Client, Origin, Request, Response8 from .exceptions import ConnectTimeout, ReadTimeout9 10 H11Event = typing.Union[11 h11.Request,5 unmodified lines17 ]18 19 20 class Connection:22- def __init__(self, timeout: TimeoutConfig, on_release: typing.Callable = None):23- self.reader = None24- self.writer = None25- self.state = h11.Connection(our_role=h11.CLIENT)21+ def __init__(22+ self,23+ origin: typing.Union[str, Origin],24+ ssl: SSLConfig = DEFAULT_SSL_CONFIG,25+ timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,26+ on_release: typing.Callable = None,27+ ):28+ self.origin = Origin(origin) if isinstance(origin, str) else origin29+ self.ssl = ssl30 self.timeout = timeout31 self.on_release = on_release32+ self._reader = None33+ self._writer = None34+ self._h11_state = h11.Connection(our_role=h11.CLIENT)35 36 @property37 def is_closed(self) -> bool:31- return self.state.our_state in (h11.CLOSED, h11.ERROR)38+ return self._h11_state.our_state in (h11.CLOSED, h11.ERROR)39 33- async def open(34- self, hostname: str, port: int, *, ssl: typing.Optional[ssl.SSLContext] = None35- ) -> None:36- try:37- self.reader, self.writer = await asyncio.wait_for( # type: ignore38- asyncio.open_connection(hostname, port, ssl=ssl),39- self.timeout.connect_timeout,40- )41- except asyncio.TimeoutError:42- raise ConnectTimeout()40+ async def send(41+ self,42+ request: Request,43+ ssl: typing.Optional[SSLConfig] = None,44+ timeout: typing.Optional[TimeoutConfig] = None,45+ stream: bool = False,46+ ) -> Response:47+ assert request.url.origin == self.origin48 44- async def send(self, request: Request) -> Response:49+ if ssl is None:50+ ssl = self.ssl51+ if timeout is None:52+ timeout = self.timeout53+54+ # Make the connection55+ if self._reader is None:56+ await self._connect(ssl, timeout)57+58+ # Start sending the request.59 method = request.method.encode()60 target = request.url.target61 headers = request.headers48-49- # Start sending the request.62 event = h11.Request(method=method, target=target, headers=headers)63 await self._send_event(event)64 65 # Send the request body.9 unmodified lines75 event = h11.EndOfMessage()76 await self._send_event(event)77 78 # Start getting the response.67- event = await self._receive_event()79+ event = await self._receive_event(timeout)80 if isinstance(event, h11.InformationalResponse):69- event = await self._receive_event()81+ event = await self._receive_event(timeout)82 assert isinstance(event, h11.Response)71- reason = event.reason.decode('latin1')83+ reason = event.reason.decode("latin1")84 status_code = event.status_code85 headers = event.headers74- body = self._body_iter()75- return Response(76- status_code=status_code, reason=reason, headers=headers, body=body, on_close=self._release86+ body = self._body_iter(timeout)87+ response = Response(88+ status_code=status_code,89+ reason=reason,90+ headers=headers,91+ body=body,92+ on_close=self._release,93 )94 95+ if not stream:96+ # Read the response body.97+ try:98+ await response.read()99+ finally:100+ await response.close()101+102+ return response103+104+ async def _connect(self, ssl: SSLConfig, timeout: TimeoutConfig) -> None:105+ ssl_context = await ssl.load_ssl_context() if self.origin.is_secure else None106+107+ try:108+ self._reader, self._writer = await asyncio.wait_for( # type: ignore109+ asyncio.open_connection(110+ self.origin.hostname, self.origin.port, ssl=ssl_context111+ ),112+ timeout.connect_timeout,113+ )114+ except asyncio.TimeoutError:115+ raise ConnectTimeout()116+79- async def _body_iter(self) -> typing.AsyncIterator[bytes]:80- event = await self._receive_event()117+ async def _body_iter(self, timeout: TimeoutConfig) -> typing.AsyncIterator[bytes]:118+ event = await self._receive_event(timeout)119 while isinstance(event, h11.Data):120 yield event.data83- event = await self._receive_event()121+ event = await self._receive_event(timeout)122 assert isinstance(event, h11.EndOfMessage)123 124 async def _send_event(self, event: H11Event) -> None:87- assert self.writer is not None125+ assert self._writer is not None126 89- data = self.state.send(event)90- self.writer.write(data)127+ data = self._h11_state.send(event)128+ self._writer.write(data)129 92- async def _receive_event(self) -> H11Event:93- assert self.reader is not None130+ async def _receive_event(self, timeout: TimeoutConfig) -> H11Event:131+ assert self._reader is not None132 95- event = self.state.next_event()133+ event = self._h11_state.next_event()134 135 while event is h11.NEED_DATA:136 try:137 data = await asyncio.wait_for(100- self.reader.read(2048), self.timeout.read_timeout138+ self._reader.read(2048), timeout.read_timeout139 )140 except asyncio.TimeoutError:141 raise ReadTimeout()104- self.state.receive_data(data)105- event = self.state.next_event()142+ self._h11_state.receive_data(data)143+ event = self._h11_state.next_event()144 145 return event146 147 async def _release(self) -> None:110- assert self.writer is not None148+ assert self._writer is not None149 112- if self.state.our_state is h11.DONE and self.state.their_state is h11.DONE:113- self.state.start_next_cycle()150+ if (151+ self._h11_state.our_state is h11.DONE152+ and self._h11_state.their_state is h11.DONE153+ ):154+ self._h11_state.start_next_cycle()155 else:115- self.close()156+ await self.close()157 158 if self.on_release is not None:159 await self.on_release(self)160 120- def close(self) -> None:121- assert self.writer is not None122-161+ async def close(self) -> None:162 event = h11.ConnectionClosed()163 try:164 # If we're in h11.MUST_CLOSE then we'll end up in h11.CLOSED.126- self.state.send(event)165+ self._h11_state.send(event)166 except h11.ProtocolError:167 # If we're in some other state then it's a premature close,168 # and we'll end up in h11.ERROR.169 pass170 171+ if self._writer is not None:132- self.writer.close()172+ self._writer.close()modified:httpcore/datastructures.py+36 added
59 unmodified lines60 @property61 def is_secure(self) -> bool:62 return self.components.scheme == "https"63 64+ @property65+ def origin(self) -> "Origin":66+ return Origin(self)67 68+69+class Origin:70+ def __init__(self, url: typing.Union[str, URL]) -> None:71+ if isinstance(url, str):72+ url = URL(url)73+ self.scheme = url.scheme74+ self.hostname = url.hostname75+ self.port = url.port76+77+ @property78+ def is_secure(self) -> bool:79+ return self.scheme == "https"80+81+ def __eq__(self, other: typing.Any) -> bool:82+ return (83+ isinstance(other, self.__class__)84+ and self.scheme == other.scheme85+ and self.hostname == other.hostname86+ and self.port == other.port87+ )88+89+ def __hash__(self) -> int:90+ return hash((self.scheme, self.hostname, self.port))91+92+93 class Request:94 def __init__(95 self,96 method: str,137 unmodified lines234 if not self.is_closed:235 self.is_closed = True236 if self.on_close is not None:237 await self.on_close()238+239+240+class Client:241+ async def send(self, request: Request, **options: typing.Any) -> Response:242+ raise NotImplementedError() # pragma: nocover243+244+ async def close(self) -> None:245+ raise NotImplementedError() # pragma: nocovermodified:httpcore/pool.py+28 added-49 removed
1 import asyncio2-import functools3-import os4-import ssl2 import typing3 from types import TracebackType4 5 from .config import (5 unmodified lines11 SSLConfig,12 TimeoutConfig,13 )14 from .connections import Connection18-from .datastructures import URL, Request, Response15+from .datastructures import Client, Origin, Request, Response16 from .exceptions import PoolTimeout17 21-ConnectionKey = typing.Tuple[str, str, int, SSLConfig, TimeoutConfig]18 23-19 class ConnectionSemaphore:20 def __init__(self, max_connections: int = None):21 if max_connections is not None:22 self.semaphore = asyncio.BoundedSemaphore(value=max_connections)14 unmodified lines37 ssl: SSLConfig = DEFAULT_SSL_CONFIG,38 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,39 limits: PoolLimits = DEFAULT_POOL_LIMITS,40 ):46- self.ssl_config = ssl41+ self.ssl = ssl42 self.timeout = timeout43 self.limits = limits44 self.is_closed = False45 self.num_active_connections = 046 self.num_keepalive_connections = 047 self._keepalive_connections = (48 {}54- ) # type: typing.Dict[ConnectionKey, typing.List[Connection]]49+ ) # type: typing.Dict[Origin, typing.List[Connection]]50 self._max_connections = ConnectionSemaphore(51 max_connections=self.limits.hard_limit52 )53 59- async def request(54+ async def send(55 self,61- method: str,62- url: str,63- *,64- headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),65- body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",66- stream: bool = False,56+ request: Request,57 ssl: typing.Optional[SSLConfig] = None,58 timeout: typing.Optional[TimeoutConfig] = None,59+ stream: bool = False,60 ) -> Response:70- if ssl is None:71- ssl = self.ssl_config72- if timeout is None:73- timeout = self.timeout74-75- parsed_url = URL(url)76- request = Request(method, parsed_url, headers=headers, body=body)77- connection = await self.acquire_connection(parsed_url, ssl=ssl, timeout=timeout)78- response = await connection.send(request)79- if not stream:80- try:81- await response.read()82- finally:83- await response.close()61+ connection = await self.acquire_connection(request.url.origin, timeout=timeout)62+ response = await connection.send(63+ request, ssl=ssl, timeout=timeout, stream=stream64+ )65 return response66 67 @property68 def num_connections(self) -> int:69 return self.num_active_connections + self.num_keepalive_connections70 71 async def acquire_connection(91- self, url: URL, ssl: SSLConfig, timeout: TimeoutConfig72+ self, origin: Origin, timeout: typing.Optional[TimeoutConfig] = None73 ) -> Connection:93- key = (url.scheme, url.hostname, url.port, ssl, timeout)74 try:95- connection = self._keepalive_connections[key].pop()96- if not self._keepalive_connections[key]:97- del self._keepalive_connections[key]75+ connection = self._keepalive_connections[origin].pop()76+ if not self._keepalive_connections[origin]:77+ del self._keepalive_connections[origin]78 self.num_keepalive_connections -= 179 self.num_active_connections += 180 81 except (KeyError, IndexError):102- if url.is_secure:103- ssl_context = await ssl.load_ssl_context()82+ if timeout is None:83+ pool_timeout = self.timeout.pool_timeout84 else:105- ssl_context = None85+ pool_timeout = timeout.pool_timeout86 87 try:108- await asyncio.wait_for(109- self._max_connections.acquire(), timeout.pool_timeout110- )88+ await asyncio.wait_for(self._max_connections.acquire(), pool_timeout)89 except asyncio.TimeoutError:90 raise PoolTimeout()113- release = functools.partial(self.release_connection, key=key)114- connection = Connection(timeout=timeout, on_release=release)91+ connection = Connection(92+ origin,93+ ssl=self.ssl,94+ timeout=self.timeout,95+ on_release=self.release_connection,96+ )97 self.num_active_connections += 1116- await connection.open(url.hostname, url.port, ssl=ssl_context)98 99 return connection100 120- async def release_connection(121- self, connection: Connection, key: ConnectionKey122- ) -> None:101+ async def release_connection(self, connection: Connection) -> None:102 if connection.is_closed:103 self._max_connections.release()104 self.num_active_connections -= 1105 elif (1 unmodified line107 and self.num_connections > self.limits.soft_limit108 ):109 self._max_connections.release()110 self.num_active_connections -= 1132- connection.close()111+ await connection.close()112 else:113 self.num_active_connections -= 1114 self.num_keepalive_connections += 1115 try:137- self._keepalive_connections[key].append(connection)116+ self._keepalive_connections[connection.origin].append(connection)117 except KeyError:139- self._keepalive_connections[key] = [connection]118+ self._keepalive_connections[connection.origin] = [connection]119 120 async def close(self) -> None:121 self.is_closed = True122 10 unmodified linesadded:httpcore/sync.py
modified:tests/test_api.py+12 added-10 removed
3 unmodified lines4 5 6 @pytest.mark.asyncio7 async def test_get(server):8- async with httpcore.ConnectionPool() as http:9- response = await http.request("GET", "http://127.0.0.1:8000/")8+ async with httpcore.ConnectionPool() as client:9+ request = httpcore.Request("GET", "http://127.0.0.1:8000/")10+ response = await client.send(request)11 assert response.status_code == 20012 assert response.body == b"Hello, world!"13 14 15 @pytest.mark.asyncio16 async def test_post(server):16- async with httpcore.ConnectionPool() as http:17- response = await http.request(17+ async with httpcore.ConnectionPool() as client:18+ request = httpcore.Request(19 "POST", "http://127.0.0.1:8000/", body=b"Hello, world!"20 )21+ response = await client.send(request)22 assert response.status_code == 20023 24 25 @pytest.mark.asyncio26 async def test_stream_response(server):25- async with httpcore.ConnectionPool() as http:26- response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)27+ async with httpcore.ConnectionPool() as client:28+ request = httpcore.Request("GET", "http://127.0.0.1:8000/")29+ response = await client.send(request, stream=True)30 assert response.status_code == 20031 assert not hasattr(response, "body")32 body = await response.read()33 assert body == b"Hello, world!"4 unmodified lines38 async def hello_world():39 yield b"Hello, "40 yield b"world!"41 39- async with httpcore.ConnectionPool() as http:40- response = await http.request(41- "POST", "http://127.0.0.1:8000/", body=hello_world()42- )42+ async with httpcore.ConnectionPool() as client:43+ request = httpcore.Request("POST", "http://127.0.0.1:8000/", body=hello_world())44+ response = await client.send(request)45 assert response.status_code == 200added:tests/test_connections.py+22 added
1+import pytest2+3+import httpcore4+5+6+@pytest.mark.asyncio7+async def test_get(server):8+ client = httpcore.Connection(origin="http://127.0.0.1:8000/")9+ request = httpcore.Request(method="GET", url="http://127.0.0.1:8000/")10+ response = await client.send(request)11+ assert response.status_code == 20012+ assert response.body == b"Hello, world!"13+14+15+@pytest.mark.asyncio16+async def test_post(server):17+ client = httpcore.Connection(origin="http://127.0.0.1:8000/")18+ request = httpcore.Request(19+ method="POST", url="http://127.0.0.1:8000/", body=b"Hello, world!"20+ )21+ response = await client.send(request)22+ assert response.status_code == 200modified:tests/test_pool.py+62 added-50 removed
6 unmodified lines7 async def test_keepalive_connections(server):8 """9 Connections should default to staying in a keep-alive state.10 """11- async with httpcore.ConnectionPool() as http:12- response = await http.request("GET", "http://127.0.0.1:8000/")13- assert http.num_active_connections == 014- assert http.num_keepalive_connections == 111+ async with httpcore.ConnectionPool() as client:12+ request = httpcore.Request("GET", "http://127.0.0.1:8000/")13+ response = await client.send(request)14+ assert client.num_active_connections == 015+ assert client.num_keepalive_connections == 116 16- response = await http.request("GET", "http://127.0.0.1:8000/")17- assert http.num_active_connections == 018- assert http.num_keepalive_connections == 117+ request = httpcore.Request("GET", "http://127.0.0.1:8000/")18+ response = await client.send(request)19+ assert client.num_active_connections == 020+ assert client.num_keepalive_connections == 121 22 23 @pytest.mark.asyncio24 async def test_differing_connection_keys(server):25 """26 Connnections to differing connection keys should result in multiple connections.27 """26- async with httpcore.ConnectionPool() as http:27- response = await http.request("GET", "http://127.0.0.1:8000/")28- assert http.num_active_connections == 029- assert http.num_keepalive_connections == 128+ async with httpcore.ConnectionPool() as client:29+ request = httpcore.Request("GET", "http://127.0.0.1:8000/")30+ response = await client.send(request)31+ assert client.num_active_connections == 032+ assert client.num_keepalive_connections == 133 31- response = await http.request("GET", "http://localhost:8000/")32- assert http.num_active_connections == 033- assert http.num_keepalive_connections == 234+ request = httpcore.Request("GET", "http://localhost:8000/")35+ response = await client.send(request)36+ assert client.num_active_connections == 037+ assert client.num_keepalive_connections == 238 39 40 @pytest.mark.asyncio41 async def test_soft_limit(server):1 unmodified line43 The soft_limit config should limit the maximum number of keep-alive connections.44 """45 limits = httpcore.PoolLimits(soft_limit=1)46 43- async with httpcore.ConnectionPool(limits=limits) as http:44- response = await http.request("GET", "http://127.0.0.1:8000/")45- assert http.num_active_connections == 046- assert http.num_keepalive_connections == 147+ async with httpcore.ConnectionPool(limits=limits) as client:48+ request = httpcore.Request("GET", "http://127.0.0.1:8000/")49+ response = await client.send(request)50+ assert client.num_active_connections == 051+ assert client.num_keepalive_connections == 152 48- response = await http.request("GET", "http://localhost:8000/")49- assert http.num_active_connections == 050- assert http.num_keepalive_connections == 153+ request = httpcore.Request("GET", "http://localhost:8000/")54+ response = await client.send(request)55+ assert client.num_active_connections == 056+ assert client.num_keepalive_connections == 157 58 59 @pytest.mark.asyncio60 async def test_streaming_response_holds_connection(server):61 """62 A streaming request should hold the connection open until the response is read.63 """58- async with httpcore.ConnectionPool() as http:59- response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)60- assert http.num_active_connections == 161- assert http.num_keepalive_connections == 064+ async with httpcore.ConnectionPool() as client:65+ request = httpcore.Request("GET", "http://127.0.0.1:8000/")66+ response = await client.send(request, stream=True)67+ assert client.num_active_connections == 168+ assert client.num_keepalive_connections == 069 70 await response.read()71 65- assert http.num_active_connections == 066- assert http.num_keepalive_connections == 172+ assert client.num_active_connections == 073+ assert client.num_keepalive_connections == 174 75 76 @pytest.mark.asyncio77 async def test_multiple_concurrent_connections(server):78 """79 Multiple conncurrent requests should open multiple conncurrent connections.80 """74- async with httpcore.ConnectionPool() as http:75- response_a = await http.request("GET", "http://127.0.0.1:8000/", stream=True)76- assert http.num_active_connections == 177- assert http.num_keepalive_connections == 081+ async with httpcore.ConnectionPool() as client:82+ request = httpcore.Request("GET", "http://127.0.0.1:8000/")83+ response_a = await client.send(request, stream=True)84+ assert client.num_active_connections == 185+ assert client.num_keepalive_connections == 086 87+ request = httpcore.Request("GET", "http://127.0.0.1:8000/")79- response_b = await http.request("GET", "http://127.0.0.1:8000/", stream=True)80- assert http.num_active_connections == 281- assert http.num_keepalive_connections == 088+ response_b = await client.send(request, stream=True)89+ assert client.num_active_connections == 290+ assert client.num_keepalive_connections == 091 92 await response_b.read()84- assert http.num_active_connections == 185- assert http.num_keepalive_connections == 193+ assert client.num_active_connections == 194+ assert client.num_keepalive_connections == 195 96 await response_a.read()88- assert http.num_active_connections == 089- assert http.num_keepalive_connections == 297+ assert client.num_active_connections == 098+ assert client.num_keepalive_connections == 299 100 101 @pytest.mark.asyncio102 async def test_close_connections(server):103 """104 Using a `Connection: close` header should close the connection.105 """106 headers = [(b"connection", b"close")]98- async with httpcore.ConnectionPool() as http:99- response = await http.request("GET", "http://127.0.0.1:8000/", headers=headers)100- assert http.num_active_connections == 0101- assert http.num_keepalive_connections == 0107+ async with httpcore.ConnectionPool() as client:108+ request = httpcore.Request("GET", "http://127.0.0.1:8000/", headers=headers)109+ response = await client.send(request)110+ assert client.num_active_connections == 0111+ assert client.num_keepalive_connections == 0112 113 114 @pytest.mark.asyncio115 async def test_standard_response_close(server):116 """117 A standard close should keep the connection open.118 """109- async with httpcore.ConnectionPool() as http:110- response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)119+ async with httpcore.ConnectionPool() as client:120+ request = httpcore.Request("GET", "http://127.0.0.1:8000/")121+ response = await client.send(request, stream=True)122 await response.read()123 await response.close()113- assert http.num_active_connections == 0114- assert http.num_keepalive_connections == 1124+ assert client.num_active_connections == 0125+ assert client.num_keepalive_connections == 1126 127 128 @pytest.mark.asyncio129 async def test_premature_response_close(server):130 """131 A premature close should close the connection.132 """122- async with httpcore.ConnectionPool() as http:123- response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)133+ async with httpcore.ConnectionPool() as client:134+ request = httpcore.Request("GET", "http://127.0.0.1:8000/")135+ response = await client.send(request, stream=True)136 await response.close()125- assert http.num_active_connections == 0126- assert http.num_keepalive_connections == 0137+ assert client.num_active_connections == 0138+ assert client.num_keepalive_connections == 0modified:tests/test_responses.py+10 added-57 removed
1 unmodified line2 3 import httpcore4 5 6-class MockHTTP(httpcore.ConnectionPool):7- async def request(8- self, method, url, *, headers=(), body=b"", stream=False9- ) -> httpcore.Response:10- if stream:6+async def streaming_body():7+ yield b"Hello, "8+ yield b"world!"9 12- async def streaming_body():13- yield b"Hello, "14- yield b"world!"10 16- return httpcore.Response(200, body=streaming_body())17- return httpcore.Response(200, body=b"Hello, world!")18-19-20-http = MockHTTP()21-22-23-@pytest.mark.asyncio24-async def test_request():25- response = await http.request("GET", "http://example.com")11+def test_response():12+ response = httpcore.Response(200, body=b"Hello, world!")13 assert response.status_code == 20014 assert response.reason == "OK"15 assert response.body == b"Hello, world!"16 assert response.is_closed17 18 19 @pytest.mark.asyncio20 async def test_read_response():34- response = await http.request("GET", "http://example.com")21+ response = httpcore.Response(200, body=b"Hello, world!")22 23 assert response.status_code == 20024 assert response.body == b"Hello, world!"25 assert response.is_closed5 unmodified lines31 assert response.is_closed32 33 34 @pytest.mark.asyncio48-async def test_stream_response():49- response = await http.request("GET", "http://example.com")35+async def test_streaming_response():36+ response = httpcore.Response(200, body=streaming_body())37 38 assert response.status_code == 20052- assert response.body == b"Hello, world!"53- assert response.is_closed54-55- body = b""56- async for part in response.stream():57- body += part58-59- assert body == b"Hello, world!"60- assert response.body == b"Hello, world!"61- assert response.is_closed62-63-64-@pytest.mark.asyncio65-async def test_read_streaming_response():66- response = await http.request("GET", "http://example.com", stream=True)67-68- assert response.status_code == 20039 assert not hasattr(response, "body")40 assert not response.is_closed41 42 body = await response.read()3 unmodified lines46 assert response.is_closed47 48 49 @pytest.mark.asyncio80-async def test_stream_streaming_response():81- response = await http.request("GET", "http://example.com", stream=True)82-83- assert response.status_code == 20084- assert not hasattr(response, "body")85- assert not response.is_closed86-87- body = b""88- async for part in response.stream():89- body += part90-91- assert body == b"Hello, world!"92- assert not hasattr(response, "body")93- assert response.is_closed94-95-96-@pytest.mark.asyncio50 async def test_cannot_read_after_stream_consumed():98- response = await http.request("GET", "http://example.com", stream=True)51+ response = httpcore.Response(200, body=streaming_body())52 53 body = b""54 async for part in response.stream():55 body += part3 unmodified lines59 60 61 @pytest.mark.asyncio62 async def test_cannot_read_after_response_closed():110- response = await http.request("GET", "http://example.com", stream=True)63+ response = httpcore.Response(200, body=streaming_body())64 65 await response.close()66 67 with pytest.raises(httpcore.ResponseClosed):7 unmodified linesmodified:tests/test_timeouts.py+11 added-7 removed
5 unmodified lines6 @pytest.mark.asyncio7 async def test_read_timeout(server):8 timeout = httpcore.TimeoutConfig(read_timeout=0.0001)9 10- async with httpcore.ConnectionPool(timeout=timeout) as http:10+ async with httpcore.ConnectionPool(timeout=timeout) as client:11 with pytest.raises(httpcore.ReadTimeout):12- await http.request("GET", "http://127.0.0.1:8000/slow_response")12+ request = httpcore.Request("GET", "http://127.0.0.1:8000/slow_response")13+ await client.send(request)14 15 16 @pytest.mark.asyncio17 async def test_connect_timeout(server):18 timeout = httpcore.TimeoutConfig(connect_timeout=0.0001)19 19- async with httpcore.ConnectionPool(timeout=timeout) as http:20+ async with httpcore.ConnectionPool(timeout=timeout) as client:21 with pytest.raises(httpcore.ConnectTimeout):22 # See https://stackoverflow.com/questions/100841/22- await http.request("GET", "http://10.255.255.1/")23+ request = httpcore.Request("GET", "http://10.255.255.1/")24+ await client.send(request)25 26 27 @pytest.mark.asyncio28 async def test_pool_timeout(server):29 timeout = httpcore.TimeoutConfig(pool_timeout=0.0001)30 limits = httpcore.PoolLimits(hard_limit=1)31 30- async with httpcore.ConnectionPool(timeout=timeout, limits=limits) as http:31- response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)32+ async with httpcore.ConnectionPool(timeout=timeout, limits=limits) as client:33+ request = httpcore.Request("GET", "http://127.0.0.1:8000/")34+ response = await client.send(request, stream=True)35 36 with pytest.raises(httpcore.PoolTimeout):34- await http.request("GET", "http://localhost:8000/")37+ request = httpcore.Request("GET", "http://127.0.0.1:8000/")38+ await client.send(request)39 40 await response.read()