Skip to content

Commit da85871

Browse files
bakerkjclaude
andauthored
style: fix lint errors surfaced by ruff v0.16.0 (#72)
Ruff 0.16.0 enables new rules that flag existing code. Apply the safe autofixes and resolve the remaining findings: - RUF046: drop redundant int() around math.ceil()/round() (already int) - PIE810: merge repeated startswith() calls into a single tuple call - G201/TRY401: use logger.exception() instead of logger.error(exc_info=True) and drop the redundant exception object from the message - SIM117: combine nested with statements - plus ruff's safe autofixes (import order, max(), unused noqa, redundant parens) Claude-Session: https://claude.ai/code/session_01PjbdedU3mPd5uYrTibuFpJ Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 39085e5 commit da85871

5 files changed

Lines changed: 22 additions & 25 deletions

File tree

custom_components/cpu_capacity/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33

44
from __future__ import annotations
55

6-
from dataclasses import dataclass
76
import logging
7+
from dataclasses import dataclass
88

99
from homeassistant.config_entries import ConfigEntry
1010
from homeassistant.core import HomeAssistant

custom_components/cpu_capacity/coordinator.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,7 @@ def __init__(
293293
}
294294

295295
self._window_sizes: dict[str, int] = {
296-
label: max(1, int(math.ceil(seconds / self._sample_interval_seconds)))
296+
label: max(1, math.ceil(seconds / self._sample_interval_seconds))
297297
for label, seconds in WINDOW_SECONDS.items()
298298
}
299299

@@ -379,10 +379,8 @@ async def _async_take_sample(self) -> None:
379379
await self.hass.async_add_executor_job(self._take_sample_sync)
380380
except (OSError, ValueError) as err:
381381
self.logger.warning("CPU sampling failed: %s", err)
382-
except Exception as err: # noqa: BLE001
383-
self.logger.error(
384-
"Unexpected error during CPU sampling: %s", err, exc_info=True
385-
)
382+
except Exception:
383+
self.logger.exception("Unexpected error during CPU sampling")
386384

387385
async def async_get_snapshot(self) -> CoordinatorSnapshot:
388386
async with self._lock:
@@ -433,8 +431,7 @@ def _take_sample_sync(self) -> None:
433431
dt = cur_total - prev_total
434432
di = cur_idle - prev_idle
435433
busy = dt - di
436-
if busy < 0:
437-
busy = 0
434+
busy = max(busy, 0)
438435

439436
load_pct = (float(busy) * 100.0 / float(dt)) if dt > 0 else 0.0
440437
mhz = current_mhz_by_cpu.get(cpu, 0.0)
@@ -537,7 +534,7 @@ async def _async_update_data(self) -> CoordinatorSnapshot:
537534
age = time.time() - snapshot["last_sample_epoch"]
538535
if age > stale_timeout:
539536
raise UpdateFailed(
540-
(f"CPU sample data is stale ({age:.1f}s > {stale_timeout:.1f}s)")
537+
f"CPU sample data is stale ({age:.1f}s > {stale_timeout:.1f}s)"
541538
)
542539

543540
return snapshot

custom_components/cpu_capacity/sensor.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33

44
from __future__ import annotations
55

6-
from dataclasses import dataclass
76
import re
7+
from dataclasses import dataclass
88
from typing import Any
99

1010
from homeassistant.components.sensor import (
@@ -165,8 +165,8 @@ def _round_summary_value(key: str, value: Any) -> Any:
165165

166166
number = float(value)
167167
if key == "max_mhz" or key.startswith("mhz_"):
168-
return int(round(number))
169-
if key.startswith("load_pct_") or key.startswith("capacity_adjusted_load_pct_"):
168+
return round(number)
169+
if key.startswith(("load_pct_", "capacity_adjusted_load_pct_")):
170170
return round(number, 4)
171171
return value
172172

@@ -193,9 +193,7 @@ def _round_native_value(metric_key: str, value: Any) -> Any:
193193
number = float(value)
194194
if metric_key == "max_mhz" or metric_key.startswith("mhz_"):
195195
return int(round(number / _MHZ_NATIVE_STEP) * _MHZ_NATIVE_STEP)
196-
if metric_key.startswith("load_pct_") or metric_key.startswith(
197-
"capacity_adjusted_load_pct_"
198-
):
196+
if metric_key.startswith(("load_pct_", "capacity_adjusted_load_pct_")):
199197
return round(number, 1)
200198
return value
201199

tests/test_coordinator.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
_safe_read_text,
1717
)
1818

19-
2019
# ---------------------------------------------------------------------------
2120
# RollingWindow
2221
# ---------------------------------------------------------------------------
@@ -155,9 +154,11 @@ def test_total_is_sum_of_all_fields(self) -> None:
155154

156155
def test_raises_if_no_cpu_entries(self) -> None:
157156
empty = "no cpu lines here\n"
158-
with patch("builtins.open", return_value=StringIO(empty)):
159-
with pytest.raises(RuntimeError, match="No per-CPU entries found"):
160-
_read_proc_stat_totals()
157+
with (
158+
patch("builtins.open", return_value=StringIO(empty)),
159+
pytest.raises(RuntimeError, match="No per-CPU entries found"),
160+
):
161+
_read_proc_stat_totals()
161162

162163

163164
# ---------------------------------------------------------------------------
@@ -194,11 +195,13 @@ def test_returns_empty_dict_on_oserror(self) -> None:
194195

195196
def test_logs_debug_on_error(self) -> None:
196197
logger = MagicMock()
197-
with patch("builtins.open", side_effect=OSError("boom")):
198-
with patch(
198+
with (
199+
patch("builtins.open", side_effect=OSError("boom")),
200+
patch(
199201
"custom_components.cpu_capacity.coordinator.logging.getLogger",
200202
return_value=logger,
201-
):
202-
_parse_proc_cpuinfo_mhz_map()
203+
),
204+
):
205+
_parse_proc_cpuinfo_mhz_map()
203206
logger.debug.assert_called_once()
204207
assert "MHz fallback" in logger.debug.call_args[0][0]

tests/test_publish_intervals.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@
1010
_publish_error,
1111
)
1212
from custom_components.cpu_capacity.const import (
13-
CONF_PUBLISH_INTERVAL_15M_SECONDS,
1413
CONF_PUBLISH_INTERVAL_1M_SECONDS,
1514
CONF_PUBLISH_INTERVAL_5M_SECONDS,
15+
CONF_PUBLISH_INTERVAL_15M_SECONDS,
1616
CONF_PUBLISH_INTERVAL_SECONDS,
1717
CONF_SAMPLE_INTERVAL_SECONDS,
1818
DEFAULT_PUBLISH_INTERVAL_SECONDS,
@@ -21,7 +21,6 @@
2121
)
2222
from custom_components.cpu_capacity.sensor import _window_for_metric
2323

24-
2524
# ---------------------------------------------------------------------------
2625
# resolve_publish_interval
2726
# ---------------------------------------------------------------------------

0 commit comments

Comments
 (0)