Skip to content
Myr

Fix CI and build failures (#7190)

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

* Migrate linting from various tooling to Ruff * Run ruff over codebase * Drop support for pypy-3.10

authored by Nate Prewitt · committed by GitHub · parent 7029833 · Browse files · 19 files+73 added−72 removed
This commit

State

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

Diff stats

19 files+73 added−72 removed

  • tests:+12 added−13 removed
  • other:+61 added−59 removed

19 files+73 added−72 removed

modified:.github/workflows/run-tests.yml+1 added-1 removed
modified:src/requests/__init__.py+5 added-6 removed
96 unmodified lines
97 except ValueError:98 return99100 if cryptography_version < [1, 3, 4]:101 warning = "Old version of cryptography ({}) may cause slowdown.".format(102 cryptography_version101 warning = (102 f"Old version of cryptography ({cryptography_version}) may cause slowdown."103 )104 warnings.warn(warning, RequestsDependencyWarning)105106
3 unmodified lines
110 urllib3.__version__, chardet_version, charset_normalizer_version111 )112except (AssertionError, ValueError):113 warnings.warn(114 "urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported "115 "version!".format(116 urllib3.__version__, chardet_version, charset_normalizer_version117 ),114 f"urllib3 ({urllib3.__version__}) or chardet "115 f"({chardet_version})/charset_normalizer ({charset_normalizer_version}) "116 "doesn't match a supported version!",117 RequestsDependencyWarning,118 )119120# Attempt to enable urllib3's fallback for SNI support
63 unmodified lines
modified:src/requests/_internal_utils.py+1 added
3 unmodified lines
45Provides utility functions that are consumed internally by Requests6which depend on extremely few external helpers (such as compat)7"""89import re1011from .compat import builtin_str12
39 unmodified lines
modified:src/requests/adapters.py+8 added-6 removed
9 unmodified lines
10import socket # noqa: F40111import typing12import warnings1314from urllib3.exceptions import ClosedPoolError, ConnectTimeoutError15from urllib3.exceptions import HTTPError as _HTTPError16from urllib3.exceptions import InvalidHeader as _InvalidHeader14from urllib3.exceptions import (15 ClosedPoolError,16 ConnectTimeoutError,17 LocationValueError,18 MaxRetryError,19 NewConnectionError,20 ProtocolError,21 ReadTimeoutError,22 ResponseError,23)24from urllib3.exceptions import HTTPError as _HTTPError25from urllib3.exceptions import InvalidHeader as _InvalidHeader26from urllib3.exceptions import ProxyError as _ProxyError24from urllib3.exceptions import ReadTimeoutError, ResponseError27from urllib3.exceptions import SSLError as _SSLError28from urllib3.poolmanager import PoolManager, proxy_from_url29from urllib3.util import Timeout as TimeoutSauce30from urllib3.util import parse_url
46 unmodified lines
7778def _urllib3_request_context(79 request: "PreparedRequest",80 verify: "bool | str | None",79 client_cert: "typing.Tuple[str, str] | str | None",81 client_cert: "tuple[str, str] | str | None",82 poolmanager: "PoolManager",81) -> "(typing.Dict[str, typing.Any], typing.Dict[str, typing.Any])":83) -> "(dict[str, typing.Any], dict[str, typing.Any])":84 host_params = {}85 pool_kwargs = {}86 parsed_request_url = urlparse(request.url)87 scheme = parsed_request_url.scheme.lower()
611 unmodified lines
modified:src/requests/auth.py+4 added-4 removed
33 unmodified lines
34 # for things like ints. This will be removed in 3.0.0.35 if not isinstance(username, basestring):36 warnings.warn(37 "Non-string usernames will no longer be supported in Requests "38 "3.0.0. Please convert the object you've passed in ({!r}) to "38 f"3.0.0. Please convert the object you've passed in ({username!r}) to "39 "a string or bytes object in the near future to avoid "40 "problems.".format(username),40 "problems.",41 category=DeprecationWarning,42 )43 username = str(username)4445 if not isinstance(password, basestring):46 warnings.warn(47 "Non-string passwords will no longer be supported in Requests "48 "3.0.0. Please convert the object you've passed in ({!r}) to "48 f"3.0.0. Please convert the object you've passed in ({type(password)!r}) to "49 "a string or bytes object in the near future to avoid "50 "problems.".format(type(password)),50 "problems.",51 category=DeprecationWarning,52 )53 password = str(password)54 # -- End Removal --
260 unmodified lines
modified:src/requests/certs.py+1 added
9 unmodified lines
10If you are packaging Requests, e.g., for a Linux distribution or a managed11environment, you can change the definition of where() to return a separately12packaged CA bundle.13"""1415from certifi import where1617if __name__ == "__main__":18 print(where())
modified:src/requests/exceptions.py+1 added
2 unmodified lines
3~~~~~~~~~~~~~~~~~~~45This module contains the set of Requests' exceptions.6"""78from urllib3.exceptions import HTTPError as BaseHTTPError910from .compat import JSONDecodeError as CompatJSONDecodeError11
141 unmodified lines
modified:src/requests/help.py+2 added-5 removed
45 unmodified lines
4647 if implementation == "CPython":48 implementation_version = platform.python_version()49 elif implementation == "PyPy":50 implementation_version = "{}.{}.{}".format(51 sys.pypy_version_info.major,52 sys.pypy_version_info.minor,53 sys.pypy_version_info.micro,54 )50 pypy = sys.pypy_version_info51 implementation_version = f"{pypy.major}.{pypy.minor}.{pypy.micro}"52 if sys.pypy_version_info.releaselevel != "final":53 implementation_version = "".join(54 [implementation_version, sys.pypy_version_info.releaselevel]55 )
76 unmodified lines
modified:src/requests/hooks.py+1 added
7 unmodified lines
89``response``:10 The response generated from a Request.11"""1213HOOKS = ["response"]141516def default_hooks():
18 unmodified lines
modified:src/requests/models.py+5 added-3 removed
32 unmodified lines
33 basestring,34 builtin_str,35 chardet,36 cookielib,37 urlencode,38 urlsplit,39 urlunparse,40)41from .compat import json as complexjson39from .compat import urlencode, urlsplit, urlunparse42from .cookies import _copy_cookie_jar, cookiejar_from_dict, get_cookie_header43from .exceptions import (44 ChunkedEncodingError,45 ConnectionError,46 ContentDecodingError,47 HTTPError,48 InvalidJSONError,49 InvalidURL,50 MissingSchema,51 StreamConsumedError,52)53from .exceptions import JSONDecodeError as RequestsJSONDecodeError50from .exceptions import MissingSchema54from .exceptions import SSLError as RequestsSSLError52from .exceptions import StreamConsumedError55from .hooks import default_hooks56from .status_codes import codes57from .structures import CaseInsensitiveDict58from .utils import (
983 unmodified lines
modified:src/requests/sessions.py+1 added
3 unmodified lines
45This module provides a Session object to manage and persist settings across6requests (cookies, auth, proxies).7"""89import os10import sys11import time12from collections import OrderedDict
820 unmodified lines
modified:src/requests/utils.py+1 added-3 removed
37 unmodified lines
38 getproxies,39 getproxies_environment,40 integer_types,41 is_urllib3_1,42)43from .compat import parse_http_list as _parse_list_header44from .compat import (42 proxy_bypass,43 proxy_bypass_environment,44 quote,45 str,46 unquote,47 urlparse,48 urlunparse,49)50from .compat import parse_http_list as _parse_list_header51from .cookies import cookiejar_from_dict52from .exceptions import (53 FileModeWarning,54 InvalidHeader,
1030 unmodified lines
modified:tests/test_lowlevel.py+1 added-1 removed
1import threading23import pytest4from tests.testserver.server import Server, consume_socket_content45import requests6from requests.compat import JSONDecodeError7from tests.testserver.server import Server, consume_socket_content89from .utils import override_environ1011
417 unmodified lines
modified:tests/test_requests.py+9 added-10 removed
42 unmodified lines
43 ProxyError,44 ReadTimeout,45 RequestException,46 RetryError,47 Timeout,48 TooManyRedirects,49 UnrewindableBodyError,50)51from requests.exceptions import SSLError as RequestsSSLError49from requests.exceptions import Timeout, TooManyRedirects, UnrewindableBodyError52from requests.hooks import default_hooks53from requests.models import PreparedRequest, urlencode54from requests.sessions import SessionRedirectMixin55from requests.structures import CaseInsensitiveDict
905 unmodified lines
961 def test_invalid_ca_certificate_path(self, httpbin_secure):962 INVALID_PATH = "/garbage"963 with pytest.raises(IOError) as e:964 requests.get(httpbin_secure(), verify=INVALID_PATH)963 assert str(964 e.value965 ) == "Could not find a suitable TLS CA certificate bundle, invalid path: {}".format(966 INVALID_PATH965 assert (966 str(e.value)967 == f"Could not find a suitable TLS CA certificate bundle, invalid path: {INVALID_PATH}"968 )969970 def test_invalid_ssl_certificate_files(self, httpbin_secure):971 INVALID_PATH = "/garbage"972 with pytest.raises(IOError) as e:973 requests.get(httpbin_secure(), cert=INVALID_PATH)973 assert str(974 e.value975 ) == "Could not find the TLS certificate file, invalid path: {}".format(976 INVALID_PATH974 assert (975 str(e.value)976 == f"Could not find the TLS certificate file, invalid path: {INVALID_PATH}"977 )978979 with pytest.raises(IOError) as e:980 requests.get(httpbin_secure(), cert=(".", INVALID_PATH))
1478 unmodified lines
2459 assert cookie.expires is None246024612462class TestMorselToCookieMaxAge:24632463 """Tests for morsel_to_cookie when morsel contains max-age."""24642465 def test_max_age_valid_int(self):2466 """Test case where a valid max age in seconds is passed."""
573 unmodified lines
modified:tests/test_testserver.py+2 added-2 removed
1 unmodified line
2import threading3import time45import pytest6from tests.testserver.server import Server67import requests8from tests.testserver.server import Server91011class TestTestServer:12 def test_basic(self):
28 unmodified lines
4142 def test_text_response(self):43 """the text_response_server sends the given text"""44 server = Server.text_response_server(45 "HTTP/1.1 200 OK\r\n" "Content-Length: 6\r\n" "\r\nroflol"45 "HTTP/1.1 200 OK\r\nContent-Length: 6\r\n\r\nroflol"46 )4748 with server as (host, port):49 r = requests.get(f"http://{host}:{port}")
116 unmodified lines
modified:.pre-commit-config.yaml+5 added-17 removed
3 unmodified lines
4- repo: https://github.com/pre-commit/pre-commit-hooks5 rev: v4.4.06 hooks:7 - id: check-yaml8 - id: debug-statements8 - id: end-of-file-fixer9 - id: trailing-whitespace11- repo: https://github.com/PyCQA/isort12 rev: 5.12.010- repo: https://github.com/astral-sh/ruff-pre-commit11 rev: v0.9.312 hooks:14 - id: isort15- repo: https://github.com/psf/black16 rev: 23.7.017 hooks:18 - id: black13 - id: ruff14 args: [--fix]15 - id: ruff-format16 exclude: tests/test_lowlevel.py20- repo: https://github.com/asottile/pyupgrade21 rev: v3.10.122 hooks:23 - id: pyupgrade24 args: [--py37-plus]25- repo: https://github.com/PyCQA/flake826 rev: 6.1.027 hooks:28 - id: flake8
modified:pyproject.toml+24 added-4 removed
1[tool.isort]2profile = "black"3src_paths = ["src/requests", "test"]4honor_noqa = true1[tool.ruff]2target-version = "py310"3src = ["src/requests", "tests"]4exclude = ["docs/", "ext/"]56[tool.ruff.lint]7select = [8 "E", # pycodestyle errors9 "W", # pycodestyle warnings10 "F", # pyflakes11 "I", # isort12 "UP", # pyupgrade13 "T10", # flake8-debugger (replaces debug-statements hook)14]15ignore = ["E203", "E501", "UP038", "UP031"]16per-file-ignores = {"src/requests/__init__.py" = ["E402", "F401"], "src/requests/compat.py" = ["E402", "F401"], "tests/compat.py" = ["F401"]}1718[tool.ruff.lint.isort]19known-first-party = ["requests"]2021[tool.ruff.format]22# Use black-compatible formatting23quote-style = "double"24indent-style = "space"2526[tool.pytest.ini_options]27addopts = "--doctest-modules"28doctest_optionflags = "NORMALIZE_WHITESPACE ELLIPSIS"29minversion = "6.2"
1 unmodified line
modified:setup.cfg-7 removed
6 unmodified lines
7 certifi>=2017.4.178 charset_normalizer>=2,<49 idna>=2.5,<410 urllib3>=1.21.1,<31112[flake8]13ignore = E203, E501, W50314per-file-ignores =15 src/requests/__init__.py:E402, F40116 src/requests/compat.py:E402, F40117 tests/compat.py:F401
modified:setup.py+1 added-3 removed
18 unmodified lines
19consider upgrading to a supported Python version.2021If you can't upgrade your Python version, you'll need to22pin to an older version of Requests (<2.32.0).23""".format(24 *(REQUIRED_PYTHON + CURRENT_PYTHON)25 )23""".format(*(REQUIRED_PYTHON + CURRENT_PYTHON))24 )25 sys.exit(1)2627
78 unmodified lines