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
Provenance
- Commit
d15dc0b- Tree
61226c2- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
e1f5b8b
21 files changed+130 added−209 removed
modified:docs/advanced.md+1 added-1 removed
241 unmodified lines242 243 ```python244 proxy = 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 )248 async 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 linesmodified:httpx/dispatch/proxy_http.py+20 added-3 removed
1 import enum2 import typing3+import warnings4 from base64 import b64encode5 6 from ..concurrency.base import ConcurrencyBackend7 from ..config import DEFAULT_POOL_LIMITS, CertTypes, PoolLimits, Timeout, VerifyTypes6 unmodified lines14 logger = get_logger(__name__)15 16 17 class 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"23 24 25+DEFAULT_MODE = "DEFAULT"26+FORWARD_ONLY = "FORWARD_ONLY"27+TUNNEL_ONLY = "TUNNEL_ONLY"28+29+30 class HTTPProxy(ConnectionPool):31 """A proxy that sends requests to the recipient server32 on behalf of the connecting client.33 """2 unmodified lines36 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 ):48 49+ 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")57+58 super(HTTPProxy, self).__init__(59 verify=verify,60 cert=cert,61 pool_limits=pool_limits,116 unmodified lines178 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_ONLY184 185 async def send(186 self,187 request: Request,25 unmodified linesmodified:httpx/__init__.py+8 added-53 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 Client5-from .concurrency.asyncio import AsyncioBackend6-from .concurrency.base import BasePoolSemaphore, BaseSocketStream, ConcurrencyBackend7-from .config import (8- USER_AGENT,9- CertTypes,10- PoolLimits,11- SSLConfig,12- Timeout,13- TimeoutConfig,14- TimeoutTypes,15- VerifyTypes,16-)17-from .dispatch.base import Dispatcher18-from .dispatch.connection import HTTPConnection19-from .dispatch.connection_pool import ConnectionPool5+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 (9+ ConnectionClosed,10 ConnectTimeout,11 CookieConflict,12 DecodingError,13 HTTPError,11 unmodified lines25 TimeoutException,26 TooManyRedirects,27 WriteTimeout,28 )41-from .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-)29+from .models import URL, Cookies, Headers, Origin, QueryParams, Request, Response30 from .status_codes import StatusCode, codes31 32 __all__ = [33 "__description__",8 unmodified lines42 "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 lines71 "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 lines3 import os4 5 import pytest6 7-from httpx import (8- URL,9- CertTypes,10- Client,11- DigestAuth,12- Dispatcher,13- ProtocolError,14- Request,15- Response,16- TimeoutTypes,17- VerifyTypes,18-)7+from httpx import URL, Client, DigestAuth, ProtocolError, Request, Response8+from httpx.config import CertTypes, TimeoutTypes, VerifyTypes9+from httpx.dispatch.base import Dispatcher10 11 12 class MockDispatch(Dispatcher):13 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:357 unmodified linesmodified:tests/client/test_cookies.py+3 added-10 removed
1 unmodified line2 from http.cookiejar import Cookie, CookieJar3 4 import pytest5 6-from httpx import (7- CertTypes,8- Client,9- Cookies,10- Dispatcher,11- Request,12- Response,13- TimeoutTypes,14- VerifyTypes,15-)6+from httpx import Client, Cookies, Request, Response7+from httpx.config import CertTypes, TimeoutTypes, VerifyTypes8+from httpx.dispatch.base import Dispatcher9 10 11 class MockDispatch(Dispatcher):12 async def send(150 unmodified linesmodified:tests/client/test_headers.py+4 added-12 removed
2 unmodified lines3 import json4 5 import pytest6 7-from httpx import (8- CertTypes,9- Client,10- Dispatcher,11- Request,12- Response,13- TimeoutTypes,14- VerifyTypes,15- __version__,16- models,17-)7+from httpx import Client, Headers, Request, Response, __version__8+from httpx.config import CertTypes, TimeoutTypes, VerifyTypes9+from httpx.dispatch.base import Dispatcher10 11 12 class MockDispatch(Dispatcher):13 async def send(109 unmodified lines123 }124 125 126 def 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"]130 131 18 unmodified linesmodified:tests/client/test_proxies.py-2 removed
38 unmodified lines39 )40 pool = client.dispatch41 proxy = client.proxies["all"]42 43- assert isinstance(pool, httpx.ConnectionPool)43 assert isinstance(proxy, httpx.HTTPProxy)44 45 for prop in [46 "verify",52 unmodified lines99 client = httpx.Client(proxies=proxies)100 dispatcher = client.dispatcher_for_url(httpx.URL(url))101 102 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 == expected5 unmodified linesmodified:tests/client/test_queryparams.py+3 added-11 removed
1 import json2 3 import pytest4 5-from httpx import (6- CertTypes,7- Client,8- Dispatcher,9- QueryParams,10- Request,11- Response,12- TimeoutTypes,13- VerifyTypes,14-)15-from httpx.models import URL5+from httpx import URL, Client, QueryParams, Request, Response6+from httpx.config import CertTypes, TimeoutTypes, VerifyTypes7+from httpx.dispatch.base import Dispatcher8 9 10 class MockDispatch(Dispatcher):11 async def send(40 unmodified linesmodified:tests/client/test_redirects.py+2 added-4 removed
3 unmodified lines4 import pytest5 6 from 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 )17+from httpx.config import CertTypes, TimeoutTypes, VerifyTypes18+from httpx.dispatch.base import Dispatcher19 20 21 class MockDispatch(Dispatcher):22 async def send(332 unmodified linesmodified:tests/dispatch/test_connection_pools.py+12 added-11 removed
1 import httpx2+from httpx.dispatch.connection_pool import ConnectionPool3 4 5 async 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) == 17 unmodified lines21 async 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) == 19 unmodified lines39 The soft_limit config should limit the maximum number of keep-alive connections.40 """41 pool_limits = httpx.PoolLimits(soft_limit=1)42 42- 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) == 17 unmodified lines55 async 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 lines70 async 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 lines93 """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) == 02 unmodified lines104 async 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) == 03 unmodified lines116 async 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) == 05 unmodified lines130 """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()137 138 # Shutdown the server to close the keep-alive connection11 unmodified lines150 """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()157 158 # Shutdown the server to close the keep-alive connection9 unmodified lines168 """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 linesmodified:tests/dispatch/test_connections.py+3 added-2 removed
1 import pytest2 3-from httpx import HTTPConnection, exceptions3+import httpx4+from httpx.dispatch.connection import HTTPConnection5 6 7 async def test_get(server, backend):8 async with HTTPConnection(origin=server.url, backend=backend) as conn:9 unmodified lines18 assert response.status_code == 20019 20 21 async 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 linesmodified:tests/dispatch/test_proxy_http.py+6 added-14 removed
20 unmodified lines21 ),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")28 29 assert response.status_code == 40427 unmodified lines57 )58 59 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")64 65 # ProxyError.request should be the CONNECT request not the original request41 unmodified lines107 ),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")114 115 assert resp.status_code == 40427 unmodified lines143 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")145 146 153-@pytest.mark.parametrize(154- "proxy_mode", [httpx.HTTPProxyMode.FORWARD_ONLY, httpx.HTTPProxyMode.DEFAULT]155-)147+@pytest.mark.parametrize("proxy_mode", ["FORWARD_ONLY", "DEFAULT"])148 async def test_proxy_forwarding(backend, proxy_mode):149 raw_io = MockRawSocketBackend(150 data_to_send=(151 [43 unmodified lines195 def 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 )201 202 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 lines4 import h2.config5 import h2.connection6 import h2.events7 8-from httpx import AsyncioBackend, BaseSocketStream, Request, Timeout8+from httpx import Request, Timeout9+from httpx.concurrency.asyncio import AsyncioBackend10+from httpx.concurrency.base import BaseSocketStream11 from tests.concurrency import sleep12 13 14 class MockHTTP2Backend:210 unmodified linesmodified:tests/models/test_url.py+1 added-2 removed
1 import pytest2 3-from httpx import URL, Origin4-from httpx.exceptions import InvalidURL3+from httpx import URL, InvalidURL, Origin4 5 6 @pytest.mark.parametrize(7 "given,idna,host,scheme,port",198 unmodified linesmodified:tests/concurrency.py+1 added-1 removed
7 unmodified lines8 import typing9 10 import trio11 12-from httpx import AsyncioBackend12+from httpx.concurrency.asyncio import AsyncioBackend13 from httpx.concurrency.trio import TrioBackend14 15 16 @functools.singledispatch30 unmodified linesmodified:tests/conftest.py+2 added-1 removed
15 unmodified lines16 )17 from uvicorn.config import Config18 from uvicorn.main import Server19 20-from httpx import URL, AsyncioBackend20+from httpx import URL21+from httpx.concurrency.asyncio import AsyncioBackend22 from httpx.concurrency.trio import TrioBackend23 24 ENVIRONMENT_VARIABLES = {25 "SSL_CERT_FILE",312 unmodified linesmodified:tests/test_concurrency.py+3 added-1 removed
1 import pytest2 import trio3 4-from httpx import AsyncioBackend, SSLConfig, Timeout4+from httpx import Timeout5+from httpx.concurrency.asyncio import AsyncioBackend6 from httpx.concurrency.trio import TrioBackend7+from httpx.config import SSLConfig8 from tests.concurrency import run_concurrently, sleep9 10 11 def get_asyncio_cipher(stream):149 unmodified linesmodified:tests/test_config.py+21 added-20 removed
5 unmodified lines6 7 import pytest8 9 import httpx10+from httpx.config import SSLConfig11 12 13 def 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 True18 19 20 def 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()24 25 26 def 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 lines36 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 lines55 56 57 def 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 True63 64 65 def 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 line72 @pytest.mark.parametrize("password", [b"password", "password"])73 def 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_REQUIRED2 unmodified lines83 84 def 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 )90 91 with pytest.raises(ssl.SSLError):92 ssl_config.load_ssl_context()93 94 95 def 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()99 100 101 def 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 False106 107 108 def 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)111 112 assert ssl_config.verify is True113 assert ssl_config.ssl_context is ssl_context114 assert repr(ssl_config) == "SSLConfig(cert=None, verify=True)"115 116 117 def test_ssl_repr():117- ssl = httpx.SSLConfig(verify=False)118+ ssl = SSLConfig(verify=False)119 assert repr(ssl) == "SSLConfig(cert=None, verify=False)"120 121 122+def test_ssl_eq():123+ ssl = SSLConfig(verify=False)124+ assert ssl == SSLConfig(verify=False)125+126+127 def test_limits_repr():128 limits = httpx.PoolLimits(hard_limit=100)129 assert repr(limits) == "PoolLimits(soft_limit=None, hard_limit=100)"130 131 126-def test_ssl_eq():127- ssl = httpx.SSLConfig(verify=False)128- assert ssl == httpx.SSLConfig(verify=False)129-130-132 def test_limits_eq():133 limits = httpx.PoolLimits(hard_limit=100)134 assert limits == httpx.PoolLimits(hard_limit=100)135 60 unmodified lines196 def test_ssl_config_support_for_keylog_file(tmpdir, monkeypatch): # pragma: nocover197 with monkeypatch.context() as m:198 m.delenv("SSLKEYLOGFILE", raising=False)199 199- ssl_config = httpx.SSLConfig(trust_env=True)200+ ssl_config = SSLConfig(trust_env=True)201 ssl_config.load_ssl_context()202 203 assert ssl_config.ssl_context.keylog_filename is None204 1 unmodified line206 207 with monkeypatch.context() as m:208 m.setenv("SSLKEYLOGFILE", filename)209 209- ssl_config = httpx.SSLConfig(trust_env=True)210+ ssl_config = SSLConfig(trust_env=True)211 ssl_config.load_ssl_context()212 213 assert ssl_config.ssl_context.keylog_filename == filename214 214- ssl_config = httpx.SSLConfig(trust_env=False)215+ ssl_config = SSLConfig(trust_env=False)216 ssl_config.load_ssl_context()217 218 assert ssl_config.ssl_context.keylog_filename is Nonemodified:tests/test_decoders.py+1 added-1 removed
106 unmodified lines107 def 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.content114 115 103 unmodified linesmodified:tests/test_multipart.py+19 added-25 removed
4 unmodified lines5 from unittest import mock6 7 import pytest8 9-from httpx import (10- CertTypes,11- Client,12- Dispatcher,13- Request,14- Response,15- TimeoutTypes,16- VerifyTypes,17- multipart,18-)9+import httpx10+from httpx.config import CertTypes, TimeoutTypes, VerifyTypes11+from httpx.dispatch.base import Dispatcher12+from httpx.multipart import _format_param, multipart_encode13 14 15 class 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)25 26 27 @pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))28 @pytest.mark.asyncio29 async def test_multipart(value, output):36- client = Client(dispatch=MockDispatch())30+ client = httpx.Client(dispatch=MockDispatch())31 32 # 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 lines50 51 @pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))52 @pytest.mark.asyncio53 async 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 lines61 62 @pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))63 @pytest.mark.asyncio64 async 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 line71 72 73 @pytest.mark.asyncio74 async def test_multipart_file_tuple():81- client = Client(dispatch=MockDispatch())75+ client = httpx.Client(dispatch=MockDispatch())76 77 # 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 lines104 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}105 106 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 lines128 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")131 138- body, content_type = multipart.multipart_encode(data={}, files=files)132+ body, content_type = multipart_encode(data={}, files=files)133 134 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 lines153 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")156 163- body, content_type = multipart.multipart_encode(data={}, files=files)157+ body, content_type = multipart_encode(data={}, files=files)158 159 assert content_type == f"multipart/form-data; boundary={boundary}"160 assert body == (161 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '7 unmodified lines169 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")172 179- body, content_type = multipart.multipart_encode(data={}, files=files)173+ body, content_type = multipart_encode(data={}, files=files)174 175 assert content_type == f"multipart/form-data; boundary={boundary}"176 assert body == (177 '--{0}\r\nContent-Disposition: form-data; name="file"; '5 unmodified lines183 184 185 class 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"'189 190 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"'193 194 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"'197 198 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
1 import pytest2 3-from httpx import (4- Client,5- ConnectTimeout,6- PoolLimits,7- PoolTimeout,8- ReadTimeout,9- Timeout,10- WriteTimeout,11-)3+import httpx4 5 6 async def test_read_timeout(server, backend):15- timeout = Timeout(read_timeout=1e-6)7+ timeout = httpx.Timeout(read_timeout=1e-6)8 17- 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"))12 13 14 async def test_write_timeout(server, backend):23- timeout = Timeout(write_timeout=1e-6)15+ timeout = httpx.Timeout(write_timeout=1e-6)16 25- 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)21 22 23 async def test_connect_timeout(server, backend):32- timeout = Timeout(connect_timeout=1e-6)24+ timeout = httpx.Timeout(connect_timeout=1e-6)25 34- 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/")30 31 32 async 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)35 44- 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/")