Rename Client to AsyncClient (with compat synonym) (#680)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Rename Client to AsyncClient (with compat synonym) * Document motivation for AsyncClient renaming
authored by Florimond Manca · committed by Tom Christie · parent 3462999 · Browse files · 24 files·+189 added−174 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: Tom Christie <tom@tomchristie.com>
Diff stats
24 files+189 added−174 removed
- tests:+128 added−124 removed
- other:+61 added−50 removed
Provenance
- Commit
e284b84- Tree
d74de9b- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
3462999
24 files changed+189 added−174 removed
modified:docs/advanced.md+32 added-27 removed
7 unmodified lines8 9 !!! hint10 A Client instance is equivalent to a Session instance in `requests`.11 12+!!! note13+ Starting from `httpx==0.10.0`, the default and recommended Client class is `AsyncClient`. This should help prevent breaking changes once sync support is reintroduced.14+15+ A `Client` synonym remains for compatibility with `httpx==0.9.*` releases, but you are encouraged to migrate to `AsyncClient` as soon as possible.16+17 ### Usage18 19 The recommended way to use a `Client` is as a context manager. This will ensure that connections are properly cleaned up when leaving the `with` block:20 21 ```python17->>> async with httpx.Client() as client:22+>>> async with httpx.AsyncClient() as client:23 ... r = await client.get('https://example.com')24 ...25 >>> r26 <Response [200 OK]>1 unmodified line28 29 Alternatively, you can explicitly close the connection pool without block-usage using `.aclose()`:30 31 ```python27->>> client = httpx.Client()32+>>> client = httpx.AsyncClient()33 >>> try:34 ... r = await client.get('https://example.com')35 ... finally:36 ... await client.aclose()12 unmodified lines49 50 ```python51 >>> url = 'http://httpbin.org/headers'52 >>> headers = {'user-agent': 'my-app/0.0.1'}48->>> async with httpx.Client(headers=headers) as client:53+>>> async with httpx.AsyncClient(headers=headers) as client:54 ... r = await client.get(url)55 ...56 >>> r.json()['headers']['User-Agent']57 'my-app/0.0.1'4 unmodified lines62 63 - For headers, query parameters and cookies, the values are merged into one.64 - For all other parameters, the request-level value is used.65 61-Additionally, `Client` constructor accepts some parameters that aren't available at the request level.66+Additionally, `Client` accepts some parameters that aren't available at the request level.67 68 One particularly useful parameter is `base_url`, which allows you to define a base URL to prepend to all outgoing requests:69 70 ```python66->>> async with httpx.Client(base_url='http://httpbin.org') as client:71+>>> async with httpx.AsyncClient(base_url='http://httpbin.org') as client:72 ... r = await client.get('/headers')73 ...74 >>> r.request.url75 URL('http://httpbin.org/headers')76 ```77 73-For a list of all available client-level parameters, see the [`Client` API reference](/api/#client).78+For a list of all available client-level parameters, see the [`AsyncClient` API reference](/api/#async-client).79 80 ## Calling into Python Web Apps81 82 You can configure an `httpx` client to call directly into a Python web22 unmodified lines105 We can make requests directly against the application, like so:106 107 ```python108 >>> import httpx104->>> async with httpx.Client(app=app) as client:109+>>> async with httpx.AsyncClient(app=app) as client:110 ... r = client.get('http://example/')111 ... assert r.status_code == 200112 ... assert r.text == "Hello World!"113 ```9 unmodified lines123 ```python124 # Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",125 # on port 123.126 dispatch = httpx.dispatch.ASGIDispatch(app=app, client=("1.2.3.4", 123))122-async with httpx.Client(dispatch=dispatch) as client:127+async with httpx.AsyncClient(dispatch=dispatch) as client:128 ...129 ```130 131 See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path`4 unmodified lines136 You can use `Client.build_request()` to build a request and137 make modifications before sending the request.138 139 ```python135->>> async with httpx.Client() as client:140+>>> async with httpx.AsyncClient() as client:141 ... req = client.build_request("OPTIONS", "https://example.com")142 ... req.url.full_path = "*" # Build an 'OPTIONS *' request for CORS143 ... r = await client.send(req)144 ...36 unmodified lines181 182 When using `Client` instances, `trust_env` should be set on the client itself, rather that on the request methods:183 184 ```python180-client = httpx.Client(trust_env=False)185+client = httpx.AsyncClient(trust_env=False)186 ```187 188 ## Unix Domain Sockets189 4 unmodified lines194 ```python195 import httpx196 197 193-async with httpx.Client(uds="/var/run/docker.sock") as client:198+async with httpx.AsyncClient(uds="/var/run/docker.sock") as client:199 # This request will connect through the socket file.200 resp = await client.get("http://localhost/version")201 ```202 7 unmodified lines210 >>> proxies = {211 ... "http": "http://127.0.0.1:3080",212 ... "https": "http://127.0.0.1:3081"213 ... }209->>> async with httpx.Client(proxies=proxies) as client:214+>>> async with httpx.AsyncClient(proxies=proxies) as client:215 ... ...216 ```217 218 Proxies can be configured for a specific scheme and host, all schemes of a host,6 unmodified lines225 ... "all://example.com": "...", # Host226 ... "http": "...", # Scheme227 ... "all": "...", # All228 ... }224->>> async with httpx.Client(proxies=proxies) as client:229+>>> async with httpx.AsyncClient(proxies=proxies) as client:230 ... ...231 ...232 >>> proxy = "..." # Shortcut for {'all': '...'}228->>> async with httpx.Client(proxies=proxy) as client:233+>>> async with httpx.AsyncClient(proxies=proxy) as client:234 ... ...235 ```236 237 !!! warning11 unmodified lines249 proxy = httpx.HTTPProxy(250 proxy_url="https://127.0.0.1",251 proxy_mode="TUNNEL_ONLY" # May be "TUNNEL_ONLY" or "FORWARD_ONLY". Defaults to "DEFAULT".252 )248-async with httpx.Client(proxies=proxy) as client:253+async with httpx.AsyncClient(proxies=proxy) as client:254 # This request will be tunneled instead of forwarded.255 r = await client.get("http://example.com")256 ```257 18 unmodified lines276 # Using the top-level API:277 await httpx.get('http://example.com/api/v1/example', timeout=10.0)278 279 # Using a client instance:275-async with httpx.Client() as client:280+async with httpx.AsyncClient() as client:281 await client.get("http://example.com/api/v1/example", timeout=10.0)282 ```283 284 Or disable timeouts for an individual request:2 unmodified lines287 # Using the top-level API:288 await httpx.get('http://example.com/api/v1/example', timeout=None)289 290 # Using a client instance:286-async with httpx.Client() as client:291+async with httpx.AsyncClient() as client:292 await client.get("http://example.com/api/v1/example", timeout=None)293 ```294 295 ### Setting a default timeout on a client1 unmodified line297 You can set a timeout on a client instance, which results in the given298 `timeout` being used as the default for requests made with this client:299 300 ```python296-client = httpx.Client() # Use a default 5s timeout everywhere.297-client = httpx.Client(timeout=10.0) # Use a default 10s timeout everywhere.298-client = httpx.Client(timeout=None) # Disable all timeouts by default.301+client = httpx.AsyncClient() # Use a default 5s timeout everywhere.302+client = httpx.AsyncClient(timeout=10.0) # Use a default 10s timeout everywhere.303+client = httpx.AsyncClient(timeout=None) # Disable all timeouts by default.304 ```305 306 ### Fine tuning the configuration307 21 unmodified lines329 330 ```python331 # A client with a 60s timeout for connecting, and a 10s timeout elsewhere.332 timeout = httpx.Timeout(10.0, connect_timeout=60.0)328-client = httpx.Client(timeout=timeout)333+client = httpx.AsyncClient(timeout=timeout)334 335 response = await client.get('http://example.com/')336 ```337 70 unmodified lines408 409 If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.410 411 ```python407-client = httpx.Client(verify=False)412+client = httpx.AsyncClient(verify=False)413 ```414 415 The `client.get(...)` method and other request methods *do not* support changing the SSL settings on a per-request basis. If you need different SSL settings in different cases you should use more that one client instance, with different settings on each. Each client will then be using an isolated connection pool with a specific fixed SSL configuration on all connections within that pool.416 24 unmodified lines441 You can also explicitly select a backend by instantiating a client with the442 `backend` argument...443 444 ```python440-client = httpx.Client(backend='auto') # Autodetection. The default case.441-client = httpx.Client(backend='asyncio') # Use asyncio as the backend.442-client = httpx.Client(backend='trio') # Use trio as the backend.445+client = httpx.AsyncClient(backend='auto') # Autodetection. The default case.446+client = httpx.AsyncClient(backend='asyncio') # Use asyncio as the backend.447+client = httpx.AsyncClient(backend='trio') # Use trio as the backend.448 ```449 450 ### [AsyncIO](https://docs.python.org/3/library/asyncio.html)451 4 unmodified lines456 import asyncio457 import httpx458 459 async def main():455- client = httpx.Client()460+ client = httpx.AsyncClient()461 response = await client.get('https://www.example.com/')462 print(response)463 464 asyncio.run(main())8 unmodified lines473 import httpx474 import trio475 476 async def main():472- client = httpx.Client()477+ client = httpx.AsyncClient()478 response = await client.get('https://www.example.com/')479 print(response)480 481 trio.run(main)4 unmodified linesmodified:docs/api.md+2 added-2 removed
30 unmodified lines31323334353536373738394041119 unmodified linesExpand all30 unmodified lines
::: httpx.delete :docstring:
## `Client`## `AsyncClient`
::: httpx.Client::: httpx.AsyncClient :docstring: :members: headers cookies params request get head options post put patch delete build_request send aclose
## `Response`119 unmodified linesExpand allmodified:docs/compatibility.md+2 added-2 removed
50 unmodified lines51 We don't support `response.is_ok` since the naming is ambiguous there, and might incorrectly imply an equivalence to `response.status_code == codes.OK`. Instead we provide the `response.is_error` property. Use `if not response.is_error:` instead of `if response.is_ok:`.52 53 ## Client instances54 55-The HTTPX equivalent of `requests.Session` is `httpx.Client`.55+The HTTPX equivalent of `requests.Session` is `httpx.AsyncClient`.56 57 ```python58 session = requests.Session(**kwargs)59 ```60 61 is generally equivalent to62 63 ```python64-client = httpx.Client(**kwargs)64+client = httpx.AsyncClient(**kwargs)65 ```66 67 ## Mocking68 1 unmodified linemodified:docs/environment_variables.md+3 added-3 removed
2 unmodified lines3 4 The HTTPX library can be configured via environment variables.5 Environment variables are used by default. To ignore environment variables, `trust_env` has to be set `False`. There are two ways to set `trust_env` to disable environment variables:6 7-* On the client via `httpx.Client(trust_env=False)`.7+* On the client via `httpx.AsyncClient(trust_env=False)`.8 * Using the top-level API, such as `httpx.get("<url>", trust_env=False)`.9 10 Here is a list of environment variables that HTTPX recognizes and what function they serve:11 11 unmodified lines23 ```python24 # test_script.py25 import httpx26 27-with httpx.Client() as client:27+with httpx.AsyncClient() as client:28 r = client.get("https://google.com")29 ```30 31 Debug output:56 unmodified lines88 ```python89 # test_script.py90 import httpx91 92-with httpx.Client() as client:92+with httpx.AsyncClient() as client:93 r = client.get("https://google.com")94 ```95 96 ```console58 unmodified linesmodified:docs/http2.md+3 added-3 removed
28 unmodified lines29 trying out our HTTP/2 support. You can do so by instantiating a client with30 HTTP/2 support enabled:31 32 ```python33-client = httpx.Client(http2=True)33+client = httpx.AsyncClient(http2=True)34 ...35 ```36 37 You can also instantiate a client as a context manager, to ensure that all38 HTTP connections are nicely scoped, and will be closed once the context block39 is exited.40 41 ```python42-async with httpx.Client(http2=True) as client:42+async with httpx.AsyncClient(http2=True) as client:43 ...44 ```45 46 ## Inspecting the HTTP version6 unmodified lines53 You can determine which version of the HTTP protocol was used by examining54 the `.http_version` property on the response.55 56 ```python57-client = httpx.Client(http2=True)57+client = httpx.AsyncClient(http2=True)58 response = await client.get(...)59 print(response.http_version) # "HTTP/1.0", "HTTP/1.1", or "HTTP/2".60 ```modified:httpx/dispatch/asgi.py+2 added-2 removed
13 unmodified lines14 This will automatically infer if 'app' is a WSGI or an ASGI application,15 and will setup an appropriate dispatch class:16 17 ```18- client = httpx.Client(app=app)18+ client = httpx.AsyncClient(app=app)19 ```20 21 Alternatively, you can setup the dispatch instance explicitly.22 This allows you to include any additional configuration arguments specific4 unmodified lines27 app=app,28 root_path="/submount",29 client=("1.2.3.4", 123)30 )31- client = httpx.Client(dispatch=dispatch)31+ client = httpx.AsyncClient(dispatch=dispatch)32 ```33 34 Arguments:35 91 unmodified linesmodified:httpx/dispatch/base.py+1 added-1 removed
16 unmodified lines17 Base class for dispatcher classes, that handle sending the request.18 19 Stubs out the interface, as well as providing a `.request()` convenience20 implementation, to make it easy to use or test stand-alone dispatchers,21- without requiring a complete `Client` instance.21+ without requiring a complete `AsyncClient` instance.22 """23 24 async def request(25 self,50 unmodified linesmodified:httpx/__init__.py+2 added-1 removed
1 from .__version__ import __description__, __title__, __version__2 from .api import delete, get, head, options, patch, post, put, request, stream3 from .auth import BasicAuth, DigestAuth4-from .client import Client4+from .client import AsyncClient, Client5 from .config import TimeoutConfig # For 0.8 backwards compat.6 from .config import PoolLimits, Timeout7 from .dispatch.proxy_http import HTTPProxy, HTTPProxyMode8 from .exceptions import (34 unmodified lines43 "put",44 "request",45 "stream",46 "codes",47+ "AsyncClient",48 "BasicAuth",49 "Client",50 "DigestAuth",51 "PoolLimits",35 unmodified linesmodified:httpx/api.py+3 added-3 removed
1 import typing2 3 from .auth import AuthTypes4-from .client import Client, StreamContextManager4+from .client import AsyncClient, StreamContextManager5 from .config import DEFAULT_TIMEOUT_CONFIG, CertTypes, TimeoutTypes, VerifyTypes6 from .models import (7 CookieTypes,8 HeaderTypes,71 unmodified lines80 >>> response81 <Response [200 OK]>82 ```83 """84- async with Client(84+ async with AsyncClient(85 cert=cert, verify=verify, timeout=timeout, trust_env=trust_env,86 ) as client:87 return await client.request(88 method=method,26 unmodified lines115 verify: VerifyTypes = True,116 cert: CertTypes = None,117 trust_env: bool = True,118 ) -> StreamContextManager:119- client = Client(cert=cert, verify=verify, trust_env=trust_env)119+ client = AsyncClient(cert=cert, verify=verify, trust_env=trust_env)120 request = Request(121 method=method,122 url=url,123 params=params,291 unmodified linesmodified:httpx/client.py+11 added-6 removed
50 unmodified lines51 52 logger = get_logger(__name__)53 54 55-class Client:55+class AsyncClient:56 """57- An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.57+ An asynchronous HTTP client, with connection pooling, HTTP/2, redirects,58+ cookie persistence, etc.59 60 Usage:61 61- ```62- >>> client = httpx.Client()62+ ```python63+ >>> client = httpx.AsyncClient()64 >>> response = client.get('https://example.org')65 ```66 67 **Parameters:**800 unmodified lines868 869 async def aclose(self) -> None:870 await self.dispatch.close()871 871- async def __aenter__(self) -> "Client":872+ async def __aenter__(self) -> "AsyncClient":873 return self874 875 async def __aexit__(876 self,46 unmodified lines923 924 class StreamContextManager:925 def __init__(926 self,926- client: Client,927+ client: AsyncClient,928 request: Request,929 *,930 auth: AuthTypes = None,931 allow_redirects: bool = True,25 unmodified lines957 ) -> None:958 await self.response.aclose()959 if self.close_client:960 await self.client.aclose()961+962+963+# For compatibility with 0.9.x.964+Client = AsyncClientmodified:tests/client/test_async_client.py+16 added-16 removed
6 unmodified lines7 8 @pytest.mark.usefixtures("async_environment")9 async def test_get(server):10 url = server.url11- async with httpx.Client() as client:11+ async with httpx.AsyncClient() as client:12 response = await client.get(url)13 assert response.status_code == 20014 assert response.text == "Hello, world!"15 assert response.http_version == "HTTP/1.1"5 unmodified lines21 @pytest.mark.usefixtures("async_environment")22 async def test_build_request(server):23 url = server.url.copy_with(path="/echo_headers")24 headers = {"Custom-header": "value"}25- async with httpx.Client() as client:25+ async with httpx.AsyncClient() as client:26 request = client.build_request("GET", url)27 request.headers.update(headers)28 response = await client.send(request)29 5 unmodified lines35 36 @pytest.mark.usefixtures("async_environment")37 async def test_post(server):38 url = server.url39- async with httpx.Client() as client:39+ async with httpx.AsyncClient() as client:40 response = await client.post(url, data=b"Hello, world!")41 assert response.status_code == 20042 43 44 @pytest.mark.usefixtures("async_environment")45 async def test_post_json(server):46 url = server.url47- async with httpx.Client() as client:47+ async with httpx.AsyncClient() as client:48 response = await client.post(url, json={"text": "Hello, world!"})49 assert response.status_code == 20050 51 52 @pytest.mark.usefixtures("async_environment")53 async def test_stream_response(server):54- async with httpx.Client() as client:54+ async with httpx.AsyncClient() as client:55 async with client.stream("GET", server.url) as response:56 body = await response.aread()57 58 assert response.status_code == 2002 unmodified lines61 62 63 @pytest.mark.usefixtures("async_environment")64 async def test_access_content_stream_response(server):65- async with httpx.Client() as client:65+ async with httpx.AsyncClient() as client:66 async with client.stream("GET", server.url) as response:67 pass68 69 assert response.status_code == 2006 unmodified lines76 async def hello_world():77 yield b"Hello, "78 yield b"world!"79 80- async with httpx.Client() as client:80+ async with httpx.AsyncClient() as client:81 response = await client.request("POST", server.url, data=hello_world())82 assert response.status_code == 20083 84 85 @pytest.mark.usefixtures("async_environment")86 async def test_raise_for_status(server):87- async with httpx.Client() as client:87+ async with httpx.AsyncClient() as client:88 for status_code in (200, 400, 404, 500, 505):89 response = await client.request(90 "GET", server.url.copy_with(path=f"/status/{status_code}")91 )7 unmodified lines99 100 101 @pytest.mark.usefixtures("async_environment")102 async def test_options(server):103- async with httpx.Client() as client:103+ async with httpx.AsyncClient() as client:104 response = await client.options(server.url)105 assert response.status_code == 200106 assert response.text == "Hello, world!"107 108 109 @pytest.mark.usefixtures("async_environment")110 async def test_head(server):111- async with httpx.Client() as client:111+ async with httpx.AsyncClient() as client:112 response = await client.head(server.url)113 assert response.status_code == 200114 assert response.text == ""115 116 117 @pytest.mark.usefixtures("async_environment")118 async def test_put(server):119- async with httpx.Client() as client:119+ async with httpx.AsyncClient() as client:120 response = await client.put(server.url, data=b"Hello, world!")121 assert response.status_code == 200122 123 124 @pytest.mark.usefixtures("async_environment")125 async def test_patch(server):126- async with httpx.Client() as client:126+ async with httpx.AsyncClient() as client:127 response = await client.patch(server.url, data=b"Hello, world!")128 assert response.status_code == 200129 130 131 @pytest.mark.usefixtures("async_environment")132 async def test_delete(server):133- async with httpx.Client() as client:133+ async with httpx.AsyncClient() as client:134 response = await client.delete(server.url)135 assert response.status_code == 200136 assert response.text == "Hello, world!"137 2 unmodified lines140 async def test_100_continue(server):141 headers = {"Expect": "100-continue"}142 data = b"Echo request body"143 144- async with httpx.Client() as client:144+ async with httpx.AsyncClient() as client:145 response = await client.post(146 server.url.copy_with(path="/echo_body"), headers=headers, data=data147 )148 5 unmodified lines154 async def test_uds(uds_server):155 url = uds_server.url156 uds = uds_server.config.uds157 assert uds is not None158- async with httpx.Client(uds=uds) as client:158+ async with httpx.AsyncClient(uds=uds) as client:159 response = await client.get(url)160 assert response.status_code == 200161 assert response.text == "Hello, world!"162 assert response.encoding == "iso-8859-1"163 164 165 async def test_explicit_backend(server, async_environment):166- async with httpx.Client(backend=async_environment) as client:166+ async with httpx.AsyncClient(backend=async_environment) as client:167 response = await client.get(server.url)168 assert response.status_code == 200169 assert response.text == "Hello, world!"modified:tests/client/test_auth.py+25 added-21 removed
3 unmodified lines4 import typing5 6 import pytest7 8-from httpx import URL, Client, DigestAuth, ProtocolError, Request, Response8+from httpx import URL, AsyncClient, DigestAuth, ProtocolError, Request, Response9 from httpx.config import CertTypes, TimeoutTypes, VerifyTypes10 from httpx.dispatch.base import Dispatcher11 12 75 unmodified lines88 async def test_basic_auth() -> None:89 url = "https://example.org/"90 auth = ("tomchristie", "password123")91 92- client = Client(dispatch=MockDispatch())92+ client = AsyncClient(dispatch=MockDispatch())93 response = await client.get(url, auth=auth)94 95 assert response.status_code == 20096 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}2 unmodified lines99 @pytest.mark.asyncio100 async def test_basic_auth_in_url() -> None:101 url = "https://tomchristie:password123@example.org/"102 103- client = Client(dispatch=MockDispatch())103+ client = AsyncClient(dispatch=MockDispatch())104 response = await client.get(url)105 106 assert response.status_code == 200107 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}3 unmodified lines111 async def test_basic_auth_on_session() -> None:112 url = "https://example.org/"113 auth = ("tomchristie", "password123")114 115- client = Client(dispatch=MockDispatch(), auth=auth)115+ client = AsyncClient(dispatch=MockDispatch(), auth=auth)116 response = await client.get(url)117 118 assert response.status_code == 200119 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}6 unmodified lines126 def auth(request: Request) -> Request:127 request.headers["Authorization"] = "Token 123"128 return request129 130- client = Client(dispatch=MockDispatch())130+ client = AsyncClient(dispatch=MockDispatch())131 response = await client.get(url, auth=auth)132 133 assert response.status_code == 200134 assert response.json() == {"auth": "Token 123"}3 unmodified lines138 async def test_netrc_auth() -> None:139 os.environ["NETRC"] = "tests/.netrc"140 url = "http://netrcexample.org"141 142- client = Client(dispatch=MockDispatch())142+ client = AsyncClient(dispatch=MockDispatch())143 response = await client.get(url)144 145 assert response.status_code == 200146 assert response.json() == {5 unmodified lines152 async def test_auth_header_has_priority_over_netrc() -> None:153 os.environ["NETRC"] = "tests/.netrc"154 url = "http://netrcexample.org"155 156- client = Client(dispatch=MockDispatch())156+ client = AsyncClient(dispatch=MockDispatch())157 response = await client.get(url, headers={"Authorization": "Override"})158 159 assert response.status_code == 200160 assert response.json() == {"auth": "Override"}3 unmodified lines164 async def test_trust_env_auth() -> None:165 os.environ["NETRC"] = "tests/.netrc"166 url = "http://netrcexample.org"167 168- client = Client(dispatch=MockDispatch(), trust_env=False)168+ client = AsyncClient(dispatch=MockDispatch(), trust_env=False)169 response = await client.get(url)170 171 assert response.status_code == 200172 assert response.json() == {"auth": None}173 174- client = Client(dispatch=MockDispatch(), trust_env=True)174+ client = AsyncClient(dispatch=MockDispatch(), trust_env=True)175 response = await client.get(url)176 177 assert response.status_code == 200178 assert response.json() == {12 unmodified lines191 async def test_auth_hidden_header() -> None:192 url = "https://example.org/"193 auth = ("example-username", "example-password")194 195- client = Client(dispatch=MockDispatch())195+ client = AsyncClient(dispatch=MockDispatch())196 response = await client.get(url, auth=auth)197 198 assert "'authorization': '[secure]'" in str(response.request.headers)199 200 201 @pytest.mark.asyncio202 async def test_auth_invalid_type() -> None:203 url = "https://example.org/"204- client = Client(204+ client = AsyncClient(205 dispatch=MockDispatch(), auth="not a tuple, not a callable", # type: ignore206 )207 with pytest.raises(TypeError):208 await client.get(url)3 unmodified lines212 async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:213 url = "https://example.org/"214 auth = DigestAuth(username="tomchristie", password="password123")215 216- client = Client(dispatch=MockDispatch())216+ client = AsyncClient(dispatch=MockDispatch())217 response = await client.get(url, auth=auth)218 219 assert response.status_code == 200220 assert response.json() == {"auth": None}4 unmodified lines225 url = "https://example.org/"226 auth = DigestAuth(username="tomchristie", password="password123")227 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'228 229- client = Client(dispatch=MockDispatch(auth_header=auth_header, status_code=200))229+ client = AsyncClient(230+ dispatch=MockDispatch(auth_header=auth_header, status_code=200)231+ )232 response = await client.get(url, auth=auth)233 234 assert response.status_code == 200235 assert response.json() == {"auth": None}3 unmodified lines239 async def test_digest_auth_401_response_without_digest_auth_header() -> None:240 url = "https://example.org/"241 auth = DigestAuth(username="tomchristie", password="password123")242 241- client = Client(dispatch=MockDispatch(auth_header="", status_code=401))243+ client = AsyncClient(dispatch=MockDispatch(auth_header="", status_code=401))244 response = await client.get(url, auth=auth)245 246 assert response.status_code == 401247 assert response.json() == {"auth": None}18 unmodified lines266 ) -> None:267 url = "https://example.org/"268 auth = DigestAuth(username="tomchristie", password="password123")269 268- client = Client(dispatch=MockDigestAuthDispatch(algorithm=algorithm))270+ client = AsyncClient(dispatch=MockDigestAuthDispatch(algorithm=algorithm))271 response = await client.get(url, auth=auth)272 273 assert response.status_code == 200274 authorization = typing.cast(dict, response.json())["auth"]19 unmodified lines294 async def test_digest_auth_no_specified_qop() -> None:295 url = "https://example.org/"296 auth = DigestAuth(username="tomchristie", password="password123")297 296- client = Client(dispatch=MockDigestAuthDispatch(qop=""))298+ client = AsyncClient(dispatch=MockDigestAuthDispatch(qop=""))299 response = await client.get(url, auth=auth)300 301 assert response.status_code == 200302 authorization = typing.cast(dict, response.json())["auth"]20 unmodified lines323 async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:324 url = "https://example.org/"325 auth = DigestAuth(username="tomchristie", password="password123")326 325- client = Client(dispatch=MockDigestAuthDispatch(qop=qop))327+ client = AsyncClient(dispatch=MockDigestAuthDispatch(qop=qop))328 await client.get(url, auth=auth)329 330 331 @pytest.mark.asyncio332 async def test_digest_auth_qop_auth_int_not_implemented() -> None:333 url = "https://example.org/"334 auth = DigestAuth(username="tomchristie", password="password123")333- client = Client(dispatch=MockDigestAuthDispatch(qop="auth-int"))335+ client = AsyncClient(dispatch=MockDigestAuthDispatch(qop="auth-int"))336 337 with pytest.raises(NotImplementedError):338 await client.get(url, auth=auth)339 1 unmodified line341 @pytest.mark.asyncio342 async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:343 url = "https://example.org/"344 auth = DigestAuth(username="tomchristie", password="password123")343- client = Client(dispatch=MockDigestAuthDispatch(qop="not-auth"))345+ client = AsyncClient(dispatch=MockDigestAuthDispatch(qop="not-auth"))346 347 with pytest.raises(ProtocolError):348 await client.get(url, auth=auth)349 2 unmodified lines352 async def test_digest_auth_incorrect_credentials() -> None:353 url = "https://example.org/"354 auth = DigestAuth(username="tomchristie", password="password123")355 354- client = Client(dispatch=MockDigestAuthDispatch(send_response_after_attempt=2))356+ client = AsyncClient(dispatch=MockDigestAuthDispatch(send_response_after_attempt=2))357 response = await client.get(url, auth=auth)358 359 assert response.status_code == 401360 13 unmodified lines374 auth_header: str,375 ) -> None:376 url = "https://example.org/"377 auth = DigestAuth(username="tomchristie", password="password123")376- client = Client(dispatch=MockDispatch(auth_header=auth_header, status_code=401))378+ client = AsyncClient(379+ dispatch=MockDispatch(auth_header=auth_header, status_code=401)380+ )381 382 with pytest.raises(ProtocolError):383 await client.get(url, auth=auth)modified:tests/client/test_client.py+17 added-17 removed
6 unmodified lines7 8 @pytest.mark.asyncio9 async def test_get(server):10 url = server.url11- async with httpx.Client() as http:11+ async with httpx.AsyncClient() as http:12 response = await http.get(url)13 assert response.status_code == 20014 assert response.url == url15 assert response.content == b"Hello, world!"11 unmodified lines27 async def test_build_request(server):28 url = server.url.copy_with(path="/echo_headers")29 headers = {"Custom-header": "value"}30 31- async with httpx.Client() as client:31+ async with httpx.AsyncClient() as client:32 request = client.build_request("GET", url)33 request.headers.update(headers)34 response = await client.send(request)35 4 unmodified lines40 41 42 @pytest.mark.asyncio43 async def test_post(server):44- async with httpx.Client() as client:44+ async with httpx.AsyncClient() as client:45 response = await client.post(server.url, data=b"Hello, world!")46 assert response.status_code == 20047 assert response.reason_phrase == "OK"48 49 50 @pytest.mark.asyncio51 async def test_post_json(server):52- async with httpx.Client() as client:52+ async with httpx.AsyncClient() as client:53 response = await client.post(server.url, json={"text": "Hello, world!"})54 assert response.status_code == 20055 assert response.reason_phrase == "OK"56 57 58 @pytest.mark.asyncio59 async def test_stream_response(server):60- async with httpx.Client() as client:60+ async with httpx.AsyncClient() as client:61 async with client.stream("GET", server.url) as response:62 content = await response.aread()63 assert response.status_code == 20064 assert content == b"Hello, world!"2 unmodified lines67 @pytest.mark.asyncio68 async def test_stream_iterator(server):69 body = b""70 71- async with httpx.Client() as client:71+ async with httpx.AsyncClient() as client:72 async with client.stream("GET", server.url) as response:73 async for chunk in response.aiter_bytes():74 body += chunk75 4 unmodified lines80 @pytest.mark.asyncio81 async def test_raw_iterator(server):82 body = b""83 84- async with httpx.Client() as client:84+ async with httpx.AsyncClient() as client:85 async with client.stream("GET", server.url) as response:86 async for chunk in response.aiter_raw():87 body += chunk88 2 unmodified lines91 92 93 @pytest.mark.asyncio94 async def test_raise_for_status(server):95- async with httpx.Client() as client:95+ async with httpx.AsyncClient() as client:96 for status_code in (200, 400, 404, 500, 505):97 response = await client.request(98 "GET", server.url.copy_with(path="/status/{}".format(status_code))99 )6 unmodified lines106 107 108 @pytest.mark.asyncio109 async def test_options(server):110- async with httpx.Client() as client:110+ async with httpx.AsyncClient() as client:111 response = await client.options(server.url)112 assert response.status_code == 200113 assert response.reason_phrase == "OK"114 115 116 @pytest.mark.asyncio117 async def test_head(server):118- async with httpx.Client() as client:118+ async with httpx.AsyncClient() as client:119 response = await client.head(server.url)120 assert response.status_code == 200121 assert response.reason_phrase == "OK"122 123 124 @pytest.mark.asyncio125 async def test_put(server):126- async with httpx.Client() as client:126+ async with httpx.AsyncClient() as client:127 response = await client.put(server.url, data=b"Hello, world!")128 assert response.status_code == 200129 assert response.reason_phrase == "OK"130 131 132 @pytest.mark.asyncio133 async def test_patch(server):134- async with httpx.Client() as client:134+ async with httpx.AsyncClient() as client:135 response = await client.patch(server.url, data=b"Hello, world!")136 assert response.status_code == 200137 assert response.reason_phrase == "OK"138 139 140 @pytest.mark.asyncio141 async def test_delete(server):142- async with httpx.Client() as client:142+ async with httpx.AsyncClient() as client:143 response = await client.delete(server.url)144 assert response.status_code == 200145 assert response.reason_phrase == "OK"146 147 148 @pytest.mark.asyncio149 async def test_base_url(server):150 base_url = server.url151- async with httpx.Client(base_url=base_url) as client:151+ async with httpx.AsyncClient(base_url=base_url) as client:152 response = await client.get("/")153 assert response.status_code == 200154 assert response.url == base_url155 2 unmodified lines158 async def test_uds(uds_server):159 url = uds_server.url160 uds = uds_server.config.uds161 assert uds is not None162- async with httpx.Client(uds=uds) as client:162+ async with httpx.AsyncClient(uds=uds) as client:163 response = await client.get(url)164 assert response.status_code == 200165 assert response.text == "Hello, world!"166 assert response.encoding == "iso-8859-1"167 168 169 def test_merge_url():170- client = httpx.Client(base_url="https://www.paypal.com/")170+ client = httpx.AsyncClient(base_url="https://www.paypal.com/")171 url = client.merge_url("http://www.paypal.com")172 173 assert url.scheme == "https"174 assert url.is_ssl1 unmodified line176 177 @pytest.mark.asyncio178 async def test_elapsed_delay(server):179 url = server.url.copy_with(path="/slow_response/100")180- async with httpx.Client() as client:180+ async with httpx.AsyncClient() as client:181 response = await client.get(url)182 assert response.elapsed.total_seconds() > 0.0modified:tests/client/test_cookies.py+7 added-7 removed
1 unmodified line2 from http.cookiejar import Cookie, CookieJar3 4 import pytest5 6-from httpx import Client, Cookies, Request, Response6+from httpx import AsyncClient, Cookies, Request, Response7 from httpx.config import CertTypes, TimeoutTypes, VerifyTypes8 from httpx.dispatch.base import Dispatcher9 10 22 unmodified lines33 """34 url = "http://example.org/echo_cookies"35 cookies = {"example-name": "example-value"}36 37- client = Client(dispatch=MockDispatch())37+ client = AsyncClient(dispatch=MockDispatch())38 response = await client.get(url, cookies=cookies)39 40 assert response.status_code == 20041 assert response.json() == {"cookies": "example-name=example-value"}27 unmodified lines69 rfc2109=False,70 )71 cookies.set_cookie(cookie)72 73- client = Client(dispatch=MockDispatch())73+ client = AsyncClient(dispatch=MockDispatch())74 response = await client.get(url, cookies=cookies)75 76 assert response.status_code == 20077 assert response.json() == {"cookies": "example-name=example-value"}27 unmodified lines105 rfc2109=False,106 )107 cookies.set_cookie(cookie)108 109- client = Client(dispatch=MockDispatch())109+ client = AsyncClient(dispatch=MockDispatch())110 client.cookies = cookies # type: ignore111 response = await client.get(url)112 113 assert response.status_code == 2009 unmodified lines123 url = "http://example.org/echo_cookies"124 cookies = Cookies()125 cookies["example-name"] = "example-value"126 127- client = Client(dispatch=MockDispatch())127+ client = AsyncClient(dispatch=MockDispatch())128 response = await client.get(url, cookies=cookies)129 130 assert response.status_code == 200131 assert response.json() == {"cookies": "example-name=example-value"}2 unmodified lines134 @pytest.mark.asyncio135 async def test_get_cookie() -> None:136 url = "http://example.org/set_cookie"137 138- client = Client(dispatch=MockDispatch())138+ client = AsyncClient(dispatch=MockDispatch())139 response = await client.get(url)140 141 assert response.status_code == 200142 assert response.cookies["example-name"] == "example-value"4 unmodified lines147 async def test_cookie_persistence() -> None:148 """149 Ensure that Client instances persist cookies between requests.150 """151- client = Client(dispatch=MockDispatch())151+ client = AsyncClient(dispatch=MockDispatch())152 153 response = await client.get("http://example.org/echo_cookies")154 assert response.status_code == 200155 assert response.json() == {"cookies": None}9 unmodified linesmodified:tests/client/test_headers.py+7 added-7 removed
2 unmodified lines3 import json4 5 import pytest6 7-from httpx import Client, Headers, Request, Response, __version__7+from httpx import AsyncClient, Headers, Request, Response, __version__8 from httpx.config import CertTypes, TimeoutTypes, VerifyTypes9 from httpx.dispatch.base import Dispatcher10 11 18 unmodified lines30 """31 url = "http://example.org/echo_headers"32 headers = {"Example-Header": "example-value"}33 34- client = Client(dispatch=MockDispatch(), headers=headers)34+ client = AsyncClient(dispatch=MockDispatch(), headers=headers)35 response = await client.get(url)36 37 assert response.status_code == 20038 assert response.json() == {12 unmodified lines51 async def test_header_merge():52 url = "http://example.org/echo_headers"53 client_headers = {"User-Agent": "python-myclient/0.2.1"}54 request_headers = {"X-Auth-Token": "FooBarBazToken"}55- client = Client(dispatch=MockDispatch(), headers=client_headers)55+ client = AsyncClient(dispatch=MockDispatch(), headers=client_headers)56 response = await client.get(url, headers=request_headers)57 58 assert response.status_code == 20059 assert response.json() == {12 unmodified lines72 async def test_header_merge_conflicting_headers():73 url = "http://example.org/echo_headers"74 client_headers = {"X-Auth-Token": "FooBar"}75 request_headers = {"X-Auth-Token": "BazToken"}76- client = Client(dispatch=MockDispatch(), headers=client_headers)76+ client = AsyncClient(dispatch=MockDispatch(), headers=client_headers)77 response = await client.get(url, headers=request_headers)78 79 assert response.status_code == 20080 assert response.json() == {10 unmodified lines91 92 @pytest.mark.asyncio93 async def test_header_update():94 url = "http://example.org/echo_headers"95- client = Client(dispatch=MockDispatch())95+ client = AsyncClient(dispatch=MockDispatch())96 first_response = await client.get(url)97 client.headers.update(98 {"User-Agent": "python-myclient/0.2.1", "Another-Header": "AThing"}99 )37 unmodified lines137 be present.138 """139 url = "http://username:password@example.org:80/echo_headers"140 141- client = Client(dispatch=MockDispatch())141+ client = AsyncClient(dispatch=MockDispatch())142 response = await client.get(url)143 144 assert response.status_code == 200145 assert response.json() == {15 unmodified lines161 the Host header.162 """163 url = "http://username:password@example.org:123/echo_headers"164 165- client = Client(dispatch=MockDispatch())165+ client = AsyncClient(dispatch=MockDispatch())166 response = await client.get(url)167 168 assert response.status_code == 200169 assert response.json() == {9 unmodified linesmodified:tests/client/test_properties.py+3 added-3 removed
1-from httpx import Client, Cookies, Headers1+from httpx import AsyncClient, Cookies, Headers2 3 4 def test_client_headers():5- client = Client()5+ client = AsyncClient()6 client.headers = {"a": "b"}7 assert isinstance(client.headers, Headers)8 assert client.headers["A"] == "b"9 10 11 def test_client_cookies():12- client = Client()12+ client = AsyncClient()13 client.cookies = {"a": "b"}14 assert isinstance(client.cookies, Cookies)15 mycookies = list(client.cookies.jar)16 assert len(mycookies) == 11 unmodified linemodified:tests/client/test_proxies.py+4 added-4 removed
18 unmodified lines19 ),20 ],21 )22 def test_proxies_parameter(proxies, expected_proxies):23- client = httpx.Client(proxies=proxies)23+ client = httpx.AsyncClient(proxies=proxies)24 25 for proxy_key, url in expected_proxies:26 assert proxy_key in client.proxies27 assert client.proxies[proxy_key].proxy_url == url1 unmodified line29 assert len(expected_proxies) == len(client.proxies)30 31 32 def test_proxies_has_same_properties_as_dispatch():33- client = httpx.Client(33+ client = httpx.AsyncClient(34 proxies="http://127.0.0.1",35 verify="/path/to/verify",36 cert="/path/to/cert",37 trust_env=False,57 unmodified lines95 ),96 ],97 )98 def test_dispatcher_for_request(url, proxies, expected):99- client = httpx.Client(proxies=proxies)99+ client = httpx.AsyncClient(proxies=proxies)100 dispatcher = client.dispatcher_for_url(httpx.URL(url))101 102 if expected is None:103 assert dispatcher is client.dispatch3 unmodified lines107 108 109 def test_unsupported_proxy_scheme():110 with pytest.raises(ValueError):111- httpx.Client(proxies="ftp://127.0.0.1")111+ httpx.AsyncClient(proxies="ftp://127.0.0.1")modified:tests/client/test_queryparams.py+5 added-5 removed
1 import json2 3 import pytest4 5-from httpx import URL, Client, QueryParams, Request, Response5+from httpx import URL, AsyncClient, QueryParams, Request, Response6 from httpx.config import CertTypes, TimeoutTypes, VerifyTypes7 from httpx.dispatch.base import Dispatcher8 9 10 unmodified lines20 return Response(200, content=body, request=request)21 22 23 def test_client_queryparams():24- client = Client(params={"a": "b"})24+ client = AsyncClient(params={"a": "b"})25 assert isinstance(client.params, QueryParams)26 assert client.params["a"] == "b"27 28 29 def test_client_queryparams_string():30- client = Client(params="a=b")30+ client = AsyncClient(params="a=b")31 assert isinstance(client.params, QueryParams)32 assert client.params["a"] == "b"33 34- client = Client()34+ client = AsyncClient()35 client.params = "a=b"36 assert isinstance(client.params, QueryParams)37 assert client.params["a"] == "b"38 2 unmodified lines41 async def test_client_queryparams_echo():42 url = "http://example.org/echo_queryparams"43 client_queryparams = "first=str"44 request_queryparams = {"second": "dict"}45- client = Client(dispatch=MockDispatch(), params=client_queryparams)45+ client = AsyncClient(dispatch=MockDispatch(), params=client_queryparams)46 response = await client.get(url, params=request_queryparams)47 48 assert response.status_code == 20049 assert response.url == URL(2 unmodified linesmodified:tests/client/test_redirects.py+21 added-21 removed
3 unmodified lines4 import pytest5 6 from httpx import (7 URL,8- Client,8+ AsyncClient,9 NotRedirectResponse,10 RedirectBodyUnavailable,11 RedirectLoop,12 Request,91 unmodified lines104 105 106 @pytest.mark.usefixtures("async_environment")107 async def test_no_redirect():108- client = Client(dispatch=MockDispatch())108+ client = AsyncClient(dispatch=MockDispatch())109 url = "https://example.com/no_redirect"110 response = await client.get(url)111 assert response.status_code == 200112 with pytest.raises(NotRedirectResponse):1 unmodified line114 115 116 @pytest.mark.usefixtures("async_environment")117 async def test_redirect_301():118- client = Client(dispatch=MockDispatch())118+ client = AsyncClient(dispatch=MockDispatch())119 response = await client.post("https://example.org/redirect_301")120 assert response.status_code == codes.OK121 assert response.url == URL("https://example.org/")122 assert len(response.history) == 1123 124 125 @pytest.mark.usefixtures("async_environment")126 async def test_redirect_302():127- client = Client(dispatch=MockDispatch())127+ client = AsyncClient(dispatch=MockDispatch())128 response = await client.post("https://example.org/redirect_302")129 assert response.status_code == codes.OK130 assert response.url == URL("https://example.org/")131 assert len(response.history) == 1132 133 134 @pytest.mark.usefixtures("async_environment")135 async def test_redirect_303():136- client = Client(dispatch=MockDispatch())136+ client = AsyncClient(dispatch=MockDispatch())137 response = await client.get("https://example.org/redirect_303")138 assert response.status_code == codes.OK139 assert response.url == URL("https://example.org/")140 assert len(response.history) == 1141 142 143 @pytest.mark.usefixtures("async_environment")144 async def test_disallow_redirects():145- client = Client(dispatch=MockDispatch())145+ client = AsyncClient(dispatch=MockDispatch())146 response = await client.post(147 "https://example.org/redirect_303", allow_redirects=False148 )149 assert response.status_code == codes.SEE_OTHER9 unmodified lines159 160 161 @pytest.mark.usefixtures("async_environment")162 async def test_relative_redirect():163- client = Client(dispatch=MockDispatch())163+ client = AsyncClient(dispatch=MockDispatch())164 response = await client.get("https://example.org/relative_redirect")165 assert response.status_code == codes.OK166 assert response.url == URL("https://example.org/")167 assert len(response.history) == 1168 169 170 @pytest.mark.usefixtures("async_environment")171 async def test_no_scheme_redirect():172- client = Client(dispatch=MockDispatch())172+ client = AsyncClient(dispatch=MockDispatch())173 response = await client.get("https://example.org/no_scheme_redirect")174 assert response.status_code == codes.OK175 assert response.url == URL("https://example.org/")176 assert len(response.history) == 1177 178 179 @pytest.mark.usefixtures("async_environment")180 async def test_fragment_redirect():181- client = Client(dispatch=MockDispatch())181+ client = AsyncClient(dispatch=MockDispatch())182 response = await client.get("https://example.org/relative_redirect#fragment")183 assert response.status_code == codes.OK184 assert response.url == URL("https://example.org/#fragment")185 assert len(response.history) == 1186 187 188 @pytest.mark.usefixtures("async_environment")189 async def test_multiple_redirects():190- client = Client(dispatch=MockDispatch())190+ client = AsyncClient(dispatch=MockDispatch())191 response = await client.get("https://example.org/multiple_redirects?count=20")192 assert response.status_code == codes.OK193 assert response.url == URL("https://example.org/multiple_redirects")194 assert len(response.history) == 208 unmodified lines203 204 205 @pytest.mark.usefixtures("async_environment")206 async def test_too_many_redirects():207- client = Client(dispatch=MockDispatch())207+ client = AsyncClient(dispatch=MockDispatch())208 with pytest.raises(TooManyRedirects):209 await client.get("https://example.org/multiple_redirects?count=21")210 211 212 @pytest.mark.usefixtures("async_environment")213 async def test_too_many_redirects_calling_next():214- client = Client(dispatch=MockDispatch())214+ client = AsyncClient(dispatch=MockDispatch())215 url = "https://example.org/multiple_redirects?count=21"216 response = await client.get(url, allow_redirects=False)217 with pytest.raises(TooManyRedirects):218 while response.is_redirect:1 unmodified line220 221 222 @pytest.mark.usefixtures("async_environment")223 async def test_redirect_loop():224- client = Client(dispatch=MockDispatch())224+ client = AsyncClient(dispatch=MockDispatch())225 with pytest.raises(RedirectLoop):226 await client.get("https://example.org/redirect_loop")227 228 229 @pytest.mark.usefixtures("async_environment")230 async def test_redirect_loop_calling_next():231- client = Client(dispatch=MockDispatch())231+ client = AsyncClient(dispatch=MockDispatch())232 url = "https://example.org/redirect_loop"233 response = await client.get(url, allow_redirects=False)234 with pytest.raises(RedirectLoop):235 while response.is_redirect:1 unmodified line237 238 239 @pytest.mark.usefixtures("async_environment")240 async def test_cross_domain_redirect():241- client = Client(dispatch=MockDispatch())241+ client = AsyncClient(dispatch=MockDispatch())242 url = "https://example.com/cross_domain"243 headers = {"Authorization": "abc"}244 response = await client.get(url, headers=headers)245 assert response.url == URL("https://example.org/cross_domain_target")1 unmodified line247 248 249 @pytest.mark.usefixtures("async_environment")250 async def test_same_domain_redirect():251- client = Client(dispatch=MockDispatch())251+ client = AsyncClient(dispatch=MockDispatch())252 url = "https://example.org/cross_domain"253 headers = {"Authorization": "abc"}254 response = await client.get(url, headers=headers)255 assert response.url == URL("https://example.org/cross_domain_target")4 unmodified lines260 async def test_body_redirect():261 """262 A 308 redirect should preserve the request body.263 """264- client = Client(dispatch=MockDispatch())264+ client = AsyncClient(dispatch=MockDispatch())265 url = "https://example.org/redirect_body"266 data = b"Example request body"267 response = await client.post(url, data=data)268 assert response.url == URL("https://example.org/redirect_body_target")5 unmodified lines274 async def test_no_body_redirect():275 """276 A 303 redirect should remove the request body.277 """278- client = Client(dispatch=MockDispatch())278+ client = AsyncClient(dispatch=MockDispatch())279 url = "https://example.org/redirect_no_body"280 data = b"Example request body"281 response = await client.post(url, data=data)282 assert response.url == URL("https://example.org/redirect_body_target")2 unmodified lines285 286 287 @pytest.mark.usefixtures("async_environment")288 async def test_cannot_redirect_streaming_body():289- client = Client(dispatch=MockDispatch())289+ client = AsyncClient(dispatch=MockDispatch())290 url = "https://example.org/redirect_body"291 292 async def streaming_body():293 yield b"Example request body"3 unmodified lines297 298 299 @pytest.mark.usefixtures("async_environment")300 async def test_cross_subdomain_redirect():301- client = Client(dispatch=MockDispatch())301+ client = AsyncClient(dispatch=MockDispatch())302 url = "https://example.com/cross_subdomain"303 response = await client.get(url)304 assert response.url == URL("https://www.example.org/cross_subdomain")305 38 unmodified lines344 345 346 @pytest.mark.usefixtures("async_environment")347 async def test_redirect_cookie_behavior():348- client = Client(dispatch=MockCookieDispatch())348+ client = AsyncClient(dispatch=MockCookieDispatch())349 350 # The client is not logged in.351 response = await client.get("https://example.com/")352 assert response.url == "https://example.com/"21 unmodified linesmodified:tests/dispatch/test_http2.py+8 added-8 removed
4 unmodified lines5 import h2.events6 import pytest7 from h2.settings import SettingCodes8 9-from httpx import Client, Response, TimeoutException9+from httpx import AsyncClient, Response, TimeoutException10 11 from .utils import MockHTTP2Backend12 13 11 unmodified lines25 @pytest.mark.asyncio26 async def test_http2_get_request():27 backend = MockHTTP2Backend(app=app)28 29- async with Client(backend=backend, http2=True) as client:29+ async with AsyncClient(backend=backend, http2=True) as client:30 response = await client.get("http://example.org")31 32 assert response.status_code == 20033 assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}2 unmodified lines36 @pytest.mark.asyncio37 async def test_http2_post_request():38 backend = MockHTTP2Backend(app=app)39 40- async with Client(backend=backend, http2=True) as client:40+ async with AsyncClient(backend=backend, http2=True) as client:41 response = await client.post("http://example.org", data=b"<data>")42 43 assert response.status_code == 20044 assert json.loads(response.content) == {7 unmodified lines52 async def test_http2_large_post_request():53 backend = MockHTTP2Backend(app=app)54 55 data = b"a" * 10000056- async with Client(backend=backend, http2=True) as client:56+ async with AsyncClient(backend=backend, http2=True) as client:57 response = await client.post("http://example.org", data=data)58 assert response.status_code == 20059 assert json.loads(response.content) == {60 "method": "POST",5 unmodified lines66 @pytest.mark.asyncio67 async def test_http2_multiple_requests():68 backend = MockHTTP2Backend(app=app)69 70- async with Client(backend=backend, http2=True) as client:70+ async with AsyncClient(backend=backend, http2=True) as client:71 response_1 = await client.get("http://example.org/1")72 response_2 = await client.get("http://example.org/2")73 response_3 = await client.get("http://example.org/3")74 14 unmodified lines89 be seemlessly reconnected.90 """91 backend = MockHTTP2Backend(app=app)92 93- async with Client(backend=backend, http2=True) as client:93+ async with AsyncClient(backend=backend, http2=True) as client:94 response_1 = await client.get("http://example.org/1")95 backend.server.close_connection = True96 response_2 = await client.get("http://example.org/2")97 7 unmodified lines105 @pytest.mark.asyncio106 async def test_http2_settings_in_handshake():107 backend = MockHTTP2Backend(app=app)108 109- async with Client(backend=backend, http2=True) as client:109+ async with AsyncClient(backend=backend, http2=True) as client:110 await client.get("http://example.org")111 112 h2_conn = backend.server.conn113 25 unmodified lines139 140 141 @pytest.mark.usefixtures("async_environment")142 async def test_http2_live_request():143- async with Client(http2=True) as client:143+ async with AsyncClient(http2=True) as client:144 try:145 resp = await client.get("https://nghttp2.org/httpbin/anything")146 except TimeoutException:147 pytest.xfail(reason="nghttp2.org appears to be unresponsive")4 unmodified linesmodified:tests/test_asgi.py+4 added-4 removed
39 unmodified lines40 41 42 @pytest.mark.asyncio43 async def test_asgi():44- client = httpx.Client(app=hello_world)44+ client = httpx.AsyncClient(app=hello_world)45 response = await client.get("http://www.example.org/")46 assert response.status_code == 20047 assert response.text == "Hello, World!"48 49 50 @pytest.mark.asyncio51 async def test_asgi_upload():52- client = httpx.Client(app=echo_body)52+ client = httpx.AsyncClient(app=echo_body)53 response = await client.post("http://www.example.org/", data=b"example")54 assert response.status_code == 20055 assert response.text == "example"56 57 58 @pytest.mark.asyncio59 async def test_asgi_exc():60- client = httpx.Client(app=raise_exc)60+ client = httpx.AsyncClient(app=raise_exc)61 with pytest.raises(ValueError):62 await client.get("http://www.example.org/")63 64 65 @pytest.mark.asyncio66 async def test_asgi_exc_after_response():67- client = httpx.Client(app=raise_exc_after_response)67+ client = httpx.AsyncClient(app=raise_exc_after_response)68 with pytest.raises(ValueError):69 await client.get("http://www.example.org/")modified:tests/test_multipart.py+4 added-4 removed
26 unmodified lines27 28 @pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))29 @pytest.mark.asyncio30 async def test_multipart(value, output):31- client = httpx.Client(dispatch=MockDispatch())31+ client = httpx.AsyncClient(dispatch=MockDispatch())32 33 # Test with a single-value 'data' argument, and a plain file 'files' argument.34 data = {"text": value}35 files = {"file": io.BytesIO(b"<file content>")}15 unmodified lines51 52 @pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))53 @pytest.mark.asyncio54 async def test_multipart_invalid_key(key):55- client = httpx.Client(dispatch=MockDispatch())55+ client = httpx.AsyncClient(dispatch=MockDispatch())56 data = {key: "abc"}57 files = {"file": io.BytesIO(b"<file content>")}58 with pytest.raises(TypeError) as e:59 await client.post("http://127.0.0.1:8000/", data=data, files=files)2 unmodified lines62 63 @pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))64 @pytest.mark.asyncio65 async def test_multipart_invalid_value(value):66- client = httpx.Client(dispatch=MockDispatch())66+ client = httpx.AsyncClient(dispatch=MockDispatch())67 data = {"text": value}68 files = {"file": io.BytesIO(b"<file content>")}69 with pytest.raises(TypeError) as e:70 await client.post("http://127.0.0.1:8000/", data=data, files=files)1 unmodified line72 73 74 @pytest.mark.asyncio75 async def test_multipart_file_tuple():76- client = httpx.Client(dispatch=MockDispatch())76+ client = httpx.AsyncClient(dispatch=MockDispatch())77 78 # Test with a list of values 'data' argument, and a tuple style 'files' argument.79 data = {"text": ["abc"]}80 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}121 unmodified linesmodified:tests/test_timeouts.py+4 added-4 removed
5 unmodified lines6 @pytest.mark.usefixtures("async_environment")7 async def test_read_timeout(server):8 timeout = httpx.Timeout(read_timeout=1e-6)9 10- async with httpx.Client(timeout=timeout) as client:10+ async with httpx.AsyncClient(timeout=timeout) as client:11 with pytest.raises(httpx.ReadTimeout):12 await client.get(server.url.copy_with(path="/slow_response"))13 14 15 @pytest.mark.usefixtures("async_environment")16 async def test_write_timeout(server):17 timeout = httpx.Timeout(write_timeout=1e-6)18 19- async with httpx.Client(timeout=timeout) as client:19+ async with httpx.AsyncClient(timeout=timeout) as client:20 with pytest.raises(httpx.WriteTimeout):21 data = b"*" * 1024 * 1024 * 10022 await client.put(server.url.copy_with(path="/slow_response"), data=data)23 1 unmodified line25 @pytest.mark.usefixtures("async_environment")26 async def test_connect_timeout(server):27 timeout = httpx.Timeout(connect_timeout=1e-6)28 29- async with httpx.Client(timeout=timeout) as client:29+ async with httpx.AsyncClient(timeout=timeout) as client:30 with pytest.raises(httpx.ConnectTimeout):31 # See https://stackoverflow.com/questions/100841/32 await client.get("http://10.255.255.1/")33 2 unmodified lines36 async def test_pool_timeout(server):37 pool_limits = httpx.PoolLimits(hard_limit=1)38 timeout = httpx.Timeout(pool_timeout=1e-4)39 40- async with httpx.Client(pool_limits=pool_limits, timeout=timeout) as client:40+ async with httpx.AsyncClient(pool_limits=pool_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/")modified:tests/test_utils.py+3 added-3 removed
91 unmodified lines92 93 @pytest.mark.asyncio94 async def test_logs_debug(server, capsys):95 with override_log_level("debug"):96- async with httpx.Client() as client:96+ async with httpx.AsyncClient() as client:97 response = await client.get(server.url)98 assert response.status_code == 20099 stderr = capsys.readouterr().err100 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr2 unmodified lines103 104 @pytest.mark.asyncio105 async def test_logs_trace(server, capsys):106 with override_log_level("trace"):107- async with httpx.Client() as client:107+ async with httpx.AsyncClient() as client:108 response = await client.get(server.url)109 assert response.status_code == 200110 stderr = capsys.readouterr().err111 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr2 unmodified lines114 115 @pytest.mark.asyncio116 async def test_logs_redirect_chain(server, capsys):117 with override_log_level("debug"):118- async with httpx.Client() as client:118+ async with httpx.AsyncClient() as client:119 response = await client.get(server.url.copy_with(path="/redirect_301"))120 assert response.status_code == 200121 122 stderr = capsys.readouterr().err.strip()165 unmodified lines