Skip to content

Commit 3fc3f79

Browse files
authored
Switch to ruff for formatting (#741)
Signed-off-by: Casper Beyer <[email protected]>
1 parent c333e88 commit 3fc3f79

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

56 files changed

+738
-1762
lines changed

.github/workflows/check.yml

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
name: check
1+
name: Check
22
on:
33
push:
44
branches:
@@ -26,8 +26,4 @@ jobs:
2626
run: uv sync --dev
2727

2828
- name: Run format check
29-
run: |
30-
uv run yapf --diff --recursive nats/
31-
32-
- name: Run isort check
33-
run: uv run isort --check-only --diff nats/src
29+
run: uv run ruff format --check

.github/workflows/test.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ jobs:
4242
4343
- name: Run tests
4444
run: |
45-
uv run flake8 --ignore="W391, W503, W504, E501" ./nats/src/nats/js/
45+
uv run flake8 --ignore="W391, W503, W504, E501, E203" ./nats/src/nats/js/
4646
uv run pytest -x -vv -s --continue-on-collection-errors ./nats/tests
4747
env:
4848
PATH: $HOME/nats-server:$PATH

nats-server/src/nats/server/__init__.py

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,7 @@
3434
FATAL_PATTERN = re.compile(r"\[FTL\]\s+(.*)")
3535
INFO_PATTERN = re.compile(r"\[INF\]\s+(.*)")
3636
READY_PATTERN = re.compile(r"Server is ready")
37-
LISTENING_PATTERN = re.compile(
38-
r"Listening for client connections on (.+):(\d+)"
39-
)
37+
LISTENING_PATTERN = re.compile(r"Listening for client connections on (.+):(\d+)")
4038

4139

4240
class ServerError(Exception):
@@ -279,7 +277,7 @@ async def wait_ready() -> tuple[str, int]:
279277

280278
if match := LISTENING_PATTERN.search(stderr_line):
281279
host_part = match.group(1)
282-
if host_part.startswith('[') and host_part.endswith(']'):
280+
if host_part.startswith("[") and host_part.endswith("]"):
283281
host = host_part[1:-1]
284282
else:
285283
host = host_part
@@ -298,13 +296,11 @@ async def wait_ready() -> tuple[str, int]:
298296
if returncode != 0:
299297
msg = f"Server exited with code {returncode}"
300298
if error_lines:
301-
errors = '\n'.join(error_lines)
299+
errors = "\n".join(error_lines)
302300
msg += f"\nErrors:\n{errors}"
303301
raise ServerError(msg)
304302

305-
raise ServerError(
306-
"Server ended without becoming ready"
307-
) # pragma: no cover
303+
raise ServerError("Server ended without becoming ready") # pragma: no cover
308304

309305
return await asyncio.wait_for(wait_ready(), timeout=timeout)
310306

@@ -413,14 +409,14 @@ async def run_cluster(
413409
node_store_dir = None
414410
if jetstream and store_dir:
415411
# Use as base directory and create subdirectory for each node
416-
node_store_dir = os.path.join(store_dir, f"node{i+1}")
412+
node_store_dir = os.path.join(store_dir, f"node{i + 1}")
417413
os.makedirs(node_store_dir, exist_ok=True)
418414

419415
server = await _run_cluster_node(
420416
config_path=config_path,
421417
port=available_ports[i],
422418
routes=routes,
423-
name=f"node{i+1}",
419+
name=f"node{i + 1}",
424420
cluster_name="cluster",
425421
cluster_port=cluster_ports[i],
426422
jetstream=jetstream,
@@ -465,9 +461,7 @@ async def _run_cluster_node(
465461
"""
466462
# Build cluster URL and routes string for CLI
467463
cluster_url = f"nats://127.0.0.1:{cluster_port}"
468-
routes_str = ",".join(
469-
f"nats://127.0.0.1:{r}" for r in routes
470-
) if routes else None
464+
routes_str = ",".join(f"nats://127.0.0.1:{r}" for r in routes) if routes else None
471465

472466
process = await _create_server_process(
473467
port=port,
@@ -480,8 +474,6 @@ async def _run_cluster_node(
480474
config_path=config_path if config_path else None,
481475
)
482476

483-
assigned_host, assigned_port = await _wait_for_server_ready(
484-
process, timeout=10.0
485-
)
477+
assigned_host, assigned_port = await _wait_for_server_ready(process, timeout=10.0)
486478

487479
return Server(process, assigned_host, assigned_port)

nats-server/tests/conftest.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,9 @@
1414
def get_nats_server_version():
1515
"""Get the nats-server version or fail if not installed."""
1616
try:
17-
result = subprocess.run(["nats-server", "--version"],
18-
capture_output=True,
19-
check=True,
20-
text=True)
17+
result = subprocess.run(
18+
["nats-server", "--version"], capture_output=True, check=True, text=True
19+
)
2120
return result.stdout.strip() or result.stderr.strip()
2221
except (subprocess.SubprocessError, FileNotFoundError) as e:
2322
pytest.fail(f"nats-server is not installed or not in PATH: {e}")

nats-server/tests/test_server.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ class ServerInfo(TypedDict):
1818
1919
See: https://docs.nats.io/reference/reference-protocols/nats-protocol#info
2020
"""
21+
2122
# Required fields
2223
server_id: str
2324
server_name: str
@@ -264,9 +265,7 @@ async def test_run_with_store_dir_as_file(tmp_path):
264265

265266
# Try to start server with JetStream using a file as store_dir
266267
with pytest.raises(ServerError) as exc_info:
267-
await run(
268-
port=0, jetstream=True, store_dir=str(store_file), timeout=2.0
269-
)
268+
await run(port=0, jetstream=True, store_dir=str(store_file), timeout=2.0)
270269

271270
# Verify the error message indicates the storage directory issue
272271
error_msg = str(exc_info.value).lower()
@@ -522,9 +521,7 @@ async def test_cluster_with_conflicting_config(tmp_path):
522521
"""Test run_cluster with config that includes cluster settings."""
523522
# The function should still work, merging config with generated cluster setup
524523
cluster = await run_cluster(
525-
"tests/configs/jetstream.conf",
526-
jetstream=True,
527-
store_dir=str(tmp_path)
524+
"tests/configs/jetstream.conf", jetstream=True, store_dir=str(tmp_path)
528525
)
529526

530527
try:
@@ -549,8 +546,10 @@ async def test_run_with_invalid_host():
549546
with pytest.raises(ServerError) as exc_info:
550547
await run(host="999.999.999.999", port=0, timeout=2.0)
551548

552-
assert "exited" in str(exc_info.value
553-
).lower() or "error" in str(exc_info.value).lower()
549+
assert (
550+
"exited" in str(exc_info.value).lower()
551+
or "error" in str(exc_info.value).lower()
552+
)
554553

555554

556555
async def test_cluster_client_url():

nats/benchmark/latency_perf.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,7 @@ def show_usage_and_die():
3434

3535
async def main():
3636
parser = argparse.ArgumentParser()
37-
parser.add_argument(
38-
"-n", "--iterations", default=DEFAULT_ITERATIONS, type=int
39-
)
37+
parser.add_argument("-n", "--iterations", default=DEFAULT_ITERATIONS, type=int)
4038
parser.add_argument("-S", "--subject", default="test")
4139
parser.add_argument("--servers", default=[], action="append")
4240
args = parser.parse_args()
@@ -60,11 +58,7 @@ async def handler(msg):
6058
start = time.monotonic()
6159
to_send = args.iterations
6260

63-
print(
64-
"Sending {} request/responses on [{}]".format(
65-
args.iterations, args.subject
66-
)
67-
)
61+
print("Sending {} request/responses on [{}]".format(args.iterations, args.subject))
6862
while to_send > 0:
6963
to_send -= 1
7064
if to_send == 0:

nats/benchmark/parser_perf.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55

66

77
class DummyNatsClient:
8-
98
def __init__(self):
109
self._subs = {}
1110
self._pongs = []
@@ -40,9 +39,7 @@ async def _process_err(self, err=None):
4039

4140
def generate_msg(subject, nbytes, reply=""):
4241
msg = []
43-
protocol_line = "MSG {subject} 1 {reply} {nbytes}\r\n".format(
44-
subject=subject, reply=reply, nbytes=nbytes
45-
).encode()
42+
protocol_line = "MSG {subject} 1 {reply} {nbytes}\r\n".format(subject=subject, reply=reply, nbytes=nbytes).encode()
4643
msg.append(protocol_line)
4744
msg.append(b"A" * nbytes)
4845
msg.append(b"r\n")

nats/benchmark/pub_perf.py

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -68,11 +68,7 @@ async def main():
6868
start = time.time()
6969
to_send = args.count
7070

71-
print(
72-
"Sending {} messages of size {} bytes on [{}]".format(
73-
args.count, args.size, args.subject
74-
)
75-
)
71+
print("Sending {} messages of size {} bytes on [{}]".format(args.count, args.size, args.subject))
7672
while to_send > 0:
7773
for i in range(0, args.batch):
7874
to_send -= 1
@@ -94,11 +90,7 @@ async def main():
9490

9591
elapsed = time.time() - start
9692
mbytes = "%.1f" % (((args.size * args.count) / elapsed) / (1024 * 1024))
97-
print(
98-
"\nTest completed : {} msgs/sec ({}) MB/sec".format(
99-
args.count / elapsed, mbytes
100-
)
101-
)
93+
print("\nTest completed : {} msgs/sec ({}) MB/sec".format(args.count / elapsed, mbytes))
10294
await nc.close()
10395

10496

nats/benchmark/pub_sub_perf.py

Lines changed: 4 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -79,11 +79,7 @@ async def handler(msg):
7979
start = time.time()
8080
to_send = args.count
8181

82-
print(
83-
"Sending {} messages of size {} bytes on [{}]".format(
84-
args.count, args.size, args.subject
85-
)
86-
)
82+
print("Sending {} messages of size {} bytes on [{}]".format(args.count, args.size, args.subject))
8783
while to_send > 0:
8884
for i in range(0, args.batch):
8985
to_send -= 1
@@ -107,17 +103,9 @@ async def handler(msg):
107103

108104
elapsed = time.time() - start
109105
mbytes = "%.1f" % (((args.size * args.count) / elapsed) / (1024 * 1024))
110-
print(
111-
"\nTest completed : {} msgs/sec sent ({}) MB/sec".format(
112-
args.count / elapsed, mbytes
113-
)
114-
)
115-
116-
print(
117-
"Received {} messages ({} msgs/sec)".format(
118-
received, received / elapsed
119-
)
120-
)
106+
print("\nTest completed : {} msgs/sec sent ({}) MB/sec".format(args.count / elapsed, mbytes))
107+
108+
print("Received {} messages ({} msgs/sec)".format(received, received / elapsed))
121109
await nc.close()
122110

123111

nats/benchmark/sub_perf.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -77,11 +77,7 @@ async def handler(msg):
7777
elapsed = time.monotonic() - start
7878
print("\nTest completed : {} msgs/sec sent".format(args.count / elapsed))
7979

80-
print(
81-
"Received {} messages ({} msgs/sec)".format(
82-
received, received / elapsed
83-
)
84-
)
80+
print("Received {} messages ({} msgs/sec)".format(received, received / elapsed))
8581
await nc.close()
8682

8783

0 commit comments

Comments
 (0)