Skip to content
Myr

Switch to sync-by-default

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 d6628ca · Browse files · 10 files+464 added−463 removed
This commit

State

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

Diff stats

10 files+464 added−463 removed

  • tests:+139 added−139 removed
  • other:+325 added−324 removed

10 files+464 added−463 removed

deleted:httpcore/backends/sync.py-315 removed
1import asyncio2import typing3from types import TracebackType45from ..client import Client6from ..config import (7 DEFAULT_MAX_REDIRECTS,8 DEFAULT_POOL_LIMITS,9 DEFAULT_SSL_CONFIG,10 DEFAULT_TIMEOUT_CONFIG,11 PoolLimits,12 SSLConfig,13 TimeoutConfig,14)15from ..models import (16 URL,17 Headers,18 HeaderTypes,19 QueryParamTypes,20 Request,21 RequestData,22 Response,23 URLTypes,24)252627class SyncResponse:28 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):29 self._response = response30 self._loop = loop3132 @property33 def status_code(self) -> int:34 return self._response.status_code3536 @property37 def reason_phrase(self) -> str:38 return self._response.reason_phrase3940 @property41 def protocol(self) -> typing.Optional[str]:42 return self._response.protocol4344 @property45 def headers(self) -> Headers:46 return self._response.headers4748 @property49 def content(self) -> bytes:50 return self._response.content5152 @property53 def text(self) -> str:54 return self._response.text5556 def read(self) -> bytes:57 return self._loop.run_until_complete(self._response.read())5859 def stream(self) -> typing.Iterator[bytes]:60 inner = self._response.stream()61 while True:62 try:63 yield self._loop.run_until_complete(inner.__anext__())64 except StopAsyncIteration as exc:65 break6667 def raw(self) -> typing.Iterator[bytes]:68 inner = self._response.raw()69 while True:70 try:71 yield self._loop.run_until_complete(inner.__anext__())72 except StopAsyncIteration as exc:73 break7475 def close(self) -> None:76 return self._loop.run_until_complete(self._response.close())7778 def __repr__(self) -> str:79 class_name = self.__class__.__name__80 return f"<{class_name}(status_code={self.status_code})>"818283class SyncClient:84 def __init__(85 self,86 ssl: SSLConfig = DEFAULT_SSL_CONFIG,87 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,88 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,89 max_redirects: int = DEFAULT_MAX_REDIRECTS,90 ) -> None:91 self._client = Client(92 ssl=ssl,93 timeout=timeout,94 pool_limits=pool_limits,95 max_redirects=max_redirects,96 )97 self._loop = asyncio.new_event_loop()9899 def request(100 self,101 method: str,102 url: URLTypes,103 *,104 data: RequestData = b"",105 query_params: QueryParamTypes = None,106 headers: HeaderTypes = None,107 stream: bool = False,108 allow_redirects: bool = True,109 ssl: SSLConfig = None,110 timeout: TimeoutConfig = None,111 ) -> SyncResponse:112 request = Request(113 method, url, data=data, query_params=query_params, headers=headers114 )115 self.prepare_request(request)116 response = self.send(117 request,118 stream=stream,119 allow_redirects=allow_redirects,120 ssl=ssl,121 timeout=timeout,122 )123 return response124125 def get(126 self,127 url: URLTypes,128 *,129 query_params: QueryParamTypes = None,130 headers: HeaderTypes = None,131 stream: bool = False,132 allow_redirects: bool = True,133 ssl: SSLConfig = None,134 timeout: TimeoutConfig = None,135 ) -> SyncResponse:136 return self.request(137 "GET",138 url,139 headers=headers,140 stream=stream,141 allow_redirects=allow_redirects,142 ssl=ssl,143 timeout=timeout,144 )145146 def options(147 self,148 url: URLTypes,149 *,150 query_params: QueryParamTypes = None,151 headers: HeaderTypes = None,152 stream: bool = False,153 allow_redirects: bool = True,154 ssl: SSLConfig = None,155 timeout: TimeoutConfig = None,156 ) -> SyncResponse:157 return self.request(158 "OPTIONS",159 url,160 headers=headers,161 stream=stream,162 allow_redirects=allow_redirects,163 ssl=ssl,164 timeout=timeout,165 )166167 def head(168 self,169 url: URLTypes,170 *,171 query_params: QueryParamTypes = None,172 headers: HeaderTypes = None,173 stream: bool = False,174 allow_redirects: bool = False, #  Note: Differs to usual default.175 ssl: SSLConfig = None,176 timeout: TimeoutConfig = None,177 ) -> SyncResponse:178 return self.request(179 "HEAD",180 url,181 headers=headers,182 stream=stream,183 allow_redirects=allow_redirects,184 ssl=ssl,185 timeout=timeout,186 )187188 def post(189 self,190 url: URLTypes,191 *,192 data: RequestData = b"",193 query_params: QueryParamTypes = None,194 headers: HeaderTypes = None,195 stream: bool = False,196 allow_redirects: bool = True,197 ssl: SSLConfig = None,198 timeout: TimeoutConfig = None,199 ) -> SyncResponse:200 return self.request(201 "POST",202 url,203 data=data,204 headers=headers,205 stream=stream,206 allow_redirects=allow_redirects,207 ssl=ssl,208 timeout=timeout,209 )210211 def put(212 self,213 url: URLTypes,214 *,215 data: RequestData = b"",216 query_params: QueryParamTypes = None,217 headers: HeaderTypes = None,218 stream: bool = False,219 allow_redirects: bool = True,220 ssl: SSLConfig = None,221 timeout: TimeoutConfig = None,222 ) -> SyncResponse:223 return self.request(224 "PUT",225 url,226 data=data,227 headers=headers,228 stream=stream,229 allow_redirects=allow_redirects,230 ssl=ssl,231 timeout=timeout,232 )233234 def patch(235 self,236 url: URLTypes,237 *,238 data: RequestData = b"",239 query_params: QueryParamTypes = None,240 headers: HeaderTypes = None,241 stream: bool = False,242 allow_redirects: bool = True,243 ssl: SSLConfig = None,244 timeout: TimeoutConfig = None,245 ) -> SyncResponse:246 return self.request(247 "PATCH",248 url,249 data=data,250 headers=headers,251 stream=stream,252 allow_redirects=allow_redirects,253 ssl=ssl,254 timeout=timeout,255 )256257 def delete(258 self,259 url: URLTypes,260 *,261 data: RequestData = b"",262 query_params: QueryParamTypes = None,263 headers: HeaderTypes = None,264 stream: bool = False,265 allow_redirects: bool = True,266 ssl: SSLConfig = None,267 timeout: TimeoutConfig = None,268 ) -> SyncResponse:269 return self.request(270 "DELETE",271 url,272 data=data,273 headers=headers,274 stream=stream,275 allow_redirects=allow_redirects,276 ssl=ssl,277 timeout=timeout,278 )279280 def prepare_request(self, request: Request) -> None:281 self._client.prepare_request(request)282283 def send(284 self,285 request: Request,286 *,287 stream: bool = False,288 allow_redirects: bool = True,289 ssl: SSLConfig = None,290 timeout: TimeoutConfig = None,291 ) -> SyncResponse:292 response = self._loop.run_until_complete(293 self._client.send(294 request,295 stream=stream,296 allow_redirects=allow_redirects,297 ssl=ssl,298 timeout=timeout,299 )300 )301 return SyncResponse(response, self._loop)302303 def close(self) -> None:304 self._loop.run_until_complete(self._client.close())305306 def __enter__(self) -> "SyncClient":307 return self308309 def __exit__(310 self,311 exc_type: typing.Type[BaseException] = None,312 exc_value: BaseException = None,313 traceback: TracebackType = None,314 ) -> None:315 self.close()
modified:httpcore/__init__.py+1 added-2 removed
1from .backends.sync import SyncClient2from .client import Client1from .client import AsyncClient, Client2from .config import PoolLimits, SSLConfig, TimeoutConfig3from .constants import Protocol, codes4from .dispatch.connection import HTTPConnection5from .dispatch.connection_pool import ConnectionPool
21 unmodified lines
modified:httpcore/client.py+241 added-2 removed
1import asyncio2import typing3from types import TracebackType45from .config import (
16 unmodified lines
22 QueryParamTypes,23 Request,24 RequestData,25 Response,26 SyncResponse,27 URLTypes,28)293029class Client:31class AsyncClient:32 def __init__(33 self,34 ssl: SSLConfig = DEFAULT_SSL_CONFIG,35 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,
320 unmodified lines
356357 async def close(self) -> None:358 await self.dispatch.close()359358 async def __aenter__(self) -> "Client":360 async def __aenter__(self) -> "AsyncClient":361 return self362363 async def __aexit__(364 self,
1 unmodified line
366 exc_value: BaseException = None,367 traceback: TracebackType = None,368 ) -> None:369 await self.close()370371372class Client:373 def __init__(374 self,375 ssl: SSLConfig = DEFAULT_SSL_CONFIG,376 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,377 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,378 max_redirects: int = DEFAULT_MAX_REDIRECTS,379 dispatch: Dispatcher = None,380 ) -> None:381 self._client = AsyncClient(382 ssl=ssl,383 timeout=timeout,384 pool_limits=pool_limits,385 max_redirects=max_redirects,386 dispatch=dispatch,387 )388 self._loop = asyncio.new_event_loop()389390 def request(391 self,392 method: str,393 url: URLTypes,394 *,395 data: RequestData = b"",396 query_params: QueryParamTypes = None,397 headers: HeaderTypes = None,398 stream: bool = False,399 allow_redirects: bool = True,400 ssl: SSLConfig = None,401 timeout: TimeoutConfig = None,402 ) -> SyncResponse:403 request = Request(404 method, url, data=data, query_params=query_params, headers=headers405 )406 self.prepare_request(request)407 response = self.send(408 request,409 stream=stream,410 allow_redirects=allow_redirects,411 ssl=ssl,412 timeout=timeout,413 )414 return response415416 def get(417 self,418 url: URLTypes,419 *,420 query_params: QueryParamTypes = None,421 headers: HeaderTypes = None,422 stream: bool = False,423 allow_redirects: bool = True,424 ssl: SSLConfig = None,425 timeout: TimeoutConfig = None,426 ) -> SyncResponse:427 return self.request(428 "GET",429 url,430 headers=headers,431 stream=stream,432 allow_redirects=allow_redirects,433 ssl=ssl,434 timeout=timeout,435 )436437 def options(438 self,439 url: URLTypes,440 *,441 query_params: QueryParamTypes = None,442 headers: HeaderTypes = None,443 stream: bool = False,444 allow_redirects: bool = True,445 ssl: SSLConfig = None,446 timeout: TimeoutConfig = None,447 ) -> SyncResponse:448 return self.request(449 "OPTIONS",450 url,451 headers=headers,452 stream=stream,453 allow_redirects=allow_redirects,454 ssl=ssl,455 timeout=timeout,456 )457458 def head(459 self,460 url: URLTypes,461 *,462 query_params: QueryParamTypes = None,463 headers: HeaderTypes = None,464 stream: bool = False,465 allow_redirects: bool = False, #  Note: Differs to usual default.466 ssl: SSLConfig = None,467 timeout: TimeoutConfig = None,468 ) -> SyncResponse:469 return self.request(470 "HEAD",471 url,472 headers=headers,473 stream=stream,474 allow_redirects=allow_redirects,475 ssl=ssl,476 timeout=timeout,477 )478479 def post(480 self,481 url: URLTypes,482 *,483 data: RequestData = b"",484 query_params: QueryParamTypes = None,485 headers: HeaderTypes = None,486 stream: bool = False,487 allow_redirects: bool = True,488 ssl: SSLConfig = None,489 timeout: TimeoutConfig = None,490 ) -> SyncResponse:491 return self.request(492 "POST",493 url,494 data=data,495 headers=headers,496 stream=stream,497 allow_redirects=allow_redirects,498 ssl=ssl,499 timeout=timeout,500 )501502 def put(503 self,504 url: URLTypes,505 *,506 data: RequestData = b"",507 query_params: QueryParamTypes = None,508 headers: HeaderTypes = None,509 stream: bool = False,510 allow_redirects: bool = True,511 ssl: SSLConfig = None,512 timeout: TimeoutConfig = None,513 ) -> SyncResponse:514 return self.request(515 "PUT",516 url,517 data=data,518 headers=headers,519 stream=stream,520 allow_redirects=allow_redirects,521 ssl=ssl,522 timeout=timeout,523 )524525 def patch(526 self,527 url: URLTypes,528 *,529 data: RequestData = b"",530 query_params: QueryParamTypes = None,531 headers: HeaderTypes = None,532 stream: bool = False,533 allow_redirects: bool = True,534 ssl: SSLConfig = None,535 timeout: TimeoutConfig = None,536 ) -> SyncResponse:537 return self.request(538 "PATCH",539 url,540 data=data,541 headers=headers,542 stream=stream,543 allow_redirects=allow_redirects,544 ssl=ssl,545 timeout=timeout,546 )547548 def delete(549 self,550 url: URLTypes,551 *,552 data: RequestData = b"",553 query_params: QueryParamTypes = None,554 headers: HeaderTypes = None,555 stream: bool = False,556 allow_redirects: bool = True,557 ssl: SSLConfig = None,558 timeout: TimeoutConfig = None,559 ) -> SyncResponse:560 return self.request(561 "DELETE",562 url,563 data=data,564 headers=headers,565 stream=stream,566 allow_redirects=allow_redirects,567 ssl=ssl,568 timeout=timeout,569 )570571 def prepare_request(self, request: Request) -> None:572 self._client.prepare_request(request)573574 def send(575 self,576 request: Request,577 *,578 stream: bool = False,579 allow_redirects: bool = True,580 ssl: SSLConfig = None,581 timeout: TimeoutConfig = None,582 ) -> SyncResponse:583 response = self._loop.run_until_complete(584 self._client.send(585 request,586 stream=stream,587 allow_redirects=allow_redirects,588 ssl=ssl,589 timeout=timeout,590 )591 )592 return SyncResponse(response, self._loop)593594 def close(self) -> None:595 self._loop.run_until_complete(self._client.close())596597 def __enter__(self) -> "Client":598 return self599600 def __exit__(601 self,602 exc_type: typing.Type[BaseException] = None,603 exc_value: BaseException = None,604 traceback: TracebackType = None,605 ) -> None:606 self.close()
modified:httpcore/models.py+81 added-4 removed
1import asyncio2import cgi3import typing4from urllib.parse import parse_qsl, urlencode5
723 unmodified lines
729 )730 and "location" in self.headers731 )732732 def __repr__(self) -> str:733 class_name = self.__class__.__name__734 return f"<{class_name}({self.status_code}, {self.reason_phrase!r})>"735733 def raise_for_status(self) -> None:734 """735 Raise the `HttpError` if one occurred.736 """
10 unmodified lines
747 message = ""748749 if message:750 raise HttpError(message)751752 def __repr__(self) -> str:753 class_name = self.__class__.__name__754 return f"<{class_name}({self.status_code}, {self.reason_phrase!r})>"755756757class SyncResponse:758 """759 A thread-synchronous response. This class proxies onto a `Response`760 instance, providing standard synchronous interfaces where required.761 """762763 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):764 self._response = response765 self._loop = loop766767 @property768 def status_code(self) -> int:769 return self._response.status_code770771 @property772 def reason_phrase(self) -> str:773 return self._response.reason_phrase774775 @property776 def protocol(self) -> typing.Optional[str]:777 return self._response.protocol778779 @property780 def url(self) -> typing.Optional[URL]:781 return self._response.url782783 @property784 def request(self) -> typing.Optional[Request]:785 return self._response.request786787 @property788 def headers(self) -> Headers:789 return self._response.headers790791 @property792 def content(self) -> bytes:793 return self._response.content794795 @property796 def text(self) -> str:797 return self._response.text798799 @property800 def encoding(self) -> str:801 return self._response.encoding802803 @property804 def is_redirect(self) -> bool:805 return self._response.is_redirect806807 def raise_for_status(self) -> None:808 return self._response.raise_for_status()809810 def read(self) -> bytes:811 return self._loop.run_until_complete(self._response.read())812813 def stream(self) -> typing.Iterator[bytes]:814 inner = self._response.stream()815 while True:816 try:817 yield self._loop.run_until_complete(inner.__anext__())818 except StopAsyncIteration as exc:819 break820821 def raw(self) -> typing.Iterator[bytes]:822 inner = self._response.raw()823 while True:824 try:825 yield self._loop.run_until_complete(inner.__anext__())826 except StopAsyncIteration as exc:827 break828829 def close(self) -> None:830 return self._loop.run_until_complete(self._response.close())
added:tests/client/test_asnyc_client.py+67 added
1import pytest23import httpcore456@pytest.mark.asyncio7async def test_get(server):8 url = "http://127.0.0.1:8000/"9 async with httpcore.AsyncClient() as client:10 response = await client.get(url)11 assert response.status_code == 20012 assert response.text == "Hello, world!"131415@pytest.mark.asyncio16async def test_post(server):17 url = "http://127.0.0.1:8000/"18 async with httpcore.AsyncClient() as client:19 response = await client.post(url, data=b"Hello, world!")20 assert response.status_code == 200212223@pytest.mark.asyncio24async def test_stream_response(server):25 async with httpcore.AsyncClient() as client:26 response = await client.request("GET", "http://127.0.0.1:8000/", stream=True)27 assert response.status_code == 20028 body = await response.read()29 assert body == b"Hello, world!"30 assert response.content == b"Hello, world!"313233@pytest.mark.asyncio34async def test_access_content_stream_response(server):35 async with httpcore.AsyncClient() as client:36 response = await client.request("GET", "http://127.0.0.1:8000/", stream=True)37 assert response.status_code == 20038 with pytest.raises(httpcore.ResponseNotRead):39 response.content404142@pytest.mark.asyncio43async def test_stream_request(server):44 async def hello_world():45 yield b"Hello, "46 yield b"world!"4748 async with httpcore.AsyncClient() as client:49 response = await client.request(50 "POST", "http://127.0.0.1:8000/", data=hello_world()51 )52 assert response.status_code == 200535455@pytest.mark.asyncio56async def test_raise_for_status(server):57 async with httpcore.AsyncClient() as client:58 for status_code in (200, 400, 404, 500, 505):59 response = await client.request(60 "GET", f"http://127.0.0.1:8000/status/{status_code}"61 )6263 if 400 <= status_code < 600:64 with pytest.raises(httpcore.exceptions.HttpError):65 response.raise_for_status()66 else:67 assert response.raise_for_status() is None
modified:tests/client/test_client.py+51 added-47 removed
1import asyncio2import functools34import pytest56import httpcore786@pytest.mark.asyncio7async def test_get(server):8 url = "http://127.0.0.1:8000/"9 async with httpcore.Client() as client:10 response = await client.get(url)11 assert response.status_code == 20012 assert response.text == "Hello, world!"9def threadpool(func):10 """11 Our sync tests should run in seperate thread to the uvicorn server.12 """1314 @functools.wraps(func)15 async def wrapped(*args, **kwargs):16 nonlocal func1715@pytest.mark.asyncio16async def test_post(server):17 url = "http://127.0.0.1:8000/"18 async with httpcore.Client() as client:19 response = await client.post(url, data=b"Hello, world!")20 assert response.status_code == 20018 loop = asyncio.get_event_loop()19 if kwargs:20 func = functools.partial(func, **kwargs)21 await loop.run_in_executor(None, func, *args)2223 return pytest.mark.asyncio(wrapped)2423@pytest.mark.asyncio24async def test_stream_response(server):25 async with httpcore.Client() as client:26 response = await client.request("GET", "http://127.0.0.1:8000/", stream=True)2526@threadpool27def test_get(server):28 with httpcore.Client() as http:29 response = http.get("http://127.0.0.1:8000/")30 assert response.status_code == 20028 body = await response.read()29 assert body == b"Hello, world!"31 assert response.content == b"Hello, world!"32 assert response.text == "Hello, world!"333433@pytest.mark.asyncio34async def test_access_content_stream_response(server):35 async with httpcore.Client() as client:36 response = await client.request("GET", "http://127.0.0.1:8000/", stream=True)35@threadpool36def test_post(server):37 with httpcore.Client() as http:38 response = http.post("http://127.0.0.1:8000/", data=b"Hello, world!")39 assert response.status_code == 20038 with pytest.raises(httpcore.ResponseNotRead):39 response.content40 assert response.reason_phrase == "OK"414242@pytest.mark.asyncio43async def test_stream_request(server):44 async def hello_world():45 yield b"Hello, "46 yield b"world!"4748 async with httpcore.Client() as client:49 response = await client.request(50 "POST", "http://127.0.0.1:8000/", data=hello_world()51 )43@threadpool44def test_stream_response(server):45 with httpcore.Client() as http:46 response = http.get("http://127.0.0.1:8000/", stream=True)47 assert response.status_code == 20048 content = response.read()49 assert content == b"Hello, world!"505155@pytest.mark.asyncio56async def test_raise_for_status(server):57 async with httpcore.Client() as client:58 for status_code in (200, 400, 404, 500, 505):59 response = await client.request(60 "GET", f"http://127.0.0.1:8000/status/{status_code}"61 )52@threadpool53def test_stream_iterator(server):54 with httpcore.Client() as http:55 response = http.get("http://127.0.0.1:8000/", stream=True)56 assert response.status_code == 20057 body = b""58 for chunk in response.stream():59 body += chunk60 assert body == b"Hello, world!"6163 if 400 <= status_code < 600:64 with pytest.raises(httpcore.exceptions.HttpError):65 response.raise_for_status()66 else:67 assert response.raise_for_status() is None6263@threadpool64def test_raw_iterator(server):65 with httpcore.Client() as http:66 response = http.get("http://127.0.0.1:8000/", stream=True)67 assert response.status_code == 20068 body = b""69 for chunk in response.raw():70 body += chunk71 assert body == b"Hello, world!"
modified:tests/client/test_redirects.py+17 added-17 removed
3 unmodified lines
4import pytest56from httpcore import (7 URL,8 Client,8 AsyncClient,9 Dispatcher,10 RedirectBodyUnavailable,11 RedirectLoop,12 Request,
74 unmodified lines
878889@pytest.mark.asyncio90async def test_redirect_301():91 client = Client(dispatch=MockDispatch())91 client = AsyncClient(dispatch=MockDispatch())92 response = await client.request("POST", "https://example.org/redirect_301")93 assert response.status_code == codes.ok94 assert response.url == URL("https://example.org/")95 assert len(response.history) == 1969798@pytest.mark.asyncio99async def test_redirect_302():100 client = Client(dispatch=MockDispatch())100 client = AsyncClient(dispatch=MockDispatch())101 response = await client.request("POST", "https://example.org/redirect_302")102 assert response.status_code == codes.ok103 assert response.url == URL("https://example.org/")104 assert len(response.history) == 1105106107@pytest.mark.asyncio108async def test_redirect_303():109 client = Client(dispatch=MockDispatch())109 client = AsyncClient(dispatch=MockDispatch())110 response = await client.request("GET", "https://example.org/redirect_303")111 assert response.status_code == codes.ok112 assert response.url == URL("https://example.org/")113 assert len(response.history) == 1114115116@pytest.mark.asyncio117async def test_disallow_redirects():118 client = Client(dispatch=MockDispatch())118 client = AsyncClient(dispatch=MockDispatch())119 response = await client.request(120 "POST", "https://example.org/redirect_303", allow_redirects=False121 )122 assert response.status_code == codes.see_other
7 unmodified lines
130131132@pytest.mark.asyncio133async def test_relative_redirect():134 client = Client(dispatch=MockDispatch())134 client = AsyncClient(dispatch=MockDispatch())135 response = await client.request("GET", "https://example.org/relative_redirect")136 assert response.status_code == codes.ok137 assert response.url == URL("https://example.org/")138 assert len(response.history) == 1139140141@pytest.mark.asyncio142async def test_no_scheme_redirect():143 client = Client(dispatch=MockDispatch())143 client = AsyncClient(dispatch=MockDispatch())144 response = await client.request("GET", "https://example.org/no_scheme_redirect")145 assert response.status_code == codes.ok146 assert response.url == URL("https://example.org/")147 assert len(response.history) == 1148149150@pytest.mark.asyncio151async def test_fragment_redirect():152 client = Client(dispatch=MockDispatch())152 client = AsyncClient(dispatch=MockDispatch())153 url = "https://example.org/relative_redirect#fragment"154 response = await client.request("GET", url)155 assert response.status_code == codes.ok156 assert response.url == URL("https://example.org/#fragment")
1 unmodified line
158159160@pytest.mark.asyncio161async def test_multiple_redirects():162 client = Client(dispatch=MockDispatch())162 client = AsyncClient(dispatch=MockDispatch())163 url = "https://example.org/multiple_redirects?count=20"164 response = await client.request("GET", url)165 assert response.status_code == codes.ok166 assert response.url == URL("https://example.org/multiple_redirects")
1 unmodified line
168169170@pytest.mark.asyncio171async def test_too_many_redirects():172 client = Client(dispatch=MockDispatch())172 client = AsyncClient(dispatch=MockDispatch())173 with pytest.raises(TooManyRedirects):174 await client.request("GET", "https://example.org/multiple_redirects?count=21")175176177@pytest.mark.asyncio178async def test_too_many_redirects_calling_next():179 client = Client(dispatch=MockDispatch())179 client = AsyncClient(dispatch=MockDispatch())180 url = "https://example.org/multiple_redirects?count=21"181 response = await client.request("GET", url, allow_redirects=False)182 with pytest.raises(TooManyRedirects):183 while response.is_redirect:
1 unmodified line
185186187@pytest.mark.asyncio188async def test_redirect_loop():189 client = Client(dispatch=MockDispatch())189 client = AsyncClient(dispatch=MockDispatch())190 with pytest.raises(RedirectLoop):191 await client.request("GET", "https://example.org/redirect_loop")192193194@pytest.mark.asyncio195async def test_redirect_loop_calling_next():196 client = Client(dispatch=MockDispatch())196 client = AsyncClient(dispatch=MockDispatch())197 url = "https://example.org/redirect_loop"198 response = await client.request("GET", url, allow_redirects=False)199 with pytest.raises(RedirectLoop):200 while response.is_redirect:
1 unmodified line
202203204@pytest.mark.asyncio205async def test_cross_domain_redirect():206 client = Client(dispatch=MockDispatch())206 client = AsyncClient(dispatch=MockDispatch())207 url = "https://example.com/cross_domain"208 headers = {"Authorization": "abc"}209 response = await client.request("GET", url, headers=headers)210 data = json.loads(response.content.decode())
2 unmodified lines
213214215@pytest.mark.asyncio216async def test_same_domain_redirect():217 client = Client(dispatch=MockDispatch())217 client = AsyncClient(dispatch=MockDispatch())218 url = "https://example.org/cross_domain"219 headers = {"Authorization": "abc"}220 response = await client.request("GET", url, headers=headers)221 data = json.loads(response.content.decode())
2 unmodified lines
224225226@pytest.mark.asyncio227async def test_body_redirect():228 client = Client(dispatch=MockDispatch())228 client = AsyncClient(dispatch=MockDispatch())229 url = "https://example.org/redirect_body"230 data = b"Example request body"231 response = await client.request("POST", url, data=data)232 data = json.loads(response.content.decode())
2 unmodified lines
235236237@pytest.mark.asyncio238async def test_cannot_redirect_streaming_body():239 client = Client(dispatch=MockDispatch())239 client = AsyncClient(dispatch=MockDispatch())240 url = "https://example.org/redirect_body"241242 async def streaming_body():243 yield b"Example request body"
3 unmodified lines
deleted:tests/test_sync.py-71 removed
1import asyncio2import functools34import pytest56import httpcore789def threadpool(func):10 """11 Our sync tests should run in seperate thread to the uvicorn server.12 """1314 @functools.wraps(func)15 async def wrapped(*args, **kwargs):16 nonlocal func1718 loop = asyncio.get_event_loop()19 if kwargs:20 func = functools.partial(func, **kwargs)21 await loop.run_in_executor(None, func, *args)2223 return pytest.mark.asyncio(wrapped)242526@threadpool27def test_get(server):28 with httpcore.SyncClient() as http:29 response = http.get("http://127.0.0.1:8000/")30 assert response.status_code == 20031 assert response.content == b"Hello, world!"32 assert response.text == "Hello, world!"333435@threadpool36def test_post(server):37 with httpcore.SyncClient() as http:38 response = http.post("http://127.0.0.1:8000/", data=b"Hello, world!")39 assert response.status_code == 20040 assert response.reason_phrase == "OK"414243@threadpool44def test_stream_response(server):45 with httpcore.SyncClient() as http:46 response = http.get("http://127.0.0.1:8000/", stream=True)47 assert response.status_code == 20048 content = response.read()49 assert content == b"Hello, world!"505152@threadpool53def test_stream_iterator(server):54 with httpcore.SyncClient() as http:55 response = http.get("http://127.0.0.1:8000/", stream=True)56 assert response.status_code == 20057 body = b""58 for chunk in response.stream():59 body += chunk60 assert body == b"Hello, world!"616263@threadpool64def test_raw_iterator(server):65 with httpcore.SyncClient() as http:66 response = http.get("http://127.0.0.1:8000/", stream=True)67 assert response.status_code == 20068 body = b""69 for chunk in response.raw():70 body += chunk71 assert body == b"Hello, world!"
modified:tests/test_timeouts.py+4 added-4 removed
1import pytest23from httpcore import (4 Client,4 AsyncClient,5 ConnectTimeout,6 PoolLimits,7 PoolTimeout,8 ReadTimeout,
4 unmodified lines
13@pytest.mark.asyncio14async def test_read_timeout(server):15 timeout = TimeoutConfig(read_timeout=0.0001)1617 async with Client(timeout=timeout) as client:17 async with AsyncClient(timeout=timeout) as client:18 with pytest.raises(ReadTimeout):19 await client.get("http://127.0.0.1:8000/slow_response")202122@pytest.mark.asyncio23async def test_connect_timeout(server):24 timeout = TimeoutConfig(connect_timeout=0.0001)2526 async with Client(timeout=timeout) as client:26 async with AsyncClient(timeout=timeout) as client:27 with pytest.raises(ConnectTimeout):28 # See https://stackoverflow.com/questions/100841/29 await client.get("http://10.255.255.1/")30
1 unmodified line
32@pytest.mark.asyncio33async def test_pool_timeout(server):34 pool_limits = PoolLimits(hard_limit=1, pool_timeout=0.0001)3536 async with Client(pool_limits=pool_limits) as client:36 async with AsyncClient(pool_limits=pool_limits) as client:37 response = await client.get("http://127.0.0.1:8000/", stream=True)3839 with pytest.raises(PoolTimeout):40 await client.get("http://localhost:8000/")
2 unmodified lines
modified:README.md+2 added-1 removed
11 unmodified lines
1213## Feature support1415* `HTTP/1.1` and `HTTP/2` Support.16* `async`/`await` support for non-thread-blocking HTTP requests.16* `async`/`await` support for non-blocking HTTP requests.17* Strict timeouts everywhere by default.18* Fully type annotated.19* 100% test coverage. *TODO - Almost there.*2021Plus all the standard features of requests...
214 unmodified lines