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
Provenance
- Commit
0c20fba- Tree
f3792b7- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent 1
0f178ca- Parent 2
b7d315a
12 files changed+426 added−429 removed
modified:httpcore/__init__.py+2 added-2 removed
1 from .config import PoolLimits, SSLConfig, TimeoutConfig2-from .connections import Connection2+from .connectionpool import ConnectionPool3 from .datastructures import URL, Origin, Request, Response4 from .exceptions import (5 BadResponse,6 ConnectTimeout,2 unmodified lines9 ResponseClosed,10 StreamConsumed,11 Timeout,12 )13-from .pool import ConnectionPool13+from .http11 import HTTP11Connection14 from .sync import SyncClient, SyncConnectionPool15 16 __version__ = "0.2.0"modified:httpcore/compat.py+1 added
1 import asyncio2 3 if hasattr(asyncio, "run"):4 asyncio_run = asyncio.run5+6 else: # pragma: nocover7 8 def asyncio_run(main, *, debug=False): # type: ignore9 if asyncio._get_running_loop() is not None:43 unmodified linesadded:httpcore/connectionpool.py+126 added
1+import asyncio2+import typing3+4+from .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+)13+from .http11 import HTTP11Connection14+from .datastructures import Client, Origin, Request, Response15+from .exceptions import PoolTimeout16+17+18+class 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+ )38+39+ 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 response49+50+ @property51+ def num_connections(self) -> int:52+ return self.num_active_connections + self.num_keepalive_connections53+54+ 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 += 163+64+ except (KeyError, IndexError):65+ if timeout is None:66+ pool_timeout = self.timeout.pool_timeout67+ else:68+ pool_timeout = timeout.pool_timeout69+70+ 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 += 181+82+ return connection83+84+ 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]102+103+ async def close(self) -> None:104+ self.is_closed = True105+106+107+class ConnectionSemaphore:108+ def __init__(self, max_connections: int = None):109+ self.max_connections = max_connections110+111+ @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._semaphore119+120+ async def acquire(self) -> None:121+ if self.semaphore is not None:122+ await self.semaphore.acquire()123+124+ def release(self) -> None:125+ if self.semaphore is not None:126+ self.semaphore.release()deleted:httpcore/connections.py-163 removed
1-import asyncio2-import typing3-4-import h115-6-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,12- h11.Response,13- h11.InformationalResponse,14- h11.Data,15- h11.EndOfMessage,16- h11.ConnectionClosed,17-]18-19-20-class 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)35-36- @property37- def is_closed(self) -> bool:38- return self._h11_state.our_state in (h11.CLOSED, h11.ERROR)39-40- 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.origin48-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.headers62- event = h11.Request(method=method, target=target, headers=headers)63- await self._send_event(event)64-65- # 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)73-74- # Finalize sending the request.75- event = h11.EndOfMessage()76- await self._send_event(event)77-78- # 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- )94-95- async def _connect(self, ssl: SSLConfig, timeout: TimeoutConfig) -> None:96- ssl_context = await ssl.load_ssl_context() if self.origin.is_secure else None97-98- 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()107-108- 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)114-115- async def _send_event(self, event: H11Event) -> None:116- assert self._writer is not None117-118- data = self._h11_state.send(event)119- self._writer.write(data)120-121- async def _receive_event(self, timeout: TimeoutConfig) -> H11Event:122- assert self._reader is not None123-124- event = self._h11_state.next_event()125-126- 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()135-136- return event137-138- async def _release(self) -> None:139- assert self._writer is not None140-141- 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()148-149- if self.on_release is not None:150- await self.on_release(self)151-152- 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- pass161-162- if self._writer is not None:163- self._writer.close()modified:httpcore/datastructures.py+4 added-8 removed
70 unmodified lines71 class 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.port78 79- @property80- def is_secure(self) -> bool:81- return self.scheme == "https"82-79 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 )86 87 def __hash__(self) -> int:92- return hash((self.scheme, self.hostname, self.port))88+ return hash((self.is_ssl, self.hostname, self.port))89 90 91 class Request:92 def __init__(188 unmodified linesadded:httpcore/http11.py+163 added
1+import asyncio2+import typing3+4+import h115+6+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,12+ h11.Response,13+ h11.InformationalResponse,14+ h11.Data,15+ h11.EndOfMessage,16+ h11.ConnectionClosed,17+]18+19+20+class 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)35+36+ @property37+ def is_closed(self) -> bool:38+ return self._h11_state.our_state in (h11.CLOSED, h11.ERROR)39+40+ 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.origin48+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.headers62+ event = h11.Request(method=method, target=target, headers=headers)63+ await self._send_event(event)64+65+ # 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)73+74+ # Finalize sending the request.75+ event = h11.EndOfMessage()76+ await self._send_event(event)77+78+ # 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+ )94+95+ 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 None99+100+ 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()107+108+ 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)114+115+ async def _send_event(self, event: H11Event) -> None:116+ assert self._writer is not None117+118+ data = self._h11_state.send(event)119+ self._writer.write(data)120+121+ async def _receive_event(self, timeout: TimeoutConfig) -> H11Event:122+ assert self._reader is not None123+124+ event = self._h11_state.next_event()125+126+ 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()135+136+ return event137+138+ async def _release(self) -> None:139+ assert self._writer is not None140+141+ 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()148+149+ if self.on_release is not None:150+ await self.on_release(self)151+152+ 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+ pass161+162+ if self._writer is not None:163+ self._writer.close()deleted:httpcore/pool.py-126 removed
1-import asyncio2-import typing3-4-from .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-)13-from .connections import Connection14-from .datastructures import Client, Origin, Request, Response15-from .exceptions import PoolTimeout16-17-18-class 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- )38-39- 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 response49-50- @property51- def num_connections(self) -> int:52- return self.num_active_connections + self.num_keepalive_connections53-54- 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 += 163-64- except (KeyError, IndexError):65- if timeout is None:66- pool_timeout = self.timeout.pool_timeout67- else:68- pool_timeout = timeout.pool_timeout69-70- 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 += 181-82- return connection83-84- 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]102-103- async def close(self) -> None:104- self.is_closed = True105-106-107-class ConnectionSemaphore:108- def __init__(self, max_connections: int = None):109- self.max_connections = max_connections110-111- @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._semaphore119-120- async def acquire(self) -> None:121- if self.semaphore is not None:122- await self.semaphore.acquire()123-124- 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 line2 from types import TracebackType3 4 from .compat import asyncio_run5 from .config import SSLConfig, TimeoutConfig6+from .connectionpool import ConnectionPool7 from .datastructures import URL, Client, Response7-from .pool import ConnectionPool8 9 10 class SyncResponse:11 def __init__(self, response: Response):79 unmodified linesadded:tests/test_connection_pools.py+126 added
1+import pytest2+3+import httpcore4+5+6+@pytest.mark.asyncio7+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 == 115+16+ response = await http.request("GET", "http://127.0.0.1:8000/")17+ assert http.num_active_connections == 018+ assert http.num_keepalive_connections == 119+20+21+@pytest.mark.asyncio22+async 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 == 130+31+ response = await http.request("GET", "http://localhost:8000/")32+ assert http.num_active_connections == 033+ assert http.num_keepalive_connections == 234+35+36+@pytest.mark.asyncio37+async 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)42+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+48+ response = await http.request("GET", "http://localhost:8000/")49+ assert http.num_active_connections == 050+ assert http.num_keepalive_connections == 151+52+53+@pytest.mark.asyncio54+async 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 == 062+63+ await response.read()64+65+ assert http.num_active_connections == 066+ assert http.num_keepalive_connections == 167+68+69+@pytest.mark.asyncio70+async 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 == 078+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 == 082+83+ await response_b.read()84+ assert http.num_active_connections == 185+ assert http.num_keepalive_connections == 186+87+ await response_a.read()88+ assert http.num_active_connections == 089+ assert http.num_keepalive_connections == 290+91+92+@pytest.mark.asyncio93+async 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 == 0102+103+104+@pytest.mark.asyncio105+async 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 == 1115+116+117+@pytest.mark.asyncio118+async 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 == 0modified:tests/test_connections.py+2 added-2 removed
3 unmodified lines4 5 6 @pytest.mark.asyncio7 async 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!"12 13 14 @pytest.mark.asyncio15 async 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 == 200deleted:tests/test_pool.py-126 removed
1-import pytest2-3-import httpcore4-5-6-@pytest.mark.asyncio7-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 == 115-16- response = await http.request("GET", "http://127.0.0.1:8000/")17- assert http.num_active_connections == 018- assert http.num_keepalive_connections == 119-20-21-@pytest.mark.asyncio22-async 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 == 130-31- response = await http.request("GET", "http://localhost:8000/")32- assert http.num_active_connections == 033- assert http.num_keepalive_connections == 234-35-36-@pytest.mark.asyncio37-async 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)42-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-48- response = await http.request("GET", "http://localhost:8000/")49- assert http.num_active_connections == 050- assert http.num_keepalive_connections == 151-52-53-@pytest.mark.asyncio54-async 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 == 062-63- await response.read()64-65- assert http.num_active_connections == 066- assert http.num_keepalive_connections == 167-68-69-@pytest.mark.asyncio70-async 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 == 078-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 == 082-83- await response_b.read()84- assert http.num_active_connections == 185- assert http.num_keepalive_connections == 186-87- await response_a.read()88- assert http.num_active_connections == 089- assert http.num_keepalive_connections == 290-91-92-@pytest.mark.asyncio93-async 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 == 0102-103-104-@pytest.mark.asyncio105-async 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 == 1115-116-117-@pytest.mark.asyncio118-async 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 == 0modified:tests/test_sync.py+1 added-1 removed
51 unmodified lines52 def 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!"