Skip to content

Commit

Permalink
Replace black with ruff format; run it
Browse files Browse the repository at this point in the history
  • Loading branch information
akx committed Feb 20, 2025
1 parent fbe41c3 commit d81997a
Show file tree
Hide file tree
Showing 29 changed files with 65 additions and 75 deletions.
2 changes: 1 addition & 1 deletion benchmarks/basic_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def wrapper(*args, **kwargs):
count = args[1]
print(f"{func.__name__} - {count} Requests")
print(f"Duration = {duration}")
print(f"Rate = {count/duration}")
print(f"Rate = {count / duration}")
print()
return ret

Expand Down
1 change: 0 additions & 1 deletion benchmarks/command_packer_benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ def pack_command(self, *args):


class CommandPackerBenchmark(Benchmark):

ARGUMENTS = (
{
"name": "connection_class",
Expand Down
1 change: 0 additions & 1 deletion benchmarks/socket_read_size.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@


class SocketReadBenchmark(Benchmark):

ARGUMENTS = (
{"name": "parser", "values": [PythonParser, _HiredisParser]},
{
Expand Down
4 changes: 2 additions & 2 deletions redis/_parsers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@
from .encoders import Encoder
from .socket import SERVER_CLOSED_CONNECTION_ERROR, SocketBuffer

MODULE_LOAD_ERROR = "Error loading the extension. " "Please check the server logs."
MODULE_LOAD_ERROR = "Error loading the extension. Please check the server logs."
NO_SUCH_MODULE_ERROR = "Error unloading module: no such module with that name"
MODULE_UNLOAD_NOT_POSSIBLE_ERROR = "Error unloading module: operation not " "possible."
MODULE_UNLOAD_NOT_POSSIBLE_ERROR = "Error unloading module: operation not possible."
MODULE_EXPORTS_DATA_TYPES_ERROR = (
"Error unloading module: the module "
"exports one or more module-side data "
Expand Down
6 changes: 2 additions & 4 deletions redis/asyncio/cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -1154,9 +1154,7 @@ def get_node(
return self.nodes_cache.get(node_name)
else:
raise DataError(
"get_node requires one of the following: "
"1. node name "
"2. host and port"
"get_node requires one of the following: 1. node name 2. host and port"
)

def set_nodes(
Expand Down Expand Up @@ -1338,7 +1336,7 @@ async def initialize(self) -> None:
if len(disagreements) > 5:
raise RedisClusterException(
f"startup_nodes could not agree on a valid "
f'slots cache: {", ".join(disagreements)}'
f"slots cache: {', '.join(disagreements)}"
)

# Validate if all slots are covered or if we should try next startup node
Expand Down
1 change: 0 additions & 1 deletion redis/auth/token.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,6 @@ def get_received_at_ms(self) -> float:


class JWToken(TokenInterface):

REQUIRED_FIELDS = {"exp"}

def __init__(self, token: str):
Expand Down
3 changes: 1 addition & 2 deletions redis/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1514,8 +1514,7 @@ def raise_first_error(self, commands, response):
def annotate_exception(self, exception, number, command):
cmd = " ".join(map(safe_str, command))
msg = (
f"Command # {number} ({cmd}) of pipeline "
f"caused error: {exception.args[0]}"
f"Command # {number} ({cmd}) of pipeline caused error: {exception.args[0]}"
)
exception.args = (msg,) + exception.args[1:]

Expand Down
5 changes: 2 additions & 3 deletions redis/cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -1628,7 +1628,7 @@ def initialize(self):
if len(disagreements) > 5:
raise RedisClusterException(
f"startup_nodes could not agree on a valid "
f'slots cache: {", ".join(disagreements)}'
f"slots cache: {', '.join(disagreements)}"
)

fully_covered = self.check_slots_coverage(tmp_slots)
Expand Down Expand Up @@ -2047,8 +2047,7 @@ def annotate_exception(self, exception, number, command):
"""
cmd = " ".join(map(safe_str, command))
msg = (
f"Command # {number} ({cmd}) of pipeline "
f"caused error: {exception.args[0]}"
f"Command # {number} ({cmd}) of pipeline caused error: {exception.args[0]}"
)
exception.args = (msg,) + exception.args[1:]

Expand Down
2 changes: 1 addition & 1 deletion redis/commands/cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -595,7 +595,7 @@ def cluster_setslot(
"CLUSTER SETSLOT", slot_id, state, node_id, target_nodes=target_node
)
elif state.upper() == "STABLE":
raise RedisError('For "stable" state please use ' "cluster_setslot_stable")
raise RedisError('For "stable" state please use cluster_setslot_stable')
else:
raise RedisError(f"Invalid slot state: {state}")

Expand Down
7 changes: 4 additions & 3 deletions redis/commands/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -3413,7 +3413,9 @@ def smembers(self, name: str) -> Union[Awaitable[Set], Set]:
"""
return self.execute_command("SMEMBERS", name, keys=[name])

def smismember(self, name: str, values: List, *args: List) -> Union[
def smismember(
self, name: str, values: List, *args: List
) -> Union[
Awaitable[List[Union[Literal[0], Literal[1]]]],
List[Union[Literal[0], Literal[1]]],
]:
Expand Down Expand Up @@ -4160,8 +4162,7 @@ def zadd(
raise DataError("ZADD allows either 'gt' or 'lt', not both")
if incr and len(mapping) != 1:
raise DataError(
"ZADD option 'incr' only works when passing a "
"single element/score pair"
"ZADD option 'incr' only works when passing a single element/score pair"
)
if nx and (gt or lt):
raise DataError("Only one of 'nx', 'lt', or 'gr' may be defined.")
Expand Down
4 changes: 1 addition & 3 deletions redis/commands/graph/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,9 +171,7 @@ def config(self, name, value=None, set=False):
if set:
params.append(value)
else:
raise DataError(
"``value`` can be provided only when ``set`` is True"
) # noqa
raise DataError("``value`` can be provided only when ``set`` is True") # noqa
return self.execute_command(CONFIG_CMD, *params)

def list_keys(self):
Expand Down
4 changes: 2 additions & 2 deletions redis/commands/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,9 @@ def stringify_param_value(value):
elif value is None:
return "null"
elif isinstance(value, (list, tuple)):
return f'[{",".join(map(stringify_param_value, value))}]'
return f"[{','.join(map(stringify_param_value, value))}]"
elif isinstance(value, dict):
return f'{{{",".join(f"{k}:{stringify_param_value(v)}" for k, v in value.items())}}}' # noqa
return f"{{{','.join(f'{k}:{stringify_param_value(v)}' for k, v in value.items())}}}" # noqa
else:
return str(value)

Expand Down
4 changes: 1 addition & 3 deletions redis/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -618,9 +618,7 @@ def read_response(
except OSError as e:
if disconnect_on_error:
self.disconnect()
raise ConnectionError(
f"Error while reading from {host_error}" f" : {e.args}"
)
raise ConnectionError(f"Error while reading from {host_error} : {e.args}")
except BaseException:
# Also by default close in case of BaseException. A lot of code
# relies on this behaviour when doing Command/Response pairs.
Expand Down
3 changes: 3 additions & 0 deletions redis/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ class ModuleError(ResponseError):

class LockError(RedisError, ValueError):
"Errors acquiring or releasing a lock"

# NOTE: For backwards compatibility, this class derives from ValueError.
# This was originally chosen to behave like threading.Lock.

Expand All @@ -89,11 +90,13 @@ def __init__(self, message=None, lock_name=None):

class LockNotOwnedError(LockError):
"Error trying to extend or release a lock that is (no longer) owned"

pass


class ChildDeadlockedError(Exception):
"Error indicating that a child process is deadlocked after a fork()"

pass


Expand Down
2 changes: 1 addition & 1 deletion redis/ocsp.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def _check_certificate(issuer_cert, ocsp_bytes, validate=True):
if ocsp_response.response_status == ocsp.OCSPResponseStatus.SUCCESSFUL:
if ocsp_response.certificate_status != ocsp.OCSPCertStatus.GOOD:
raise ConnectionError(
f'Received an {str(ocsp_response.certificate_status).split(".")[1]} '
f"Received an {str(ocsp_response.certificate_status).split('.')[1]} "
"ocsp certificate status"
)
else:
Expand Down
2 changes: 1 addition & 1 deletion redis/sentinel.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ def __repr__(self):
)
return (
f"<{type(self).__module__}.{type(self).__name__}"
f'(sentinels=[{",".join(sentinel_addresses)}])>'
f"(sentinels=[{','.join(sentinel_addresses)}])>"
)

def check_master_state(self, state, service_name):
Expand Down
2 changes: 1 addition & 1 deletion tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def build_docs(c):
def linters(c):
"""Run code linters"""
run("ruff check tests redis")
run("black --target-version py37 --check --diff tests redis")
run("ruff format --check --diff tests redis")
run("vulture redis whitelist.py --min-confidence 80")


Expand Down
2 changes: 1 addition & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -775,7 +775,7 @@ def wait_for_command(client, monitor, command, key=None):
if Version(redis_version) >= Version("5.0.0"):
id_str = str(client.client_id())
else:
id_str = f"{random.randrange(2 ** 32):08x}"
id_str = f"{random.randrange(2**32):08x}"
key = f"__REDIS-PY-{id_str}__"
client.get(key)
while True:
Expand Down
2 changes: 1 addition & 1 deletion tests/test_asyncio/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ async def wait_for_command(
if Version(redis_version) >= Version("5.0.0"):
id_str = str(await client.client_id())
else:
id_str = f"{random.randrange(2 ** 32):08x}"
id_str = f"{random.randrange(2**32):08x}"
key = f"__REDIS-PY-{id_str}__"
await client.get(key)
while True:
Expand Down
11 changes: 5 additions & 6 deletions tests/test_asyncio/test_cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,6 @@ async def get_mocked_redis_client(
with mock.patch.object(ClusterNode, "execute_command") as execute_command_mock:

async def execute_command(*_args, **_kwargs):

if _args[0] == "CLUSTER SLOTS":
if cluster_slots_raise_error:
raise ResponseError()
Expand Down Expand Up @@ -1577,23 +1576,23 @@ async def test_cluster_bitop_not_empty_string(self, r: RedisCluster) -> None:

@skip_if_server_version_lt("2.6.0")
async def test_cluster_bitop_not(self, r: RedisCluster) -> None:
test_str = b"\xAA\x00\xFF\x55"
test_str = b"\xaa\x00\xff\x55"
correct = ~0xAA00FF55 & 0xFFFFFFFF
await r.set("{foo}a", test_str)
await r.bitop("not", "{foo}r", "{foo}a")
assert int(binascii.hexlify(await r.get("{foo}r")), 16) == correct

@skip_if_server_version_lt("2.6.0")
async def test_cluster_bitop_not_in_place(self, r: RedisCluster) -> None:
test_str = b"\xAA\x00\xFF\x55"
test_str = b"\xaa\x00\xff\x55"
correct = ~0xAA00FF55 & 0xFFFFFFFF
await r.set("{foo}a", test_str)
await r.bitop("not", "{foo}a", "{foo}a")
assert int(binascii.hexlify(await r.get("{foo}a")), 16) == correct

@skip_if_server_version_lt("2.6.0")
async def test_cluster_bitop_single_string(self, r: RedisCluster) -> None:
test_str = b"\x01\x02\xFF"
test_str = b"\x01\x02\xff"
await r.set("{foo}a", test_str)
await r.bitop("and", "{foo}res1", "{foo}a")
await r.bitop("or", "{foo}res2", "{foo}a")
Expand All @@ -1604,8 +1603,8 @@ async def test_cluster_bitop_single_string(self, r: RedisCluster) -> None:

@skip_if_server_version_lt("2.6.0")
async def test_cluster_bitop_string_operands(self, r: RedisCluster) -> None:
await r.set("{foo}a", b"\x01\x02\xFF\xFF")
await r.set("{foo}b", b"\x01\x02\xFF")
await r.set("{foo}a", b"\x01\x02\xff\xff")
await r.set("{foo}b", b"\x01\x02\xff")
await r.bitop("and", "{foo}res1", "{foo}a", "{foo}b")
await r.bitop("or", "{foo}res2", "{foo}a", "{foo}b")
await r.bitop("xor", "{foo}res3", "{foo}a", "{foo}b")
Expand Down
15 changes: 8 additions & 7 deletions tests/test_asyncio/test_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -711,8 +711,9 @@ async def test_config_set_for_search_module(self, r: redis.Redis):
"search-default-dialect"
] == default_dialect_new
assert (
(await r.ft().config_get("*"))[b"DEFAULT_DIALECT"]
).decode() == default_dialect_new
((await r.ft().config_get("*"))[b"DEFAULT_DIALECT"]).decode()
== default_dialect_new
)
except AssertionError as ex:
raise ex
finally:
Expand Down Expand Up @@ -844,7 +845,7 @@ async def test_bitop_not_empty_string(self, r: redis.Redis):
@skip_if_server_version_lt("2.6.0")
@pytest.mark.onlynoncluster
async def test_bitop_not(self, r: redis.Redis):
test_str = b"\xAA\x00\xFF\x55"
test_str = b"\xaa\x00\xff\x55"
correct = ~0xAA00FF55 & 0xFFFFFFFF
await r.set("a", test_str)
await r.bitop("not", "r", "a")
Expand All @@ -853,7 +854,7 @@ async def test_bitop_not(self, r: redis.Redis):
@skip_if_server_version_lt("2.6.0")
@pytest.mark.onlynoncluster
async def test_bitop_not_in_place(self, r: redis.Redis):
test_str = b"\xAA\x00\xFF\x55"
test_str = b"\xaa\x00\xff\x55"
correct = ~0xAA00FF55 & 0xFFFFFFFF
await r.set("a", test_str)
await r.bitop("not", "a", "a")
Expand All @@ -862,7 +863,7 @@ async def test_bitop_not_in_place(self, r: redis.Redis):
@skip_if_server_version_lt("2.6.0")
@pytest.mark.onlynoncluster
async def test_bitop_single_string(self, r: redis.Redis):
test_str = b"\x01\x02\xFF"
test_str = b"\x01\x02\xff"
await r.set("a", test_str)
await r.bitop("and", "res1", "a")
await r.bitop("or", "res2", "a")
Expand All @@ -874,8 +875,8 @@ async def test_bitop_single_string(self, r: redis.Redis):
@skip_if_server_version_lt("2.6.0")
@pytest.mark.onlynoncluster
async def test_bitop_string_operands(self, r: redis.Redis):
await r.set("a", b"\x01\x02\xFF\xFF")
await r.set("b", b"\x01\x02\xFF")
await r.set("a", b"\x01\x02\xff\xff")
await r.set("b", b"\x01\x02\xff")
await r.bitop("and", "res1", "a", "b")
await r.bitop("or", "res2", "a", "b")
await r.bitop("xor", "res3", "a", "b")
Expand Down
3 changes: 1 addition & 2 deletions tests/test_asyncio/test_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ async def test_graph_creation(decoded_r: redis.Redis):
await graph.commit()

query = (
'MATCH (p:person)-[v:visited {purpose:"pleasure"}]->(c:country) '
"RETURN p, v, c"
'MATCH (p:person)-[v:visited {purpose:"pleasure"}]->(c:country) RETURN p, v, c'
)

result = await graph.query(query)
Expand Down
12 changes: 6 additions & 6 deletions tests/test_asyncio/test_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -1797,10 +1797,10 @@ async def test_binary_and_text_fields(decoded_r: redis.Redis):
docs[0]["vector_emb"], dtype=np.float32
)

assert np.array_equal(
decoded_vec_from_search_results, fake_vec
), "The vectors are not equal"
assert np.array_equal(decoded_vec_from_search_results, fake_vec), (
"The vectors are not equal"
)

assert (
docs[0]["first_name"] == mixed_data["first_name"]
), "The text field is not decoded correctly"
assert docs[0]["first_name"] == mixed_data["first_name"], (
"The text field is not decoded correctly"
)
1 change: 0 additions & 1 deletion tests/test_auth/test_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@


class TestToken:

def test_simple_token(self):
token = SimpleToken(
"value",
Expand Down
10 changes: 5 additions & 5 deletions tests/test_cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -1692,23 +1692,23 @@ def test_cluster_bitop_not_empty_string(self, r):

@skip_if_server_version_lt("2.6.0")
def test_cluster_bitop_not(self, r):
test_str = b"\xAA\x00\xFF\x55"
test_str = b"\xaa\x00\xff\x55"
correct = ~0xAA00FF55 & 0xFFFFFFFF
r["{foo}a"] = test_str
r.bitop("not", "{foo}r", "{foo}a")
assert int(binascii.hexlify(r["{foo}r"]), 16) == correct

@skip_if_server_version_lt("2.6.0")
def test_cluster_bitop_not_in_place(self, r):
test_str = b"\xAA\x00\xFF\x55"
test_str = b"\xaa\x00\xff\x55"
correct = ~0xAA00FF55 & 0xFFFFFFFF
r["{foo}a"] = test_str
r.bitop("not", "{foo}a", "{foo}a")
assert int(binascii.hexlify(r["{foo}a"]), 16) == correct

@skip_if_server_version_lt("2.6.0")
def test_cluster_bitop_single_string(self, r):
test_str = b"\x01\x02\xFF"
test_str = b"\x01\x02\xff"
r["{foo}a"] = test_str
r.bitop("and", "{foo}res1", "{foo}a")
r.bitop("or", "{foo}res2", "{foo}a")
Expand All @@ -1719,8 +1719,8 @@ def test_cluster_bitop_single_string(self, r):

@skip_if_server_version_lt("2.6.0")
def test_cluster_bitop_string_operands(self, r):
r["{foo}a"] = b"\x01\x02\xFF\xFF"
r["{foo}b"] = b"\x01\x02\xFF"
r["{foo}a"] = b"\x01\x02\xff\xff"
r["{foo}b"] = b"\x01\x02\xff"
r.bitop("and", "{foo}res1", "{foo}a", "{foo}b")
r.bitop("or", "{foo}res2", "{foo}a", "{foo}b")
r.bitop("xor", "{foo}res3", "{foo}a", "{foo}b")
Expand Down
Loading

0 comments on commit d81997a

Please sign in to comment.