Skip to content

Commit 5cf5edf

Browse files
Apply assorted ruff rules (#12988)
* Apply ruff/flake8-comprehensions rule C420 C420 Unnecessary dict comprehension for iterable; use `dict.fromkeys` instead * Apply ruff/flake8-pie rule PIE810 PIE810 Call `startswith` once with a `tuple` * Apply ruff/flake8-pyi rule PYI009 PYI009 Empty body should contain `...`, not `pass` * Apply ruff/flake8-pytest-style rule PT006 PT006 Wrong type passed to first argument of `pytest.mark.parametrize`; expected `str` * Apply ruff/flake8-simplify rule SIM103 SIM103 Return the condition directly * Apply ruff/Perflint rule PERF401 PERF401 Use `list.extend` to create a transformed list * Apply ruff/pygrep-hooks rule PGH003 PGH003 Use specific rule codes when ignoring type issues * Apply ruff/Pylint rule PLR5501 PLR5501 Use `elif` instead of `else` then `if`, to reduce indentation * Apply ruff/refurb rule FURB136 FURB136 Replace `x if x < y else y` with `min(x, y)` * Address new flake8 issue Need type annotation for "tags" (hint: "tags: List[<type>] = ...") [var-annotated] * Revert "Apply ruff/Perflint rule PERF401" This reverts commit 69d4725.
1 parent abc011b commit 5cf5edf

File tree

11 files changed

+51
-66
lines changed

11 files changed

+51
-66
lines changed

.github/bin/merge_rust_coverage.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def main(*lcov_paths: str):
8181
}
8282
coverage_data.add_arcs(covered_lines)
8383
coverage_data.add_file_tracers(
84-
{file_name: "None.RustCoveragePlugin" for file_name in covered_lines}
84+
dict.fromkeys(covered_lines, "None.RustCoveragePlugin")
8585
)
8686
coverage_data.write()
8787

src/cryptography/hazmat/backends/openssl/backend.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -260,9 +260,7 @@ def dh_x942_serialization_supported(self) -> bool:
260260
return self._lib.Cryptography_HAS_EVP_PKEY_DHX == 1
261261

262262
def x25519_supported(self) -> bool:
263-
if self._fips_enabled:
264-
return False
265-
return True
263+
return not self._fips_enabled
266264

267265
def x448_supported(self) -> bool:
268266
if self._fips_enabled:
@@ -274,9 +272,7 @@ def x448_supported(self) -> bool:
274272
)
275273

276274
def ed25519_supported(self) -> bool:
277-
if self._fips_enabled:
278-
return False
279-
return True
275+
return not self._fips_enabled
280276

281277
def ed448_supported(self) -> bool:
282278
if self._fips_enabled:
@@ -294,9 +290,7 @@ def ecdsa_deterministic_supported(self) -> bool:
294290
)
295291

296292
def poly1305_supported(self) -> bool:
297-
if self._fips_enabled:
298-
return False
299-
return True
293+
return not self._fips_enabled
300294

301295
def pkcs7_supported(self) -> bool:
302296
return (

src/cryptography/hazmat/bindings/_rust/x509.pyi

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -298,5 +298,4 @@ class ServerVerifier:
298298
class Store:
299299
def __init__(self, certs: list[x509.Certificate]) -> None: ...
300300

301-
class VerificationError(Exception):
302-
pass
301+
class VerificationError(Exception): ...

src/cryptography/hazmat/primitives/kdf/kbkdf.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -117,9 +117,7 @@ def _valid_byte_length(value: int) -> bool:
117117
raise TypeError("value must be of type int")
118118

119119
value_bin = utils.int_to_bytes(1, value)
120-
if not 1 <= len(value_bin) <= 4:
121-
return False
122-
return True
120+
return 1 <= len(value_bin) <= 4
123121

124122
def derive(
125123
self, key_material: utils.Buffer, prf_output_size: int

src/cryptography/x509/name.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -144,9 +144,8 @@ def __init__(
144144
)
145145
if not isinstance(value, bytes):
146146
raise TypeError("value must be bytes for BitString")
147-
else:
148-
if not isinstance(value, str):
149-
raise TypeError("value argument must be a str")
147+
elif not isinstance(value, str):
148+
raise TypeError("value argument must be a str")
150149

151150
length_limits = _NAMEOID_LENGTH_LIMIT.get(oid)
152151
if length_limits is not None:

tests/hazmat/primitives/test_kbkdf.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -299,7 +299,7 @@ def test_keyword_only_break_location(self, backend):
299299
None,
300300
backend,
301301
0, # break_location
302-
) # type: ignore
302+
) # type: ignore[misc]
303303

304304
def test_invalid_break_location(self, backend):
305305
with pytest.raises(
@@ -770,7 +770,7 @@ def test_keyword_only_break_location(self, backend):
770770
None,
771771
backend,
772772
0, # break_location
773-
) # type: ignore
773+
) # type: ignore[misc]
774774

775775
def test_invalid_break_location(self, backend):
776776
with pytest.raises(

tests/hazmat/primitives/test_ssh.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -160,17 +160,17 @@ def run_partial_pubkey(self, pubdata, backend):
160160
load_ssh_public_key(new_pub, backend)
161161

162162
@pytest.mark.parametrize(
163-
("key_file",),
163+
"key_file",
164164
[
165-
("rsa-nopsw.key",),
166-
("rsa-psw.key",),
167-
("dsa-nopsw.key",),
168-
("dsa-psw.key",),
169-
("ecdsa-nopsw.key",),
170-
("ecdsa-psw.key",),
171-
("ed25519-nopsw.key",),
172-
("ed25519-psw.key",),
173-
("ed25519-aesgcm-psw.key",),
165+
"rsa-nopsw.key",
166+
"rsa-psw.key",
167+
"dsa-nopsw.key",
168+
"dsa-psw.key",
169+
"ecdsa-nopsw.key",
170+
"ecdsa-psw.key",
171+
"ed25519-nopsw.key",
172+
"ed25519-psw.key",
173+
"ed25519-aesgcm-psw.key",
174174
],
175175
)
176176
def test_load_ssh_private_key(self, key_file, backend):

tests/hazmat/primitives/test_xofhash.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ def test_shake128_variable(self, backend, subtests):
9898
data = b""
9999
stride = random.randint(1, 128)
100100
while remaining > 0:
101-
stride = remaining if remaining < stride else stride
101+
stride = min(stride, remaining)
102102
data += m.squeeze(stride)
103103
remaining -= stride
104104
assert data == binascii.unhexlify(vector["output"])
@@ -126,7 +126,7 @@ def test_shake256_variable(self, backend, subtests):
126126
data = b""
127127
stride = random.randint(1, 128)
128128
while remaining > 0:
129-
stride = remaining if remaining < stride else stride
129+
stride = min(stride, remaining)
130130
data += m.squeeze(stride)
131131
remaining -= stride
132132
assert data == binascii.unhexlify(vector["output"])

tests/utils.py

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ def load_hash_vectors(vector_data):
120120
for line in vector_data:
121121
line = line.strip()
122122

123-
if not line or line.startswith("#") or line.startswith("["):
123+
if not line or line.startswith(("#", "[")):
124124
continue
125125

126126
if line.startswith("Len"):
@@ -133,7 +133,7 @@ def load_hash_vectors(vector_data):
133133
# string as hex 00, which is of course not actually an empty
134134
# string. So we parse the provided length and catch this edge case.
135135
msg = line.split(" = ")[1].encode("ascii") if length > 0 else b""
136-
elif line.startswith("MD") or line.startswith("Output"):
136+
elif line.startswith(("MD", "Output")):
137137
md = line.split(" = ")[1]
138138
# after MD is found the Msg+MD (+ potential key) tuple is complete
139139
if key is not None:
@@ -162,10 +162,8 @@ def load_pkcs1_vectors(vector_data):
162162
examples = []
163163
vectors = []
164164
for line in vector_data:
165-
if (
166-
line.startswith("# PSS Example")
167-
or line.startswith("# OAEP Example")
168-
or line.startswith("# PKCS#1 v1.5")
165+
if line.startswith(
166+
("# PSS Example", "# OAEP Example", "# PKCS#1 v1.5")
169167
):
170168
if example_vector:
171169
for key, value in example_vector.items():
@@ -202,13 +200,12 @@ def load_pkcs1_vectors(vector_data):
202200
attr = None
203201
elif example_vector and line.startswith("#"):
204202
continue
205-
else:
206-
if attr is not None and example_vector is not None:
207-
example_vector[attr].append(line.strip())
208-
continue
203+
elif attr is not None and example_vector is not None:
204+
example_vector[attr].append(line.strip())
205+
continue
209206

210-
if line.startswith("# Example") or line.startswith(
211-
"# ============================================="
207+
if line.startswith(
208+
("# Example", "# =============================================")
212209
):
213210
if key:
214211
assert private_key_vector
@@ -271,9 +268,8 @@ def load_pkcs1_vectors(vector_data):
271268
attr = "iqmp"
272269
elif line.startswith("#"):
273270
attr = None
274-
else:
275-
if key is not None and attr is not None:
276-
key[attr].append(line.strip())
271+
elif key is not None and attr is not None:
272+
key[attr].append(line.strip())
277273
return vectors
278274

279275

@@ -343,7 +339,7 @@ def load_fips_dsa_key_pair_vectors(vector_data):
343339
for line in vector_data:
344340
line = line.strip()
345341

346-
if not line or line.startswith("#") or line.startswith("[mod"):
342+
if not line or line.startswith(("#", "[mod")):
347343
continue
348344

349345
if line.startswith("P"):
@@ -607,7 +603,7 @@ def load_kasvs_ecdh_vectors(vector_data):
607603
"P-521": "secp521r1",
608604
}
609605

610-
tags = []
606+
tags: typing.List[str] = []
611607
sets = {}
612608
vectors = []
613609

@@ -720,7 +716,7 @@ def load_rfc6979_vectors(vector_data):
720716
reading_key = False
721717
current_key_name = None
722718

723-
if line.startswith("PrivateKey=") or line.startswith("PublicKey="):
719+
if line.startswith(("PrivateKey=", "PublicKey=")):
724720
reading_key = True
725721
current_key_name = line.split("=")[1].strip()
726722
keys[current_key_name] = []

tests/wycheproof/test_rsa.py

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -279,19 +279,18 @@ def test_rsa_pkcs1_encryption(backend, wycheproof):
279279
binascii.unhexlify(wycheproof.testcase["ct"]), padding.PKCS1v15()
280280
)
281281
assert pt == binascii.unhexlify(wycheproof.testcase["msg"])
282+
elif backend._lib.Cryptography_HAS_IMPLICIT_RSA_REJECTION:
283+
try:
284+
assert key.decrypt(
285+
binascii.unhexlify(wycheproof.testcase["ct"]),
286+
padding.PKCS1v15(),
287+
) != binascii.unhexlify(wycheproof.testcase["ct"])
288+
except ValueError:
289+
# Some raise ValueError due to length mismatch.
290+
pass
282291
else:
283-
if backend._lib.Cryptography_HAS_IMPLICIT_RSA_REJECTION:
284-
try:
285-
assert key.decrypt(
286-
binascii.unhexlify(wycheproof.testcase["ct"]),
287-
padding.PKCS1v15(),
288-
) != binascii.unhexlify(wycheproof.testcase["ct"])
289-
except ValueError:
290-
# Some raise ValueError due to length mismatch.
291-
pass
292-
else:
293-
with pytest.raises(ValueError):
294-
key.decrypt(
295-
binascii.unhexlify(wycheproof.testcase["ct"]),
296-
padding.PKCS1v15(),
297-
)
292+
with pytest.raises(ValueError):
293+
key.decrypt(
294+
binascii.unhexlify(wycheproof.testcase["ct"]),
295+
padding.PKCS1v15(),
296+
)

0 commit comments

Comments
 (0)