Skip to content
Myr

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

24 files+189 added−174 removed

modified:docs/advanced.md+32 added-27 removed
7 unmodified lines
89!!! hint10 A Client instance is equivalent to a Session instance in `requests`.1112!!! 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.1415 A `Client` synonym remains for compatibility with `httpx==0.9.*` releases, but you are encouraged to migrate to `AsyncClient` as soon as possible.1617### Usage1819The 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:2021```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 line
2829Alternatively, you can explicitly close the connection pool without block-usage using `.aclose()`:3031```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 lines
4950```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 lines
6263 - For headers, query parameters and cookies, the values are merged into one.64 - For all other parameters, the request-level value is used.6561Additionally, `Client` constructor accepts some parameters that aren't available at the request level.66Additionally, `Client` accepts some parameters that aren't available at the request level.6768One particularly useful parameter is `base_url`, which allows you to define a base URL to prepend to all outgoing requests:6970```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.url75URL('http://httpbin.org/headers')76```7773For a list of all available client-level parameters, see the [`Client` API reference](/api/#client).78For a list of all available client-level parameters, see the [`AsyncClient` API reference](/api/#async-client).7980## Calling into Python Web Apps8182You can configure an `httpx` client to call directly into a Python web
22 unmodified lines
105We can make requests directly against the application, like so:106107```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 lines
123```python124# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",125# on port 123.126dispatch = httpx.dispatch.ASGIDispatch(app=app, client=("1.2.3.4", 123))122async with httpx.Client(dispatch=dispatch) as client:127async with httpx.AsyncClient(dispatch=dispatch) as client:128 ...129```130131See [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 lines
136You can use `Client.build_request()` to build a request and137make modifications before sending the request.138139```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 lines
181182When using `Client` instances, `trust_env` should be set on the client itself, rather that on the request methods:183184```python180client = httpx.Client(trust_env=False)185client = httpx.AsyncClient(trust_env=False)186```187188## Unix Domain Sockets189
4 unmodified lines
194```python195import httpx196197193async with httpx.Client(uds="/var/run/docker.sock") as client:198async 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 lines
210>>> 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```217218Proxies can be configured for a specific scheme and host, all schemes of a host,
6 unmodified lines
225... "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```236237!!! warning
11 unmodified lines
249proxy = 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)248async with httpx.Client(proxies=proxy) as client:253async 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 lines
276# Using the top-level API:277await httpx.get('http://example.com/api/v1/example', timeout=10.0)278279# Using a client instance:275async with httpx.Client() as client:280async with httpx.AsyncClient() as client:281 await client.get("http://example.com/api/v1/example", timeout=10.0)282```283284Or disable timeouts for an individual request:
2 unmodified lines
287# Using the top-level API:288await httpx.get('http://example.com/api/v1/example', timeout=None)289290# Using a client instance:286async with httpx.Client() as client:291async with httpx.AsyncClient() as client:292 await client.get("http://example.com/api/v1/example", timeout=None)293```294295### Setting a default timeout on a client
1 unmodified line
297You 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:299300```python296client = httpx.Client() # Use a default 5s timeout everywhere.297client = httpx.Client(timeout=10.0) # Use a default 10s timeout everywhere.298client = httpx.Client(timeout=None) # Disable all timeouts by default.301client = httpx.AsyncClient() # Use a default 5s timeout everywhere.302client = httpx.AsyncClient(timeout=10.0) # Use a default 10s timeout everywhere.303client = httpx.AsyncClient(timeout=None) # Disable all timeouts by default.304```305306### Fine tuning the configuration307
21 unmodified lines
329330```python331# A client with a 60s timeout for connecting, and a 10s timeout elsewhere.332timeout = httpx.Timeout(10.0, connect_timeout=60.0)328client = httpx.Client(timeout=timeout)333client = httpx.AsyncClient(timeout=timeout)334335response = await client.get('http://example.com/')336```337
70 unmodified lines
408409If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.410411```python407client = httpx.Client(verify=False)412client = httpx.AsyncClient(verify=False)413```414415The `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 lines
441You can also explicitly select a backend by instantiating a client with the442`backend` argument...443444```python440client = httpx.Client(backend='auto') # Autodetection. The default case.441client = httpx.Client(backend='asyncio') # Use asyncio as the backend.442client = httpx.Client(backend='trio') # Use trio as the backend.445client = httpx.AsyncClient(backend='auto') # Autodetection. The default case.446client = httpx.AsyncClient(backend='asyncio') # Use asyncio as the backend.447client = httpx.AsyncClient(backend='trio') # Use trio as the backend.448```449450### [AsyncIO](https://docs.python.org/3/library/asyncio.html)451
4 unmodified lines
456import asyncio457import httpx458459async def main():455 client = httpx.Client()460 client = httpx.AsyncClient()461 response = await client.get('https://www.example.com/')462 print(response)463464asyncio.run(main())
8 unmodified lines
473import httpx474import trio475476async def main():472 client = httpx.Client()477 client = httpx.AsyncClient()478 response = await client.get('https://www.example.com/')479 print(response)480481trio.run(main)
4 unmodified lines
modified:docs/api.md+2 added-2 removed
modified:docs/compatibility.md+2 added-2 removed
50 unmodified lines
51We 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:`.5253## Client instances5455The HTTPX equivalent of `requests.Session` is `httpx.Client`.55The HTTPX equivalent of `requests.Session` is `httpx.AsyncClient`.5657```python58session = requests.Session(**kwargs)59```6061is generally equivalent to6263```python64client = httpx.Client(**kwargs)64client = httpx.AsyncClient(**kwargs)65```6667## Mocking68
1 unmodified line
modified:docs/environment_variables.md+3 added-3 removed
2 unmodified lines
34The HTTPX library can be configured via environment variables.5Environment 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:67* 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)`.910Here is a list of environment variables that HTTPX recognizes and what function they serve:11
11 unmodified lines
23```python24# test_script.py25import httpx2627with httpx.Client() as client:27with httpx.AsyncClient() as client:28 r = client.get("https://google.com")29```3031Debug output:
56 unmodified lines
88```python89# test_script.py90import httpx9192with httpx.Client() as client:92with httpx.AsyncClient() as client:93 r = client.get("https://google.com")94```9596```console
58 unmodified lines
modified:docs/http2.md+3 added-3 removed
28 unmodified lines
29trying out our HTTP/2 support. You can do so by instantiating a client with30HTTP/2 support enabled:3132```python33client = httpx.Client(http2=True)33client = httpx.AsyncClient(http2=True)34...35```3637You can also instantiate a client as a context manager, to ensure that all38HTTP connections are nicely scoped, and will be closed once the context block39is exited.4041```python42async with httpx.Client(http2=True) as client:42async with httpx.AsyncClient(http2=True) as client:43 ...44```4546## Inspecting the HTTP version
6 unmodified lines
53You can determine which version of the HTTP protocol was used by examining54the `.http_version` property on the response.5556```python57client = httpx.Client(http2=True)57client = httpx.AsyncClient(http2=True)58response = await client.get(...)59print(response.http_version) # "HTTP/1.0", "HTTP/1.1", or "HTTP/2".60```
modified:httpx/dispatch/asgi.py+2 added-2 removed
13 unmodified lines
14 This will automatically infer if 'app' is a WSGI or an ASGI application,15 and will setup an appropriate dispatch class:1617 ```18 client = httpx.Client(app=app)18 client = httpx.AsyncClient(app=app)19 ```2021 Alternatively, you can setup the dispatch instance explicitly.22 This allows you to include any additional configuration arguments specific
4 unmodified lines
27 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 ```3334 Arguments:35
91 unmodified lines
modified:httpx/dispatch/base.py+1 added-1 removed
16 unmodified lines
17 Base class for dispatcher classes, that handle sending the request.1819 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 """2324 async def request(25 self,
50 unmodified lines
modified:httpx/__init__.py+2 added-1 removed
1from .__version__ import __description__, __title__, __version__2from .api import delete, get, head, options, patch, post, put, request, stream3from .auth import BasicAuth, DigestAuth4from .client import Client4from .client import AsyncClient, Client5from .config import TimeoutConfig # For 0.8 backwards compat.6from .config import PoolLimits, Timeout7from .dispatch.proxy_http import HTTPProxy, HTTPProxyMode8from .exceptions import (
34 unmodified lines
43 "put",44 "request",45 "stream",46 "codes",47 "AsyncClient",48 "BasicAuth",49 "Client",50 "DigestAuth",51 "PoolLimits",
35 unmodified lines
modified:httpx/api.py+3 added-3 removed
1import typing23from .auth import AuthTypes4from .client import Client, StreamContextManager4from .client import AsyncClient, StreamContextManager5from .config import DEFAULT_TIMEOUT_CONFIG, CertTypes, TimeoutTypes, VerifyTypes6from .models import (7 CookieTypes,8 HeaderTypes,
71 unmodified lines
80 >>> 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 lines
115 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 lines
modified:httpx/client.py+11 added-6 removed
50 unmodified lines
5152logger = get_logger(__name__)535455class Client:55class 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.5960 Usage:6161 ```62 >>> client = httpx.Client()62 ```python63 >>> client = httpx.AsyncClient()64 >>> response = client.get('https://example.org')65 ```6667 **Parameters:**
800 unmodified lines
868869 async def aclose(self) -> None:870 await self.dispatch.close()871871 async def __aenter__(self) -> "Client":872 async def __aenter__(self) -> "AsyncClient":873 return self874875 async def __aexit__(876 self,
46 unmodified lines
923924class 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 lines
957 ) -> None:958 await self.response.aclose()959 if self.close_client:960 await self.client.aclose()961962963# For compatibility with 0.9.x.964Client = AsyncClient
modified:tests/client/test_async_client.py+16 added-16 removed
6 unmodified lines
78@pytest.mark.usefixtures("async_environment")9async 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 lines
21@pytest.mark.usefixtures("async_environment")22async 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 lines
3536@pytest.mark.usefixtures("async_environment")37async 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 == 200424344@pytest.mark.usefixtures("async_environment")45async 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 == 200505152@pytest.mark.usefixtures("async_environment")53async 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()5758 assert response.status_code == 200
2 unmodified lines
616263@pytest.mark.usefixtures("async_environment")64async 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 pass6869 assert response.status_code == 200
6 unmodified lines
76 async def hello_world():77 yield b"Hello, "78 yield b"world!"7980 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 == 200838485@pytest.mark.usefixtures("async_environment")86async 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 lines
99100101@pytest.mark.usefixtures("async_environment")102async 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!"107108109@pytest.mark.usefixtures("async_environment")110async 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 == ""115116117@pytest.mark.usefixtures("async_environment")118async 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 == 200122123124@pytest.mark.usefixtures("async_environment")125async 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 == 200129130131@pytest.mark.usefixtures("async_environment")132async 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 lines
140async def test_100_continue(server):141 headers = {"Expect": "100-continue"}142 data = b"Echo request body"143144 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 lines
154async 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"163164165async 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 lines
4import typing56import pytest78from httpx import URL, Client, DigestAuth, ProtocolError, Request, Response8from httpx import URL, AsyncClient, DigestAuth, ProtocolError, Request, Response9from httpx.config import CertTypes, TimeoutTypes, VerifyTypes10from httpx.dispatch.base import Dispatcher1112
75 unmodified lines
88async def test_basic_auth() -> None:89 url = "https://example.org/"90 auth = ("tomchristie", "password123")9192 client = Client(dispatch=MockDispatch())92 client = AsyncClient(dispatch=MockDispatch())93 response = await client.get(url, auth=auth)9495 assert response.status_code == 20096 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}
2 unmodified lines
99@pytest.mark.asyncio100async def test_basic_auth_in_url() -> None:101 url = "https://tomchristie:password123@example.org/"102103 client = Client(dispatch=MockDispatch())103 client = AsyncClient(dispatch=MockDispatch())104 response = await client.get(url)105106 assert response.status_code == 200107 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}
3 unmodified lines
111async def test_basic_auth_on_session() -> None:112 url = "https://example.org/"113 auth = ("tomchristie", "password123")114115 client = Client(dispatch=MockDispatch(), auth=auth)115 client = AsyncClient(dispatch=MockDispatch(), auth=auth)116 response = await client.get(url)117118 assert response.status_code == 200119 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}
6 unmodified lines
126 def auth(request: Request) -> Request:127 request.headers["Authorization"] = "Token 123"128 return request129130 client = Client(dispatch=MockDispatch())130 client = AsyncClient(dispatch=MockDispatch())131 response = await client.get(url, auth=auth)132133 assert response.status_code == 200134 assert response.json() == {"auth": "Token 123"}
3 unmodified lines
138async def test_netrc_auth() -> None:139 os.environ["NETRC"] = "tests/.netrc"140 url = "http://netrcexample.org"141142 client = Client(dispatch=MockDispatch())142 client = AsyncClient(dispatch=MockDispatch())143 response = await client.get(url)144145 assert response.status_code == 200146 assert response.json() == {
5 unmodified lines
152async def test_auth_header_has_priority_over_netrc() -> None:153 os.environ["NETRC"] = "tests/.netrc"154 url = "http://netrcexample.org"155156 client = Client(dispatch=MockDispatch())156 client = AsyncClient(dispatch=MockDispatch())157 response = await client.get(url, headers={"Authorization": "Override"})158159 assert response.status_code == 200160 assert response.json() == {"auth": "Override"}
3 unmodified lines
164async def test_trust_env_auth() -> None:165 os.environ["NETRC"] = "tests/.netrc"166 url = "http://netrcexample.org"167168 client = Client(dispatch=MockDispatch(), trust_env=False)168 client = AsyncClient(dispatch=MockDispatch(), trust_env=False)169 response = await client.get(url)170171 assert response.status_code == 200172 assert response.json() == {"auth": None}173174 client = Client(dispatch=MockDispatch(), trust_env=True)174 client = AsyncClient(dispatch=MockDispatch(), trust_env=True)175 response = await client.get(url)176177 assert response.status_code == 200178 assert response.json() == {
12 unmodified lines
191async def test_auth_hidden_header() -> None:192 url = "https://example.org/"193 auth = ("example-username", "example-password")194195 client = Client(dispatch=MockDispatch())195 client = AsyncClient(dispatch=MockDispatch())196 response = await client.get(url, auth=auth)197198 assert "'authorization': '[secure]'" in str(response.request.headers)199200201@pytest.mark.asyncio202async 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 lines
212async 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")215216 client = Client(dispatch=MockDispatch())216 client = AsyncClient(dispatch=MockDispatch())217 response = await client.get(url, auth=auth)218219 assert response.status_code == 200220 assert response.json() == {"auth": None}
4 unmodified lines
225 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"'228229 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)233234 assert response.status_code == 200235 assert response.json() == {"auth": None}
3 unmodified lines
239async def test_digest_auth_401_response_without_digest_auth_header() -> None:240 url = "https://example.org/"241 auth = DigestAuth(username="tomchristie", password="password123")242241 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)245246 assert response.status_code == 401247 assert response.json() == {"auth": None}
18 unmodified lines
266) -> None:267 url = "https://example.org/"268 auth = DigestAuth(username="tomchristie", password="password123")269268 client = Client(dispatch=MockDigestAuthDispatch(algorithm=algorithm))270 client = AsyncClient(dispatch=MockDigestAuthDispatch(algorithm=algorithm))271 response = await client.get(url, auth=auth)272273 assert response.status_code == 200274 authorization = typing.cast(dict, response.json())["auth"]
19 unmodified lines
294async def test_digest_auth_no_specified_qop() -> None:295 url = "https://example.org/"296 auth = DigestAuth(username="tomchristie", password="password123")297296 client = Client(dispatch=MockDigestAuthDispatch(qop=""))298 client = AsyncClient(dispatch=MockDigestAuthDispatch(qop=""))299 response = await client.get(url, auth=auth)300301 assert response.status_code == 200302 authorization = typing.cast(dict, response.json())["auth"]
20 unmodified lines
323async 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")326325 client = Client(dispatch=MockDigestAuthDispatch(qop=qop))327 client = AsyncClient(dispatch=MockDigestAuthDispatch(qop=qop))328 await client.get(url, auth=auth)329330331@pytest.mark.asyncio332async 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"))336337 with pytest.raises(NotImplementedError):338 await client.get(url, auth=auth)339
1 unmodified line
341@pytest.mark.asyncio342async 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"))346347 with pytest.raises(ProtocolError):348 await client.get(url, auth=auth)349
2 unmodified lines
352async def test_digest_auth_incorrect_credentials() -> None:353 url = "https://example.org/"354 auth = DigestAuth(username="tomchristie", password="password123")355354 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)358359 assert response.status_code == 401360
13 unmodified lines
374 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 )381382 with pytest.raises(ProtocolError):383 await client.get(url, auth=auth)
modified:tests/client/test_client.py+17 added-17 removed
6 unmodified lines
78@pytest.mark.asyncio9async 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 lines
27async def test_build_request(server):28 url = server.url.copy_with(path="/echo_headers")29 headers = {"Custom-header": "value"}3031 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 lines
404142@pytest.mark.asyncio43async 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"484950@pytest.mark.asyncio51async 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"565758@pytest.mark.asyncio59async 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 lines
67@pytest.mark.asyncio68async def test_stream_iterator(server):69 body = b""7071 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 lines
80@pytest.mark.asyncio81async def test_raw_iterator(server):82 body = b""8384 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 lines
919293@pytest.mark.asyncio94async 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 lines
106107108@pytest.mark.asyncio109async 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"114115116@pytest.mark.asyncio117async 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"122123124@pytest.mark.asyncio125async 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"130131132@pytest.mark.asyncio133async 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"138139140@pytest.mark.asyncio141async 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"146147148@pytest.mark.asyncio149async 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 lines
158async 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"167168169def 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")172173 assert url.scheme == "https"174 assert url.is_ssl
1 unmodified line
176177@pytest.mark.asyncio178async 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.0
modified:tests/client/test_cookies.py+7 added-7 removed
1 unmodified line
2from http.cookiejar import Cookie, CookieJar34import pytest56from httpx import Client, Cookies, Request, Response6from httpx import AsyncClient, Cookies, Request, Response7from httpx.config import CertTypes, TimeoutTypes, VerifyTypes8from httpx.dispatch.base import Dispatcher910
22 unmodified lines
33 """34 url = "http://example.org/echo_cookies"35 cookies = {"example-name": "example-value"}3637 client = Client(dispatch=MockDispatch())37 client = AsyncClient(dispatch=MockDispatch())38 response = await client.get(url, cookies=cookies)3940 assert response.status_code == 20041 assert response.json() == {"cookies": "example-name=example-value"}
27 unmodified lines
69 rfc2109=False,70 )71 cookies.set_cookie(cookie)7273 client = Client(dispatch=MockDispatch())73 client = AsyncClient(dispatch=MockDispatch())74 response = await client.get(url, cookies=cookies)7576 assert response.status_code == 20077 assert response.json() == {"cookies": "example-name=example-value"}
27 unmodified lines
105 rfc2109=False,106 )107 cookies.set_cookie(cookie)108109 client = Client(dispatch=MockDispatch())109 client = AsyncClient(dispatch=MockDispatch())110 client.cookies = cookies # type: ignore111 response = await client.get(url)112113 assert response.status_code == 200
9 unmodified lines
123 url = "http://example.org/echo_cookies"124 cookies = Cookies()125 cookies["example-name"] = "example-value"126127 client = Client(dispatch=MockDispatch())127 client = AsyncClient(dispatch=MockDispatch())128 response = await client.get(url, cookies=cookies)129130 assert response.status_code == 200131 assert response.json() == {"cookies": "example-name=example-value"}
2 unmodified lines
134@pytest.mark.asyncio135async def test_get_cookie() -> None:136 url = "http://example.org/set_cookie"137138 client = Client(dispatch=MockDispatch())138 client = AsyncClient(dispatch=MockDispatch())139 response = await client.get(url)140141 assert response.status_code == 200142 assert response.cookies["example-name"] == "example-value"
4 unmodified lines
147async 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())152153 response = await client.get("http://example.org/echo_cookies")154 assert response.status_code == 200155 assert response.json() == {"cookies": None}
9 unmodified lines
modified:tests/client/test_headers.py+7 added-7 removed
2 unmodified lines
3import json45import pytest67from httpx import Client, Headers, Request, Response, __version__7from httpx import AsyncClient, Headers, Request, Response, __version__8from httpx.config import CertTypes, TimeoutTypes, VerifyTypes9from httpx.dispatch.base import Dispatcher1011
18 unmodified lines
30 """31 url = "http://example.org/echo_headers"32 headers = {"Example-Header": "example-value"}3334 client = Client(dispatch=MockDispatch(), headers=headers)34 client = AsyncClient(dispatch=MockDispatch(), headers=headers)35 response = await client.get(url)3637 assert response.status_code == 20038 assert response.json() == {
12 unmodified lines
51async 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)5758 assert response.status_code == 20059 assert response.json() == {
12 unmodified lines
72async 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)7879 assert response.status_code == 20080 assert response.json() == {
10 unmodified lines
9192@pytest.mark.asyncio93async 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 lines
137 be present.138 """139 url = "http://username:password@example.org:80/echo_headers"140141 client = Client(dispatch=MockDispatch())141 client = AsyncClient(dispatch=MockDispatch())142 response = await client.get(url)143144 assert response.status_code == 200145 assert response.json() == {
15 unmodified lines
161 the Host header.162 """163 url = "http://username:password@example.org:123/echo_headers"164165 client = Client(dispatch=MockDispatch())165 client = AsyncClient(dispatch=MockDispatch())166 response = await client.get(url)167168 assert response.status_code == 200169 assert response.json() == {
9 unmodified lines
modified:tests/client/test_properties.py+3 added-3 removed
1from httpx import Client, Cookies, Headers1from httpx import AsyncClient, Cookies, Headers234def 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"91011def 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) == 1
1 unmodified line
modified:tests/client/test_proxies.py+4 added-4 removed
18 unmodified lines
19 ),20 ],21)22def test_proxies_parameter(proxies, expected_proxies):23 client = httpx.Client(proxies=proxies)23 client = httpx.AsyncClient(proxies=proxies)2425 for proxy_key, url in expected_proxies:26 assert proxy_key in client.proxies27 assert client.proxies[proxy_key].proxy_url == url
1 unmodified line
29 assert len(expected_proxies) == len(client.proxies)303132def 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 lines
95 ),96 ],97)98def 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))101102 if expected is None:103 assert dispatcher is client.dispatch
3 unmodified lines
107108109def 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
1import json23import pytest45from httpx import URL, Client, QueryParams, Request, Response5from httpx import URL, AsyncClient, QueryParams, Request, Response6from httpx.config import CertTypes, TimeoutTypes, VerifyTypes7from httpx.dispatch.base import Dispatcher89
10 unmodified lines
20 return Response(200, content=body, request=request)212223def 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"272829def 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"3334 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 lines
41async 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)4748 assert response.status_code == 20049 assert response.url == URL(
2 unmodified lines
modified:tests/client/test_redirects.py+21 added-21 removed
3 unmodified lines
4import pytest56from httpx import (7 URL,8 Client,8 AsyncClient,9 NotRedirectResponse,10 RedirectBodyUnavailable,11 RedirectLoop,12 Request,
91 unmodified lines
104105106@pytest.mark.usefixtures("async_environment")107async 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 line
114115116@pytest.mark.usefixtures("async_environment")117async 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) == 1123124125@pytest.mark.usefixtures("async_environment")126async 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) == 1132133134@pytest.mark.usefixtures("async_environment")135async 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) == 1141142143@pytest.mark.usefixtures("async_environment")144async 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_OTHER
9 unmodified lines
159160161@pytest.mark.usefixtures("async_environment")162async 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) == 1168169170@pytest.mark.usefixtures("async_environment")171async 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) == 1177178179@pytest.mark.usefixtures("async_environment")180async 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) == 1186187188@pytest.mark.usefixtures("async_environment")189async 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) == 20
8 unmodified lines
203204205@pytest.mark.usefixtures("async_environment")206async 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")210211212@pytest.mark.usefixtures("async_environment")213async 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 line
220221222@pytest.mark.usefixtures("async_environment")223async 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")227228229@pytest.mark.usefixtures("async_environment")230async 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 line
237238239@pytest.mark.usefixtures("async_environment")240async 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 line
247248249@pytest.mark.usefixtures("async_environment")250async 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 lines
260async 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 lines
274async 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 lines
285286287@pytest.mark.usefixtures("async_environment")288async def test_cannot_redirect_streaming_body():289 client = Client(dispatch=MockDispatch())289 client = AsyncClient(dispatch=MockDispatch())290 url = "https://example.org/redirect_body"291292 async def streaming_body():293 yield b"Example request body"
3 unmodified lines
297298299@pytest.mark.usefixtures("async_environment")300async 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 lines
344345346@pytest.mark.usefixtures("async_environment")347async def test_redirect_cookie_behavior():348 client = Client(dispatch=MockCookieDispatch())348 client = AsyncClient(dispatch=MockCookieDispatch())349350 # The client is not logged in.351 response = await client.get("https://example.com/")352 assert response.url == "https://example.com/"
21 unmodified lines
modified:tests/dispatch/test_http2.py+8 added-8 removed
4 unmodified lines
5import h2.events6import pytest7from h2.settings import SettingCodes89from httpx import Client, Response, TimeoutException9from httpx import AsyncClient, Response, TimeoutException1011from .utils import MockHTTP2Backend1213
11 unmodified lines
25@pytest.mark.asyncio26async def test_http2_get_request():27 backend = MockHTTP2Backend(app=app)2829 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")3132 assert response.status_code == 20033 assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}
2 unmodified lines
36@pytest.mark.asyncio37async def test_http2_post_request():38 backend = MockHTTP2Backend(app=app)3940 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>")4243 assert response.status_code == 20044 assert json.loads(response.content) == {
7 unmodified lines
52async def test_http2_large_post_request():53 backend = MockHTTP2Backend(app=app)5455 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 lines
66@pytest.mark.asyncio67async def test_http2_multiple_requests():68 backend = MockHTTP2Backend(app=app)6970 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 lines
89 be seemlessly reconnected.90 """91 backend = MockHTTP2Backend(app=app)9293 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 lines
105@pytest.mark.asyncio106async def test_http2_settings_in_handshake():107 backend = MockHTTP2Backend(app=app)108109 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")111112 h2_conn = backend.server.conn113
25 unmodified lines
139140141@pytest.mark.usefixtures("async_environment")142async 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 lines
modified:tests/test_asgi.py+4 added-4 removed
39 unmodified lines
404142@pytest.mark.asyncio43async 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!"484950@pytest.mark.asyncio51async 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"565758@pytest.mark.asyncio59async 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/")636465@pytest.mark.asyncio66async 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 lines
2728@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))29@pytest.mark.asyncio30async def test_multipart(value, output):31 client = httpx.Client(dispatch=MockDispatch())31 client = httpx.AsyncClient(dispatch=MockDispatch())3233 # 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 lines
5152@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))53@pytest.mark.asyncio54async 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 lines
6263@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))64@pytest.mark.asyncio65async 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 line
727374@pytest.mark.asyncio75async def test_multipart_file_tuple():76 client = httpx.Client(dispatch=MockDispatch())76 client = httpx.AsyncClient(dispatch=MockDispatch())7778 # 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 lines
modified:tests/test_timeouts.py+4 added-4 removed
5 unmodified lines
6@pytest.mark.usefixtures("async_environment")7async def test_read_timeout(server):8 timeout = httpx.Timeout(read_timeout=1e-6)910 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"))131415@pytest.mark.usefixtures("async_environment")16async def test_write_timeout(server):17 timeout = httpx.Timeout(write_timeout=1e-6)1819 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 line
25@pytest.mark.usefixtures("async_environment")26async def test_connect_timeout(server):27 timeout = httpx.Timeout(connect_timeout=1e-6)2829 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 lines
36async def test_pool_timeout(server):37 pool_limits = httpx.PoolLimits(hard_limit=1)38 timeout = httpx.Timeout(pool_timeout=1e-4)3940 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 lines
9293@pytest.mark.asyncio94async 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 stderr
2 unmodified lines
103104@pytest.mark.asyncio105async 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 stderr
2 unmodified lines
114115@pytest.mark.asyncio116async 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 == 200121122 stderr = capsys.readouterr().err.strip()
165 unmodified lines