Skip to content

Commit

Permalink
run ruff format
Browse files Browse the repository at this point in the history
  • Loading branch information
ThirVondukr committed Sep 16, 2024
1 parent 73ddde3 commit af4d28f
Show file tree
Hide file tree
Showing 16 changed files with 122 additions and 113 deletions.
8 changes: 5 additions & 3 deletions admin/regen.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,11 @@ def replace_section(data, ident, content):
\# \s end \s* {ident} \s* \n
\#[-=]{{10,}}\n
(?P<tail>.*)
""".format(**dict(
ident=re.escape(ident).replace("\\ ", "\\s+"),
)),
""".format(
**dict(
ident=re.escape(ident).replace("\\ ", "\\s+"),
)
),
data.replace("\r\n", "\n"),
)
assert m, f"{ident!r} section not found"
Expand Down
4 changes: 1 addition & 3 deletions passlib/apache.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,9 +347,7 @@ def _encode_field(self, value, param="field"):
if len(value) > 255:
raise ValueError(f"{param} must be at most 255 characters: {value!r}")
if any(c in _INVALID_FIELD_CHARS for c in value):
raise ValueError(
f"{param} contains invalid characters: {value!r}"
)
raise ValueError(f"{param} contains invalid characters: {value!r}")
return value

def _decode_field(self, value):
Expand Down
14 changes: 8 additions & 6 deletions passlib/handlers/argon2.py
Original file line number Diff line number Diff line change
Expand Up @@ -736,9 +736,10 @@ def _load_backend_mixin(mixin_cls, name, dryrun):
type_map[type] = getattr(TypeEnum, type.upper())
except AttributeError:
# TYPE_ID support not added until v18.2
assert type not in (TYPE_I, TYPE_D), (
f"unexpected missing type: {type!r}"
)
assert type not in (
TYPE_I,
TYPE_D,
), f"unexpected missing type: {type!r}"
mixin_cls._backend_type_map = type_map

# set version info, and run common setup
Expand Down Expand Up @@ -872,9 +873,10 @@ def _load_backend_mixin(mixin_cls, name, dryrun):
type_map[type] = getattr(_argon2pure, "ARGON2" + type.upper())
except AttributeError:
# TYPE_ID support not added until v1.3
assert type not in (TYPE_I, TYPE_D), (
f"unexpected missing type: {type!r}"
)
assert type not in (
TYPE_I,
TYPE_D,
), f"unexpected missing type: {type!r}"
mixin_cls._backend_type_map = type_map

mixin_cls.version = mixin_cls.max_version = max_version
Expand Down
4 changes: 1 addition & 3 deletions passlib/handlers/bcrypt.py
Original file line number Diff line number Diff line change
Expand Up @@ -1049,9 +1049,7 @@ def __init__(self, version=None, **kwds):
@classmethod
def _norm_version(cls, version):
if version not in cls._supported_versions:
raise ValueError(
f"{cls.name}: unknown or unsupported version: {version!r}"
)
raise ValueError(f"{cls.name}: unknown or unsupported version: {version!r}")
return version

def _calc_checksum(self, secret):
Expand Down
6 changes: 3 additions & 3 deletions passlib/handlers/fshp.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,9 @@ def __init__(self, variant=None, **kwds):
variant = self._norm_variant(variant)
elif self.use_defaults:
variant = self.default_variant
assert self._norm_variant(variant) == variant, (
f"invalid default variant: {variant!r}"
)
assert (
self._norm_variant(variant) == variant
), f"invalid default variant: {variant!r}"
else:
raise TypeError("no variant specified")
self.variant = variant
Expand Down
3 changes: 1 addition & 2 deletions passlib/handlers/scram.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,8 +249,7 @@ def to_string(self):
salt = bascii_to_str(ab64_encode(self.salt))
chkmap = self.checksum
chk_str = ",".join(
f"{alg}={bascii_to_str(ab64_encode(chkmap[alg]))}"
for alg in self.algs
f"{alg}={bascii_to_str(ab64_encode(chkmap[alg]))}" for alg in self.algs
)
return "$scram$%d$%s$%s" % (self.rounds, salt, chk_str)

Expand Down
4 changes: 3 additions & 1 deletion passlib/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,9 @@ def get_crypt_handler(name, default=_UNSET):
handler = _handlers.get(name)
if handler:
# XXX: issue deprecation warning here?
assert is_crypt_handler(handler), f"unexpected object: name={name!r} object={handler!r}"
assert is_crypt_handler(
handler
), f"unexpected object: name={name!r} object={handler!r}"
return handler

# then get real handler & register it
Expand Down
4 changes: 3 additions & 1 deletion passlib/totp.py
Original file line number Diff line number Diff line change
Expand Up @@ -1521,7 +1521,9 @@ def to_uri(self, label=None, issuer=None):
# NOTE: not using urllib.urlencode() because it encodes ' ' as '+';
# but spec says to use '%20', and not sure how fragile
# the various totp clients' parsers are.
param_str = "&".join("{}={}".format(key, quote(value, "")) for key, value in params)
param_str = "&".join(
"{}={}".format(key, quote(value, "")) for key, value in params
)
assert param_str, "param_str should never be empty"

# render uri
Expand Down
26 changes: 12 additions & 14 deletions passlib/utils/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,9 @@ def guess_app_stacklevel(start=1):
def warn_hash_settings_deprecation(handler, kwds):
warn(
"passing settings to {handler}.hash() is deprecated, and won't be supported in Passlib 2.0; "
"use '{handler}.using(**settings).hash(secret)' instead".format(**dict(handler=handler.name)),
"use '{handler}.using(**settings).hash(secret)' instead".format(
**dict(handler=handler.name)
),
DeprecationWarning,
stacklevel=guess_app_stacklevel(2),
)
Expand Down Expand Up @@ -364,7 +366,9 @@ def validate_default_value(handler, default, norm, param="value"):
designed to get out of the way and reduce overhead when asserts are stripped.
"""
assert default is not None, f"{handler.name} lacks default {param}"
assert norm(default) == default, f"{handler.name}: invalid default {param}: {default!r}"
assert (
norm(default) == default
), f"{handler.name}: invalid default {param}: {default!r}"
return True


Expand Down Expand Up @@ -747,9 +751,7 @@ def _calc_checksum(self, secret): # pragma: no cover
calc checksum implementations may assume secret is always
either str or bytes, checks are performed by verify/etc.
"""
raise NotImplementedError(
f"{self.__class__} must implement _calc_checksum()"
)
raise NotImplementedError(f"{self.__class__} must implement _calc_checksum()")

@classmethod
def hash(cls, secret, **kwds):
Expand Down Expand Up @@ -1745,9 +1747,9 @@ def __init__(self, rounds=None, **kwds):
rounds = self._parse_rounds(rounds)
elif self.use_defaults:
rounds = self._generate_rounds()
assert self._norm_rounds(rounds) == rounds, (
f"generated invalid rounds: {rounds!r}"
)
assert (
self._norm_rounds(rounds) == rounds
), f"generated invalid rounds: {rounds!r}"
else:
raise TypeError("no rounds specified")
self.rounds = rounds
Expand Down Expand Up @@ -1800,9 +1802,7 @@ def _generate_rounds(cls):
# load default rounds
rounds = cls.default_rounds
if rounds is None:
raise TypeError(
f"{cls.name} rounds value must be specified explicitly"
)
raise TypeError(f"{cls.name} rounds value must be specified explicitly")

# randomly vary the rounds slightly basic on vary_rounds parameter.
# reads default_rounds internally.
Expand Down Expand Up @@ -2136,9 +2136,7 @@ def _set_backend(cls, name, dryrun):
kwds["dryrun"] = dryrun
ok = loader(**kwds)
if ok is False:
raise exc.MissingBackendError(
f"{cls.name}: backend not available: {name}"
)
raise exc.MissingBackendError(f"{cls.name}: backend not available: {name}")
elif ok is not True:
raise AssertionError(
"backend loaders must return True or False" f": {ok!r}"
Expand Down
12 changes: 9 additions & 3 deletions tests/test_crypto_des.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,13 +139,17 @@ def test_03_encrypt_bytes(self):
# test 56-bit version
key2 = shrink_des_key(key)
result = des_encrypt_block(key2, plaintext)
assert result == correct, f"key={key!r} shrink(key)={key2!r} plaintext={plaintext!r}:"
assert (
result == correct
), f"key={key!r} shrink(key)={key2!r} plaintext={plaintext!r}:"

# test with random parity bits
for _ in range(20):
key3 = _pack64(self._random_parity(_unpack64(key)))
result = des_encrypt_block(key3, plaintext)
assert result == correct, f"key={key!r} rndparity(key)={key3!r} plaintext={plaintext!r}:"
assert (
result == correct
), f"key={key!r} rndparity(key)={key3!r} plaintext={plaintext!r}:"

# check invalid keys
stub = b"\x00" * 8
Expand Down Expand Up @@ -184,7 +188,9 @@ def test_04_encrypt_ints(self):
for _ in range(20):
key3 = self._random_parity(key)
result = des_encrypt_int_block(key3, plaintext)
assert result == correct, f"key={key!r} rndparity(key)={key3!r} plaintext={plaintext!r}:"
assert (
result == correct
), f"key={key!r} rndparity(key)={key3!r} plaintext={plaintext!r}:"

# check invalid keys
with pytest.raises(TypeError):
Expand Down
4 changes: 2 additions & 2 deletions tests/test_crypto_digest.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,8 +303,8 @@ def helper(secret=b"secret", salt=b"salt", rounds=1, keylen=1, hash="md5"):
class Pbkdf2Test(TestCase):
"""test pbkdf2() support"""

descriptionPrefix = (
"passlib.crypto.digest.pbkdf2_hmac() <backends: {}>".format(", ".join(PBKDF2_BACKENDS))
descriptionPrefix = "passlib.crypto.digest.pbkdf2_hmac() <backends: {}>".format(
", ".join(PBKDF2_BACKENDS)
)

pbkdf2_test_vectors = [
Expand Down
6 changes: 3 additions & 3 deletions tests/test_crypto_scrypt.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,9 +454,9 @@ def test_other_backends(self):
result = hexstr(scrypt_mod.scrypt(secret, salt, n, r, p, ks))
assert len(result) == 2 * ks
if previous is not None:
assert result == previous, (
f"{name!r} output differs from others {available!r}: {[secret, salt, n, r, p, ks]!r}"
)
assert (
result == previous
), f"{name!r} output differs from others {available!r}: {[secret, salt, n, r, p, ks]!r}"

def test_backend(self):
"""backend management"""
Expand Down
24 changes: 12 additions & 12 deletions tests/test_ext_django.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,13 +262,13 @@ def assert_unpatched(self):
# make sure no objects have been replaced, by checking __module__
for obj, attr, source, patched in self._iter_patch_candidates():
if patched:
assert source.startswith("django.contrib.auth."), (
f"obj={obj!r} attr={attr!r} was not reverted: {source!r}"
)
assert source.startswith(
"django.contrib.auth."
), f"obj={obj!r} attr={attr!r} was not reverted: {source!r}"
else:
assert not source.startswith("passlib."), (
f"obj={obj!r} attr={attr!r} should not have been patched: {source!r}"
)
assert not source.startswith(
"passlib."
), f"obj={obj!r} attr={attr!r} should not have been patched: {source!r}"

def assert_patched(self, context=None):
"""
Expand All @@ -282,13 +282,13 @@ def assert_patched(self, context=None):
# make sure only the expected objects have been patched
for obj, attr, source, patched in self._iter_patch_candidates():
if patched:
assert source == "passlib.ext.django.utils", (
f"obj={obj!r} attr={attr!r} should have been patched: {source!r}"
)
assert (
source == "passlib.ext.django.utils"
), f"obj={obj!r} attr={attr!r} should have been patched: {source!r}"
else:
assert not source.startswith("passlib."), (
f"obj={obj!r} attr={attr!r} should not have been patched: {source!r}"
)
assert not source.startswith(
"passlib."
), f"obj={obj!r} attr={attr!r} should not have been patched: {source!r}"

# check context matches
if context is not None:
Expand Down
4 changes: 1 addition & 3 deletions tests/test_handlers_bcrypt.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,9 +232,7 @@ def check_bcrypt(secret, hash):
try:
return bcrypt.hashpw(secret, hash) == hash
except ValueError:
raise ValueError(
f"bcrypt rejected hash: {hash!r} (secret={secret!r})"
)
raise ValueError(f"bcrypt rejected hash: {hash!r} (secret={secret!r})")

return check_bcrypt

Expand Down
12 changes: 6 additions & 6 deletions tests/test_handlers_django.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,12 @@ def test_90_django_reference(self):

assert self.known_correct_hashes
for secret, hash_ in self.iter_known_hashes():
assert check_password(secret, hash_), (
f"secret={secret!r} hash={hash_!r} failed to verify"
)
assert not check_password("x" + secret, hash_), (
f"mangled secret={secret!r} hash={hash_!r} incorrect verified"
)
assert check_password(
secret, hash_
), f"secret={secret!r} hash={hash_!r} failed to verify"
assert not check_password(
"x" + secret, hash_
), f"mangled secret={secret!r} hash={hash_!r} incorrect verified"

def test_91_django_generation(self):
"""test against output of Django's make_password()"""
Expand Down
Loading

0 comments on commit af4d28f

Please sign in to comment.