Skip to content
Myr

Merge pull request #15 from encode/module-renaming

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Module renaming

authored by Tom Christie · committed by GitHub · parents 0f178ca, b7d315a · Browse files · 12 files+426 added−429 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

12 files+426 added−429 removed

  • tests:+129 added−129 removed
  • other:+297 added−300 removed

12 files+426 added−429 removed

modified:httpcore/__init__.py+2 added-2 removed
1from .config import PoolLimits, SSLConfig, TimeoutConfig2from .connections import Connection2from .connectionpool import ConnectionPool3from .datastructures import URL, Origin, Request, Response4from .exceptions import (5 BadResponse,6 ConnectTimeout,
2 unmodified lines
9 ResponseClosed,10 StreamConsumed,11 Timeout,12)13from .pool import ConnectionPool13from .http11 import HTTP11Connection14from .sync import SyncClient, SyncConnectionPool1516__version__ = "0.2.0"
modified:httpcore/compat.py+1 added
1import asyncio23if hasattr(asyncio, "run"):4 asyncio_run = asyncio.run56else: # pragma: nocover78 def asyncio_run(main, *, debug=False): # type: ignore9 if asyncio._get_running_loop() is not None:
43 unmodified lines
added:httpcore/connectionpool.py+126 added
1import asyncio2import typing34from .config import (5 DEFAULT_CA_BUNDLE_PATH,6 DEFAULT_POOL_LIMITS,7 DEFAULT_SSL_CONFIG,8 DEFAULT_TIMEOUT_CONFIG,9 PoolLimits,10 SSLConfig,11 TimeoutConfig,12)13from .http11 import HTTP11Connection14from .datastructures import Client, Origin, Request, Response15from .exceptions import PoolTimeout161718class ConnectionPool(Client):19 def __init__(20 self,21 *,22 ssl: SSLConfig = DEFAULT_SSL_CONFIG,23 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,24 limits: PoolLimits = DEFAULT_POOL_LIMITS,25 ):26 self.ssl = ssl27 self.timeout = timeout28 self.limits = limits29 self.is_closed = False30 self.num_active_connections = 031 self.num_keepalive_connections = 032 self._keepalive_connections = (33 {}34 ) # type: typing.Dict[Origin, typing.List[HTTP11Connection]]35 self._max_connections = ConnectionSemaphore(36 max_connections=self.limits.hard_limit37 )3839 async def send(40 self,41 request: Request,42 *,43 ssl: typing.Optional[SSLConfig] = None,44 timeout: typing.Optional[TimeoutConfig] = None,45 ) -> Response:46 connection = await self.acquire_connection(request.url.origin, timeout=timeout)47 response = await connection.send(request, ssl=ssl, timeout=timeout)48 return response4950 @property51 def num_connections(self) -> int:52 return self.num_active_connections + self.num_keepalive_connections5354 async def acquire_connection(55 self, origin: Origin, timeout: typing.Optional[TimeoutConfig] = None56 ) -> HTTP11Connection:57 try:58 connection = self._keepalive_connections[origin].pop()59 if not self._keepalive_connections[origin]:60 del self._keepalive_connections[origin]61 self.num_keepalive_connections -= 162 self.num_active_connections += 16364 except (KeyError, IndexError):65 if timeout is None:66 pool_timeout = self.timeout.pool_timeout67 else:68 pool_timeout = timeout.pool_timeout6970 try:71 await asyncio.wait_for(self._max_connections.acquire(), pool_timeout)72 except asyncio.TimeoutError:73 raise PoolTimeout()74 connection = HTTP11Connection(75 origin,76 ssl=self.ssl,77 timeout=self.timeout,78 on_release=self.release_connection,79 )80 self.num_active_connections += 18182 return connection8384 async def release_connection(self, connection: HTTP11Connection) -> None:85 if connection.is_closed:86 self._max_connections.release()87 self.num_active_connections -= 188 elif (89 self.limits.soft_limit is not None90 and self.num_connections > self.limits.soft_limit91 ):92 self._max_connections.release()93 self.num_active_connections -= 194 await connection.close()95 else:96 self.num_active_connections -= 197 self.num_keepalive_connections += 198 try:99 self._keepalive_connections[connection.origin].append(connection)100 except KeyError:101 self._keepalive_connections[connection.origin] = [connection]102103 async def close(self) -> None:104 self.is_closed = True105106107class ConnectionSemaphore:108 def __init__(self, max_connections: int = None):109 self.max_connections = max_connections110111 @property112 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:113 if not hasattr(self, "_semaphore"):114 if self.max_connections is None:115 self._semaphore = None116 else:117 self._semaphore = asyncio.BoundedSemaphore(value=self.max_connections)118 return self._semaphore119120 async def acquire(self) -> None:121 if self.semaphore is not None:122 await self.semaphore.acquire()123124 def release(self) -> None:125 if self.semaphore is not None:126 self.semaphore.release()
deleted:httpcore/connections.py-163 removed
1import asyncio2import typing34import h1156from .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,12 h11.Response,13 h11.InformationalResponse,14 h11.Data,15 h11.EndOfMessage,16 h11.ConnectionClosed,17]181920class Connection(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:38 return self._h11_state.our_state in (h11.CLOSED, h11.ERROR)3940 async def send(41 self,42 request: Request,43 *,44 ssl: typing.Optional[SSLConfig] = None,45 timeout: typing.Optional[TimeoutConfig] = None,46 ) -> Response:47 assert request.url.origin == self.origin4849 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.headers62 event = h11.Request(method=method, target=target, headers=headers)63 await self._send_event(event)6465 # Send the request body.66 if request.is_streaming:67 async for data in request.stream():68 event = h11.Data(data=data)69 await self._send_event(event)70 elif request.body:71 event = h11.Data(data=request.body)72 await self._send_event(event)7374 # Finalize sending the request.75 event = h11.EndOfMessage()76 await self._send_event(event)7778 # Start getting the response.79 event = await self._receive_event(timeout)80 if isinstance(event, h11.InformationalResponse):81 event = await self._receive_event(timeout)82 assert isinstance(event, h11.Response)83 reason = event.reason.decode("latin1")84 status_code = event.status_code85 headers = event.headers86 body = self._body_iter(timeout)87 return Response(88 status_code=status_code,89 reason=reason,90 headers=headers,91 body=body,92 on_close=self._release,93 )9495 async def _connect(self, ssl: SSLConfig, timeout: TimeoutConfig) -> None:96 ssl_context = await ssl.load_ssl_context() if self.origin.is_secure else None9798 try:99 self._reader, self._writer = await asyncio.wait_for( # type: ignore100 asyncio.open_connection(101 self.origin.hostname, self.origin.port, ssl=ssl_context102 ),103 timeout.connect_timeout,104 )105 except asyncio.TimeoutError:106 raise ConnectTimeout()107108 async def _body_iter(self, timeout: TimeoutConfig) -> typing.AsyncIterator[bytes]:109 event = await self._receive_event(timeout)110 while isinstance(event, h11.Data):111 yield event.data112 event = await self._receive_event(timeout)113 assert isinstance(event, h11.EndOfMessage)114115 async def _send_event(self, event: H11Event) -> None:116 assert self._writer is not None117118 data = self._h11_state.send(event)119 self._writer.write(data)120121 async def _receive_event(self, timeout: TimeoutConfig) -> H11Event:122 assert self._reader is not None123124 event = self._h11_state.next_event()125126 while event is h11.NEED_DATA:127 try:128 data = await asyncio.wait_for(129 self._reader.read(2048), timeout.read_timeout130 )131 except asyncio.TimeoutError:132 raise ReadTimeout()133 self._h11_state.receive_data(data)134 event = self._h11_state.next_event()135136 return event137138 async def _release(self) -> None:139 assert self._writer is not None140141 if (142 self._h11_state.our_state is h11.DONE143 and self._h11_state.their_state is h11.DONE144 ):145 self._h11_state.start_next_cycle()146 else:147 await self.close()148149 if self.on_release is not None:150 await self.on_release(self)151152 async def close(self) -> None:153 event = h11.ConnectionClosed()154 try:155 # If we're in h11.MUST_CLOSE then we'll end up in h11.CLOSED.156 self._h11_state.send(event)157 except h11.ProtocolError:158 # If we're in some other state then it's a premature close,159 # and we'll end up in h11.ERROR.160 pass161162 if self._writer is not None:163 self._writer.close()
modified:httpcore/datastructures.py+4 added-8 removed
70 unmodified lines
71class Origin:72 def __init__(self, url: typing.Union[str, URL]) -> None:73 if isinstance(url, str):74 url = URL(url)75 self.scheme = url.scheme76 self.hostname = url.hostname75 self.is_ssl = url.scheme == "https"76 self.hostname = url.hostname.lower()77 self.port = url.port7879 @property80 def is_secure(self) -> bool:81 return self.scheme == "https"8279 def __eq__(self, other: typing.Any) -> bool:80 return (81 isinstance(other, self.__class__)86 and self.scheme == other.scheme82 and self.is_ssl == other.is_ssl83 and self.hostname == other.hostname84 and self.port == other.port85 )8687 def __hash__(self) -> int:92 return hash((self.scheme, self.hostname, self.port))88 return hash((self.is_ssl, self.hostname, self.port))899091class Request:92 def __init__(
188 unmodified lines
added:httpcore/http11.py+163 added
1import asyncio2import typing34import h1156from .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,12 h11.Response,13 h11.InformationalResponse,14 h11.Data,15 h11.EndOfMessage,16 h11.ConnectionClosed,17]181920class HTTP11Connection(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:38 return self._h11_state.our_state in (h11.CLOSED, h11.ERROR)3940 async def send(41 self,42 request: Request,43 *,44 ssl: typing.Optional[SSLConfig] = None,45 timeout: typing.Optional[TimeoutConfig] = None,46 ) -> Response:47 assert request.url.origin == self.origin4849 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.headers62 event = h11.Request(method=method, target=target, headers=headers)63 await self._send_event(event)6465 # Send the request body.66 if request.is_streaming:67 async for data in request.stream():68 event = h11.Data(data=data)69 await self._send_event(event)70 elif request.body:71 event = h11.Data(data=request.body)72 await self._send_event(event)7374 # Finalize sending the request.75 event = h11.EndOfMessage()76 await self._send_event(event)7778 # Start getting the response.79 event = await self._receive_event(timeout)80 if isinstance(event, h11.InformationalResponse):81 event = await self._receive_event(timeout)82 assert isinstance(event, h11.Response)83 reason = event.reason.decode("latin1")84 status_code = event.status_code85 headers = event.headers86 body = self._body_iter(timeout)87 return Response(88 status_code=status_code,89 reason=reason,90 headers=headers,91 body=body,92 on_close=self._release,93 )9495 async def _connect(self, ssl: SSLConfig, timeout: TimeoutConfig) -> None:96 hostname = self.origin.hostname97 port = self.origin.port98 ssl_context = await ssl.load_ssl_context() if self.origin.is_ssl else None99100 try:101 self._reader, self._writer = await asyncio.wait_for( # type: ignore102 asyncio.open_connection(hostname, port, ssl=ssl_context),103 timeout.connect_timeout,104 )105 except asyncio.TimeoutError:106 raise ConnectTimeout()107108 async def _body_iter(self, timeout: TimeoutConfig) -> typing.AsyncIterator[bytes]:109 event = await self._receive_event(timeout)110 while isinstance(event, h11.Data):111 yield event.data112 event = await self._receive_event(timeout)113 assert isinstance(event, h11.EndOfMessage)114115 async def _send_event(self, event: H11Event) -> None:116 assert self._writer is not None117118 data = self._h11_state.send(event)119 self._writer.write(data)120121 async def _receive_event(self, timeout: TimeoutConfig) -> H11Event:122 assert self._reader is not None123124 event = self._h11_state.next_event()125126 while event is h11.NEED_DATA:127 try:128 data = await asyncio.wait_for(129 self._reader.read(2048), timeout.read_timeout130 )131 except asyncio.TimeoutError:132 raise ReadTimeout()133 self._h11_state.receive_data(data)134 event = self._h11_state.next_event()135136 return event137138 async def _release(self) -> None:139 assert self._writer is not None140141 if (142 self._h11_state.our_state is h11.DONE143 and self._h11_state.their_state is h11.DONE144 ):145 self._h11_state.start_next_cycle()146 else:147 await self.close()148149 if self.on_release is not None:150 await self.on_release(self)151152 async def close(self) -> None:153 event = h11.ConnectionClosed()154 try:155 # If we're in h11.MUST_CLOSE then we'll end up in h11.CLOSED.156 self._h11_state.send(event)157 except h11.ProtocolError:158 # If we're in some other state then it's a premature close,159 # and we'll end up in h11.ERROR.160 pass161162 if self._writer is not None:163 self._writer.close()
deleted:httpcore/pool.py-126 removed
1import asyncio2import typing34from .config import (5 DEFAULT_CA_BUNDLE_PATH,6 DEFAULT_POOL_LIMITS,7 DEFAULT_SSL_CONFIG,8 DEFAULT_TIMEOUT_CONFIG,9 PoolLimits,10 SSLConfig,11 TimeoutConfig,12)13from .connections import Connection14from .datastructures import Client, Origin, Request, Response15from .exceptions import PoolTimeout161718class ConnectionPool(Client):19 def __init__(20 self,21 *,22 ssl: SSLConfig = DEFAULT_SSL_CONFIG,23 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,24 limits: PoolLimits = DEFAULT_POOL_LIMITS,25 ):26 self.ssl = ssl27 self.timeout = timeout28 self.limits = limits29 self.is_closed = False30 self.num_active_connections = 031 self.num_keepalive_connections = 032 self._keepalive_connections = (33 {}34 ) # type: typing.Dict[Origin, typing.List[Connection]]35 self._max_connections = ConnectionSemaphore(36 max_connections=self.limits.hard_limit37 )3839 async def send(40 self,41 request: Request,42 *,43 ssl: typing.Optional[SSLConfig] = None,44 timeout: typing.Optional[TimeoutConfig] = None,45 ) -> Response:46 connection = await self.acquire_connection(request.url.origin, timeout=timeout)47 response = await connection.send(request, ssl=ssl, timeout=timeout)48 return response4950 @property51 def num_connections(self) -> int:52 return self.num_active_connections + self.num_keepalive_connections5354 async def acquire_connection(55 self, origin: Origin, timeout: typing.Optional[TimeoutConfig] = None56 ) -> Connection:57 try:58 connection = self._keepalive_connections[origin].pop()59 if not self._keepalive_connections[origin]:60 del self._keepalive_connections[origin]61 self.num_keepalive_connections -= 162 self.num_active_connections += 16364 except (KeyError, IndexError):65 if timeout is None:66 pool_timeout = self.timeout.pool_timeout67 else:68 pool_timeout = timeout.pool_timeout6970 try:71 await asyncio.wait_for(self._max_connections.acquire(), pool_timeout)72 except asyncio.TimeoutError:73 raise PoolTimeout()74 connection = Connection(75 origin,76 ssl=self.ssl,77 timeout=self.timeout,78 on_release=self.release_connection,79 )80 self.num_active_connections += 18182 return connection8384 async def release_connection(self, connection: Connection) -> None:85 if connection.is_closed:86 self._max_connections.release()87 self.num_active_connections -= 188 elif (89 self.limits.soft_limit is not None90 and self.num_connections > self.limits.soft_limit91 ):92 self._max_connections.release()93 self.num_active_connections -= 194 await connection.close()95 else:96 self.num_active_connections -= 197 self.num_keepalive_connections += 198 try:99 self._keepalive_connections[connection.origin].append(connection)100 except KeyError:101 self._keepalive_connections[connection.origin] = [connection]102103 async def close(self) -> None:104 self.is_closed = True105106107class ConnectionSemaphore:108 def __init__(self, max_connections: int = None):109 self.max_connections = max_connections110111 @property112 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:113 if not hasattr(self, "_semaphore"):114 if self.max_connections is None:115 self._semaphore = None116 else:117 self._semaphore = asyncio.BoundedSemaphore(value=self.max_connections)118 return self._semaphore119120 async def acquire(self) -> None:121 if self.semaphore is not None:122 await self.semaphore.acquire()123124 def release(self) -> None:125 if self.semaphore is not None:126 self.semaphore.release()
modified:httpcore/sync.py+1 added-1 removed
1 unmodified line
2from types import TracebackType34from .compat import asyncio_run5from .config import SSLConfig, TimeoutConfig6from .connectionpool import ConnectionPool7from .datastructures import URL, Client, Response7from .pool import ConnectionPool8910class SyncResponse:11 def __init__(self, response: Response):
79 unmodified lines
added:tests/test_connection_pools.py+126 added
1import pytest23import httpcore456@pytest.mark.asyncio7async 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 == 11516 response = await http.request("GET", "http://127.0.0.1:8000/")17 assert http.num_active_connections == 018 assert http.num_keepalive_connections == 1192021@pytest.mark.asyncio22async def test_differing_connection_keys(server):23 """24 Connnections to differing connection keys should result in multiple connections.25 """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 == 13031 response = await http.request("GET", "http://localhost:8000/")32 assert http.num_active_connections == 033 assert http.num_keepalive_connections == 2343536@pytest.mark.asyncio37async def test_soft_limit(server):38 """39 The soft_limit config should limit the maximum number of keep-alive connections.40 """41 limits = httpcore.PoolLimits(soft_limit=1)4243 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 == 14748 response = await http.request("GET", "http://localhost:8000/")49 assert http.num_active_connections == 050 assert http.num_keepalive_connections == 1515253@pytest.mark.asyncio54async def test_streaming_response_holds_connection(server):55 """56 A streaming request should hold the connection open until the response is read.57 """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 == 06263 await response.read()6465 assert http.num_active_connections == 066 assert http.num_keepalive_connections == 1676869@pytest.mark.asyncio70async def test_multiple_concurrent_connections(server):71 """72 Multiple conncurrent requests should open multiple conncurrent connections.73 """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 == 07879 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 == 08283 await response_b.read()84 assert http.num_active_connections == 185 assert http.num_keepalive_connections == 18687 await response_a.read()88 assert http.num_active_connections == 089 assert http.num_keepalive_connections == 2909192@pytest.mark.asyncio93async def test_close_connections(server):94 """95 Using a `Connection: close` header should close the connection.96 """97 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 == 0102103104@pytest.mark.asyncio105async def test_standard_response_close(server):106 """107 A standard close should keep the connection open.108 """109 async with httpcore.ConnectionPool() as http:110 response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)111 await response.read()112 await response.close()113 assert http.num_active_connections == 0114 assert http.num_keepalive_connections == 1115116117@pytest.mark.asyncio118async def test_premature_response_close(server):119 """120 A premature close should close the connection.121 """122 async with httpcore.ConnectionPool() as http:123 response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)124 await response.close()125 assert http.num_active_connections == 0126 assert http.num_keepalive_connections == 0
modified:tests/test_connections.py+2 added-2 removed
3 unmodified lines
456@pytest.mark.asyncio7async def test_get(server):8 http = httpcore.Connection(origin="http://127.0.0.1:8000/")8 http = httpcore.HTTP11Connection(origin="http://127.0.0.1:8000/")9 response = await http.request("GET", "http://127.0.0.1:8000/")10 assert response.status_code == 20011 assert response.body == b"Hello, world!"121314@pytest.mark.asyncio15async def test_post(server):16 http = httpcore.Connection(origin="http://127.0.0.1:8000/")16 http = httpcore.HTTP11Connection(origin="http://127.0.0.1:8000/")17 response = await http.request(18 "POST", "http://127.0.0.1:8000/", body=b"Hello, world!"19 )20 assert response.status_code == 200
deleted:tests/test_pool.py-126 removed
1import pytest23import httpcore456@pytest.mark.asyncio7async 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 == 11516 response = await http.request("GET", "http://127.0.0.1:8000/")17 assert http.num_active_connections == 018 assert http.num_keepalive_connections == 1192021@pytest.mark.asyncio22async def test_differing_connection_keys(server):23 """24 Connnections to differing connection keys should result in multiple connections.25 """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 == 13031 response = await http.request("GET", "http://localhost:8000/")32 assert http.num_active_connections == 033 assert http.num_keepalive_connections == 2343536@pytest.mark.asyncio37async def test_soft_limit(server):38 """39 The soft_limit config should limit the maximum number of keep-alive connections.40 """41 limits = httpcore.PoolLimits(soft_limit=1)4243 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 == 14748 response = await http.request("GET", "http://localhost:8000/")49 assert http.num_active_connections == 050 assert http.num_keepalive_connections == 1515253@pytest.mark.asyncio54async def test_streaming_response_holds_connection(server):55 """56 A streaming request should hold the connection open until the response is read.57 """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 == 06263 await response.read()6465 assert http.num_active_connections == 066 assert http.num_keepalive_connections == 1676869@pytest.mark.asyncio70async def test_multiple_concurrent_connections(server):71 """72 Multiple conncurrent requests should open multiple conncurrent connections.73 """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 == 07879 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 == 08283 await response_b.read()84 assert http.num_active_connections == 185 assert http.num_keepalive_connections == 18687 await response_a.read()88 assert http.num_active_connections == 089 assert http.num_keepalive_connections == 2909192@pytest.mark.asyncio93async def test_close_connections(server):94 """95 Using a `Connection: close` header should close the connection.96 """97 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 == 0102103104@pytest.mark.asyncio105async def test_standard_response_close(server):106 """107 A standard close should keep the connection open.108 """109 async with httpcore.ConnectionPool() as http:110 response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)111 await response.read()112 await response.close()113 assert http.num_active_connections == 0114 assert http.num_keepalive_connections == 1115116117@pytest.mark.asyncio118async def test_premature_response_close(server):119 """120 A premature close should close the connection.121 """122 async with httpcore.ConnectionPool() as http:123 response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)124 await response.close()125 assert http.num_active_connections == 0126 assert http.num_keepalive_connections == 0
modified:tests/test_sync.py+1 added-1 removed
51 unmodified lines
52def test_stream_iterator(server):53 with httpcore.SyncConnectionPool() as http:54 response = http.request("GET", "http://127.0.0.1:8000/", stream=True)55 assert response.status_code == 20056 body = b''56 body = b""57 for chunk in response.stream():58 body += chunk59 assert body == b"Hello, world!"