Skip to content
Myr

Ruff linter: Use the default line-length (#2922)

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

authored by T-256 · committed by GitHub · parent 90d71e6 · Browse files · 15 files+89 added−58 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: Tester <Tester@test.com>
  • Co-authored-by: Kar Petrosyan <92274156+karpetrosyan@users.noreply.github.com>

Diff stats

15 files+89 added−58 removed

  • tests:+15 added−7 removed
  • other:+74 added−51 removed

15 files+89 added−58 removed

modified:httpx/_transports/default.py+4 added-2 removed
188 unmodified lines
189 http2=http2,190 )191 else: # pragma: no cover192 raise ValueError(193 f"Proxy protocol must be either 'http', 'https', or 'socks5', but got {proxy.url.scheme!r}."193 "Proxy protocol must be either 'http', 'https', or 'socks5',"194 f" but got {proxy.url.scheme!r}."195 )196197 def __enter__(self: T) -> T: # Use generics for subclass support.198 self._pool.__enter__()
129 unmodified lines
328 http2=http2,329 )330 else: # pragma: no cover331 raise ValueError(331 f"Proxy protocol must be either 'http', 'https', or 'socks5', but got {proxy.url.scheme!r}."332 "Proxy protocol must be either 'http', 'https', or 'socks5',"333 " but got {proxy.url.scheme!r}."334 )335336 async def __aenter__(self: A) -> A: # Use generics for subclass support.337 await self._pool.__aenter__()
43 unmodified lines
modified:httpx/_client.py+6 added-2 removed
1262 unmodified lines
1263 def __enter__(self: T) -> T:1264 if self._state != ClientState.UNOPENED:1265 msg = {1266 ClientState.OPENED: "Cannot open a client instance more than once.",1267 ClientState.CLOSED: "Cannot reopen a client instance, once it has been closed.",1267 ClientState.CLOSED: (1268 "Cannot reopen a client instance, once it has been closed."1269 ),1270 }[self._state]1271 raise RuntimeError(msg)12721273 self._state = ClientState.OPENED
707 unmodified lines
1981 async def __aenter__(self: U) -> U:1982 if self._state != ClientState.UNOPENED:1983 msg = {1984 ClientState.OPENED: "Cannot open a client instance more than once.",1983 ClientState.CLOSED: "Cannot reopen a client instance, once it has been closed.",1985 ClientState.CLOSED: (1986 "Cannot reopen a client instance, once it has been closed."1987 ),1988 }[self._state]1989 raise RuntimeError(msg)19901991 self._state = ClientState.OPENED
19 unmodified lines
modified:httpx/_decoders.py+2 added-1 removed
257 unmodified lines
258class LineDecoder:259 """260 Handles incrementally reading lines from text.261262 Has the same behaviour as the stdllib splitlines, but handling the input iteratively.262 Has the same behaviour as the stdllib splitlines,263 but handling the input iteratively.264 """265266 def __init__(self) -> None:267 self.buffer: typing.List[str] = []
58 unmodified lines
modified:httpx/_exceptions.py+8 added-2 removed
311 unmodified lines
312 Attempted to access streaming response content, without having called `read()`.313 """314315 def __init__(self) -> None:316 message = "Attempted to access streaming response content, without having called `read()`."316 message = (317 "Attempted to access streaming response content,"318 " without having called `read()`."319 )320 super().__init__(message)321322323class RequestNotRead(StreamError):
1 unmodified line
325 Attempted to access streaming request content, without having called `read()`.326 """327328 def __init__(self) -> None:326 message = "Attempted to access streaming request content, without having called `read()`."329 message = (330 "Attempted to access streaming request content,"331 " without having called `read()`."332 )333 super().__init__(message)334335336@contextlib.contextmanager
13 unmodified lines
modified:httpx/_main.py+6 added-5 removed
61 unmodified lines
62 "--cookies [cyan]<NAME VALUE> ...", "Cookies to include in the request."63 )64 table.add_row(65 "--auth [cyan]<USER PASS>",66 "Username and password to include in the request. Specify '-' for the password to use "67 "a password prompt. Note that using --verbose/-v will expose the Authorization "68 "header, including the password encoding in a trivially reversible format.",66 "Username and password to include in the request. Specify '-' for the password"67 " to use a password prompt. Note that using --verbose/-v will expose"68 " the Authorization header, including the password encoding"69 " in a trivially reversible format.",70 )7172 table.add_row(73 "--proxies [cyan]URL",
1 unmodified line
75 )7677 table.add_row(78 "--timeout [cyan]FLOAT",78 "Timeout value to use for network operations, such as establishing the connection, "79 "reading some data, etc... [Default: 5.0]",79 "Timeout value to use for network operations, such as establishing the"80 " connection, reading some data, etc... [Default: 5.0]",81 )8283 table.add_row("--follow-redirects", "Automatically follow redirects.")84 table.add_row("--no-verify", "Disable SSL verification.")
423 unmodified lines
modified:httpx/_models.py+2 added-1 removed
356 unmodified lines
357 #358 # Using `content=...` implies automatically populated `Host` and content359 # headers, of either `Content-Length: ...` or `Transfer-Encoding: chunked`.360 #361 # Using `stream=...` will not automatically include *any* auto-populated headers.361 # Using `stream=...` will not automatically include *any*362 # auto-populated headers.363 #364 # As an end-user you don't really need `stream=...`. It's only365 # useful when:366 #
849 unmodified lines
modified:httpx/_multipart.py+10 added-7 removed
46 unmodified lines
47 f"Invalid type for name. Expected str, got {type(name)}: {name!r}"48 )49 if value is not None and not isinstance(value, (str, bytes, int, float)):50 raise TypeError(51 f"Invalid type for value. Expected primitive type, got {type(value)}: {value!r}"51 "Invalid type for value. Expected primitive type,"52 f" got {type(value)}: {value!r}"53 )54 self.name = name55 self.value: typing.Union[str, bytes] = (56 value if isinstance(value, bytes) else primitive_value_to_str(value)
39 unmodified lines
96 headers: typing.Dict[str, str] = {}97 content_type: typing.Optional[str] = None9899 # This large tuple based API largely mirror's requests' API99 # It would be good to think of better APIs for this that we could include in httpx 2.0100 # since variable length tuples (especially of 4 elements) are quite unwieldly100 # It would be good to think of better APIs for this that we could101 # include in httpx 2.0 since variable length tuples(especially of 4 elements)102 # are quite unwieldly103 if isinstance(value, tuple):104 if len(value) == 2:103 # neither the 3rd parameter (content_type) nor the 4th (headers) was included105 # neither the 3rd parameter (content_type) nor the 4th (headers)106 # was included107 filename, fileobj = value # type: ignore108 elif len(value) == 3:109 filename, fileobj, content_type = value # type: ignore110 else:
7 unmodified lines
118 content_type = guess_content_type(filename)119120 has_content_type_header = any("content-type" in key.lower() for key in headers)121 if content_type is not None and not has_content_type_header:119 # note that unlike requests, we ignore the content_type120 # provided in the 3rd tuple element if it is also included in the headers121 # requests does the opposite (it overwrites the header with the 3rd tuple element)122 # note that unlike requests, we ignore the content_type provided in the 3rd123 # tuple element if it is also included in the headers requests does124 # the opposite (it overwrites the headerwith the 3rd tuple element)125 headers["Content-Type"] = content_type126127 if isinstance(fileobj, io.StringIO):128 raise TypeError(
141 unmodified lines
modified:httpx/_urlparse.py+22 added-19 removed
358 unmodified lines
359360361def validate_path(path: str, has_scheme: bool, has_authority: bool) -> None:362 """363 Path validation rules that depend on if the URL contains a scheme or authority component.363 Path validation rules that depend on if the URL contains364 a scheme or authority component.365366 See https://datatracker.ietf.org/doc/html/rfc3986.html#section-3.3367 """368 if has_authority:368 # > If a URI contains an authority component, then the path component369 # > must either be empty or begin with a slash ("/") character."369 # If a URI contains an authority component, then the path component370 # must either be empty or begin with a slash ("/") character."371 if path and not path.startswith("/"):372 raise InvalidURL("For absolute URLs, path must be empty or begin with '/'")373 else:373 # > If a URI does not contain an authority component, then the path cannot begin374 # > with two slash characters ("//").374 # If a URI does not contain an authority component, then the path cannot begin375 # with two slash characters ("//").376 if path.startswith("//"):377 raise InvalidURL(378 "URLs with no authority component cannot have a path starting with '//'"379 )379 # > In addition, a URI reference (Section 4.1) may be a relative-path reference, in which380 # > case the first path segment cannot contain a colon (":") character.380 # In addition, a URI reference (Section 4.1) may be a relative-path reference,381 # in which case the first path segment cannot contain a colon (":") character.382 if path.startswith(":") and not has_scheme:383 raise InvalidURL(384 "URLs with no scheme component cannot have a path starting with ':'"385 )
63 unmodified lines
449 )450451452def urlencode(items: typing.List[typing.Tuple[str, str]]) -> str:453 """452 # We can use a much simpler version of the stdlib urlencode here because453 # we don't need to handle a bunch of different typing cases, such as bytes vs str.454 #455 # https://github.com/python/cpython/blob/b2f7b2ef0b5421e01efb8c7bee2ef95d3bab77eb/Lib/urllib/parse.py#L926456 #457 # Note that we use '%20' encoding for spaces. and '%2F for '/'.458 # This is slightly different than `requests`, but is the behaviour that browsers use.459 #460 # See461 # - https://github.com/encode/httpx/issues/2536462 # - https://github.com/encode/httpx/issues/2721463 # - https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode454 We can use a much simpler version of the stdlib urlencode here because455 we don't need to handle a bunch of different typing cases, such as bytes vs str.456457 https://github.com/python/cpython/blob/b2f7b2ef0b5421e01efb8c7bee2ef95d3bab77eb/Lib/urllib/parse.py#L926458459 Note that we use '%20' encoding for spaces. and '%2F for '/'.460 This is slightly different than `requests`, but is the behaviour that browsers use.461462 See463 - https://github.com/encode/httpx/issues/2536464 - https://github.com/encode/httpx/issues/2721465 - https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode466 """467 return "&".join([quote(k, safe="") + "=" + quote(v, safe="") for k, v in items])
modified:httpx/_urls.py+14 added-8 removed
49 unmodified lines
50 url = httpx.URL("http://xn--fiqs8s.icom.museum")51 assert url.raw_host == b"xn--fiqs8s.icom.museum"5253 * `url.port` is either None or an integer. URLs that include the default port for54 "http", "https", "ws", "wss", and "ftp" schemes have their port normalized to `None`.54 "http", "https", "ws", "wss", and "ftp" schemes have their port55 normalized to `None`.5657 assert httpx.URL("http://example.com") == httpx.URL("http://example.com:80")58 assert httpx.URL("http://example.com").port is None59 assert httpx.URL("http://example.com:80").port is None6060 * `url.userinfo` is raw bytes, without URL escaping. Usually you'll want to work with61 `url.username` and `url.password` instead, which handle the URL escaping.61 * `url.userinfo` is raw bytes, without URL escaping. Usually you'll want to work62 with `url.username` and `url.password` instead, which handle the URL escaping.6364 * `url.raw_path` is raw bytes of both the path and query, without URL escaping.65 This portion is used as the target when constructing HTTP requests. Usually you'll66 want to work with `url.path` instead.6767 * `url.query` is raw bytes, without URL escaping. A URL query string portion can only68 be properly URL escaped when decoding the parameter names and values themselves.68 * `url.query` is raw bytes, without URL escaping. A URL query string portion can69 only be properly URL escaped when decoding the parameter names and values70 themselves.71 """7273 def __init__(74 self, url: typing.Union["URL", str] = "", **kwargs: typing.Any
41 unmodified lines
116 elif isinstance(url, URL):117 self._uri_reference = url._uri_reference.copy_with(**kwargs)118 else:119 raise TypeError(118 f"Invalid type for url. Expected str or httpx.URL, got {type(url)}: {url!r}"120 "Invalid type for url. Expected str or httpx.URL,"121 f" got {type(url)}: {url!r}"122 )123124 @property125 def scheme(self) -> str:
181 unmodified lines
307 """308 Provides the (scheme, host, port, target) for the outgoing request.309310 In older versions of `httpx` this was used in the low-level transport API.308 We no longer use `RawURL`, and this property will be deprecated in a future release.311 We no longer use `RawURL`, and this property will be deprecated312 in a future release.313 """314 return RawURL(315 self.raw_scheme,316 self.raw_host,
28 unmodified lines
345 available via properties on the `URL` class.346347 For example:348345 url = httpx.URL("https://www.example.com").copy_with(username="jo@gmail.com", password="a secret")349 url = httpx.URL("https://www.example.com").copy_with(350 username="jo@gmail.com", password="a secret"351 )352 assert url == "https://jo%40email.com:a%20secret@www.example.com"353 """354 return URL(self, **kwargs)355
293 unmodified lines
modified:tests/client/test_auth.py+2 added-1 removed
594 unmodified lines
595596 # with this we now force a 401 on a subsequent (but initial) request597 app.send_response_after_attempt = 2598599 # we expect the client again to try to authenticate, i.e. the history length must be 1599 # we expect the client again to try to authenticate,600 # i.e. the history length must be 1601 response_2 = await client.get(url, auth=auth)602 assert response_2.status_code == 200603 assert len(response_2.history) == 1604
190 unmodified lines
modified:tests/models/test_cookies.py+3 added-3 removed
90 unmodified lines
91 cookies = httpx.Cookies()92 cookies.set(name="foo", value="bar", domain="http://blah.com")93 cookies.set(name="fizz", value="buzz", domain="http://hello.com")9495 assert (96 repr(cookies)97 == "<Cookies[<Cookie foo=bar for http://blah.com />, <Cookie fizz=buzz for http://hello.com />]>"95 assert repr(cookies) == (96 "<Cookies[<Cookie foo=bar for http://blah.com />,"97 " <Cookie fizz=buzz for http://hello.com />]>"98 )
modified:tests/test_config.py+4 added-1 removed
99 unmodified lines
100101102def test_limits_repr():103 limits = httpx.Limits(max_connections=100)104 expected = "Limits(max_connections=100, max_keepalive_connections=None, keepalive_expiry=5.0)"104 expected = (105 "Limits(max_connections=100, max_keepalive_connections=None,"106 " keepalive_expiry=5.0)"107 )108 assert repr(limits) == expected109110111def test_limits_eq():
112 unmodified lines
modified:tests/test_multipart.py+4 added-1 removed
172 unmodified lines
173 )174175176def test_multipart_headers_include_content_type() -> None:177 """Content-Type from 4th tuple parameter (headers) should override the 3rd parameter (content_type)"""177 """178 Content-Type from 4th tuple parameter (headers) should179 override the 3rd parameter (content_type)180 """181 file_name = "test.txt"182 file_content = io.BytesIO(b"<file content>")183 file_content_type = "text/plain"184 file_headers = {"Content-Type": "image/png"}
283 unmodified lines
modified:tests/test_utils.py+2 added-1 removed
107 unmodified lines
108 assert caplog.record_tuples == [109 (110 "httpx",111 logging.INFO,112 'HTTP Request: GET http://127.0.0.1:8000/redirect_301 "HTTP/1.1 301 Moved Permanently"',112 "HTTP Request: GET http://127.0.0.1:8000/redirect_301"113 ' "HTTP/1.1 301 Moved Permanently"',114 ),115 (116 "httpx",117 logging.INFO,
171 unmodified lines
modified:pyproject.toml-4 removed
95 unmodified lines
96# https://beta.ruff.rs/docs/configuration/#using-rufftoml97[tool.ruff]98select = ["E", "F", "I", "B", "PIE"]99ignore = ["B904", "B028"]100line-length = 88100102[tool.ruff.pycodestyle]103max-line-length = 120104101[tool.ruff.isort]102combine-as-imports = true103104[tool.mypy]
24 unmodified lines