Skip to content
Myr

Treat warnings as errors (#1687)

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

* Treat warnings as errors * Defensive programming in Client.__del__ to avoid possible warnings on partially initialized instances * Linting * Ignore linting getattr errors in __del__ * getattr requires a default * Tighten up closing of auth_flow generators * Switch multipart test to open file in a context manager * Ignore warnings on uvicorn * Drop -Werror from addopts * Warings specified entirely in 'filterwarnings' section * Use ssl.PROTOCOL_TLS_CLIENT instead of deprecated ssl.PROTOCOL_TLS * Push 'check_hostname = False' above 'context.verify_mode = ssl.CERT_NONE' * Introduce set_minimum_tls_version_1_2 compatible across different python versions * Commenting * Add missing annotation * Exclude _compat from coverage

authored by Tom Christie · committed by GitHub · parent 47d712c · Browse files · 5 files+110 added−77 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: Joe <nigelchiang@outlook.com>
  • Co-authored-by: jianghang <jianghang@didiglobal.com>

Diff stats

5 files+110 added−77 removed

  • tests:+26 added−25 removed
  • other:+84 added−52 removed

5 files+110 added−77 removed

modified:httpx/_client.py+56 added-44 removed
895 unmodified lines
896 allow_redirects: bool,897 history: typing.List[Response],898 ) -> Response:899 auth_flow = auth.sync_auth_flow(request)900 try:900 request = next(auth_flow)901 request = next(auth_flow)902902 for hook in self._event_hooks["request"]:903 hook(request)903 for hook in self._event_hooks["request"]:904 hook(request)905905 while True:906 response = self._send_handling_redirects(907 request,908 timeout=timeout,909 allow_redirects=allow_redirects,910 history=history,911 )912 try:906 while True:907 response = self._send_handling_redirects(908 request,909 timeout=timeout,910 allow_redirects=allow_redirects,911 history=history,912 )913 try:914 try:914 next_request = auth_flow.send(response)915 except StopIteration:916 return response915 next_request = auth_flow.send(response)916 except StopIteration:917 return response918918 response.history = list(history)919 response.read()920 request = next_request921 history.append(response)919 response.history = list(history)920 response.read()921 request = next_request922 history.append(response)923923 except Exception as exc:924 response.close()925 raise exc924 except Exception as exc:925 response.close()926 raise exc927 finally:928 auth_flow.close()929930 def _send_handling_redirects(931 self,932 request: Request,
313 unmodified lines
1246 if transport is not None:1247 transport.__exit__(exc_type, exc_value, traceback)12481249 def __del__(self) -> None:1247 if self._state == ClientState.OPENED:1250 # We use 'getattr' here, to manage the case where '__del__()' is called1251 # on a partically initiallized instance that raised an exception during1252 # the call to '__init__()'.1253 if getattr(self, "_state", None) == ClientState.OPENED: # noqa: B0091254 self.close()125512561257class AsyncClient(BaseClient):
335 unmodified lines
1593 allow_redirects: bool,1594 history: typing.List[Response],1595 ) -> Response:1596 auth_flow = auth.async_auth_flow(request)1597 try:1591 request = await auth_flow.__anext__()1598 request = await auth_flow.__anext__()15991593 for hook in self._event_hooks["request"]:1594 await hook(request)1600 for hook in self._event_hooks["request"]:1601 await hook(request)16021596 while True:1597 response = await self._send_handling_redirects(1598 request,1599 timeout=timeout,1600 allow_redirects=allow_redirects,1601 history=history,1602 )1603 try:1603 while True:1604 response = await self._send_handling_redirects(1605 request,1606 timeout=timeout,1607 allow_redirects=allow_redirects,1608 history=history,1609 )1610 try:1611 try:1605 next_request = await auth_flow.asend(response)1606 except StopAsyncIteration:1607 return response1612 next_request = await auth_flow.asend(response)1613 except StopAsyncIteration:1614 return response16151609 response.history = list(history)1610 await response.aread()1611 request = next_request1612 history.append(response)1616 response.history = list(history)1617 await response.aread()1618 request = next_request1619 history.append(response)16201614 except Exception as exc:1615 await response.aclose()1616 raise exc1621 except Exception as exc:1622 await response.aclose()1623 raise exc1624 finally:1625 await auth_flow.aclose()16261627 async def _send_handling_redirects(1628 self,1629 request: Request,
320 unmodified lines
1950 if proxy is not None:1951 await proxy.__aexit__(exc_type, exc_value, traceback)19521953 def __del__(self) -> None:1945 if self._state == ClientState.OPENED:1954 # We use 'getattr' here, to manage the case where '__del__()' is called1955 # on a partically initiallized instance that raised an exception during1956 # the call to '__init__()'.1957 if getattr(self, "_state", None) == ClientState.OPENED: # noqa: B0091958 # Unlike the sync case, we cannot silently close the client when1959 # it is garbage collected, because `.aclose()` is an async operation,1960 # but `__del__` is not.1961 #
21 unmodified lines
modified:httpx/_compat.py+20 added-1 removed
1"""2The _compat module is used for code which requires branching between different3Python environments. It is excluded from the code coverage checks.4"""5import ssl6import sys78# `contextlib.asynccontextmanager` exists from Python 3.7 onwards.9# For 3.6 we require the `async_generator` package for a backported version.10try:11 from contextlib import asynccontextmanager # type: ignore5except ImportError: # pragma: no cover12except ImportError:13 from async_generator import asynccontextmanager # type: ignore # noqa141516def set_minimum_tls_version_1_2(context: ssl.SSLContext) -> None:17 if sys.version_info >= (3, 10):18 context.minimum_version = ssl.TLSVersion.TLSv1_219 else:20 # These become deprecated in favor of 'context.minimum_version'21 # from Python 3.10 onwards.22 context.options |= ssl.OP_NO_SSLv223 context.options |= ssl.OP_NO_SSLv324 context.options |= ssl.OP_NO_TLSv125 context.options |= ssl.OP_NO_TLSv1_1
modified:httpx/_config.py+4 added-6 removed
4 unmodified lines
5from pathlib import Path67import certifi89from ._compat import set_minimum_tls_version_1_210from ._models import URL, Headers11from ._types import CertTypes, HeaderTypes, TimeoutTypes, URLTypes, VerifyTypes12from ._utils import get_ca_bundle_from_env, get_logger13
76 unmodified lines
90 """91 Return an SSL context for unverified connections.92 """93 context = self._create_default_ssl_context()93 context.verify_mode = ssl.CERT_NONE94 context.check_hostname = False95 context.verify_mode = ssl.CERT_NONE96 self._load_client_certs(context)97 return context9899 def load_ssl_context_verify(self) -> ssl.SSLContext:
53 unmodified lines
153 """154 Creates the default SSLContext object that's used for both verified155 and unverified connections.156 """156 context = ssl.SSLContext(ssl.PROTOCOL_TLS)157 context.options |= ssl.OP_NO_SSLv2158 context.options |= ssl.OP_NO_SSLv3159 context.options |= ssl.OP_NO_TLSv1160 context.options |= ssl.OP_NO_TLSv1_1157 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)158 set_minimum_tls_version_1_2(context)159 context.options |= ssl.OP_NO_COMPRESSION160 context.set_ciphers(DEFAULT_CIPHERS)161162 if ssl.HAS_ALPN:
196 unmodified lines
modified:tests/test_multipart.py+26 added-25 removed
105 unmodified lines
106 "d": "",107 "e": True,108 "f": "",109 }110 with open(path, "rb") as input_file:110 files = {"file": ("name.txt", open(path, "rb"))}111 files = {"file": ("name.txt", input_file)}112112 with mock.patch("os.urandom", return_value=os.urandom(16)):113 boundary = os.urandom(16).hex()113 with mock.patch("os.urandom", return_value=os.urandom(16)):114 boundary = os.urandom(16).hex()115115 headers, stream = encode_request(data=data, files=files)116 assert isinstance(stream, typing.Iterable)116 headers, stream = encode_request(data=data, files=files)117 assert isinstance(stream, typing.Iterable)118118 content = (119 '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'120 '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'121 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'122 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'123 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'124 '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'125 '--{0}\r\nContent-Disposition: form-data; name="e"\r\n\r\ntrue\r\n'126 '--{0}\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'127 '--{0}\r\nContent-Disposition: form-data; name="file";'128 ' filename="name.txt"\r\n'129 "Content-Type: text/plain\r\n\r\n<file content>\r\n"130 "--{0}--\r\n"131 "".format(boundary).encode("ascii")132 )133 assert headers == {134 "Content-Type": f"multipart/form-data; boundary={boundary}",135 "Content-Length": str(len(content)),136 }137 assert content == b"".join(stream)119 content = (120 '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'121 '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'122 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'123 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'124 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'125 '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'126 '--{0}\r\nContent-Disposition: form-data; name="e"\r\n\r\ntrue\r\n'127 '--{0}\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'128 '--{0}\r\nContent-Disposition: form-data; name="file";'129 ' filename="name.txt"\r\n'130 "Content-Type: text/plain\r\n\r\n<file content>\r\n"131 "--{0}--\r\n"132 "".format(boundary).encode("ascii")133 )134 assert headers == {135 "Content-Type": f"multipart/form-data; boundary={boundary}",136 "Content-Length": str(len(content)),137 }138 assert content == b"".join(stream)139140141def test_multipart_encode_unicode_file_contents() -> None:142 files = {"file": ("name.txt", "<únicode string>")}
153 unmodified lines
modified:setup.cfg+4 added-1 removed
14 unmodified lines
15combine_as_imports = True1617[tool:pytest]18addopts = -rxXs19filterwarnings =20 error21 default:::uvicorn22markers =23 copied_from(source, changes=None): mark test as copied from somewhere else, along with a description of changes made to accodomate e.g. our test setup2425[coverage:run]23omit = venv/*26omit = venv/*, httpx/_compat.py27include = httpx/*, tests/*