Skip to content
Myr

Tighten up top-level API to only expose public API (#608)

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

* Tighten up top-level API to only expose public API * Leave HTTPProxyMode for backwards compat, raising warnings. * Add missing import

authored by Tom Christie · committed by GitHub · parent e1f5b8b · Browse files · 21 files+130 added−209 removed
This commit

State

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

Diff stats

21 files+130 added−209 removed

  • tests:+101 added−152 removed
  • other:+29 added−57 removed

21 files+130 added−209 removed

modified:docs/advanced.md+1 added-1 removed
241 unmodified lines
242243```python244proxy = httpx.HTTPProxy(245 proxy_url="https://127.0.0.1",246 proxy_mode=httpx.HTTPProxyMode.TUNNEL_ONLY246 proxy_mode="TUNNEL_ONLY" # May be "TUNNEL_ONLY" or "FORWARD_ONLY". Defaults to "DEFAULT".247)248async with httpx.Client(proxies=proxy) as client:249 # This request will be tunneled instead of forwarded.250 r = await client.get("http://example.com")
230 unmodified lines
modified:httpx/dispatch/proxy_http.py+20 added-3 removed
1import enum2import typing3import warnings4from base64 import b64encode56from ..concurrency.base import ConcurrencyBackend7from ..config import DEFAULT_POOL_LIMITS, CertTypes, PoolLimits, Timeout, VerifyTypes
6 unmodified lines
14logger = get_logger(__name__)151617class HTTPProxyMode(enum.Enum):18 # This enum is pending deprecation in order to reduce API surface area,19 # but is currently still around for 0.8 backwards compat.20 DEFAULT = "DEFAULT"21 FORWARD_ONLY = "FORWARD_ONLY"22 TUNNEL_ONLY = "TUNNEL_ONLY"232425DEFAULT_MODE = "DEFAULT"26FORWARD_ONLY = "FORWARD_ONLY"27TUNNEL_ONLY = "TUNNEL_ONLY"282930class HTTPProxy(ConnectionPool):31 """A proxy that sends requests to the recipient server32 on behalf of the connecting client.33 """
2 unmodified lines
36 self,37 proxy_url: URLTypes,38 *,39 proxy_headers: HeaderTypes = None,32 proxy_mode: HTTPProxyMode = HTTPProxyMode.DEFAULT,40 proxy_mode: str = "DEFAULT",41 verify: VerifyTypes = True,42 cert: CertTypes = None,43 trust_env: bool = None,44 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,45 http2: bool = False,46 backend: typing.Union[str, ConcurrencyBackend] = "auto",47 ):4849 if isinstance(proxy_mode, HTTPProxyMode):50 warnings.warn(51 "The 'HTTPProxyMode' enum is pending deprecation. "52 "Use a plain string instead. proxy_mode='FORWARD_ONLY', or "53 "proxy_mode='TUNNEL_ONLY'."54 )55 proxy_mode = proxy_mode.value56 assert proxy_mode in ("DEFAULT", "FORWARD_ONLY", "TUNNEL_ONLY")5758 super(HTTPProxy, self).__init__(59 verify=verify,60 cert=cert,61 pool_limits=pool_limits,
116 unmodified lines
178 then the proxy will forward all 'HTTP' requests and179 tunnel all 'HTTPS' requests.180 """181 return (165 self.proxy_mode == HTTPProxyMode.DEFAULT and not origin.is_ssl166 ) or self.proxy_mode == HTTPProxyMode.FORWARD_ONLY182 self.proxy_mode == DEFAULT_MODE and not origin.is_ssl183 ) or self.proxy_mode == FORWARD_ONLY184185 async def send(186 self,187 request: Request,
25 unmodified lines
modified:httpx/__init__.py+8 added-53 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 Client5from .concurrency.asyncio import AsyncioBackend6from .concurrency.base import BasePoolSemaphore, BaseSocketStream, ConcurrencyBackend7from .config import (8 USER_AGENT,9 CertTypes,10 PoolLimits,11 SSLConfig,12 Timeout,13 TimeoutConfig,14 TimeoutTypes,15 VerifyTypes,16)17from .dispatch.base import Dispatcher18from .dispatch.connection import HTTPConnection19from .dispatch.connection_pool import ConnectionPool5from .config import TimeoutConfig # For 0.8 backwards compat.6from .config import PoolLimits, Timeout7from .dispatch.proxy_http import HTTPProxy, HTTPProxyMode8from .exceptions import (9 ConnectionClosed,10 ConnectTimeout,11 CookieConflict,12 DecodingError,13 HTTPError,
11 unmodified lines
25 TimeoutException,26 TooManyRedirects,27 WriteTimeout,28)41from .models import (42 URL,43 AuthTypes,44 Cookies,45 CookieTypes,46 Headers,47 HeaderTypes,48 Origin,49 QueryParams,50 QueryParamTypes,51 Request,52 RequestData,53 RequestFiles,54 Response,55 ResponseContent,56 URLTypes,57)29from .models import URL, Cookies, Headers, Origin, QueryParams, Request, Response30from .status_codes import StatusCode, codes3132__all__ = [33 "__description__",
8 unmodified lines
42 "patch",43 "put",44 "request",45 "stream",46 "codes",47 "BasicAuth",48 "Client",49 "DigestAuth",77 "AsyncioBackend",78 "USER_AGENT",79 "CertTypes",50 "PoolLimits",81 "SSLConfig",51 "Timeout",83 "TimeoutConfig",84 "VerifyTypes",85 "HTTPConnection",86 "BasePoolSemaphore",87 "ConnectionPool",52 "TimeoutConfig", # For 0.8 backwards compat.53 "HTTPProxy",89 "HTTPProxyMode",54 "HTTPProxyMode", # For 0.8 backwards compat.55 "ConnectTimeout",56 "CookieConflict",57 "ConnectionClosed",58 "DecodingError",59 "HTTPError",60 "InvalidURL",61 "NotRedirectResponse",
9 unmodified lines
71 "TooManyRedirects",72 "WriteTimeout",73 "BaseSocketStream",74 "ConcurrencyBackend",109 "Dispatcher",75 "URL",111 "URLTypes",76 "StatusCode",113 "codes",114 "TimeoutTypes",115 "AuthTypes",77 "Cookies",117 "CookieTypes",78 "Headers",119 "HeaderTypes",79 "Origin",80 "QueryParams",122 "QueryParamTypes",81 "Request",124 "RequestData",82 "TimeoutException",83 "Response",127 "ResponseContent",128 "RequestFiles",84 "DigestAuth",85]
modified:tests/client/test_auth.py+3 added-12 removed
2 unmodified lines
3import os45import pytest67from httpx import (8 URL,9 CertTypes,10 Client,11 DigestAuth,12 Dispatcher,13 ProtocolError,14 Request,15 Response,16 TimeoutTypes,17 VerifyTypes,18)7from httpx import URL, Client, DigestAuth, ProtocolError, Request, Response8from httpx.config import CertTypes, TimeoutTypes, VerifyTypes9from httpx.dispatch.base import Dispatcher101112class MockDispatch(Dispatcher):13 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:
357 unmodified lines
modified:tests/client/test_cookies.py+3 added-10 removed
1 unmodified line
2from http.cookiejar import Cookie, CookieJar34import pytest56from httpx import (7 CertTypes,8 Client,9 Cookies,10 Dispatcher,11 Request,12 Response,13 TimeoutTypes,14 VerifyTypes,15)6from httpx import Client, Cookies, Request, Response7from httpx.config import CertTypes, TimeoutTypes, VerifyTypes8from httpx.dispatch.base import Dispatcher91011class MockDispatch(Dispatcher):12 async def send(
150 unmodified lines
modified:tests/client/test_headers.py+4 added-12 removed
2 unmodified lines
3import json45import pytest67from httpx import (8 CertTypes,9 Client,10 Dispatcher,11 Request,12 Response,13 TimeoutTypes,14 VerifyTypes,15 __version__,16 models,17)7from httpx import Client, Headers, Request, Response, __version__8from httpx.config import CertTypes, TimeoutTypes, VerifyTypes9from httpx.dispatch.base import Dispatcher101112class MockDispatch(Dispatcher):13 async def send(
109 unmodified lines
123 }124125126def test_header_does_not_exist():135 headers = models.Headers({"foo": "bar"})127 headers = Headers({"foo": "bar"})128 with pytest.raises(KeyError):129 del headers["baz"]130131
18 unmodified lines
modified:tests/client/test_proxies.py-2 removed
38 unmodified lines
39 )40 pool = client.dispatch41 proxy = client.proxies["all"]4243 assert isinstance(pool, httpx.ConnectionPool)43 assert isinstance(proxy, httpx.HTTPProxy)4445 for prop in [46 "verify",
52 unmodified lines
99 client = httpx.Client(proxies=proxies)100 dispatcher = client.dispatcher_for_url(httpx.URL(url))101102 if expected is None:104 assert isinstance(dispatcher, httpx.ConnectionPool)103 assert dispatcher is client.dispatch104 else:105 assert isinstance(dispatcher, httpx.HTTPProxy)106 assert dispatcher.proxy_url == expected
5 unmodified lines
modified:tests/client/test_queryparams.py+3 added-11 removed
1import json23import pytest45from httpx import (6 CertTypes,7 Client,8 Dispatcher,9 QueryParams,10 Request,11 Response,12 TimeoutTypes,13 VerifyTypes,14)15from httpx.models import URL5from httpx import URL, Client, QueryParams, Request, Response6from httpx.config import CertTypes, TimeoutTypes, VerifyTypes7from httpx.dispatch.base import Dispatcher8910class MockDispatch(Dispatcher):11 async def send(
40 unmodified lines
modified:tests/client/test_redirects.py+2 added-4 removed
3 unmodified lines
4import pytest56from httpx import (7 URL,8 CertTypes,8 Client,10 Dispatcher,9 NotRedirectResponse,10 RedirectBodyUnavailable,11 RedirectLoop,12 Request,13 Response,16 TimeoutTypes,14 TooManyRedirects,18 VerifyTypes,15 codes,16)17from httpx.config import CertTypes, TimeoutTypes, VerifyTypes18from httpx.dispatch.base import Dispatcher192021class MockDispatch(Dispatcher):22 async def send(
332 unmodified lines
modified:tests/dispatch/test_connection_pools.py+12 added-11 removed
1import httpx2from httpx.dispatch.connection_pool import ConnectionPool345async def test_keepalive_connections(server, backend):6 """7 Connections should default to staying in a keep-alive state.8 """8 async with httpx.ConnectionPool(backend=backend) as http:9 async with ConnectionPool(backend=backend) as http:10 response = await http.request("GET", server.url)11 await response.read()12 assert len(http.active_connections) == 013 assert len(http.keepalive_connections) == 1
7 unmodified lines
21async def test_differing_connection_keys(server, backend):22 """23 Connections to differing connection keys should result in multiple connections.24 """24 async with httpx.ConnectionPool(backend=backend) as http:25 async with ConnectionPool(backend=backend) as http:26 response = await http.request("GET", server.url)27 await response.read()28 assert len(http.active_connections) == 029 assert len(http.keepalive_connections) == 1
9 unmodified lines
39 The soft_limit config should limit the maximum number of keep-alive connections.40 """41 pool_limits = httpx.PoolLimits(soft_limit=1)4242 async with httpx.ConnectionPool(pool_limits=pool_limits, backend=backend) as http:43 async with ConnectionPool(pool_limits=pool_limits, backend=backend) as http:44 response = await http.request("GET", server.url)45 await response.read()46 assert len(http.active_connections) == 047 assert len(http.keepalive_connections) == 1
7 unmodified lines
55async def test_streaming_response_holds_connection(server, backend):56 """57 A streaming request should hold the connection open until the response is read.58 """58 async with httpx.ConnectionPool(backend=backend) as http:59 async with ConnectionPool(backend=backend) as http:60 response = await http.request("GET", server.url)61 assert len(http.active_connections) == 162 assert len(http.keepalive_connections) == 063
6 unmodified lines
70async def test_multiple_concurrent_connections(server, backend):71 """72 Multiple conncurrent requests should open multiple conncurrent connections.73 """73 async with httpx.ConnectionPool(backend=backend) as http:74 async with ConnectionPool(backend=backend) as http:75 response_a = await http.request("GET", server.url)76 assert len(http.active_connections) == 177 assert len(http.keepalive_connections) == 078
14 unmodified lines
93 """94 Using a `Connection: close` header should close the connection.95 """96 headers = [(b"connection", b"close")]96 async with httpx.ConnectionPool(backend=backend) as http:97 async with ConnectionPool(backend=backend) as http:98 response = await http.request("GET", server.url, headers=headers)99 await response.read()100 assert len(http.active_connections) == 0101 assert len(http.keepalive_connections) == 0
2 unmodified lines
104async def test_standard_response_close(server, backend):105 """106 A standard close should keep the connection open.107 """107 async with httpx.ConnectionPool(backend=backend) as http:108 async with ConnectionPool(backend=backend) as http:109 response = await http.request("GET", server.url)110 await response.read()111 await response.close()112 assert len(http.active_connections) == 0
3 unmodified lines
116async def test_premature_response_close(server, backend):117 """118 A premature close should close the connection.119 """119 async with httpx.ConnectionPool(backend=backend) as http:120 async with ConnectionPool(backend=backend) as http:121 response = await http.request("GET", server.url)122 await response.close()123 assert len(http.active_connections) == 0124 assert len(http.keepalive_connections) == 0
5 unmodified lines
130 """131 Upon keep-alive connection closed by remote a new connection132 should be reestablished.133 """133 async with httpx.ConnectionPool(backend=backend) as http:134 async with ConnectionPool(backend=backend) as http:135 response = await http.request("GET", server.url)136 await response.read()137138 # Shutdown the server to close the keep-alive connection
11 unmodified lines
150 """151 Upon keep-alive connection closed by remote a new connection152 should be reestablished.153 """153 async with httpx.ConnectionPool(backend=backend) as http:154 async with ConnectionPool(backend=backend) as http:155 response = await http.request("GET", server.url)156 await response.read()157158 # Shutdown the server to close the keep-alive connection
9 unmodified lines
168 """169 Verify that max_connections semaphore is released170 properly on a disconnected connection.171 """171 async with httpx.ConnectionPool(172 async with ConnectionPool(173 pool_limits=httpx.PoolLimits(hard_limit=1), backend=backend174 ) as http:175 response = await http.request("GET", server.url)176 await response.read()
6 unmodified lines
modified:tests/dispatch/test_connections.py+3 added-2 removed
1import pytest23from httpx import HTTPConnection, exceptions3import httpx4from httpx.dispatch.connection import HTTPConnection567async def test_get(server, backend):8 async with HTTPConnection(origin=server.url, backend=backend) as conn:
9 unmodified lines
18 assert response.status_code == 200192021async def test_premature_close(server, backend):21 with pytest.raises(exceptions.ConnectionClosed):22 with pytest.raises(httpx.ConnectionClosed):23 async with HTTPConnection(origin=server.url, backend=backend) as conn:24 response = await conn.request(25 "GET", server.url.copy_with(path="/premature_close")26 )
25 unmodified lines
modified:tests/dispatch/test_proxy_http.py+6 added-14 removed
20 unmodified lines
21 ),22 backend=backend,23 )24 async with httpx.HTTPProxy(25 proxy_url="http://127.0.0.1:8000",26 backend=raw_io,27 proxy_mode=httpx.HTTPProxyMode.TUNNEL_ONLY,25 proxy_url="http://127.0.0.1:8000", backend=raw_io, proxy_mode="TUNNEL_ONLY",26 ) as proxy:27 response = await proxy.request("GET", "http://example.com")2829 assert response.status_code == 404
27 unmodified lines
57 )5859 with pytest.raises(httpx.ProxyError) as e:60 async with httpx.HTTPProxy(63 proxy_url="http://127.0.0.1:8000",64 backend=raw_io,65 proxy_mode=httpx.HTTPProxyMode.TUNNEL_ONLY,61 proxy_url="http://127.0.0.1:8000", backend=raw_io, proxy_mode="TUNNEL_ONLY",62 ) as proxy:63 await proxy.request("GET", "http://example.com")6465 # ProxyError.request should be the CONNECT request not the original request
41 unmodified lines
107 ),108 backend=backend,109 )110 async with httpx.HTTPProxy(115 proxy_url="http://127.0.0.1:8000",116 backend=raw_io,117 proxy_mode=httpx.HTTPProxyMode.TUNNEL_ONLY,111 proxy_url="http://127.0.0.1:8000", backend=raw_io, proxy_mode="TUNNEL_ONLY",112 ) as proxy:113 resp = await proxy.request("GET", "https://example.com")114115 assert resp.status_code == 404
27 unmodified lines
143 assert recv[3].startswith(b"GET / HTTP/1.1\r\nhost: example.com\r\n")144 assert recv[4].startswith(b"GET /target HTTP/1.1\r\nhost: example.com\r\n")145146153@pytest.mark.parametrize(154 "proxy_mode", [httpx.HTTPProxyMode.FORWARD_ONLY, httpx.HTTPProxyMode.DEFAULT]155)147@pytest.mark.parametrize("proxy_mode", ["FORWARD_ONLY", "DEFAULT"])148async def test_proxy_forwarding(backend, proxy_mode):149 raw_io = MockRawSocketBackend(150 data_to_send=(151 [
43 unmodified lines
195def test_proxy_repr():196 proxy = httpx.HTTPProxy(197 "http://127.0.0.1:1080",198 proxy_headers={"Custom": "Header"},207 proxy_mode=httpx.HTTPProxyMode.DEFAULT,199 proxy_mode="DEFAULT",200 )201202 assert repr(proxy) == (203 "HTTPProxy(proxy_url=URL('http://127.0.0.1:1080') "204 "proxy_headers=Headers({'custom': 'Header'}) "213 "proxy_mode=<HTTPProxyMode.DEFAULT: 'DEFAULT'>)"205 "proxy_mode='DEFAULT')"206 )
modified:tests/dispatch/utils.py+3 added-1 removed
3 unmodified lines
4import h2.config5import h2.connection6import h2.events78from httpx import AsyncioBackend, BaseSocketStream, Request, Timeout8from httpx import Request, Timeout9from httpx.concurrency.asyncio import AsyncioBackend10from httpx.concurrency.base import BaseSocketStream11from tests.concurrency import sleep121314class MockHTTP2Backend:
210 unmodified lines
modified:tests/models/test_url.py+1 added-2 removed
1import pytest23from httpx import URL, Origin4from httpx.exceptions import InvalidURL3from httpx import URL, InvalidURL, Origin456@pytest.mark.parametrize(7 "given,idna,host,scheme,port",
198 unmodified lines
modified:tests/concurrency.py+1 added-1 removed
7 unmodified lines
8import typing910import trio1112from httpx import AsyncioBackend12from httpx.concurrency.asyncio import AsyncioBackend13from httpx.concurrency.trio import TrioBackend141516@functools.singledispatch
30 unmodified lines
modified:tests/conftest.py+2 added-1 removed
15 unmodified lines
16)17from uvicorn.config import Config18from uvicorn.main import Server1920from httpx import URL, AsyncioBackend20from httpx import URL21from httpx.concurrency.asyncio import AsyncioBackend22from httpx.concurrency.trio import TrioBackend2324ENVIRONMENT_VARIABLES = {25 "SSL_CERT_FILE",
312 unmodified lines
modified:tests/test_concurrency.py+3 added-1 removed
1import pytest2import trio34from httpx import AsyncioBackend, SSLConfig, Timeout4from httpx import Timeout5from httpx.concurrency.asyncio import AsyncioBackend6from httpx.concurrency.trio import TrioBackend7from httpx.config import SSLConfig8from tests.concurrency import run_concurrently, sleep91011def get_asyncio_cipher(stream):
149 unmodified lines
modified:tests/test_config.py+21 added-20 removed
5 unmodified lines
67import pytest89import httpx10from httpx.config import SSLConfig111213def test_load_ssl_config():13 ssl_config = httpx.SSLConfig()14 ssl_config = SSLConfig()15 context = ssl_config.load_ssl_context()16 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED17 assert context.check_hostname is True181920def test_load_ssl_config_verify_non_existing_path():20 ssl_config = httpx.SSLConfig(verify="/path/to/nowhere")21 ssl_config = SSLConfig(verify="/path/to/nowhere")22 with pytest.raises(IOError):23 ssl_config.load_ssl_context()242526def test_load_ssl_config_verify_existing_file():26 ssl_config = httpx.SSLConfig(verify=httpx.config.DEFAULT_CA_BUNDLE_PATH)27 ssl_config = SSLConfig(verify=httpx.config.DEFAULT_CA_BUNDLE_PATH)28 context = ssl_config.load_ssl_context()29 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED30 assert context.check_hostname is True31
4 unmodified lines
36 ca_cert_pem_file37 if config.endswith("_FILE")38 else str(Path(ca_cert_pem_file).parent)39 )39 ssl_config = httpx.SSLConfig(trust_env=True)40 ssl_config = SSLConfig(trust_env=True)41 context = ssl_config.load_ssl_context()42 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED43 assert context.check_hostname is True44 assert ssl_config.verify == os.environ[config]
10 unmodified lines
555657def test_load_ssl_config_verify_directory():58 path = httpx.config.DEFAULT_CA_BUNDLE_PATH.parent58 ssl_config = httpx.SSLConfig(verify=path)59 ssl_config = SSLConfig(verify=path)60 context = ssl_config.load_ssl_context()61 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED62 assert context.check_hostname is True636465def test_load_ssl_config_cert_and_key(cert_pem_file, cert_private_key_file):65 ssl_config = httpx.SSLConfig(cert=(cert_pem_file, cert_private_key_file))66 ssl_config = SSLConfig(cert=(cert_pem_file, cert_private_key_file))67 context = ssl_config.load_ssl_context()68 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED69 assert context.check_hostname is True70
1 unmodified line
72@pytest.mark.parametrize("password", [b"password", "password"])73def test_load_ssl_config_cert_and_encrypted_key(74 cert_pem_file, cert_encrypted_private_key_file, password75):75 ssl_config = httpx.SSLConfig(76 ssl_config = SSLConfig(77 cert=(cert_pem_file, cert_encrypted_private_key_file, password)78 )79 context = ssl_config.load_ssl_context()80 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED
2 unmodified lines
8384def test_load_ssl_config_cert_and_key_invalid_password(85 cert_pem_file, cert_encrypted_private_key_file86):86 ssl_config = httpx.SSLConfig(87 ssl_config = SSLConfig(88 cert=(cert_pem_file, cert_encrypted_private_key_file, "password1")89 )9091 with pytest.raises(ssl.SSLError):92 ssl_config.load_ssl_context()939495def test_load_ssl_config_cert_without_key_raises(cert_pem_file):95 ssl_config = httpx.SSLConfig(cert=cert_pem_file)96 ssl_config = SSLConfig(cert=cert_pem_file)97 with pytest.raises(ssl.SSLError):98 ssl_config.load_ssl_context()99100101def test_load_ssl_config_no_verify():101 ssl_config = httpx.SSLConfig(verify=False)102 ssl_config = SSLConfig(verify=False)103 context = ssl_config.load_ssl_context()104 assert context.verify_mode == ssl.VerifyMode.CERT_NONE105 assert context.check_hostname is False106107108def test_load_ssl_context():109 ssl_context = ssl.create_default_context()109 ssl_config = httpx.SSLConfig(verify=ssl_context)110 ssl_config = SSLConfig(verify=ssl_context)111112 assert ssl_config.verify is True113 assert ssl_config.ssl_context is ssl_context114 assert repr(ssl_config) == "SSLConfig(cert=None, verify=True)"115116117def test_ssl_repr():117 ssl = httpx.SSLConfig(verify=False)118 ssl = SSLConfig(verify=False)119 assert repr(ssl) == "SSLConfig(cert=None, verify=False)"120121122def test_ssl_eq():123 ssl = SSLConfig(verify=False)124 assert ssl == SSLConfig(verify=False)125126127def test_limits_repr():128 limits = httpx.PoolLimits(hard_limit=100)129 assert repr(limits) == "PoolLimits(soft_limit=None, hard_limit=100)"130131126def test_ssl_eq():127 ssl = httpx.SSLConfig(verify=False)128 assert ssl == httpx.SSLConfig(verify=False)129130132def test_limits_eq():133 limits = httpx.PoolLimits(hard_limit=100)134 assert limits == httpx.PoolLimits(hard_limit=100)135
60 unmodified lines
196def test_ssl_config_support_for_keylog_file(tmpdir, monkeypatch): # pragma: nocover197 with monkeypatch.context() as m:198 m.delenv("SSLKEYLOGFILE", raising=False)199199 ssl_config = httpx.SSLConfig(trust_env=True)200 ssl_config = SSLConfig(trust_env=True)201 ssl_config.load_ssl_context()202203 assert ssl_config.ssl_context.keylog_filename is None204
1 unmodified line
206207 with monkeypatch.context() as m:208 m.setenv("SSLKEYLOGFILE", filename)209209 ssl_config = httpx.SSLConfig(trust_env=True)210 ssl_config = SSLConfig(trust_env=True)211 ssl_config.load_ssl_context()212213 assert ssl_config.ssl_context.keylog_filename == filename214214 ssl_config = httpx.SSLConfig(trust_env=False)215 ssl_config = SSLConfig(trust_env=False)216 ssl_config.load_ssl_context()217218 assert ssl_config.ssl_context.keylog_filename is None
modified:tests/test_decoders.py+1 added-1 removed
106 unmodified lines
107def test_decoding_errors(header_value):108 headers = [(b"Content-Encoding", header_value)]109 body = b"test 123"110 compressed_body = brotli.compress(body)[3:]111 with pytest.raises(httpx.exceptions.DecodingError):111 with pytest.raises(httpx.DecodingError):112 response = httpx.Response(200, headers=headers, content=compressed_body)113 response.content114115
103 unmodified lines
modified:tests/test_multipart.py+19 added-25 removed
4 unmodified lines
5from unittest import mock67import pytest89from httpx import (10 CertTypes,11 Client,12 Dispatcher,13 Request,14 Response,15 TimeoutTypes,16 VerifyTypes,17 multipart,18)9import httpx10from httpx.config import CertTypes, TimeoutTypes, VerifyTypes11from httpx.dispatch.base import Dispatcher12from httpx.multipart import _format_param, multipart_encode131415class MockDispatch(Dispatcher):16 async def send(17 self,24 request: Request,18 request: httpx.Request,19 verify: VerifyTypes = None,20 cert: CertTypes = None,21 timeout: TimeoutTypes = None,28 ) -> Response:22 ) -> httpx.Response:23 content = await request.read()30 return Response(200, content=content)24 return httpx.Response(200, content=content)252627@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))28@pytest.mark.asyncio29async def test_multipart(value, output):36 client = Client(dispatch=MockDispatch())30 client = httpx.Client(dispatch=MockDispatch())3132 # Test with a single-value 'data' argument, and a plain file 'files' argument.33 data = {"text": value}34 files = {"file": io.BytesIO(b"<file content>")}
15 unmodified lines
5051@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))52@pytest.mark.asyncio53async def test_multipart_invalid_key(key):60 client = Client(dispatch=MockDispatch())54 client = httpx.Client(dispatch=MockDispatch())55 data = {key: "abc"}56 files = {"file": io.BytesIO(b"<file content>")}57 with pytest.raises(TypeError) as e:58 await client.post("http://127.0.0.1:8000/", data=data, files=files)
2 unmodified lines
6162@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))63@pytest.mark.asyncio64async def test_multipart_invalid_value(value):71 client = Client(dispatch=MockDispatch())65 client = httpx.Client(dispatch=MockDispatch())66 data = {"text": value}67 files = {"file": io.BytesIO(b"<file content>")}68 with pytest.raises(TypeError) as e:69 await client.post("http://127.0.0.1:8000/", data=data, files=files)
1 unmodified line
717273@pytest.mark.asyncio74async def test_multipart_file_tuple():81 client = Client(dispatch=MockDispatch())75 client = httpx.Client(dispatch=MockDispatch())7677 # Test with a list of values 'data' argument, and a tuple style 'files' argument.78 data = {"text": ["abc"]}79 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}
24 unmodified lines
104 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}105106 with mock.patch("os.urandom", return_value=os.urandom(16)):107 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")114 body, content_type = multipart.multipart_encode(data=data, files=files)108 body, content_type = multipart_encode(data=data, files=files)109 assert content_type == f"multipart/form-data; boundary={boundary}"110 assert body == (111 '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'112 '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'
15 unmodified lines
128 files = {"file": (None, io.BytesIO(b"<file content>"))}129 with mock.patch("os.urandom", return_value=os.urandom(16)):130 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")131138 body, content_type = multipart.multipart_encode(data={}, files=files)132 body, content_type = multipart_encode(data={}, files=files)133134 assert content_type == f"multipart/form-data; boundary={boundary}"135 assert body == (136 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'
16 unmodified lines
153 files = {"file": (file_name, io.BytesIO(b"<file content>"))}154 with mock.patch("os.urandom", return_value=os.urandom(16)):155 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")156163 body, content_type = multipart.multipart_encode(data={}, files=files)157 body, content_type = multipart_encode(data={}, files=files)158159 assert content_type == f"multipart/form-data; boundary={boundary}"160 assert body == (161 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '
7 unmodified lines
169 files = {"file": ("test.txt", "<string content>", "text/plain")}170 with mock.patch("os.urandom", return_value=os.urandom(16)):171 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")172179 body, content_type = multipart.multipart_encode(data={}, files=files)173 body, content_type = multipart_encode(data={}, files=files)174175 assert content_type == f"multipart/form-data; boundary={boundary}"176 assert body == (177 '--{0}\r\nContent-Disposition: form-data; name="file"; '
5 unmodified lines
183184185class TestHeaderParamHTML5Formatting:186 def test_unicode(self):193 param = multipart._format_param("filename", "n\u00e4me")187 param = _format_param("filename", "n\u00e4me")188 assert param == b'filename="n\xc3\xa4me"'189190 def test_ascii(self):197 param = multipart._format_param("filename", b"name")191 param = _format_param("filename", b"name")192 assert param == b'filename="name"'193194 def test_unicode_escape(self):201 param = multipart._format_param("filename", "hello\\world\u0022")195 param = _format_param("filename", "hello\\world\u0022")196 assert param == b'filename="hello\\\\world%22"'197198 def test_unicode_with_control_character(self):205 param = multipart._format_param("filename", "hello\x1A\x1B\x1C")199 param = _format_param("filename", "hello\x1A\x1B\x1C")200 assert param == b'filename="hello%1A\x1B%1C"'
modified:tests/test_timeouts.py+14 added-22 removed
1import pytest23from httpx import (4 Client,5 ConnectTimeout,6 PoolLimits,7 PoolTimeout,8 ReadTimeout,9 Timeout,10 WriteTimeout,11)3import httpx456async def test_read_timeout(server, backend):15 timeout = Timeout(read_timeout=1e-6)7 timeout = httpx.Timeout(read_timeout=1e-6)817 async with Client(timeout=timeout, backend=backend) as client:18 with pytest.raises(ReadTimeout):9 async with httpx.Client(timeout=timeout, backend=backend) as client:10 with pytest.raises(httpx.ReadTimeout):11 await client.get(server.url.copy_with(path="/slow_response"))121314async def test_write_timeout(server, backend):23 timeout = Timeout(write_timeout=1e-6)15 timeout = httpx.Timeout(write_timeout=1e-6)1625 async with Client(timeout=timeout, backend=backend) as client:26 with pytest.raises(WriteTimeout):17 async with httpx.Client(timeout=timeout, backend=backend) as client:18 with pytest.raises(httpx.WriteTimeout):19 data = b"*" * 1024 * 1024 * 10020 await client.put(server.url.copy_with(path="/slow_response"), data=data)212223async def test_connect_timeout(server, backend):32 timeout = Timeout(connect_timeout=1e-6)24 timeout = httpx.Timeout(connect_timeout=1e-6)2534 async with Client(timeout=timeout, backend=backend) as client:35 with pytest.raises(ConnectTimeout):26 async with httpx.Client(timeout=timeout, backend=backend) as client:27 with pytest.raises(httpx.ConnectTimeout):28 # See https://stackoverflow.com/questions/100841/29 await client.get("http://10.255.255.1/")303132async def test_pool_timeout(server, backend):41 pool_limits = PoolLimits(hard_limit=1)42 timeout = Timeout(pool_timeout=1e-4)33 pool_limits = httpx.PoolLimits(hard_limit=1)34 timeout = httpx.Timeout(pool_timeout=1e-4)3544 async with Client(36 async with httpx.Client(37 pool_limits=pool_limits, timeout=timeout, backend=backend38 ) as client:39 async with client.stream("GET", server.url):48 with pytest.raises(PoolTimeout):40 with pytest.raises(httpx.PoolTimeout):41 await client.get("http://localhost:8000/")