Skip to content
Myr

Version 0.15.0 (#1301)

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

* Version 0.15.0 * Update CHANGELOG.md Co-authored-by: Jamie Hewland <jamie.hewland@hpe.com> * Escalate deprecations into removals. * Deprecate overly verbose timeout parameter names * Fully deprecate max_keepalive in favour of explicit max_keepalive_connections * Fully deprecate PoolLimits in favour of Limits * Deprecate instantiating 'Timeout' without fully explicit values * Include deprecation notes in changelog * Use httpcore 0.11.x

authored by Tom Christie · committed by GitHub · parent 8e4a8a1 · Browse files · 18 files+117 added−208 removed
This commit

State

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

Trailers

  • Co-authored-by: Jamie Hewland <jamie.hewland@hpe.com>

Diff stats

18 files+117 added−208 removed

  • tests:+46 added−90 removed
  • other:+71 added−118 removed

18 files+117 added−208 removed

modified:httpx/_transports/asgi.py+6 added-5 removed
1from typing import TYPE_CHECKING, Callable, List, Mapping, Optional, Tuple, Union1from typing import TYPE_CHECKING, Callable, List, Optional, Tuple, Union23import httpcore4import sniffio5
60 unmodified lines
66 self.raise_app_exceptions = raise_app_exceptions67 self.root_path = root_path68 self.client = client6970 async def request(70 async def arequest(71 self,72 method: bytes,73 url: Tuple[bytes, bytes, Optional[int], bytes],74 headers: List[Tuple[bytes, bytes]] = None,75 stream: httpcore.AsyncByteStream = None,76 timeout: Mapping[str, Optional[float]] = None,77 ) -> Tuple[bytes, int, bytes, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream]:76 ext: dict = None,77 ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]:78 headers = [] if headers is None else headers79 stream = httpcore.PlainByteStream(content=b"") if stream is None else stream8081 # ASGI scope.
71 unmodified lines
153 assert status_code is not None154 assert response_headers is not None155156 stream = httpcore.PlainByteStream(content=b"".join(body_parts))157 ext = {}158158 return (b"HTTP/1.1", status_code, b"", response_headers, stream)159 return (status_code, response_headers, stream, ext)
modified:httpx/_transports/wsgi.py+4 added-7 removed
62 unmodified lines
63 method: bytes,64 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],65 headers: typing.List[typing.Tuple[bytes, bytes]] = None,66 stream: httpcore.SyncByteStream = None,67 timeout: typing.Mapping[str, typing.Optional[float]] = None,67 ext: dict = None,68 ) -> typing.Tuple[69 bytes,70 int,71 bytes,72 typing.List[typing.Tuple[bytes, bytes]],73 httpcore.SyncByteStream,69 int, typing.List[typing.Tuple[bytes, bytes]], httpcore.SyncByteStream, dict70 ]:71 headers = [] if headers is None else headers72 stream = httpcore.PlainByteStream(content=b"") if stream is None else stream73
48 unmodified lines
122 (key.encode("ascii"), value.encode("ascii"))123 for key, value in seen_response_headers124 ]125 stream = httpcore.IteratorByteStream(iterator=result)126 ext = {}127131 return (b"HTTP/1.1", status_code, b"", headers, stream)128 return (status_code, headers, stream, ext)
modified:httpx/__init__.py+1 added-2 removed
1from .__version__ import __description__, __title__, __version__2from ._api import delete, get, head, options, patch, post, put, request, stream3from ._auth import Auth, BasicAuth, DigestAuth4from ._client import AsyncClient, Client5from ._config import Limits, PoolLimits, Proxy, Timeout, create_ssl_context5from ._config import Limits, Proxy, Timeout, create_ssl_context6from ._exceptions import (7 CloseError,8 ConnectError,9 ConnectTimeout,
59 unmodified lines
69 "NetworkError",70 "NotRedirectResponse",71 "options",72 "patch",73 "PoolLimits",73 "PoolTimeout",74 "post",75 "ProtocolError",76 "Proxy",
33 unmodified lines
modified:httpx/__version__.py+1 added-1 removed
1__title__ = "httpx"2__description__ = "A next generation HTTP client, for Python 3."3__version__ = "0.14.3"3__version__ = "0.15.0"
modified:httpx/_client.py+6 added-18 removed
848 unmodified lines
849 timer = Timer()850 timer.sync_start()851852 with map_exceptions(HTTPCORE_EXC_MAP, request=request):853 (854 http_version,855 status_code,856 reason_phrase,857 headers,858 stream,859 ) = transport.request(853 (status_code, headers, stream, ext) = transport.request(854 request.method.encode(),855 request.url.raw,856 headers=request.headers.raw,857 stream=request.stream, # type: ignore864 timeout=timeout.as_dict(),858 ext={"timeout": timeout.as_dict()},859 )860861 def on_close(response: Response) -> None:862 response.elapsed = datetime.timedelta(timer.sync_elapsed())
1 unmodified line
864 stream.close()865866 response = Response(867 status_code,874 http_version=http_version.decode("ascii"),868 headers=headers,869 stream=stream, # type: ignore870 ext=ext,871 request=request,872 on_close=on_close,873 )874
619 unmodified lines
1494 timer = Timer()1495 await timer.async_start()14961497 with map_exceptions(HTTPCORE_EXC_MAP, request=request):1504 (1505 http_version,1506 status_code,1507 reason_phrase,1508 headers,1509 stream,1510 ) = await transport.request(1498 (status_code, headers, stream, ext,) = await transport.arequest(1499 request.method.encode(),1500 request.url.raw,1501 headers=request.headers.raw,1502 stream=request.stream, # type: ignore1515 timeout=timeout.as_dict(),1503 ext={"timeout": timeout.as_dict()},1504 )15051506 async def on_close(response: Response) -> None:1507 response.elapsed = datetime.timedelta(await timer.async_elapsed())
1 unmodified line
1509 await stream.aclose()15101511 response = Response(1512 status_code,1525 http_version=http_version.decode("ascii"),1513 headers=headers,1514 stream=stream, # type: ignore1515 ext=ext,1516 request=request,1517 on_close=on_close,1518 )1519
322 unmodified lines
modified:httpx/_config.py+3 added-62 removed
1import os2import ssl3import typing4import warnings4from base64 import b64encode5from pathlib import Path67import certifi89from ._models import URL, Headers10from ._types import CertTypes, HeaderTypes, TimeoutTypes, URLTypes, VerifyTypes12from ._utils import get_ca_bundle_from_env, get_logger, warn_deprecated11from ._utils import get_ca_bundle_from_env, get_logger1213DEFAULT_CIPHERS = ":".join(14 [15 "ECDHE+AESGCM",
194 unmodified lines
210 connect: typing.Union[None, float, UnsetType] = UNSET,211 read: typing.Union[None, float, UnsetType] = UNSET,212 write: typing.Union[None, float, UnsetType] = UNSET,213 pool: typing.Union[None, float, UnsetType] = UNSET,215 # Deprecated aliases.216 connect_timeout: typing.Union[None, float, UnsetType] = UNSET,217 read_timeout: typing.Union[None, float, UnsetType] = UNSET,218 write_timeout: typing.Union[None, float, UnsetType] = UNSET,219 pool_timeout: typing.Union[None, float, UnsetType] = UNSET,214 ):221 if not isinstance(connect_timeout, UnsetType):222 warn_deprecated(223 "httpx.Timeout(..., connect_timeout=...) is deprecated and will "224 "raise errors in a future version. "225 "Use httpx.Timeout(..., connect=...) instead."226 )227 connect = connect_timeout228229 if not isinstance(read_timeout, UnsetType):230 warn_deprecated(231 "httpx.Timeout(..., read_timeout=...) is deprecated and will "232 "raise errors in a future version. "233 "Use httpx.Timeout(..., write=...) instead."234 )235 read = read_timeout236237 if not isinstance(write_timeout, UnsetType):238 warn_deprecated(239 "httpx.Timeout(..., write_timeout=...) is deprecated and will "240 "raise errors in a future version. "241 "Use httpx.Timeout(..., write=...) instead."242 )243 write = write_timeout244245 if not isinstance(pool_timeout, UnsetType):246 warn_deprecated(247 "httpx.Timeout(..., pool_timeout=...) is deprecated and will "248 "raise errors in a future version. "249 "Use httpx.Timeout(..., pool=...) instead."250 )251 pool = pool_timeout252215 if isinstance(timeout, Timeout):216 # Passed as a single explicit Timeout.217 assert connect is UNSET218 assert read is UNSET
20 unmodified lines
239 self.write = write240 self.pool = pool241 else:242 if isinstance(timeout, UnsetType):281 warnings.warn(243 raise ValueError(244 "httpx.Timeout must either include a default, or set all "283 "four parameters explicitly. Omitting the default argument "284 "is deprecated and will raise errors in a future version.",285 DeprecationWarning,245 "four parameters explicitly."246 )287 timeout = None247 self.connect = timeout if isinstance(connect, UnsetType) else connect248 self.read = timeout if isinstance(read, UnsetType) else read249 self.write = timeout if isinstance(write, UnsetType) else write250 self.pool = timeout if isinstance(pool, UnsetType) else pool
42 unmodified lines
293 self,294 *,295 max_connections: int = None,296 max_keepalive_connections: int = None,338 # Deprecated parameter naming, in favour of more explicit version:339 max_keepalive: int = None,297 ):341 if max_keepalive is not None:342 warnings.warn(343 "'max_keepalive' is deprecated. Use 'max_keepalive_connections'.",344 DeprecationWarning,345 )346 max_keepalive_connections = max_keepalive347298 self.max_connections = max_connections299 self.max_keepalive_connections = max_keepalive_connections300301 def __eq__(self, other: typing.Any) -> bool:
10 unmodified lines
312 f"max_keepalive_connections={self.max_keepalive_connections})"313 )314315366class PoolLimits(Limits):367 def __init__(self, **kwargs: typing.Any) -> None:368 warn_deprecated(369 "httpx.PoolLimits(...) is deprecated and will raise errors in the future. "370 "Use httpx.Limits(...) instead."371 )372 super().__init__(**kwargs)373374316class Proxy:317 def __init__(318 self, url: URLTypes, *, headers: HeaderTypes = None, mode: str = "DEFAULT"319 ):
37 unmodified lines
modified:httpx/_models.py+7 added-22 removed
3 unmodified lines
4import email.message5import json as jsonlib6import typing7import urllib.request8import warnings8from collections.abc import MutableMapping9from http.cookiejar import Cookie, CookieJar10from urllib.parse import parse_qsl, quote, unquote, urlencode11
259 unmodified lines
271 self.raw_path,272 )273274 @property276 def is_ssl(self) -> bool:277 message = 'URL.is_ssl() is pending deprecation. Use url.scheme == "https"'278 warnings.warn(message, DeprecationWarning)279 return self.scheme == "https"280281 @property275 def is_absolute_url(self) -> bool:276 """277 Return `True` for absolute URLs such as 'http://example.com/path',278 and `False` for relative URLs such as '/path'.
238 unmodified lines
517 class_name = self.__class__.__name__518 query_string = str(self)519 return f"{class_name}({query_string!r})"520528 def getlist(self, key: typing.Any) -> typing.List[str]:529 message = (530 "QueryParams.getlist() is pending deprecation. Use QueryParams.get_list()"531 )532 warnings.warn(message, DeprecationWarning)533 return self.get_list(key)521535522class Headers(typing.MutableMapping[str, str]):523 """524 HTTP headers, as a case-insensitive multi-dict.525 """
216 unmodified lines
742 if no_duplicate_keys:743 return f"{class_name}({as_dict!r}{encoding_str})"744 return f"{class_name}({as_list!r}{encoding_str})"745760 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:761 message = "Headers.getlist() is pending deprecation. Use Headers.get_list()"762 warnings.warn(message, DeprecationWarning)763 return self.get_list(key, split_commas=split_commas)746765747class Request:748 def __init__(749 self,750 method: typing.Union[str, bytes],
112 unmodified lines
863 text: str = None,864 html: str = None,865 json: typing.Any = None,866 stream: ByteStream = None,886 http_version: str = None,867 request: Request = None,868 ext: dict = None,869 history: typing.List["Response"] = None,870 on_close: typing.Callable = None,871 ):872 self.status_code = status_code892 self.http_version = http_version873 self.headers = Headers(headers)874875 self._request: typing.Optional[Request] = request876877 self.call_next: typing.Optional[typing.Callable] = None878879 self.ext = {} if ext is None else ext880 self.history = [] if history is None else list(history)881 self._on_close = on_close882883 self.is_closed = False
61 unmodified lines
945 def request(self, value: Request) -> None:946 self._request = value947948 @property949 def http_version(self) -> str:950 return self.ext.get("http_version", "HTTP/1.1")951952 @property953 def reason_phrase(self) -> str:969 return codes.get_reason_phrase(self.status_code)954 return self.ext.get("reason", codes.get_reason_phrase(self.status_code))955956 @property957 def url(self) -> typing.Optional[URL]:958 """
508 unmodified lines
modified:tests/client/test_auth.py+28 added-32 removed
11 unmodified lines
12import pytest1314import httpx15from httpx import URL, Auth, BasicAuth, DigestAuth, ProtocolError, Request, Response16from tests.utils import AsyncMockTransport, MockTransport16from tests.utils import MockTransport1718from ..common import FIXTURES_DIR1920
133 unmodified lines
154 url = "https://example.org/"155 auth = ("tomchristie", "password123")156 app = App()157158 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:158 async with httpx.AsyncClient(transport=MockTransport(app)) as client:159 response = await client.get(url, auth=auth)160161 assert response.status_code == 200162 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}
3 unmodified lines
166async def test_basic_auth_in_url() -> None:167 url = "https://tomchristie:password123@example.org/"168 app = App()169170 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:170 async with httpx.AsyncClient(transport=MockTransport(app)) as client:171 response = await client.get(url)172173 assert response.status_code == 200174 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}
4 unmodified lines
179 url = "https://example.org/"180 auth = ("tomchristie", "password123")181 app = App()182183 async with httpx.AsyncClient(184 transport=AsyncMockTransport(app), auth=auth185 ) as client:183 async with httpx.AsyncClient(transport=MockTransport(app), auth=auth) as client:184 response = await client.get(url)185186 assert response.status_code == 200187 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}
7 unmodified lines
195 def auth(request: Request) -> Request:196 request.headers["Authorization"] = "Token 123"197 return request198201 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:199 async with httpx.AsyncClient(transport=MockTransport(app)) as client:200 response = await client.get(url, auth=auth)201202 assert response.status_code == 200203 assert response.json() == {"auth": "Token 123"}
4 unmodified lines
208 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")209 url = "http://netrcexample.org"210 app = App()211214 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:212 async with httpx.AsyncClient(transport=MockTransport(app)) as client:213 response = await client.get(url)214215 assert response.status_code == 200216 assert response.json() == {
6 unmodified lines
223 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")224 url = "http://netrcexample.org"225 app = App()226229 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:227 async with httpx.AsyncClient(transport=MockTransport(app)) as client:228 response = await client.get(url, headers={"Authorization": "Override"})229230 assert response.status_code == 200231 assert response.json() == {"auth": "Override"}
5 unmodified lines
237 url = "http://netrcexample.org"238 app = App()239240 async with httpx.AsyncClient(243 transport=AsyncMockTransport(app), trust_env=False241 transport=MockTransport(app), trust_env=False242 ) as client:243 response = await client.get(url)244245 assert response.status_code == 200246 assert response.json() == {"auth": None}247248 async with httpx.AsyncClient(251 transport=AsyncMockTransport(app), trust_env=True249 transport=MockTransport(app), trust_env=True250 ) as client:251 response = await client.get(url)252253 assert response.status_code == 200
7 unmodified lines
261 url = "https://example.org/"262 auth = ("tomchristie", "password123")263 app = App()264267 async with httpx.AsyncClient(268 transport=AsyncMockTransport(app), auth=auth269 ) as client:265 async with httpx.AsyncClient(transport=MockTransport(app), auth=auth) as client:266 response = await client.get(url, auth=None)267268 assert response.status_code == 200269 assert response.json() == {"auth": None}
11 unmodified lines
281 url = "https://example.org/"282 auth = ("example-username", "example-password")283 app = App()284289 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:285 async with httpx.AsyncClient(transport=MockTransport(app)) as client:286 response = await client.get(url, auth=auth)287288 assert "'authorization': '[secure]'" in str(response.request.headers)289
1 unmodified line
291@pytest.mark.asyncio292async def test_auth_property() -> None:293 app = App()294299 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:295 async with httpx.AsyncClient(transport=MockTransport(app)) as client:296 assert client.auth is None297298 client.auth = ("tomchristie", "password123") # type: ignore299 assert isinstance(client.auth, BasicAuth)
9 unmodified lines
309 app = App()310311 with pytest.raises(TypeError):312 client = httpx.AsyncClient(317 transport=AsyncMockTransport(app),313 transport=MockTransport(app),314 auth="not a tuple, not a callable", # type: ignore315 )316321 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:317 async with httpx.AsyncClient(transport=MockTransport(app)) as client:318 with pytest.raises(TypeError):319 await client.get(auth="not a tuple, not a callable") # type: ignore320321 with pytest.raises(TypeError):
5 unmodified lines
327 url = "https://example.org/"328 auth = DigestAuth(username="tomchristie", password="password123")329 app = App()330335 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:331 async with httpx.AsyncClient(transport=MockTransport(app)) as client:332 response = await client.get(url, auth=auth)333334 assert response.status_code == 200335 assert response.json() == {"auth": None}
20 unmodified lines
356 auth = DigestAuth(username="tomchristie", password="password123")357 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'358 app = App(auth_header=auth_header, status_code=200)359364 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:360 async with httpx.AsyncClient(transport=MockTransport(app)) as client:361 response = await client.get(url, auth=auth)362363 assert response.status_code == 200364 assert response.json() == {"auth": None}
5 unmodified lines
370 url = "https://example.org/"371 auth = DigestAuth(username="tomchristie", password="password123")372 app = App(auth_header="", status_code=401)373378 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:374 async with httpx.AsyncClient(transport=MockTransport(app)) as client:375 response = await client.get(url, auth=auth)376377 assert response.status_code == 401378 assert response.json() == {"auth": None}
20 unmodified lines
399 url = "https://example.org/"400 auth = DigestAuth(username="tomchristie", password="password123")401 app = DigestApp(algorithm=algorithm)402407 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:403 async with httpx.AsyncClient(transport=MockTransport(app)) as client:404 response = await client.get(url, auth=auth)405406 assert response.status_code == 200407 assert len(response.history) == 1
22 unmodified lines
430 url = "https://example.org/"431 auth = DigestAuth(username="tomchristie", password="password123")432 app = DigestApp(qop="")433438 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:434 async with httpx.AsyncClient(transport=MockTransport(app)) as client:435 response = await client.get(url, auth=auth)436437 assert response.status_code == 200438 assert len(response.history) == 1
23 unmodified lines
462 url = "https://example.org/"463 auth = DigestAuth(username="tomchristie", password="password123")464 app = DigestApp(qop=qop)465470 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:466 async with httpx.AsyncClient(transport=MockTransport(app)) as client:467 response = await client.get(url, auth=auth)468469 assert response.status_code == 200470 assert len(response.history) == 1
4 unmodified lines
475 url = "https://example.org/"476 auth = DigestAuth(username="tomchristie", password="password123")477 app = DigestApp(qop="auth-int")478483 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:479 async with httpx.AsyncClient(transport=MockTransport(app)) as client:480 with pytest.raises(NotImplementedError):481 await client.get(url, auth=auth)482483
2 unmodified lines
486 url = "https://example.org/"487 auth = DigestAuth(username="tomchristie", password="password123")488 app = DigestApp(qop="not-auth")489494 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:490 async with httpx.AsyncClient(transport=MockTransport(app)) as client:491 with pytest.raises(ProtocolError):492 await client.get(url, auth=auth)493494
2 unmodified lines
497 url = "https://example.org/"498 auth = DigestAuth(username="tomchristie", password="password123")499 app = DigestApp(send_response_after_attempt=2)500505 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:501 async with httpx.AsyncClient(transport=MockTransport(app)) as client:502 response = await client.get(url, auth=auth)503504 assert response.status_code == 401505 assert len(response.history) == 1
13 unmodified lines
519 url = "https://example.org/"520 auth = DigestAuth(username="tomchristie", password="password123")521 app = App(auth_header=auth_header, status_code=401)522527 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:523 async with httpx.AsyncClient(transport=MockTransport(app)) as client:524 with pytest.raises(ProtocolError):525 await client.get(url, auth=auth)526527
25 unmodified lines
553 url = "https://example.org/"554 auth = RepeatAuth(repeat=2)555 app = App(auth_header="abc")556561 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:557 async with httpx.AsyncClient(transport=MockTransport(app)) as client:558 response = await client.get(url, auth=auth)559560 assert response.status_code == 200561 assert response.json() == {"auth": "Repeat abc.abc"}
43 unmodified lines
605606 async def streaming_body():607 yield b"Example request body" # pragma: nocover608613 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:609 async with httpx.AsyncClient(transport=MockTransport(app)) as client:610 with pytest.raises(httpx.StreamConsumed):611 await client.post(url, data=streaming_body(), auth=auth)612613
6 unmodified lines
620 url = "https://example.org/"621 auth = ResponseBodyAuth("xyz")622 app = App()623628 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:624 async with httpx.AsyncClient(transport=MockTransport(app)) as client:625 response = await client.get(url, auth=auth)626627 assert response.status_code == 200628 assert response.json() == {"auth": '{"auth": "xyz"}'}
25 unmodified lines
654 url = "https://example.org/"655 auth = SyncOrAsyncAuth()656 app = App()657662 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:658 async with httpx.AsyncClient(transport=MockTransport(app)) as client:659 response = await client.get(url, auth=auth)660661 assert response.status_code == 200662 assert response.json() == {"auth": "async-auth"}
15 unmodified lines
modified:tests/client/test_client.py-2 removed
177 unmodified lines
178def test_merge_absolute_url():179 client = httpx.Client(base_url="https://www.example.com/")180 request = client.build_request("GET", "http://www.example.com/")181 assert request.url == "http://www.example.com/"182 with pytest.warns(DeprecationWarning):183 assert not request.url.is_ssl182183184def test_merge_relative_url():185 client = httpx.Client(base_url="https://www.example.com/")
88 unmodified lines
modified:tests/client/test_event_hooks.py+4 added-4 removed
1import pytest23import httpx4from tests.utils import AsyncMockTransport, MockTransport4from tests.utils import MockTransport567def app(request: httpx.Request) -> httpx.Response:8 if request.url.path == "/redirect":
63 unmodified lines
7273 event_hooks = {"request": [on_request], "response": [on_response]}7475 async with httpx.AsyncClient(76 event_hooks=event_hooks, transport=AsyncMockTransport(app)76 event_hooks=event_hooks, transport=MockTransport(app)77 ) as http:78 await http.get("http://127.0.0.1:8000/", auth=("username", "password"))7980 assert events == [
22 unmodified lines
103104 event_hooks = {"response": [raise_on_4xx_5xx]}105106 async with httpx.AsyncClient(107 event_hooks=event_hooks, transport=AsyncMockTransport(app)107 event_hooks=event_hooks, transport=MockTransport(app)108 ) as http:109 try:110 await http.get("http://127.0.0.1:8000/status/400")111 except httpx.HTTPStatusError as exc:
53 unmodified lines
165166 event_hooks = {"request": [on_request], "response": [on_response]}167168 async with httpx.AsyncClient(169 event_hooks=event_hooks, transport=AsyncMockTransport(app)169 event_hooks=event_hooks, transport=MockTransport(app)170 ) as http:171 await http.get("http://127.0.0.1:8000/redirect", auth=("username", "password"))172173 assert events == [
16 unmodified lines
modified:tests/client/test_redirects.py+3 added-3 removed
1import httpcore2import pytest34import httpx5from tests.utils import AsyncMockTransport, MockTransport5from tests.utils import MockTransport678def redirects(request: httpx.Request) -> httpx.Response:9 if request.url.scheme not in ("http", "https"):
221 unmodified lines
231232233@pytest.mark.usefixtures("async_environment")234async def test_async_too_many_redirects():235 async with httpx.AsyncClient(transport=AsyncMockTransport(redirects)) as client:235 async with httpx.AsyncClient(transport=MockTransport(redirects)) as client:236 with pytest.raises(httpx.TooManyRedirects):237 await client.get("https://example.org/multiple_redirects?count=21")238239240@pytest.mark.usefixtures("async_environment")241async def test_async_too_many_redirects_calling_next():242 async with httpx.AsyncClient(transport=AsyncMockTransport(redirects)) as client:242 async with httpx.AsyncClient(transport=MockTransport(redirects)) as client:243 url = "https://example.org/multiple_redirects?count=21"244 response = await client.get(url, allow_redirects=False)245 with pytest.raises(httpx.TooManyRedirects):246 while response.is_redirect:
170 unmodified lines
modified:tests/models/test_headers.py-3 removed
13 unmodified lines
14 assert h.get("a") == "123, 456"15 assert h.get("nope", default=None) is None16 assert h.get_list("a") == ["123", "456"]1718 with pytest.warns(DeprecationWarning):19 assert h.getlist("a") == ["123", "456"]2018 assert list(h.keys()) == ["a", "b"]19 assert list(h.values()) == ["123, 456", "789"]20 assert list(h.items()) == [("a", "123, 456"), ("b", "789")]21 assert h.multi_items() == [("a", "123"), ("a", "456"), ("b", "789")]
153 unmodified lines
modified:tests/models/test_queryparams.py-3 removed
19 unmodified lines
20 assert q.get("a") == "456"21 assert q.get("nope", default=None) is None22 assert q.get_list("a") == ["123", "456"]2324 with pytest.warns(DeprecationWarning):25 assert q.getlist("a") == ["123", "456"]2624 assert list(q.keys()) == ["a", "b"]25 assert list(q.values()) == ["456", "789"]26 assert list(q.items()) == [("a", "456"), ("b", "789")]27 assert len(q) == 2
65 unmodified lines
modified:tests/test_config.py+2 added-13 removed
108 unmodified lines
109 limits = httpx.Limits(max_connections=100)110 assert limits == httpx.Limits(max_connections=100)111112113def test_pool_limits_deprecated():114 with pytest.warns(DeprecationWarning):115 httpx.PoolLimits()116117118def test_max_keepalive_deprecated():119 with pytest.warns(DeprecationWarning):120 httpx.Limits(max_keepalive=50)121122113def test_timeout_eq():114 timeout = httpx.Timeout(timeout=5.0)115 assert timeout == httpx.Timeout(timeout=5.0)116
31 unmodified lines
148 assert timeout == httpx.Timeout(timeout=(5.0, 5.0, 5.0, 60.0))149150151def test_timeout_missing_default():162 with pytest.warns(DeprecationWarning):163 timeout = httpx.Timeout(pool=60.0)164 assert timeout == httpx.Timeout(timeout=(None, None, None, 60.0))152 with pytest.raises(ValueError):153 httpx.Timeout(pool=60.0)154155156def test_timeout_from_tuple():157 timeout = httpx.Timeout(timeout=(5.0, 5.0, 5.0, 5.0))
74 unmodified lines
modified:tests/test_timeouts.py-14 removed
39 unmodified lines
40 async with httpx.AsyncClient(limits=limits, timeout=timeout) as client:41 async with client.stream("GET", server.url):42 with pytest.raises(httpx.PoolTimeout):43 await client.get("http://localhost:8000/")444546def test_deprecated_verbose_timeout_params():47 with pytest.warns(DeprecationWarning):48 httpx.Timeout(None, read_timeout=1.0)4950 with pytest.warns(DeprecationWarning):51 httpx.Timeout(None, write_timeout=1.0)5253 with pytest.warns(DeprecationWarning):54 httpx.Timeout(None, connect_timeout=1.0)5556 with pytest.warns(DeprecationWarning):57 httpx.Timeout(None, pool_timeout=1.0)
modified:tests/utils.py+9 added-16 removed
1import contextlib2import logging3import os4from typing import Callable, List, Mapping, Optional, Tuple4from typing import Callable, List, Optional, Tuple56import httpcore78import httpx
14 unmodified lines
23 # Reset the logger so we don't have verbose output in all unit tests24 logging.getLogger("httpx").handlers = []252627class MockTransport(httpcore.SyncHTTPTransport):27class MockTransport(httpcore.SyncHTTPTransport, httpcore.AsyncHTTPTransport):28 def __init__(self, handler: Callable) -> None:29 self.handler = handler3031 def request(
1 unmodified line
33 method: bytes,34 url: Tuple[bytes, bytes, Optional[int], bytes],35 headers: List[Tuple[bytes, bytes]] = None,36 stream: httpcore.SyncByteStream = None,37 timeout: Mapping[str, Optional[float]] = None,38 ) -> Tuple[bytes, int, bytes, List[Tuple[bytes, bytes]], httpcore.SyncByteStream]:37 ext: dict = None,38 ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.SyncByteStream, dict]:39 request = httpx.Request(40 method=method,41 url=url,42 headers=headers,
1 unmodified line
44 )45 request.read()46 response = self.handler(request)47 return (48 (response.http_version or "HTTP/1.1").encode("ascii"),48 response.status_code,50 response.reason_phrase.encode("ascii"),49 response.headers.raw,50 response.stream,51 response.ext,52 )535556class AsyncMockTransport(httpcore.AsyncHTTPTransport):57 def __init__(self, handler: Callable) -> None:58 self.handler = handler5960 async def request(54 async def arequest(55 self,56 method: bytes,57 url: Tuple[bytes, bytes, Optional[int], bytes],58 headers: List[Tuple[bytes, bytes]] = None,59 stream: httpcore.AsyncByteStream = None,66 timeout: Mapping[str, Optional[float]] = None,67 ) -> Tuple[bytes, int, bytes, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream]:60 ext: dict = None,61 ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]:62 request = httpx.Request(63 method=method,64 url=url,65 headers=headers,
1 unmodified line
67 )68 await request.aread()69 response = self.handler(request)70 return (77 (response.http_version or "HTTP/1.1").encode("ascii"),71 response.status_code,79 response.reason_phrase.encode("ascii"),72 response.headers.raw,73 response.stream,74 response.ext,75 )
modified:CHANGELOG.md+42 added
2 unmodified lines
3All notable changes to this project will be documented in this file.45The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).67## 0.15.089### Added1011* Added support for event hooks. (Pull #1246)12* Added support for authentication flows which require either sync or async I/O. (Pull #1217)13* Added support for monitoring download progress with `response.num_bytes_downloaded`. (Pull #1268)14* Added `Request(content=...)` for byte content, instead of overloading `Request(data=...)` (Pull #1266)15* Added support for all URL components as parameter names when using `url.copy_with(...)`. (Pull #1285)16* Neater split between automatically populated headers on `Request` instances, vs default `client.headers`. (Pull #1248)17* Unclosed `AsyncClient` instances will now raise warnings if garbage collected. (Pull #1197)18* Support `Response(content=..., text=..., html=..., json=...)` for creating usable response instances in code. (Pull #1265, #1297)19* Support instantiating requests from the low-level transport API. (Pull #1293)20* Raise errors on invalid URL types. (Pull #1259)2122### Changed2324* Cleaned up expected behaviour for URL escaping. `url.path` is now URL escaped. (Pull #1285)25* Cleaned up expected behaviour for bytes vs str in URL components. `url.userinfo` and `url.query` are not URL escaped, and so return bytes. (Pull #1285)26* Drop `url.authority` property in favour of `url.netloc`, since "authority" was semantically incorrect. (Pull #1285)27* Drop `url.full_path` property in favour of `url.raw_path`, for better consistency with other parts of the API. (Pull #1285)28* No longer use the `chardet` library for auto-detecting charsets, instead defaulting to a simpler approach when no charset is specified. (#1269)2930### Fixed3132* Swapped ordering of redirects and authentication flow. (Pull #1267)33* `.netrc` lookups should use host, not host+port. (Pull #1298)3435### Removed3637* The `URLLib3Transport` class no longer exists. We've published it instead as an example of [a custom transport class](https://gist.github.com/florimondmanca/d56764d78d748eb9f73165da388e546e). (Pull #1182)38* Drop `request.timer` attribute, which was being used internally to set `response.elapsed`. (Pull #1249)39* Drop `response.decoder` attribute, which was being used internally. (Pull #1276)40* `Request.prepare()` is now a private method. (Pull #1284)41* The `Headers.getlist()` method had previously been deprecated in favour of `Headers.get_list()`. It is now fully removed.42* The `QueryParams.getlist()` method had previously been deprecated in favour of `QueryParams.get_list()`. It is now fully removed.43* The `URL.is_ssl` property had previously been deprecated in favour of `URL.scheme == "https"`. It is now fully removed.44* The `httpx.PoolLimits` class had previously been deprecated in favour of `httpx.Limits`. It is now fully removed.45* The `max_keepalive` setting had previously been deprecated in favour of the more explicit `max_keepalive_connections`. It is now fully removed.46* The verbose `httpx.Timeout(5.0, connect_timeout=60.0)` style had previously been deprecated in favour of `httpx.Timeout(5.0, connect=60.0)`. It is now fully removed.47* Support for instantiating a timeout config missing some defaults, such as `httpx.Timeout(connect=60.0)`, had previously been deprecated in favour of enforcing a more explicit style, such as `httpx.Timeout(5.0, connect=60.0)`. This is now strictly enforced.4849## 0.14.3 (September 2nd, 2020)5051### Added52
594 unmodified lines
modified:setup.py+1 added-1 removed
56 unmodified lines
57 install_requires=[58 "certifi",59 "sniffio",60 "rfc3986[idna2008]>=1.3,<2",61 "httpcore==0.10.*",61 "httpcore==0.11.*",62 ],63 extras_require={64 "http2": "h2==3.*",65 "brotli": "brotlipy==0.7.*",
17 unmodified lines