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
Provenance
- Commit
f8bec2f- Tree
cc3c638- Author
Nate Prewitt <nate.prewitt@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
7029833
19 files changed+73 added−72 removed
modified:.github/workflows/run-tests.yml+1 added-1 removed
10 unmodified lines1112131415151617181956 unmodified lines10 unmodified lines timeout-minutes: 10 strategy: fail-fast: false matrix: python-version: ["3.9", "3.10", "3.11", "3.12", "3.13", "3.14-dev", "pypy-3.10", "pypy-3.11"] python-version: ["3.9", "3.10", "3.11", "3.12", "3.13", "3.14-dev", "pypy-3.11"] os: [ubuntu-22.04, macOS-latest, windows-latest] # Pypy-3.11 can't install openssl-sys with rust # which prevents us from testing in GHA. exclude:56 unmodified linesmodified:src/requests/__init__.py+5 added-6 removed
96 unmodified lines97 except ValueError:98 return99 100 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)105 106 3 unmodified lines110 urllib3.__version__, chardet_version, charset_normalizer_version111 )112 except (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 )119 120 # Attempt to enable urllib3's fallback for SNI support63 unmodified linesmodified:src/requests/_internal_utils.py+1 added
3 unmodified lines4 5 Provides utility functions that are consumed internally by Requests6 which depend on extremely few external helpers (such as compat)7 """8+9 import re10 11 from .compat import builtin_str12 39 unmodified linesmodified:src/requests/adapters.py+8 added-6 removed
9 unmodified lines10 import socket # noqa: F40111 import typing12 import warnings13 14-from urllib3.exceptions import ClosedPoolError, ConnectTimeoutError15-from urllib3.exceptions import HTTPError as _HTTPError16-from urllib3.exceptions import InvalidHeader as _InvalidHeader14 from urllib3.exceptions import (15+ ClosedPoolError,16+ ConnectTimeoutError,17 LocationValueError,18 MaxRetryError,19 NewConnectionError,20 ProtocolError,21+ ReadTimeoutError,22+ ResponseError,23 )24+from urllib3.exceptions import HTTPError as _HTTPError25+from urllib3.exceptions import InvalidHeader as _InvalidHeader26 from urllib3.exceptions import ProxyError as _ProxyError24-from urllib3.exceptions import ReadTimeoutError, ResponseError27 from urllib3.exceptions import SSLError as _SSLError28 from urllib3.poolmanager import PoolManager, proxy_from_url29 from urllib3.util import Timeout as TimeoutSauce30 from urllib3.util import parse_url46 unmodified lines77 78 def _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 linesmodified:src/requests/auth.py+4 added-4 removed
33 unmodified lines34 # 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)44 45 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 linesmodified:src/requests/certs.py+1 added
9 unmodified lines10 If you are packaging Requests, e.g., for a Linux distribution or a managed11 environment, you can change the definition of where() to return a separately12 packaged CA bundle.13 """14+15 from certifi import where16 17 if __name__ == "__main__":18 print(where())modified:src/requests/exceptions.py+1 added
2 unmodified lines3 ~~~~~~~~~~~~~~~~~~~4 5 This module contains the set of Requests' exceptions.6 """7+8 from urllib3.exceptions import HTTPError as BaseHTTPError9 10 from .compat import JSONDecodeError as CompatJSONDecodeError11 141 unmodified linesmodified:src/requests/help.py+2 added-5 removed
45 unmodified lines46 47 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 linesmodified:src/requests/hooks.py+1 added
7 unmodified lines8 9 ``response``:10 The response generated from a Request.11 """12+13 HOOKS = ["response"]14 15 16 def default_hooks():18 unmodified linesmodified:src/requests/models.py+5 added-3 removed
32 unmodified lines33 basestring,34 builtin_str,35 chardet,36 cookielib,37+ urlencode,38+ urlsplit,39+ urlunparse,40 )41 from .compat import json as complexjson39-from .compat import urlencode, urlsplit, urlunparse42 from .cookies import _copy_cookie_jar, cookiejar_from_dict, get_cookie_header43 from .exceptions import (44 ChunkedEncodingError,45 ConnectionError,46 ContentDecodingError,47 HTTPError,48 InvalidJSONError,49 InvalidURL,50+ MissingSchema,51+ StreamConsumedError,52 )53 from .exceptions import JSONDecodeError as RequestsJSONDecodeError50-from .exceptions import MissingSchema54 from .exceptions import SSLError as RequestsSSLError52-from .exceptions import StreamConsumedError55 from .hooks import default_hooks56 from .status_codes import codes57 from .structures import CaseInsensitiveDict58 from .utils import (983 unmodified linesmodified:src/requests/sessions.py+1 added
3 unmodified lines4 5 This module provides a Session object to manage and persist settings across6 requests (cookies, auth, proxies).7 """8+9 import os10 import sys11 import time12 from collections import OrderedDict820 unmodified linesmodified:src/requests/utils.py+1 added-3 removed
37 unmodified lines38 getproxies,39 getproxies_environment,40 integer_types,41 is_urllib3_1,42-)43-from .compat import parse_http_list as _parse_list_header44-from .compat import (42 proxy_bypass,43 proxy_bypass_environment,44 quote,45 str,46 unquote,47 urlparse,48 urlunparse,49 )50+from .compat import parse_http_list as _parse_list_header51 from .cookies import cookiejar_from_dict52 from .exceptions import (53 FileModeWarning,54 InvalidHeader,1030 unmodified linesmodified:tests/test_lowlevel.py+1 added-1 removed
1 import threading2 3 import pytest4-from tests.testserver.server import Server, consume_socket_content4 5 import requests6 from requests.compat import JSONDecodeError7+from tests.testserver.server import Server, consume_socket_content8 9 from .utils import override_environ10 11 417 unmodified linesmodified:tests/test_requests.py+9 added-10 removed
42 unmodified lines43 ProxyError,44 ReadTimeout,45 RequestException,46 RetryError,47+ Timeout,48+ TooManyRedirects,49+ UnrewindableBodyError,50 )51 from requests.exceptions import SSLError as RequestsSSLError49-from requests.exceptions import Timeout, TooManyRedirects, UnrewindableBodyError52 from requests.hooks import default_hooks53 from requests.models import PreparedRequest, urlencode54 from requests.sessions import SessionRedirectMixin55 from requests.structures import CaseInsensitiveDict905 unmodified lines961 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 )969 970 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 )978 979 with pytest.raises(IOError) as e:980 requests.get(httpbin_secure(), cert=(".", INVALID_PATH))1478 unmodified lines2459 assert cookie.expires is None2460 2461 2462 class TestMorselToCookieMaxAge:2463-2463 """Tests for morsel_to_cookie when morsel contains max-age."""2464 2465 def test_max_age_valid_int(self):2466 """Test case where a valid max age in seconds is passed."""573 unmodified linesmodified:tests/test_testserver.py+2 added-2 removed
1 unmodified line2 import threading3 import time4 5 import pytest6-from tests.testserver.server import Server6 7 import requests8+from tests.testserver.server import Server9 10 11 class TestTestServer:12 def test_basic(self):28 unmodified lines41 42 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 )47 48 with server as (host, port):49 r = requests.get(f"http://{host}:{port}")116 unmodified linesmodified:.pre-commit-config.yaml+5 added-17 removed
3 unmodified lines4 - 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: flake8modified:pyproject.toml+24 added-4 removed
1-[tool.isort]2-profile = "black"3-src_paths = ["src/requests", "test"]4-honor_noqa = true1+[tool.ruff]2+target-version = "py310"3+src = ["src/requests", "tests"]4+exclude = ["docs/", "ext/"]5 6+[tool.ruff.lint]7+select = [8+ "E", # pycodestyle errors9+ "W", # pycodestyle warnings10+ "F", # pyflakes11+ "I", # isort12+ "UP", # pyupgrade13+ "T10", # flake8-debugger (replaces debug-statements hook)14+]15+ignore = ["E203", "E501", "UP038", "UP031"]16+per-file-ignores = {"src/requests/__init__.py" = ["E402", "F401"], "src/requests/compat.py" = ["E402", "F401"], "tests/compat.py" = ["F401"]}17+18+[tool.ruff.lint.isort]19+known-first-party = ["requests"]20+21+[tool.ruff.format]22+# Use black-compatible formatting23+quote-style = "double"24+indent-style = "space"25+26 [tool.pytest.ini_options]27 addopts = "--doctest-modules"28 doctest_optionflags = "NORMALIZE_WHITESPACE ELLIPSIS"29 minversion = "6.2"1 unmodified linemodified:setup.cfg-7 removed
6 unmodified lines7 certifi>=2017.4.178 charset_normalizer>=2,<49 idna>=2.5,<410 urllib3>=1.21.1,<311-12-[flake8]13-ignore = E203, E501, W50314-per-file-ignores =15- src/requests/__init__.py:E402, F40116- src/requests/compat.py:E402, F40117- tests/compat.py:F401modified:setup.py+1 added-3 removed
18 unmodified lines19 consider upgrading to a supported Python version.20 21 If you can't upgrade your Python version, you'll need to22 pin 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)26 27 78 unmodified lines