Skip to content

Commit eed032c

Browse files
Alexander Martynenkoclaude
andcommitted
fix: resolve all ruff lint errors (54 issues)
- B904: add `from None`/`from err` to re-raises in except clauses - B008: suppress for FastAPI Depends() pattern (standard usage) - B905: add strict= to zip() calls - B007: rename unused loop vars to _ - SIM102/SIM108/SIM110: simplify conditionals and ternaries - F841: remove unused variable assignments - F811: deduplicate conftest fixtures (remove MockBpfMap-based versions superseded by MagicMock-based versions) - E402: move mid-file imports to top in conftest files - N818: rename exception to end with Error Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 3c47b3e commit eed032c

17 files changed

Lines changed: 48 additions & 97 deletions

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ target-version = "py312"
6161

6262
[tool.ruff.lint]
6363
select = ["E", "F", "W", "I", "N", "B", "C4", "SIM"]
64-
ignore = ["E501"]
64+
ignore = ["E501", "B008"]
6565

6666
[tool.mypy]
6767
python_version = "3.12"

src/katran/api/rest/app.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ def _parse_protocol(proto_str: str) -> Protocol:
8585
try:
8686
return Protocol[proto_str.upper()]
8787
except KeyError:
88-
raise HTTPException(status_code=400, detail=f"Invalid protocol: {proto_str}")
88+
raise HTTPException(status_code=400, detail=f"Invalid protocol: {proto_str}") from None
8989

9090

9191
def _vip_to_response(vip: Any) -> VipResponse:

src/katran/bpf/maps/ch_rings_map.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ def write_ring(
162162
old_ring = self.read_ring(vip_num)
163163
updates = {}
164164

165-
for i, (old_val, new_val) in enumerate(zip(old_ring, ring)):
165+
for i, (old_val, new_val) in enumerate(zip(old_ring, ring, strict=False)):
166166
if old_val != new_val:
167167
updates[i] = new_val
168168

@@ -288,7 +288,7 @@ def write_ring_incremental(
288288

289289
# Compute positions that changed
290290
updates = {}
291-
for i, (old_val, new_val) in enumerate(zip(old_ring, new_ring)):
291+
for i, (old_val, new_val) in enumerate(zip(old_ring, new_ring, strict=False)):
292292
if old_val != new_val:
293293
updates[i] = new_val
294294

src/katran/bpf/maps/lru_map.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ def get_cache_stats(self) -> dict[str, int]:
188188
backend_counts: dict[int, int] = {}
189189
total = 0
190190

191-
for flow, cached in self.items():
191+
for _flow, cached in self.items():
192192
total += 1
193193
backend_counts[cached.pos] = backend_counts.get(cached.pos, 0) + 1
194194

src/katran/bpf/maps/reals_map.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -239,9 +239,7 @@ def sync_from_map(self) -> None:
239239

240240
for i in range(1, self._max_reals):
241241
real_def = self.get(i)
242-
if real_def is not None:
243-
# Check if entry is non-zero (has valid address)
244-
if real_def.address.packed != b"\x00" * 4:
242+
if real_def is not None and real_def.address.packed != b"\x00" * 4:
245243
self._reals_cache[i] = real_def
246244
self._index_allocator.reserve(i)
247245

src/katran/core/config.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -169,9 +169,7 @@ def _is_flat_config(data: dict[str, Any]) -> bool:
169169
if set(data.keys()) & unambiguous_flat:
170170
return True
171171
# "interface" exists in both formats: str in flat, dict in nested
172-
if "interface" in data and isinstance(data["interface"], str):
173-
return True
174-
return False
172+
return bool("interface" in data and isinstance(data["interface"], str))
175173

176174

177175
def _normalize_flat_config(data: dict[str, Any]) -> dict[str, Any]:
@@ -229,25 +227,25 @@ def from_yaml(cls, path: str | Path) -> KatranConfig:
229227
with open(path) as f:
230228
data = yaml.safe_load(f)
231229
except FileNotFoundError:
232-
raise ConfigurationError(f"Config file not found: {path}")
230+
raise ConfigurationError(f"Config file not found: {path}") from None
233231
except yaml.YAMLError as e:
234-
raise ConfigurationError(f"Invalid YAML: {e}")
232+
raise ConfigurationError(f"Invalid YAML: {e}") from e
235233

236234
if data is None:
237235
data = {}
238236

239237
try:
240238
return cls.model_validate(data)
241239
except Exception as e:
242-
raise ConfigurationError(str(e))
240+
raise ConfigurationError(str(e)) from e
243241

244242
@classmethod
245243
def from_dict(cls, data: dict[str, Any]) -> KatranConfig:
246244
"""Load configuration from a dictionary."""
247245
try:
248246
return cls.model_validate(data)
249247
except Exception as e:
250-
raise ConfigurationError(str(e))
248+
raise ConfigurationError(str(e)) from e
251249

252250
def validate_paths(self) -> list[str]:
253251
"""

src/katran/core/types.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -141,10 +141,7 @@ def from_bytes(cls, data: bytes) -> VipKey:
141141
# Check if IPv6 (non-zero bytes after first 4)
142142
is_ipv6 = any(data[4:16])
143143

144-
if is_ipv6:
145-
address = IPv6Address(data[:16])
146-
else:
147-
address = IPv4Address(data[:4])
144+
address = IPv6Address(data[:16]) if is_ipv6 else IPv4Address(data[:4])
148145

149146
# Port (2 bytes, network byte order)
150147
port = struct.unpack("!H", data[16:18])[0]
@@ -285,10 +282,7 @@ def from_bytes(cls, data: bytes) -> RealDefinition:
285282
try:
286283
flags = RealFlags(data[16])
287284

288-
if flags & RealFlags.IPV6:
289-
address = IPv6Address(data[:16])
290-
else:
291-
address = IPv4Address(data[:4])
285+
address = IPv6Address(data[:16]) if flags & RealFlags.IPV6 else IPv4Address(data[:4])
292286

293287
return cls(address=address, flags=flags)
294288

src/katran/lb/maglev.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -150,10 +150,7 @@ def _is_prime(n: int) -> bool:
150150
return True
151151
if n % 2 == 0:
152152
return False
153-
for i in range(3, int(n**0.5) + 1, 2):
154-
if n % i == 0:
155-
return False
156-
return True
153+
return all(n % i != 0 for i in range(3, int(n ** 0.5) + 1, 2))
157154

158155

159156
def _gen_maglev_permutation(endpoint: Endpoint, ring_size: int) -> tuple[int, int]:
@@ -356,7 +353,7 @@ def rebuild(
356353
# Compute changes
357354
changes: dict[int, tuple[int, int]] = {}
358355
if old_ring and len(old_ring) == len(new_ring):
359-
for i, (old_val, new_val) in enumerate(zip(old_ring, new_ring)):
356+
for i, (old_val, new_val) in enumerate(zip(old_ring, new_ring, strict=False)):
360357
if old_val != new_val:
361358
changes[i] = (old_val, new_val)
362359

@@ -434,7 +431,7 @@ def compute_ring_changes(old_ring: list[int], new_ring: list[int]) -> tuple[int,
434431
if len(old_ring) != len(new_ring):
435432
raise ValueError("Rings must be the same size")
436433

437-
changed = sum(1 for o, n in zip(old_ring, new_ring) if o != n)
434+
changed = sum(1 for o, n in zip(old_ring, new_ring, strict=False) if o != n)
438435
percentage = (changed / len(old_ring)) * 100 if old_ring else 0.0
439436

440437
return changed, percentage
@@ -468,7 +465,7 @@ def compute_ring_updates(old_ring: list[int], new_ring: list[int]) -> dict[int,
468465
raise ValueError("Rings must be the same size")
469466

470467
updates: dict[int, int] = {}
471-
for i, (old_val, new_val) in enumerate(zip(old_ring, new_ring)):
468+
for i, (old_val, new_val) in enumerate(zip(old_ring, new_ring, strict=False)):
472469
if old_val != new_val:
473470
updates[i] = new_val
474471

tests/conftest.py

Lines changed: 4 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import tempfile
66
from ipaddress import IPv4Address, IPv6Address
77
from pathlib import Path
8+
from unittest.mock import MagicMock
89

910
import pytest
1011

@@ -19,6 +20,9 @@
1920
VipKey,
2021
VipMeta,
2122
)
23+
from katran.lb.maglev import MaglevHashRing
24+
from katran.lb.real_manager import RealManager
25+
from katran.lb.vip_manager import VipManager
2226

2327
# =============================================================================
2428
# Sample Data Fixtures
@@ -177,24 +181,6 @@ def items(self):
177181
return list(self._data.items())
178182

179183

180-
@pytest.fixture
181-
def mock_vip_map() -> MockBpfMap:
182-
"""Mock VIP map."""
183-
return MockBpfMap(key_size=20, value_size=8)
184-
185-
186-
@pytest.fixture
187-
def mock_reals_map() -> MockBpfMap:
188-
"""Mock reals map."""
189-
return MockBpfMap(key_size=4, value_size=20)
190-
191-
192-
@pytest.fixture
193-
def mock_ch_rings_map() -> MockBpfMap:
194-
"""Mock consistent hash rings map."""
195-
return MockBpfMap(key_size=4, value_size=4)
196-
197-
198184
@pytest.fixture
199185
def mock_stats_map() -> MockBpfMap:
200186
"""Mock statistics map."""
@@ -205,12 +191,6 @@ def mock_stats_map() -> MockBpfMap:
205191
# Manager Fixtures (for Phase 2 unit tests)
206192
# =============================================================================
207193

208-
from unittest.mock import MagicMock
209-
210-
from katran.lb.maglev import MaglevHashRing
211-
from katran.lb.real_manager import RealManager
212-
from katran.lb.vip_manager import VipManager
213-
214194

215195
@pytest.fixture
216196
def mock_vip_map():

tests/e2e/conftest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def api_client(api_url) -> httpx.Client:
7878
client = httpx.Client(base_url=api_url, timeout=30.0)
7979

8080
# Wait for API readiness
81-
for attempt in range(30):
81+
for _attempt in range(30):
8282
try:
8383
resp = client.get("/health")
8484
if resp.status_code == 200:

0 commit comments

Comments
 (0)