Skip to content
Myr

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

11 files+273 added−222 removed

modified:httpcore/__init__.py+2 added-1 removed
1from .config import PoolLimits, SSLConfig, TimeoutConfig2from .connections import Connection2from .datastructures import URL, Request, Response3from .datastructures import URL, Origin, Request, Response4from .exceptions import (5 BadResponse,6 ConnectTimeout,7 PoolTimeout,
8 unmodified lines
modified:httpcore/config.py+2 added
1import asyncio2import os3import ssl4import typing56import certifi
166 unmodified lines
modified:httpcore/connections.py+88 added-48 removed
1import asyncio2import ssl2import typing34import h1157from .config import TimeoutConfig8from .datastructures import Request, Response6from .config import DEFAULT_SSL_CONFIG, DEFAULT_TIMEOUT_CONFIG, SSLConfig, TimeoutConfig7from .datastructures import Client, Origin, Request, Response8from .exceptions import ConnectTimeout, ReadTimeout910H11Event = typing.Union[11 h11.Request,
5 unmodified lines
17]181920class 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)3536 @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)3933 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.origin4844 async def send(self, request: Request) -> Response:49 if ssl is None:50 ssl = self.ssl51 if timeout is None:52 timeout = self.timeout5354 # Make the connection55 if self._reader is None:56 await self._connect(ssl, timeout)5758 #  Start sending the request.59 method = request.method.encode()60 target = request.url.target61 headers = request.headers4849 #  Start sending the request.62 event = h11.Request(method=method, target=target, headers=headers)63 await self._send_event(event)6465 # Send the request body.
9 unmodified lines
75 event = h11.EndOfMessage()76 await self._send_event(event)7778 # 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 )9495 if not stream:96 # Read the response body.97 try:98 await response.read()99 finally:100 await response.close()101102 return response103104 async def _connect(self, ssl: SSLConfig, timeout: TimeoutConfig) -> None:105 ssl_context = await ssl.load_ssl_context() if self.origin.is_secure else None106107 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()11679 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)123124 async def _send_event(self, event: H11Event) -> None:87 assert self.writer is not None125 assert self._writer is not None12689 data = self.state.send(event)90 self.writer.write(data)127 data = self._h11_state.send(event)128 self._writer.write(data)12992 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 None13295 event = self.state.next_event()133 event = self._h11_state.next_event()134135 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()144145 return event146147 async def _release(self) -> None:110 assert self.writer is not None148 assert self._writer is not None149112 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()157158 if self.on_release is not None:159 await self.on_release(self)160120 def close(self) -> None:121 assert self.writer is not None122161 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 pass170171 if self._writer is not None:132 self.writer.close()172 self._writer.close()
modified:httpcore/datastructures.py+36 added
59 unmodified lines
60 @property61 def is_secure(self) -> bool:62 return self.components.scheme == "https"6364 @property65 def origin(self) -> "Origin":66 return Origin(self)676869class 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.port7677 @property78 def is_secure(self) -> bool:79 return self.scheme == "https"8081 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 )8889 def __hash__(self) -> int:90 return hash((self.scheme, self.hostname, self.port))919293class Request:94 def __init__(95 self,96 method: str,
137 unmodified lines
234 if not self.is_closed:235 self.is_closed = True236 if self.on_close is not None:237 await self.on_close()238239240class Client:241 async def send(self, request: Request, **options: typing.Any) -> Response:242 raise NotImplementedError() # pragma: nocover243244 async def close(self) -> None:245 raise NotImplementedError() # pragma: nocover
modified:httpcore/pool.py+28 added-49 removed
1import asyncio2import functools3import os4import ssl2import typing3from types import TracebackType45from .config import (
5 unmodified lines
11 SSLConfig,12 TimeoutConfig,13)14from .connections import Connection18from .datastructures import URL, Request, Response15from .datastructures import Client, Origin, Request, Response16from .exceptions import PoolTimeout1721ConnectionKey = typing.Tuple[str, str, int, SSLConfig, TimeoutConfig]182319class 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 lines
37 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 )5359 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.timeout7475 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 response6667 @property68 def num_connections(self) -> int:69 return self.num_active_connections + self.num_keepalive_connections7071 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 += 18081 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_timeout8687 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)9899 return connection100120 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 line
107 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]119120 async def close(self) -> None:121 self.is_closed = True122
10 unmodified lines
added:httpcore/sync.py
modified:tests/test_api.py+12 added-10 removed
3 unmodified lines
456@pytest.mark.asyncio7async 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!"131415@pytest.mark.asyncio16async 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 == 200232425@pytest.mark.asyncio26async 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 lines
38 async def hello_world():39 yield b"Hello, "40 yield b"world!"4139 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 == 200
added:tests/test_connections.py+22 added
1import pytest23import httpcore456@pytest.mark.asyncio7async 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!"131415@pytest.mark.asyncio16async 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 == 200
modified:tests/test_pool.py+62 added-50 removed
6 unmodified lines
7async 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 == 11616 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 == 1212223@pytest.mark.asyncio24async 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 == 13331 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 == 2383940@pytest.mark.asyncio41async def test_soft_limit(server):
1 unmodified line
43 The soft_limit config should limit the maximum number of keep-alive connections.44 """45 limits = httpcore.PoolLimits(soft_limit=1)4643 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 == 15248 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 == 1575859@pytest.mark.asyncio60async 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 == 06970 await response.read()7165 assert http.num_active_connections == 066 assert http.num_keepalive_connections == 172 assert client.num_active_connections == 073 assert client.num_keepalive_connections == 1747576@pytest.mark.asyncio77async 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 == 08687 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 == 09192 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 == 19596 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 == 299100101@pytest.mark.asyncio102async 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 == 0112113114@pytest.mark.asyncio115async 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 == 1126127128@pytest.mark.asyncio129async 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 == 0
modified:tests/test_responses.py+10 added-57 removed
1 unmodified line
23import httpcore456class MockHTTP(httpcore.ConnectionPool):7 async def request(8 self, method, url, *, headers=(), body=b"", stream=False9 ) -> httpcore.Response:10 if stream:6async def streaming_body():7 yield b"Hello, "8 yield b"world!"912 async def streaming_body():13 yield b"Hello, "14 yield b"world!"1016 return httpcore.Response(200, body=streaming_body())17 return httpcore.Response(200, body=b"Hello, world!")181920http = MockHTTP()212223@pytest.mark.asyncio24async def test_request():25 response = await http.request("GET", "http://example.com")11def 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_closed171819@pytest.mark.asyncio20async def test_read_response():34 response = await http.request("GET", "http://example.com")21 response = httpcore.Response(200, body=b"Hello, world!")2223 assert response.status_code == 20024 assert response.body == b"Hello, world!"25 assert response.is_closed
5 unmodified lines
31 assert response.is_closed323334@pytest.mark.asyncio48async def test_stream_response():49 response = await http.request("GET", "http://example.com")35async def test_streaming_response():36 response = httpcore.Response(200, body=streaming_body())3738 assert response.status_code == 20052 assert response.body == b"Hello, world!"53 assert response.is_closed5455 body = b""56 async for part in response.stream():57 body += part5859 assert body == b"Hello, world!"60 assert response.body == b"Hello, world!"61 assert response.is_closed626364@pytest.mark.asyncio65async def test_read_streaming_response():66 response = await http.request("GET", "http://example.com", stream=True)6768 assert response.status_code == 20039 assert not hasattr(response, "body")40 assert not response.is_closed4142 body = await response.read()
3 unmodified lines
46 assert response.is_closed474849@pytest.mark.asyncio80async def test_stream_streaming_response():81 response = await http.request("GET", "http://example.com", stream=True)8283 assert response.status_code == 20084 assert not hasattr(response, "body")85 assert not response.is_closed8687 body = b""88 async for part in response.stream():89 body += part9091 assert body == b"Hello, world!"92 assert not hasattr(response, "body")93 assert response.is_closed949596@pytest.mark.asyncio50async 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())5253 body = b""54 async for part in response.stream():55 body += part
3 unmodified lines
596061@pytest.mark.asyncio62async 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())6465 await response.close()6667 with pytest.raises(httpcore.ResponseClosed):
7 unmodified lines
modified:tests/test_timeouts.py+11 added-7 removed
5 unmodified lines
6@pytest.mark.asyncio7async def test_read_timeout(server):8 timeout = httpcore.TimeoutConfig(read_timeout=0.0001)910 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)141516@pytest.mark.asyncio17async def test_connect_timeout(server):18 timeout = httpcore.TimeoutConfig(connect_timeout=0.0001)1919 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)252627@pytest.mark.asyncio28async def test_pool_timeout(server):29 timeout = httpcore.TimeoutConfig(pool_timeout=0.0001)30 limits = httpcore.PoolLimits(hard_limit=1)3130 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)3536 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)3940 await response.read()