Enable ruff B (bugbear) and fix violations#1683
Conversation
Adds flake8-bugbear to the enforced ruff rule set and fixes the existing 7 violations. Notable: tests/test_model.py:840 had `services == X(...)` instead of `services = X(...)`, leaving the subsequent `services.services[0] ==` assertion checking the same from_pb-derived model twice instead of exercising from_dict. The reassignment now makes the `from_dict` path the one being verified, matching the test's name. Other fixes: - B904: chain `raise X from err` in _frame_helper/noise.py and host_resolver.py so re-raised exceptions preserve their cause. - B007: drop unused loop variables (`for _ in range(5)` and iterate dict keys directly in test_core).
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #1683 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 25 25
Lines 4152 4152
=========================================
Hits 4152 4152 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (9)
WalkthroughPR adds exception chaining to preserve error context in API error handlers, enables flake8-bugbear linting rules, fixes unused variable warnings across benchmarks and tests, and corrects test logic bugs in model and message type tests. ChangesAPI Quality and Code Health
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Suggested labels
Suggested reviewers
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Pull request overview
This PR expands the repository’s Ruff lint enforcement by enabling the B (flake8-bugbear) ruleset and applies small targeted code/test changes to resolve the newly-enforced violations.
Changes:
- Enable Ruff
B(bugbear) rules inpyproject.toml. - Fix a no-op comparison in
test_bluetooth_gatt_services_from_dictso the test actually validates thefrom_dictpath. - Improve exception chaining (
raise ... from err) and rename unused loop variables to_to satisfy bugbear rules.
Reviewed changes
Copilot reviewed 9 out of 9 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
pyproject.toml |
Enables Ruff bugbear (B) lint rules. |
tests/test_model.py |
Fixes a no-op expression by assigning the from_dict result before assertions. |
tests/test_core.py |
Avoids an unused loop variable by iterating dict keys only. |
tests/test__frame_helper.py |
Renames an unused loop variable to _. |
tests/benchmarks/test_bluetooth.py |
Renames an unused loop variable to _ in benchmark setup. |
bench/raw_ble_plain_text.py |
Renames an unused loop variable to _ in the bench script. |
aioesphomeapi/host_resolver.py |
Preserves exception cause when wrapping getaddrinfo failures. |
aioesphomeapi/_frame_helper/noise.py |
Preserves exception cause when rejecting malformed PSKs. |
tests/test_reconnect_logic.py |
Preserves exception cause when translating a timeout into APIConnectionError. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| try: | ||
| psk_bytes = binascii.a2b_base64(psk) | ||
| except ValueError: | ||
| except ValueError as err: | ||
| raise InvalidEncryptionKeyAPIError( | ||
| f"{self._log_name}: Malformed PSK (length={len(psk)}), " | ||
| "expected base64-encoded 32-byte value", | ||
| server_name, | ||
| server_mac, | ||
| ) | ||
| ) from err |
Adds PGH (pygrep-hooks) to the ruff rule selection so blanket `# type: ignore` and `# flake8: noqa` directives are flagged. All 12 existing violations are converted to specific codes: - 10 `# type: ignore` -> `# type: ignore[attr-defined]` on `from .api_pb2 import (...)` blocks (protobuf-generated module lacks stubs for its dynamically-emitted symbols). - 1 `# type: ignore` -> `# type: ignore[union-attr]` on the HomeassistantServiceMap iteration in `_convert_homeassistant_service_map` (mypy widens the iter element to `str | Any` after the dict isinstance branch). - `# flake8: noqa` on `aioesphomeapi/__init__.py` -> `# ruff: noqa: F401, F403` (file is the public re-export surface; F401 covers the unused-name warnings on each re-export and F403 covers the `from .model import *`). Follows the cadence of esphome#1678 (PTH) and esphome#1679 (PT006/PT007) and esphome#1683 (B) -- one ruff family at a time.
What does this implement/fix?
Adds the
B(flake8-bugbear) rule set to the enforced ruff lintconfiguration and fixes the 7 existing violations across the repo.
The notable fix is
tests/test_model.py:840, whereservices == BluetoothGATTServicesModel.from_dict(...)was ano-op expression (B015 caught it). The intent was to rebuild
servicesfrom the dict form and verify it parses to the samestructure — the next
assert services.services[0] == ...wasotherwise re-checking the from_pb-derived model. Changing
==to=makes thefrom_dictpath the one actually being asserted,matching the test name
test_bluetooth_gatt_services_from_dict.Other violations:
from err/from Nonein_frame_helper/noise.py::_decode_noise_psk,host_resolver.py::_async_resolve_host_getaddrinfo, and theresolver test helper. Preserves the cause chain on tracebacks.
_.Types of changes
Related issue or feature (if applicable):
Follows the same pattern as the recent PT006/PT007 (#1679) and PTH
(#1678) rule-set additions: enable one ruff family at a time, fix
the existing violations, lock it in.
Pull request in esphome (if applicable):
n/a — no
api.protochanges.Checklist:
tests/folder).Quality Report
Changes: 9 files changed, 11 insertions(+), 10 deletions(-)
Code scan: clean
Tests: failed (FAILED)
Branch hygiene: clean
Generated by Kōan post-mission quality pipeline