From da6f25c6a3e73e5857979d6f7611abd182678718 Mon Sep 17 00:00:00 2001 From: zigpy-review-bot <286747149+zigpy-review-bot@users.noreply.github.com> Date: Mon, 28 Sep 2026 03:00:44 +0200 Subject: [PATCH 1/4] Replace black, isort, flake8, autoflake and pyupgrade with ruff --- .github/workflows/matchers/flake8.json | 30 --------- .pre-commit-config.yaml | 43 ++----------- pyproject.toml | 87 +++++++++++++++++++------- requirements_test.txt | 6 +- ruff.toml | 71 --------------------- tox.ini | 9 ++- 6 files changed, 77 insertions(+), 169 deletions(-) delete mode 100644 .github/workflows/matchers/flake8.json delete mode 100644 ruff.toml diff --git a/.github/workflows/matchers/flake8.json b/.github/workflows/matchers/flake8.json deleted file mode 100644 index e059a1cf5..000000000 --- a/.github/workflows/matchers/flake8.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "problemMatcher": [ - { - "owner": "flake8-error", - "severity": "error", - "pattern": [ - { - "regexp": "^(.*):(\\d+):(\\d+):\\s([EF]\\d{3}\\s.*)$", - "file": 1, - "line": 2, - "column": 3, - "message": 4 - } - ] - }, - { - "owner": "flake8-warning", - "severity": "warning", - "pattern": [ - { - "regexp": "^(.*):(\\d+):(\\d+):\\s([CDNW]\\d{3}\\s.*)$", - "file": 1, - "line": 2, - "column": 3, - "message": 4 - } - ] - } - ] -} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index d328e4387..8dc1dbe6f 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,37 +1,13 @@ repos: - - repo: https://github.com/asottile/pyupgrade - rev: v3.21.2 + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.16.9 hooks: - - id: pyupgrade - args: [--py311-plus] - - - repo: https://github.com/PyCQA/autoflake - rev: v2.0.2 - hooks: - - id: autoflake - - - repo: https://github.com/psf/black - rev: 23.3.0 - hooks: - - id: black - args: - - --quiet - - - repo: https://github.com/pycqa/flake8 - rev: 7.0.0 - hooks: - - id: flake8 - entry: pflake8 - additional_dependencies: - - pyproject-flake8==7.0.0 - - - repo: https://github.com/PyCQA/isort - rev: 5.12.0 - hooks: - - id: isort + - id: ruff-check + args: ["--fix", "--exit-non-zero-on-fix"] + - id: ruff-format - repo: https://github.com/codespell-project/codespell - rev: v2.2.4 + rev: v2.4.3 hooks: - id: codespell args: @@ -45,10 +21,3 @@ repos: - id: mypy additional_dependencies: - zigpy - - - repo: https://github.com/charliermarsh/ruff-pre-commit - rev: v0.0.261 - hooks: - - id: ruff - args: - - --fix diff --git a/pyproject.toml b/pyproject.toml index 84074acd2..ea92d27d9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,13 +38,73 @@ enabled = true [project.scripts] bellows = "bellows.cli.main:main" -[tool.isort] -profile = "black" +[tool.ruff] +target-version = "py311" +line-length = 88 + +[tool.ruff.lint] +select = [ + "B", # flake8-bugbear + "C", # complexity + "D", # docstrings + "E", # pycodestyle + "F", # pyflakes/autoflake + "I", # isort + "ICN001", # import concentions; {name} should be imported as {asname} + "PGH004", # Use specific rule codes when using noqa + "PLC0414", # Useless import alias. Import alias does not rename original package. + "RUF006", # Store a reference to the return value of asyncio.create_task + "SIM", # flake8-simplify + "T20", # flake8-print + "TRY004", # Prefer TypeError exception for invalid type + "UP", # pyupgrade + "W", # pycodestyle +] + +ignore = [ + "D100", # Missing docstring in public module + "D101", # Missing docstring in public class + "D102", # Missing docstring in public method + "D103", # Missing docstring in public function + "D104", # Missing docstring in public package + "D105", # Missing docstring in magic method + "D106", # Missing docstring in public nested class + "D107", # Missing docstring in `__init__` + "D202", # No blank lines allowed after function docstring + "D203", # 1 blank line required before class docstring + "D205", # 1 blank line required between summary line and description + "D213", # Multi-line docstring summary should start at the second line + "D400", # First line should end with a period + "D401", # First line of docstring should be in imperative mood: + "D406", # Section name should end with a newline + "D407", # Section name underlining + "D415", # First line should end with a period, question mark, or exclamation point + "E501", # line too long + # the rules below this line should be corrected + "PGH004", # Use specific rule codes when using `noqa` +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["F811", "F401", "F403"] + +[tool.ruff.lint.flake8-pytest-style] +fixture-parentheses = false + +[tool.ruff.lint.pyupgrade] +keep-runtime-typing = true + +[tool.ruff.lint.isort] # will group `import x` and `from x import` of the same module. -force_sort_within_sections = true -known_first_party = ["bellows", "tests"] -forced_separate = "tests" -combine_as_imports = true +force-sort-within-sections = true +known-first-party = [ + "bellows", + "tests", +] +forced-separate = ["tests"] +combine-as-imports = true + +[tool.ruff.lint.mccabe] +max-complexity = 25 [tool.mypy] ignore_errors = true @@ -52,20 +112,6 @@ ignore_errors = true [tool.pytest.ini_options] asyncio_mode = "auto" -[tool.flake8] -exclude = ".venv,.git,.tox,docs,venv,bin,lib,deps,build" -# To work with Black -max-line-length = 88 -# W503: Line break occurred before a binary operator -# E203: Whitespace before ':' -# E501: line too long -# D202 No blank lines allowed after function docstring -ignore = "W503,E203,E501,D202" -per-file-ignores = """ - tests/*:F811,F401,F403 - bellows/types/named.py:E266 -""" - [tool.coverage.run] source = ["bellows"] omit = [ @@ -73,7 +119,6 @@ omit = [ "bellows/typing.py", ] - [tool.coverage.report] exclude_also = [ "raise AssertionError", diff --git a/requirements_test.txt b/requirements_test.txt index 8e3a9e69e..20dcbd31b 100644 --- a/requirements_test.txt +++ b/requirements_test.txt @@ -1,9 +1,6 @@ # Test dependencies. asynctest -isort -black -flake8 codecov colorlog codespell @@ -16,5 +13,4 @@ pytest-timeout pytest-asyncio>=0.17 pytest>=7.1.3 zigpy>=0.54.1 -ruff==0.0.261 -Flake8-pyproject +ruff==0.16.9 diff --git a/ruff.toml b/ruff.toml deleted file mode 100644 index 19c2a7c31..000000000 --- a/ruff.toml +++ /dev/null @@ -1,71 +0,0 @@ -target-version = "py311" - -select = [ - "B007", # Loop control variable {name} not used within loop body - "B014", # Exception handler with duplicate exception - "C", # complexity - "D", # docstrings - "E", # pycodestyle - "F", # pyflakes/autoflake - "ICN001", # import concentions; {name} should be imported as {asname} - "PGH004", # Use specific rule codes when using noqa - "PLC0414", # Useless import alias. Import alias does not rename original package. - "SIM105", # Use contextlib.suppress({exception}) instead of try-except-pass - "SIM117", # Merge with-statements that use the same scope - "SIM118", # Use {key} in {dict} instead of {key} in {dict}.keys() - "SIM201", # Use {left} != {right} instead of not {left} == {right} - "SIM212", # Use {a} if {a} else {b} instead of {b} if not {a} else {a} - "SIM300", # Yoda conditions. Use 'age == 42' instead of '42 == age'. - "SIM401", # Use get from dict with default instead of an if block - "T20", # flake8-print - "TRY004", # Prefer TypeError exception for invalid type - "RUF006", # Store a reference to the return value of asyncio.create_task - "UP", # pyupgrade - "W", # pycodestyle -] - -ignore = [ - "D100", # Missing docstring in public module - "D101", # Missing docstring in public class - "D102", # Missing docstring in public method - "D103", # Missing docstring in public function - "D104", # Missing docstring in public package - "D105", # Missing docstring in magic method - "D106", # Missing docstring in public nested class - "D107", # Missing docstring in `__init__` - "D202", # No blank lines allowed after function docstring - "D203", # 1 blank line required before class docstring - "D205", # 1 blank line required between summary line and description - "D213", # Multi-line docstring summary should start at the second line - "D400", # First line should end with a period - "D401", # First line of docstring should be in imperative mood: - "D406", # Section name should end with a newline - "D407", # Section name underlining - "D415", # First line should end with a period, question mark, or exclamation point - "E501", # line too long - # the rules below this line should be corrected - "PGH004", # Use specific rule codes when using `noqa` -] - -extend-exclude = [ - "tests" -] - -[flake8-pytest-style] -fixture-parentheses = false - -[pyupgrade] -keep-runtime-typing = true - -[isort] -# will group `import x` and `from x import` of the same module. -force-sort-within-sections = true -known-first-party = [ - "bellows", - "tests", -] -forced-separate = ["tests"] -combine-as-imports = true - -[mccabe] -max-complexity = 25 \ No newline at end of file diff --git a/tox.ini b/tox.ini index 13e0fe6d5..9fc2e1ab7 100644 --- a/tox.ini +++ b/tox.ini @@ -4,7 +4,7 @@ # and then run "tox" from this directory. [tox] -envlist = py37, py38, lint, black +envlist = py37, py38, lint, format skip_missing_interpreters = True [testenv] @@ -16,13 +16,12 @@ deps = -rrequirements_test.txt [testenv:lint] basepython = python3 commands = - pre-commit run --hook-stage manual flake8 --all-files - pre-commit run --hook-stage manual isort --all-files --show-diff-on-failure + pre-commit run --hook-stage manual ruff-check --all-files --show-diff-on-failure pre-commit run --hook-stage manual codespell --all-files -[testenv:black] +[testenv:format] setenv = LC_ALL=C.UTF-8 LANG=C.UTF-8 commands= - pre-commit run --hook-stage manual black --all-files --show-diff-on-failure + pre-commit run --hook-stage manual ruff-format --all-files --show-diff-on-failure From a118e4f79607e3bdd2d2965bd219d05f279a2f8a Mon Sep 17 00:00:00 2001 From: zigpy-review-bot <286747149+zigpy-review-bot@users.noreply.github.com> Date: Mon, 28 Sep 2026 03:05:45 +0200 Subject: [PATCH 2/4] Apply ruff fixes Mostly autofixes: import sorting, pyupgrade rewrites, ruff format output (lowercase hex escapes, joined implicit string concatenations) and unused loop variables. By hand: - Remove the stray fourth quote that opened every EZSP version module docstring (`""""EZSP ...`). - Drop a dead `stack_status = asyncio.Future()` in `EZSP.leaveNetwork`, immediately rebound by the `with` statement (F811). - Create the default `RuntimeError` in `_cancel_pending_data_frames` per call instead of sharing one instance created at import time (B008). - Exception chaining for re-raised errors, explicit zip(strict=...), %-formatting -> f-strings in the CLI, and keep a reference to background tasks in a test (RUF006). --- bellows/ash.py | 16 +-- bellows/cli/__init__.py | 2 +- bellows/cli/application.py | 7 +- bellows/cli/ncp.py | 6 +- bellows/cli/network.py | 10 +- bellows/cli/stream.py | 2 +- bellows/cli/tone.py | 2 +- bellows/cli/util.py | 5 +- bellows/ezsp/__init__.py | 12 +- bellows/ezsp/protocol.py | 2 +- bellows/ezsp/v10/__init__.py | 5 +- bellows/ezsp/v11/__init__.py | 5 +- bellows/ezsp/v12/__init__.py | 5 +- bellows/ezsp/v13/__init__.py | 5 +- bellows/ezsp/v14/__init__.py | 5 +- bellows/ezsp/v16/__init__.py | 5 +- bellows/ezsp/v17/__init__.py | 5 +- bellows/ezsp/v18/__init__.py | 5 +- bellows/ezsp/v19/__init__.py | 5 +- bellows/ezsp/v4/__init__.py | 5 +- bellows/ezsp/v5/__init__.py | 5 +- bellows/ezsp/v6/__init__.py | 5 +- bellows/ezsp/v7/__init__.py | 5 +- bellows/ezsp/v8/__init__.py | 5 +- bellows/ezsp/v9/__init__.py | 5 +- bellows/ezsp/xncp.py | 1 + bellows/thread.py | 10 +- bellows/zigbee/application.py | 11 +- bellows/zigbee/util.py | 2 +- tests/common.py | 2 +- tests/test_application.py | 264 ++++++++++++++++++---------------- tests/test_ash.py | 74 +++++----- tests/test_commands.py | 4 +- tests/test_ezsp_protocol.py | 20 +-- tests/test_ezsp_v12.py | 2 +- tests/test_ezsp_v13.py | 2 +- tests/test_ezsp_v14.py | 21 ++- tests/test_ezsp_v19.py | 2 +- tests/test_ezsp_v4.py | 7 +- tests/test_ezsp_v7.py | 5 +- tests/test_fragmentation.py | 15 +- tests/test_thread.py | 2 +- tests/test_xncp.py | 6 +- 43 files changed, 295 insertions(+), 294 deletions(-) diff --git a/bellows/ash.py b/bellows/ash.py index 48b492caa..106fed1a8 100644 --- a/bellows/ash.py +++ b/bellows/ash.py @@ -70,10 +70,7 @@ def generate_random_sequence(length: int) -> bytes: for _i in range(length): output.append(rand) - if rand & 0b00000001 == 0: - rand = rand >> 1 - else: - rand = (rand >> 1) ^ 0xB8 + rand = rand >> 1 if rand & 0b00000001 == 0 else (rand >> 1) ^ 0xB8 return output @@ -178,7 +175,9 @@ class DataFrame(AshFrame): @staticmethod def _randomize(data: bytes) -> bytes: assert len(data) <= len(PSEUDO_RANDOM_DATA_SEQUENCE) - return bytes([a ^ b for a, b in zip(data, PSEUDO_RANDOM_DATA_SEQUENCE)]) + return bytes( + [a ^ b for a, b in zip(data, PSEUDO_RANDOM_DATA_SEQUENCE, strict=False)] + ) @classmethod def from_bytes(cls, data: bytes) -> DataFrame: @@ -380,9 +379,10 @@ def connection_lost(self, exc: Exception | None) -> None: def eof_received(self): self._ezsp_protocol.eof_received() - def _cancel_pending_data_frames( - self, exc: BaseException = RuntimeError("Connection has been closed") - ): + def _cancel_pending_data_frames(self, exc: BaseException | None = None): + if exc is None: + exc = RuntimeError("Connection has been closed") + for fut in self._pending_data_frames.values(): if not fut.done(): fut.set_exception(exc) diff --git a/bellows/cli/__init__.py b/bellows/cli/__init__.py index 1c8f38366..9b783eb01 100644 --- a/bellows/cli/__init__.py +++ b/bellows/cli/__init__.py @@ -1,2 +1,2 @@ -# flake8: noqa +# ruff: noqa from . import application, backup, dump, ncp, network, stream, tone diff --git a/bellows/cli/application.py b/bellows/cli/application.py index 9d175df6b..e835e1c84 100644 --- a/bellows/cli/application.py +++ b/bellows/cli/application.py @@ -123,8 +123,7 @@ def print_clusters(title, clusters): click.echo(" %s: Uninitialized") else: click.echo( - " %s: profile=0x%02x, device_type=%s" - % (epid, ep.profile_id, ep.device_type) + f" {epid}: profile=0x{ep.profile_id:02x}, device_type={ep.device_type!s}" ) print_clusters("Input Clusters", ep.in_clusters) print_clusters("Output Clusters", ep.out_clusters) @@ -278,9 +277,7 @@ async def read_attribute(ctx, attribute, manufacturer): click.echo("Received empty response") elif attribute not in v[0]: click.echo( - "Attribute {} not successful. Status={}".format( - attribute, v[1][attribute] - ) + f"Attribute {attribute} not successful. Status={v[1][attribute]}" ) else: click.echo(f"{attribute}={v[0][attribute]}") diff --git a/bellows/cli/ncp.py b/bellows/cli/ncp.py index bbe0471ad..4b588d5e9 100644 --- a/bellows/cli/ncp.py +++ b/bellows/cli/ncp.py @@ -39,18 +39,18 @@ async def config(ctx, config, all_): try: config = t.EzspConfigId(int(config)) except ValueError: - raise click.BadArgumentUsage(f"Invalid config ID: {config}") + raise click.BadArgumentUsage(f"Invalid config ID: {config}") from None else: try: config = t.EzspConfigId[config] except KeyError: - raise click.BadArgumentUsage(f"Invalid config name: {config}") + raise click.BadArgumentUsage(f"Invalid config name: {config}") from None try: value = t.uint16_t(value) if not (0 <= value <= 65535): raise ValueError(f"{value} out of allowed range 0..65535") except ValueError as e: - raise click.BadArgumentUsage(f"Invalid value: {e}") + raise click.BadArgumentUsage(f"Invalid value: {e}") from e v = await s.setConfigurationValue(config, value) click.echo(v) diff --git a/bellows/cli/network.py b/bellows/cli/network.py index ff10de65e..984dc9d19 100644 --- a/bellows/cli/network.py +++ b/bellows/cli/network.py @@ -43,8 +43,9 @@ def cb(fut, frame_name, response): scan_type = t.EzspNetworkScanType.ACTIVE_SCAN channel_mask = util.channel_mask(channels) click.echo( - "PAN not provided, scanning channels %s..." - % (" ".join(map(str, channels)),) + "PAN not provided, scanning channels {}...".format( + " ".join(map(str, channels)) + ) ) v = await s.startScan(scan_type, channel_mask, 3) @@ -64,10 +65,7 @@ def cb(fut, frame_name, response): click.echo(f"Found network {pan_id} {extended_pan_id} on channel {channel}") - if pan_id is None: - pan_id = t.uint16_t(0) - else: - pan_id = t.uint16_t(pan_id) + pan_id = t.uint16_t(0) if pan_id is None else t.uint16_t(pan_id) if isinstance(extended_pan_id, str): extended_pan_id = util.parse_epan(extended_pan_id) if extended_pan_id is None: diff --git a/bellows/cli/stream.py b/bellows/cli/stream.py index eb77dd00a..be6792ddb 100644 --- a/bellows/cli/stream.py +++ b/bellows/cli/stream.py @@ -28,7 +28,7 @@ def stream(ctx, channel, power): if start_time: duration = time.time() - start_time click.echo( - "\nStreamed on channel %d for %0.2fs" % (channel, duration), err=True + f"\nStreamed on channel {channel:d} for {duration:0.2f}s", err=True ) finally: if "ezsp" in ctx.obj: diff --git a/bellows/cli/tone.py b/bellows/cli/tone.py index 50a02e1ec..0808e44ae 100644 --- a/bellows/cli/tone.py +++ b/bellows/cli/tone.py @@ -28,7 +28,7 @@ def tone(ctx, channel, power): if start_time: duration = time.time() - start_time click.echo( - "\nStreamed on channel %d for %0.2fs" % (channel, duration), err=True + f"\nStreamed on channel {channel:d} for {duration:0.2f}s", err=True ) finally: if "ezsp" in ctx.obj: diff --git a/bellows/cli/util.py b/bellows/cli/util.py index 76f835119..18ca8184e 100644 --- a/bellows/cli/util.py +++ b/bellows/cli/util.py @@ -169,7 +169,7 @@ def get_endpoint(app, node, endpoint_id): return (dev, None) if endpoint_id not in dev.endpoints: - click.echo("Device %s has no endpoint %d" % (node, endpoint_id)) + click.echo(f"Device {node} has no endpoint {endpoint_id:d}") return (dev, None) return (dev, dev.endpoints[endpoint_id]) @@ -182,8 +182,7 @@ def get_in_cluster(app, node, endpoint_id, cluster_id): if cluster_id not in endpoint.in_clusters: click.echo( - "Device %s has no cluster %d on endpoint %d" - % (node, cluster_id, endpoint_id) + f"Device {node} has no cluster {cluster_id:d} on endpoint {endpoint_id:d}" ) return (dev, endpoint, None) diff --git a/bellows/ezsp/__init__.py b/bellows/ezsp/__init__.py index a21138292..e296f278f 100644 --- a/bellows/ezsp/__init__.py +++ b/bellows/ezsp/__init__.py @@ -200,7 +200,7 @@ async def version(self): await self._command("version", desiredProtocolVersion=ver) LOGGER.debug( - ("EZSP Stack Type: %s" ", Stack Version: %04x" ", Protocol version: %s"), + "EZSP Stack Type: %s, Stack Version: %04x, Protocol version: %s", stack_type, stack_version, ver, @@ -325,8 +325,6 @@ async def leaveNetwork( ), ) -> None: """Send leaveNetwork command and wait for stackStatusHandler frame.""" - stack_status = asyncio.Future() - with self.wait_for_stack_status(t.sl_Status.NETWORK_DOWN) as stack_status: status = await self._protocol.leave_network(options=options) if status != t.sl_Status.OK: @@ -398,8 +396,8 @@ async def get_board_info( # Tokens are fixed-length and initially filled with \xFF but also can end # with \x00 - while value.endswith((b"\xFF", b"\x00")): - value = value.rstrip(b"\xFF").rstrip(b"\x00") + while value.endswith((b"\xff", b"\x00")): + value = value.rstrip(b"\xff").rstrip(b"\x00") try: result = value.decode("utf-8") @@ -772,10 +770,10 @@ async def send_xncp_frame( try: rsp_frame = xncp.XncpCommand.from_bytes(data) - except ValueError: + except ValueError as exc: raise InvalidCommandPayload( f"Invalid XNCP response: {data!r}", raw_bytes=data - ) + ) from exc if isinstance(rsp_frame.payload, xncp.Unknown): raise InvalidCommandError(f"XNCP firmware does not support {payload}") diff --git a/bellows/ezsp/protocol.py b/bellows/ezsp/protocol.py index 4b0853602..a8aebe7c4 100644 --- a/bellows/ezsp/protocol.py +++ b/bellows/ezsp/protocol.py @@ -281,7 +281,7 @@ def __getattr__(self, name: str) -> Callable: return functools.partial(self.command, name) - async def pre_permit(self, time_s: int) -> None: + async def pre_permit(self, time_s: int) -> None: # noqa: B027 """Schedule task before allowing new joins.""" @abc.abstractmethod diff --git a/bellows/ezsp/v10/__init__.py b/bellows/ezsp/v10/__init__.py index bea19c46b..9486de60c 100644 --- a/bellows/ezsp/v10/__init__.py +++ b/bellows/ezsp/v10/__init__.py @@ -1,4 +1,5 @@ -""""EZSP Protocol version 10 protocol handler.""" +"""EZSP Protocol version 10 protocol handler.""" + from __future__ import annotations import logging @@ -9,8 +10,8 @@ from bellows.exception import InvalidCommandError import bellows.types as t -from . import commands, config from ..v9 import EZSPv9 +from . import commands, config LOGGER = logging.getLogger(__name__) diff --git a/bellows/ezsp/v11/__init__.py b/bellows/ezsp/v11/__init__.py index 1752c0da6..d7e67e2e9 100644 --- a/bellows/ezsp/v11/__init__.py +++ b/bellows/ezsp/v11/__init__.py @@ -1,10 +1,11 @@ -""""EZSP Protocol version 11 protocol handler.""" +"""EZSP Protocol version 11 protocol handler.""" + import voluptuous as vol import bellows.config -from . import commands, config from ..v10 import EZSPv10 +from . import commands, config class EZSPv11(EZSPv10): diff --git a/bellows/ezsp/v12/__init__.py b/bellows/ezsp/v12/__init__.py index 0a80e6804..e80a60df7 100644 --- a/bellows/ezsp/v12/__init__.py +++ b/bellows/ezsp/v12/__init__.py @@ -1,10 +1,11 @@ -""""EZSP Protocol version 12 protocol handler.""" +"""EZSP Protocol version 12 protocol handler.""" + import voluptuous as vol import bellows.config -from . import commands, config from ..v11 import EZSPv11 +from . import commands, config class EZSPv12(EZSPv11): diff --git a/bellows/ezsp/v13/__init__.py b/bellows/ezsp/v13/__init__.py index 999a9bc7f..71241c16b 100644 --- a/bellows/ezsp/v13/__init__.py +++ b/bellows/ezsp/v13/__init__.py @@ -1,4 +1,5 @@ -""""EZSP Protocol version 13 protocol handler.""" +"""EZSP Protocol version 13 protocol handler.""" + from __future__ import annotations from collections.abc import AsyncGenerator, Iterable @@ -11,8 +12,8 @@ import bellows.config import bellows.types as t -from . import commands, config from ..v12 import EZSPv12 +from . import commands, config LOGGER = logging.getLogger(__name__) diff --git a/bellows/ezsp/v14/__init__.py b/bellows/ezsp/v14/__init__.py index 34e882f6b..da60bf233 100644 --- a/bellows/ezsp/v14/__init__.py +++ b/bellows/ezsp/v14/__init__.py @@ -1,4 +1,5 @@ -""""EZSP Protocol version 14 protocol handler.""" +"""EZSP Protocol version 14 protocol handler.""" + from __future__ import annotations from collections.abc import AsyncGenerator @@ -10,8 +11,8 @@ import bellows.config import bellows.types as t -from . import commands, config from ..v13 import EZSPv13 +from . import commands, config class EZSPv14(EZSPv13): diff --git a/bellows/ezsp/v16/__init__.py b/bellows/ezsp/v16/__init__.py index 5ddbf58ce..a2b53ac14 100644 --- a/bellows/ezsp/v16/__init__.py +++ b/bellows/ezsp/v16/__init__.py @@ -1,12 +1,13 @@ -""""EZSP Protocol version 16 protocol handler.""" +"""EZSP Protocol version 16 protocol handler.""" + from __future__ import annotations import voluptuous as vol import bellows.config -from . import commands, config from ..v14 import EZSPv14 +from . import commands, config class EZSPv16(EZSPv14): diff --git a/bellows/ezsp/v17/__init__.py b/bellows/ezsp/v17/__init__.py index 1f6d98329..8294969ee 100644 --- a/bellows/ezsp/v17/__init__.py +++ b/bellows/ezsp/v17/__init__.py @@ -1,12 +1,13 @@ -""""EZSP Protocol version 17 protocol handler.""" +"""EZSP Protocol version 17 protocol handler.""" + from __future__ import annotations import voluptuous as vol import bellows.config -from . import commands, config from ..v16 import EZSPv16 +from . import commands, config class EZSPv17(EZSPv16): diff --git a/bellows/ezsp/v18/__init__.py b/bellows/ezsp/v18/__init__.py index f087a8d1b..3f06029ad 100644 --- a/bellows/ezsp/v18/__init__.py +++ b/bellows/ezsp/v18/__init__.py @@ -1,12 +1,13 @@ -""""EZSP Protocol version 18 protocol handler.""" +"""EZSP Protocol version 18 protocol handler.""" + from __future__ import annotations import voluptuous as vol import bellows.config -from . import commands, config from ..v17 import EZSPv17 +from . import commands, config class EZSPv18(EZSPv17): diff --git a/bellows/ezsp/v19/__init__.py b/bellows/ezsp/v19/__init__.py index 93a14dd21..7e48857cf 100644 --- a/bellows/ezsp/v19/__init__.py +++ b/bellows/ezsp/v19/__init__.py @@ -1,12 +1,13 @@ -""""EZSP Protocol version 19 protocol handler.""" +"""EZSP Protocol version 19 protocol handler.""" + from __future__ import annotations import voluptuous as vol import bellows.config -from . import commands, config from ..v18 import EZSPv18 +from . import commands, config class EZSPv19(EZSPv18): diff --git a/bellows/ezsp/v4/__init__.py b/bellows/ezsp/v4/__init__.py index 46ae33c33..7f00e00ba 100644 --- a/bellows/ezsp/v4/__init__.py +++ b/bellows/ezsp/v4/__init__.py @@ -1,4 +1,5 @@ -""""EZSP Protocol version 4 command.""" +"""EZSP Protocol version 4 command.""" + from __future__ import annotations from collections.abc import AsyncGenerator, Iterable @@ -12,8 +13,8 @@ import bellows.types as t from bellows.zigbee.util import ezsp_key_to_zigpy_key -from . import commands, config from .. import protocol +from . import commands, config LOGGER = logging.getLogger(__name__) diff --git a/bellows/ezsp/v5/__init__.py b/bellows/ezsp/v5/__init__.py index 0a741a120..7a187d70b 100644 --- a/bellows/ezsp/v5/__init__.py +++ b/bellows/ezsp/v5/__init__.py @@ -1,4 +1,5 @@ -""""EZSP Protocol version 5 protocol handler.""" +"""EZSP Protocol version 5 protocol handler.""" + from __future__ import annotations from collections.abc import AsyncGenerator @@ -9,8 +10,8 @@ import bellows.config import bellows.types as t -from . import commands, config from ..v4 import EZSPv4 +from . import commands, config LOGGER = logging.getLogger(__name__) diff --git a/bellows/ezsp/v6/__init__.py b/bellows/ezsp/v6/__init__.py index 729357edb..d663f2df8 100644 --- a/bellows/ezsp/v6/__init__.py +++ b/bellows/ezsp/v6/__init__.py @@ -1,4 +1,5 @@ -""""EZSP Protocol version 6 protocol handler.""" +"""EZSP Protocol version 6 protocol handler.""" + import logging import voluptuous @@ -6,8 +7,8 @@ import bellows.config import bellows.types as t -from . import commands, config from ..v5 import EZSPv5 +from . import commands, config LOGGER = logging.getLogger(__name__) diff --git a/bellows/ezsp/v7/__init__.py b/bellows/ezsp/v7/__init__.py index 9e26d9043..668e414f4 100644 --- a/bellows/ezsp/v7/__init__.py +++ b/bellows/ezsp/v7/__init__.py @@ -1,4 +1,5 @@ -""""EZSP Protocol version 7 protocol handler.""" +"""EZSP Protocol version 7 protocol handler.""" + from __future__ import annotations from collections.abc import AsyncGenerator @@ -9,8 +10,8 @@ import bellows.config import bellows.types as t -from . import commands, config from ..v6 import EZSPv6 +from . import commands, config LOGGER = logging.getLogger(__name__) diff --git a/bellows/ezsp/v8/__init__.py b/bellows/ezsp/v8/__init__.py index b2b55dde2..9d6f288b9 100644 --- a/bellows/ezsp/v8/__init__.py +++ b/bellows/ezsp/v8/__init__.py @@ -1,4 +1,5 @@ -""""EZSP Protocol version 8 protocol handler.""" +"""EZSP Protocol version 8 protocol handler.""" + import asyncio import logging @@ -7,8 +8,8 @@ import bellows.config import bellows.types as t -from . import commands, config from ..v7 import EZSPv7 +from . import commands, config LOGGER = logging.getLogger(__name__) diff --git a/bellows/ezsp/v9/__init__.py b/bellows/ezsp/v9/__init__.py index bc589c939..23ab37220 100644 --- a/bellows/ezsp/v9/__init__.py +++ b/bellows/ezsp/v9/__init__.py @@ -1,4 +1,5 @@ -""""EZSP Protocol version 9 protocol handler.""" +"""EZSP Protocol version 9 protocol handler.""" + from __future__ import annotations import logging @@ -8,8 +9,8 @@ import bellows.config import bellows.types as t -from . import commands, config from ..v8 import EZSPv8 +from . import commands, config LOGGER = logging.getLogger(__name__) diff --git a/bellows/ezsp/xncp.py b/bellows/ezsp/xncp.py index 1048e9676..f5d636acc 100644 --- a/bellows/ezsp/xncp.py +++ b/bellows/ezsp/xncp.py @@ -1,4 +1,5 @@ """Custom EZSP commands.""" + from __future__ import annotations from collections.abc import Callable diff --git a/bellows/thread.py b/bellows/thread.py index a10b58d93..f25014821 100644 --- a/bellows/thread.py +++ b/bellows/thread.py @@ -88,9 +88,7 @@ def __getattr__(self, name): func = getattr(self._obj, name) if not callable(func): raise TypeError( - "Can only use ThreadsafeProxy with callable attributes: {}.{}".format( - self._obj.__class__.__name__, name - ) + f"Can only use ThreadsafeProxy with callable attributes: {self._obj.__class__.__name__}.{name}" ) def func_wrapper(*args, **kwargs): @@ -112,10 +110,8 @@ def check_result_wrapper(): result = call() if result is not None: raise TypeError( - ( - "ThreadsafeProxy can only wrap functions with no return" - "value \nUse an async method to return values: {}.{}" - ).format(self._obj.__class__.__name__, name) + "ThreadsafeProxy can only wrap functions with no return" + f"value \nUse an async method to return values: {self._obj.__class__.__name__}.{name}" ) loop.call_soon_threadsafe(check_result_wrapper) diff --git a/bellows/zigbee/application.py b/bellows/zigbee/application.py index 11b3eb0f2..9e7e1af6a 100644 --- a/bellows/zigbee/application.py +++ b/bellows/zigbee/application.py @@ -537,9 +537,9 @@ async def write_network_info( if use_hashed_tclk and not stack_specific.get("hashed_tclk"): # Generate a random default - network_info.stack_specific.setdefault("ezsp", {})[ - "hashed_tclk" - ] = os.urandom(16).hex() + network_info.stack_specific.setdefault("ezsp", {})["hashed_tclk"] = ( + os.urandom(16).hex() + ) initial_security_state = util.zha_security( network_info=network_info, @@ -779,10 +779,7 @@ def _handle_frame_sent( status: t.sl_Status, message: bytes, ): - if status == t.sl_Status.OK: - msg = "success" - else: - msg = "failure" + msg = "success" if status == t.sl_Status.OK else "failure" if message_type in ( t.EmberOutgoingMessageType.OUTGOING_BROADCAST, diff --git a/bellows/zigbee/util.py b/bellows/zigbee/util.py index 12e38079f..7a39b6ddb 100644 --- a/bellows/zigbee/util.py +++ b/bellows/zigbee/util.py @@ -152,7 +152,7 @@ def run_length_debug( result = joiner.join( f"{count}*{item}" if count > 1 else item - for item, count in zip(unique_items, counts) + for item, count in zip(unique_items, counts, strict=True) ) if not result: diff --git a/tests/common.py b/tests/common.py index f7af50f77..2f807ba14 100644 --- a/tests/common.py +++ b/tests/common.py @@ -6,7 +6,7 @@ def mock_ezsp_commands(ezsp: ProtocolHandler) -> ProtocolHandler: - for command_name, (_command_id, tx_schema, _rx_schema) in ezsp.COMMANDS.items(): + for command_name, (_command_id, _tx_schema, _rx_schema) in ezsp.COMMANDS.items(): # TODO: make this end-to-end instead of relying on this serialization hack async def fake_sender(*args, _command_name=command_name, _ezsp=ezsp, **kwargs): # Trigger an exception early diff --git a/tests/test_application.py b/tests/test_application.py index 4bfce5f05..8b4ec2f56 100644 --- a/tests/test_application.py +++ b/tests/test_application.py @@ -340,8 +340,9 @@ def mock_for_startup( app, nwk_type, ieee, auto_form, init, ezsp_version, board_info, network_state ) - with patch("bellows.ezsp.EZSP", return_value=ezsp_mock), patch( - "zigpy.device.Device._initialize", new=AsyncMock() + with ( + patch("bellows.ezsp.EZSP", return_value=ezsp_mock), + patch("zigpy.device.Device._initialize", new=AsyncMock()), ): yield ezsp_mock @@ -465,16 +466,16 @@ def _handle_incoming_aps_frame(app, aps_frame, type): app.ezsp_callback_handler( "incomingMessageHandler", list( - dict( - type=type, - apsFrame=aps_frame, - lastHopLqi=123, - lastHopRssi=-45, - sender=0xABCD, - bindingIndex=56, - addressIndex=78, - message=b"test message", - ).values() + { + "type": type, + "apsFrame": aps_frame, + "lastHopLqi": 123, + "lastHopRssi": -45, + "sender": 0xABCD, + "bindingIndex": 56, + "addressIndex": 78, + "message": b"test message", + }.values() ), ) @@ -716,7 +717,7 @@ async def test_force_remove(app, ieee): def test_sequence(app): - for i in range(1000): + for _i in range(1000): seq = app.get_sequence() assert seq >= 0 assert seq < 256 @@ -748,15 +749,15 @@ async def test_permit_with_link_key(app, ieee): async def test_permit_with_link_key_failure(app, ieee): app._ezsp._protocol.add_transient_link_key.return_value = t.EmberStatus.ERR_FATAL - with patch("zigpy.application.ControllerApplication.permit") as permit_mock: - with pytest.raises(ControllerError): - await app.permit_with_link_key( - ieee, - zigpy_t.KeyData.convert( - "11:22:33:44:55:66:77:88:11:22:33:44:55:66:77:88" - ), - 60, - ) + with ( + patch("zigpy.application.ControllerApplication.permit") as permit_mock, + pytest.raises(ControllerError), + ): + await app.permit_with_link_key( + ieee, + zigpy_t.KeyData.convert("11:22:33:44:55:66:77:88:11:22:33:44:55:66:77:88"), + 60, + ) assert permit_mock.await_count == 0 assert app._ezsp._protocol.add_transient_link_key.await_count == 1 @@ -786,14 +787,14 @@ def send_unicast(aps_frame, data, message_tag, nwk): app.ezsp_callback_handler, "messageSentHandler", list( - dict( - type=t.EmberOutgoingMessageType.OUTGOING_DIRECT, - indexOrDestination=0x1234, - apsFrame=aps_frame, - messageTag=message_tag, - status=bellows.types.sl_Status.OK, - message=b"", - ).values() + { + "type": t.EmberOutgoingMessageType.OUTGOING_DIRECT, + "indexOrDestination": 0x1234, + "apsFrame": aps_frame, + "messageTag": message_tag, + "status": bellows.types.sl_Status.OK, + "message": b"", + }.values() ), ) @@ -838,14 +839,14 @@ def send_unicast(*args, **kwargs): app.ezsp_callback_handler, "messageSentHandler", list( - dict( - type=t.EmberOutgoingMessageType.OUTGOING_DIRECT, - indexOrDestination=0x1234, - apsFrame=sentinel.aps, - messageTag=MSG_TAG, - status=sent_handler_status, - message=b"", - ).values() + { + "type": t.EmberOutgoingMessageType.OUTGOING_DIRECT, + "indexOrDestination": 0x1234, + "apsFrame": sentinel.aps, + "messageTag": MSG_TAG, + "status": sent_handler_status, + "message": b"", + }.values() ), ) @@ -980,14 +981,14 @@ def xncp_send_unicast(*args, **kwargs): app.ezsp_callback_handler, "messageSentHandler", list( - dict( - type=t.EmberOutgoingMessageType.OUTGOING_DIRECT, - indexOrDestination=0x1234, - apsFrame=sentinel.aps, - messageTag=MSG_TAG, - status=bellows.types.sl_Status.OK, - message=b"", - ).values() + { + "type": t.EmberOutgoingMessageType.OUTGOING_DIRECT, + "indexOrDestination": 0x1234, + "apsFrame": sentinel.aps, + "messageTag": MSG_TAG, + "status": bellows.types.sl_Status.OK, + "message": b"", + }.values() ), ) @@ -1257,6 +1258,7 @@ async def test_send_packet_unicast_concurrency(app, packet, monkeypatch): max_concurrency = 0 in_flight_requests = 0 + reply_tasks = [] async def send_message_sent_reply( type, indexOrDestination, apsFrame, messageTag, message @@ -1271,14 +1273,14 @@ async def send_message_sent_reply( app.ezsp_callback_handler( "messageSentHandler", list( - dict( - type=type, - indexOrDestination=indexOrDestination, - apsFrame=apsFrame, - messageTag=messageTag, - status=t.EmberStatus.SUCCESS, - message=b"", - ).values() + { + "type": type, + "indexOrDestination": indexOrDestination, + "apsFrame": apsFrame, + "messageTag": messageTag, + "status": t.EmberStatus.SUCCESS, + "message": b"", + }.values() ), ) @@ -1288,13 +1290,15 @@ async def send_unicast(nwk, aps_frame, message_tag, data): in_flight_requests += 1 max_concurrency = max(max_concurrency, in_flight_requests) - asyncio.create_task( - send_message_sent_reply( - t.EmberOutgoingMessageType.OUTGOING_DIRECT, - nwk, - aps_frame, - message_tag, - data, + reply_tasks.append( + asyncio.create_task( + send_message_sent_reply( + t.EmberOutgoingMessageType.OUTGOING_DIRECT, + nwk, + aps_frame, + message_tag, + data, + ) ) ) @@ -1328,14 +1332,14 @@ async def test_send_packet_broadcast(app, packet): app.ezsp_callback_handler, "messageSentHandler", list( - dict( - type=t.EmberOutgoingMessageType.OUTGOING_BROADCAST, - indexOrDestination=0xFFFE, - apsFrame=sentinel.aps, - messageTag=MSG_TAG, - status=t.EmberStatus.SUCCESS, - message=b"", - ).values() + { + "type": t.EmberOutgoingMessageType.OUTGOING_BROADCAST, + "indexOrDestination": 0xFFFE, + "apsFrame": sentinel.aps, + "messageTag": MSG_TAG, + "status": t.EmberStatus.SUCCESS, + "message": b"", + }.values() ), ) @@ -1374,14 +1378,14 @@ async def test_send_packet_broadcast_ignored_delivery_failure(app, packet): app.ezsp_callback_handler, "messageSentHandler", list( - dict( - type=t.EmberOutgoingMessageType.OUTGOING_BROADCAST, - indexOrDestination=0xFFFE, - apsFrame=sentinel.aps, - messageTag=MSG_TAG, - status=t.EmberStatus.DELIVERY_FAILED, - message=b"", - ).values() + { + "type": t.EmberOutgoingMessageType.OUTGOING_BROADCAST, + "indexOrDestination": 0xFFFE, + "apsFrame": sentinel.aps, + "messageTag": MSG_TAG, + "status": t.EmberStatus.DELIVERY_FAILED, + "message": b"", + }.values() ), ) @@ -1427,14 +1431,14 @@ async def test_send_packet_multicast(app, packet): app.ezsp_callback_handler, "messageSentHandler", list( - dict( - type=t.EmberOutgoingMessageType.OUTGOING_MULTICAST, - indexOrDestination=0x1234, - apsFrame=sentinel.aps, - messageTag=MSG_TAG, - status=t.EmberStatus.SUCCESS, - message=b"", - ).values() + { + "type": t.EmberOutgoingMessageType.OUTGOING_MULTICAST, + "indexOrDestination": 0x1234, + "apsFrame": sentinel.aps, + "messageTag": MSG_TAG, + "status": t.EmberStatus.SUCCESS, + "message": b"", + }.values() ), ) @@ -1498,14 +1502,14 @@ async def nop_mock(): return ([0] * 10,) raise TimeoutError - app._ezsp._protocol.getValue.return_value = [t.EmberStatus.SUCCESS, b"\xFE"] + app._ezsp._protocol.getValue.return_value = [t.EmberStatus.SUCCESS, b"\xfe"] app._ezsp._protocol.nop.side_effect = nop_mock app._ezsp._protocol.readCounters.side_effect = nop_mock app._ezsp._protocol.readAndClearCounters.side_effect = nop_mock app._ctrl_event.set() app.connection_lost = MagicMock() - for i in range(nop_success): + for _i in range(nop_success): await app._watchdog_feed() # Fail four times in a row to exhaust the watchdog buffer @@ -1541,7 +1545,7 @@ async def counters_mock(): raise TimeoutError app._ezsp._protocol.getValue = AsyncMock( - return_value=[t.EmberStatus.SUCCESS, b"\xFE"] + return_value=[t.EmberStatus.SUCCESS, b"\xfe"] ) app._ezsp._protocol.readCounters = AsyncMock(side_effect=counters_mock) app._ezsp._protocol.nop = AsyncMock(side_effect=EzspError) @@ -2203,9 +2207,8 @@ async def test_connect_failure(app: ControllerApplication) -> None: app._ezsp.connect = AsyncMock() app._ezsp = None - with patch("bellows.ezsp.EZSP", return_value=ezsp): - with pytest.raises(OSError): - await app.connect() + with patch("bellows.ezsp.EZSP", return_value=ezsp), pytest.raises(OSError): + await app.connect() assert app._ezsp is None @@ -2218,9 +2221,12 @@ async def test_repair_tclk_partner_ieee( """Test that EZSP is reset after repairing TCLK.""" app._reset = AsyncMock() - with mock_for_startup(app, ieee), patch( - "bellows.zigbee.repairs.fix_invalid_tclk_partner_ieee", - AsyncMock(return_value=False), + with ( + mock_for_startup(app, ieee), + patch( + "bellows.zigbee.repairs.fix_invalid_tclk_partner_ieee", + AsyncMock(return_value=False), + ), ): await app.connect() await app.start_network() @@ -2228,9 +2234,12 @@ async def test_repair_tclk_partner_ieee( assert len(app._reset.mock_calls) == 0 app._reset.reset_mock() - with mock_for_startup(app, ieee), patch( - "bellows.zigbee.repairs.fix_invalid_tclk_partner_ieee", - AsyncMock(return_value=True), + with ( + mock_for_startup(app, ieee), + patch( + "bellows.zigbee.repairs.fix_invalid_tclk_partner_ieee", + AsyncMock(return_value=True), + ), ): await app.start_network() @@ -2535,9 +2544,10 @@ async def test_write_network_info_formation_failure_no_retry( app._ezsp._protocol.formNetwork.return_value = [t.EmberStatus.ERR_FATAL] - with patch.object(app, "_reset"), pytest.raises( - zigpy.exceptions.FormationFailure - ) as exc_info: + with ( + patch.object(app, "_reset"), + pytest.raises(zigpy.exceptions.FormationFailure) as exc_info, + ): await app.write_network_info( node_info=zigpy_backup.node_info, network_info=network_info, @@ -2784,7 +2794,7 @@ async def test_network_scan_failure(app: ControllerApplication) -> None: app._ezsp._protocol.startScan.return_value = [t.sl_Status.FAIL] with pytest.raises(zigpy.exceptions.ControllerException): - async for beacon in app.network_scan( + async for _beacon in app.network_scan( channels=t.Channels.from_channel_list([11, 15, 26]), duration_exp=4 ): pass @@ -2802,7 +2812,7 @@ async def receive_packets() -> None: { "linkQuality": 150, "rssi": -70, - "packetContents": b"packet 1\xAB\xCD", + "packetContents": b"packet 1\xab\xcd", }.values() ), ) @@ -2815,7 +2825,7 @@ async def receive_packets() -> None: { "linkQuality": 200, "rssi": -50, - "packetContents": b"packet 2\xAB\xCD", + "packetContents": b"packet 2\xab\xcd", }.values() ), ) @@ -2858,7 +2868,7 @@ async def test_packet_capture_failure(app: ControllerApplication) -> None: app._ezsp._protocol.mfglibStart.return_value = [t.sl_Status.FAIL] with pytest.raises(zigpy.exceptions.ControllerException): - async for packet in app.packet_capture(channel=15): + async for _packet in app.packet_capture(channel=15): pass @@ -2870,26 +2880,32 @@ async def test_migration_failure_eui64_overwrite_confirmation( # Migration explicitly fails if we need to write the EUI64 but the adapter treats it # as a write-once operation - with pytest.raises( - zigpy.exceptions.DestructiveWriteNetworkSettings, - match=( - "Please upgrade your adapter firmware. The adapter IEEE address needs to be" - " replaced and firmware 'Mock version' does not support writing it multiple" - " times." + with ( + pytest.raises( + zigpy.exceptions.DestructiveWriteNetworkSettings, + match=( + "Please upgrade your adapter firmware. The adapter IEEE address needs to be" + " replaced and firmware 'Mock version' does not support writing it multiple" + " times." + ), ), + patch.object(app, "_reset"), ): - with patch.object(app, "_reset"): - await app.write_network_info( - node_info=zigpy_backup.node_info.replace( - ieee=t.EUI64.convert("aa:aa:aa:aa:aa:aa:aa:aa") - ), - network_info=zigpy_backup.network_info, - ) + await app.write_network_info( + node_info=zigpy_backup.node_info.replace( + ieee=t.EUI64.convert("aa:aa:aa:aa:aa:aa:aa:aa") + ), + network_info=zigpy_backup.network_info, + ) # Even if we opt in, if the adapter doesn't support it, we can't do anything - with patch.object(app, "_reset"), patch.object( - app._ezsp, "write_custom_eui64", wraps=app._ezsp.write_custom_eui64 - ), patch.object(app._ezsp, "can_burn_userdata_custom_eui64", return_value=False): + with ( + patch.object(app, "_reset"), + patch.object( + app._ezsp, "write_custom_eui64", wraps=app._ezsp.write_custom_eui64 + ), + patch.object(app._ezsp, "can_burn_userdata_custom_eui64", return_value=False), + ): with pytest.raises( zigpy.exceptions.CannotWriteNetworkSettings, match=( @@ -2915,9 +2931,11 @@ async def test_migration_failure_eui64_overwrite_confirmation( assert app._ezsp.write_custom_eui64.mock_calls == [] # It works if everything is correct - with patch.object(app, "_reset"), patch.object( - app._ezsp, "write_custom_eui64" - ), patch.object(app._ezsp, "can_burn_userdata_custom_eui64", return_value=True): + with ( + patch.object(app, "_reset"), + patch.object(app._ezsp, "write_custom_eui64"), + patch.object(app._ezsp, "can_burn_userdata_custom_eui64", return_value=True), + ): await app.write_network_info( node_info=zigpy_backup.node_info.replace( ieee=t.EUI64.convert("aa:aa:aa:aa:aa:aa:aa:aa") diff --git a/tests/test_ash.py b/tests/test_ash.py index 8b1169260..405370722 100644 --- a/tests/test_ash.py +++ b/tests/test_ash.py @@ -163,48 +163,48 @@ def test_ash_protocol_event_propagation() -> None: def test_stuffing(): - assert ash.AshProtocol._stuff_bytes(b"\x7E") == b"\x7D\x5E" - assert ash.AshProtocol._stuff_bytes(b"\x11") == b"\x7D\x31" - assert ash.AshProtocol._stuff_bytes(b"\x13") == b"\x7D\x33" - assert ash.AshProtocol._stuff_bytes(b"\x18") == b"\x7D\x38" - assert ash.AshProtocol._stuff_bytes(b"\x1A") == b"\x7D\x3A" - assert ash.AshProtocol._stuff_bytes(b"\x7D") == b"\x7D\x5D" - - assert ash.AshProtocol._unstuff_bytes(b"\x7D\x5E") == b"\x7E" - assert ash.AshProtocol._unstuff_bytes(b"\x7D\x31") == b"\x11" - assert ash.AshProtocol._unstuff_bytes(b"\x7D\x33") == b"\x13" - assert ash.AshProtocol._unstuff_bytes(b"\x7D\x38") == b"\x18" - assert ash.AshProtocol._unstuff_bytes(b"\x7D\x3A") == b"\x1A" - assert ash.AshProtocol._unstuff_bytes(b"\x7D\x5D") == b"\x7D" - - assert ash.AshProtocol._stuff_bytes(b"\x7F") == b"\x7F" - assert ash.AshProtocol._unstuff_bytes(b"\x7F") == b"\x7F" + assert ash.AshProtocol._stuff_bytes(b"\x7e") == b"\x7d\x5e" + assert ash.AshProtocol._stuff_bytes(b"\x11") == b"\x7d\x31" + assert ash.AshProtocol._stuff_bytes(b"\x13") == b"\x7d\x33" + assert ash.AshProtocol._stuff_bytes(b"\x18") == b"\x7d\x38" + assert ash.AshProtocol._stuff_bytes(b"\x1a") == b"\x7d\x3a" + assert ash.AshProtocol._stuff_bytes(b"\x7d") == b"\x7d\x5d" + + assert ash.AshProtocol._unstuff_bytes(b"\x7d\x5e") == b"\x7e" + assert ash.AshProtocol._unstuff_bytes(b"\x7d\x31") == b"\x11" + assert ash.AshProtocol._unstuff_bytes(b"\x7d\x33") == b"\x13" + assert ash.AshProtocol._unstuff_bytes(b"\x7d\x38") == b"\x18" + assert ash.AshProtocol._unstuff_bytes(b"\x7d\x3a") == b"\x1a" + assert ash.AshProtocol._unstuff_bytes(b"\x7d\x5d") == b"\x7d" + + assert ash.AshProtocol._stuff_bytes(b"\x7f") == b"\x7f" + assert ash.AshProtocol._unstuff_bytes(b"\x7f") == b"\x7f" with pytest.raises(ash.ParsingError): # AB is not a sequence of bytes that can be unescaped - assert ash.AshProtocol._unstuff_bytes(b"\x7D\xAB") + assert ash.AshProtocol._unstuff_bytes(b"\x7d\xab") def test_pseudo_random_data_sequence(): - assert ash.PSEUDO_RANDOM_DATA_SEQUENCE.startswith(b"\x42\x21\xA8\x54\x2A") + assert ash.PSEUDO_RANDOM_DATA_SEQUENCE.startswith(b"\x42\x21\xa8\x54\x2a") def test_frame_parsing_errors(): with pytest.raises(ash.ParsingError, match=r"Frame is too short:"): - assert ash.RstFrame.from_bytes(b"\xC0\x38") + assert ash.RstFrame.from_bytes(b"\xc0\x38") with pytest.raises(ash.ParsingError, match=r"Invalid CRC bytes in frame"): - assert ash.RstFrame.from_bytes(b"\xC0\xAB\xCD") + assert ash.RstFrame.from_bytes(b"\xc0\xab\xcd") def test_rst_frame(): assert ash.RstFrame() == ash.RstFrame() - assert ash.RstFrame().to_bytes() == b"\xC0\x38\xBC" - assert ash.RstFrame.from_bytes(b"\xC0\x38\xBC") == ash.RstFrame() + assert ash.RstFrame().to_bytes() == b"\xc0\x38\xbc" + assert ash.RstFrame.from_bytes(b"\xc0\x38\xbc") == ash.RstFrame() assert str(ash.RstFrame()) == "RstFrame()" with pytest.raises(ash.ParsingError, match=r"Invalid data for RST frame:"): - ash.RstFrame.from_bytes(ash.AshFrame.append_crc(b"\xC0\xAB")) + ash.RstFrame.from_bytes(ash.AshFrame.append_crc(b"\xc0\xab")) def test_rstack_frame(): @@ -315,8 +315,8 @@ def test_buffer_growth(): protocol = ash.AshProtocol(ezsp) # Receive a lot of bogus data - for i in range(1000): - protocol.data_received(b"\xEE" * 100) + for _i in range(1000): + protocol.data_received(b"\xee" * 100) # Make sure our internal buffer doesn't blow up assert len(protocol._buffer) == ash.MAX_BUFFER_SIZE @@ -391,7 +391,7 @@ async def test_frame_parsing_failure_recovery(caplog) -> None: with caplog.at_level(logging.DEBUG): protocol.data_received( - ash.AshFrame.append_crc(b"\xFESome unknown frame") + ash.AshFrame.append_crc(b"\xfeSome unknown frame") + bytes([ash.Reserved.FLAG]) ) @@ -546,9 +546,8 @@ async def test_ash_end_to_end(transport_cls: type[FakeTransport]) -> None: # Let's let a request fail due to a connectivity issue. The link stays down until # every retry has timed out, however long that takes on a loaded machine. - with patch.object(ncp_transport, "paused", True): - with pytest.raises(TimeoutError): - await host.send_data(b"host failure") + with patch.object(ncp_transport, "paused", True), pytest.raises(TimeoutError): + await host.send_data(b"host failure") ncp_ezsp.data_received.reset_mock() host_ezsp.data_received.reset_mock() @@ -569,9 +568,8 @@ async def test_ash_end_to_end(transport_cls: type[FakeTransport]) -> None: assert host._ncp_reset_code is None assert ncp._ncp_reset_code is None - with patch.object(host_transport, "paused", True): - with pytest.raises(TimeoutError): - await ncp.send_data(b"ncp failure") + with patch.object(host_transport, "paused", True), pytest.raises(TimeoutError): + await ncp.send_data(b"ncp failure") assert ( host._ncp_reset_code is t.NcpResetCode.ERROR_EXCEEDED_MAXIMUM_ACK_TIMEOUT_COUNT @@ -605,9 +603,9 @@ async def test_ash_end_to_end(transport_cls: type[FakeTransport]) -> None: patch("bellows.ash.T_RX_ACK_MAX", host._t_rx_ack), patch.object(FakeTransportRandomLoss, "loss_rate", 0.0), patch.object(ncp, "nak_state", True), + pytest.raises(ash.NotAcked), ): - with pytest.raises(ash.NotAcked): - await host.send_data(b"ncp NAKing until failure") + await host.send_data(b"ncp NAKing until failure") async def test_rstack_cancels_pending_frames() -> None: @@ -661,7 +659,7 @@ async def test_reject_condition_prevents_nak_amplification(caplog) -> None: protocol._ncp_state = ash.NcpState.CONNECTED # Send first bad DATA frame with invalid CRC (control byte 0x00 = DATA frame) - bad_frame_1 = b"\x00Some bad data\xDE\xAD" # Invalid CRC + bad_frame_1 = b"\x00Some bad data\xde\xad" # Invalid CRC protocol.data_received(bad_frame_1 + bytes([ash.Reserved.FLAG])) # Should enter reject condition and send one NAK @@ -677,7 +675,7 @@ async def test_reject_condition_prevents_nak_amplification(caplog) -> None: transport.write.reset_mock() # Send second bad DATA frame with invalid CRC - bad_frame_2 = b"\x00More bad data\xBE\xEF" # Invalid CRC + bad_frame_2 = b"\x00More bad data\xbe\xef" # Invalid CRC protocol.data_received(bad_frame_2 + bytes([ash.Reserved.FLAG])) # Should suppress NAK due to reject condition @@ -687,7 +685,7 @@ async def test_reject_condition_prevents_nak_amplification(caplog) -> None: caplog.clear() # Send third bad DATA frame with invalid CRC - bad_frame_3 = b"\x00Even more bad data\xCA\xFE" # Invalid CRC + bad_frame_3 = b"\x00Even more bad data\xca\xfe" # Invalid CRC protocol.data_received(bad_frame_3 + bytes([ash.Reserved.FLAG])) # Still suppressing @@ -709,7 +707,7 @@ async def test_reject_condition_prevents_nak_amplification(caplog) -> None: transport.write.reset_mock() # Now another bad frame should trigger reject condition again - bad_frame_4 = b"\x00Bad again\xFA\xDE" # Invalid CRC + bad_frame_4 = b"\x00Bad again\xfa\xde" # Invalid CRC protocol.data_received(bad_frame_4 + bytes([ash.Reserved.FLAG])) # Should enter reject condition again and send NAK diff --git a/tests/test_commands.py b/tests/test_commands.py index 1657fd6ec..e10c89d3d 100644 --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -26,8 +26,8 @@ def commands(request): def test_names(commands): """Test that names of commands seem valid""" anum = string.ascii_letters + string.digits - for command in commands.keys(): - assert all([c in anum for c in command]), command + for command in commands: + assert all(c in anum for c in command), command def test_ids(commands): diff --git a/tests/test_ezsp_protocol.py b/tests/test_ezsp_protocol.py index 3906eb5ea..bf51a2cce 100644 --- a/tests/test_ezsp_protocol.py +++ b/tests/test_ezsp_protocol.py @@ -112,7 +112,7 @@ async def test_logging_frame_parsing_failure(prot_hndl, caplog) -> None: with caplog.at_level(logging.WARNING): with pytest.raises(ValueError): - prot_hndl(b"\xAA\xAA\x71\x22") + prot_hndl(b"\xaa\xaa\x71\x22") assert "Failed to parse frame getKeyTableEntry: b'22'" in caplog.text @@ -202,9 +202,9 @@ async def test_incoming_fragmented_message_incomplete(prot_hndl, caplog): assert len(prot_hndl._fragment_ack_tasks) == 1 ack_task = next(iter(prot_hndl._fragment_ack_tasks)) await asyncio.gather(ack_task) # Ensure task completes and triggers callback - assert ( - len(prot_hndl._fragment_ack_tasks) == 0 - ), "Done callback should have removed task" + assert len(prot_hndl._fragment_ack_tasks) == 0, ( + "Done callback should have removed task" + ) prot_hndl._handle_callback.assert_not_called() assert "Fragment reassembly not complete. waiting for more data." in caplog.text @@ -252,9 +252,9 @@ async def test_incoming_fragmented_message_complete(prot_hndl, caplog): assert len(prot_hndl._fragment_ack_tasks) == 1 ack_task = next(iter(prot_hndl._fragment_ack_tasks)) await asyncio.gather(ack_task) # Ensure task completes and triggers callback - assert ( - len(prot_hndl._fragment_ack_tasks) == 0 - ), "Done callback should have removed task" + assert len(prot_hndl._fragment_ack_tasks) == 0, ( + "Done callback should have removed task" + ) prot_hndl._handle_callback.assert_not_called() assert ( @@ -268,9 +268,9 @@ async def test_incoming_fragmented_message_complete(prot_hndl, caplog): assert len(prot_hndl._fragment_ack_tasks) == 1 ack_task = next(iter(prot_hndl._fragment_ack_tasks)) await asyncio.gather(ack_task) # Ensure task completes and triggers callback - assert ( - len(prot_hndl._fragment_ack_tasks) == 0 - ), "Done callback should have removed task" + assert len(prot_hndl._fragment_ack_tasks) == 0, ( + "Done callback should have removed task" + ) prot_hndl._handle_callback.assert_called_once_with( "incomingMessageHandler", diff --git a/tests/test_ezsp_v12.py b/tests/test_ezsp_v12.py index ebbbaa8b2..09df6d87e 100644 --- a/tests/test_ezsp_v12.py +++ b/tests/test_ezsp_v12.py @@ -45,7 +45,7 @@ def test_check_key_context(ezsp_f) -> None: _, tx_schema, rx_schema = ezsp_f.COMMANDS["checkKeyContext"] assert t.serialize_dict((), {"context": context}, tx_schema) == bytes.fromhex( - "04" "00" "00" "0807060504030201" "00" "02" "00000000" + "0400000807060504030201000200000000" ) assert t.deserialize_dict(b"\x00\x00\x00\x00", rx_schema) == ( {"status": t.sl_Status.OK}, diff --git a/tests/test_ezsp_v13.py b/tests/test_ezsp_v13.py index 59ae03d6c..2b42eedea 100644 --- a/tests/test_ezsp_v13.py +++ b/tests/test_ezsp_v13.py @@ -243,7 +243,7 @@ def test_check_key_context(ezsp_f) -> None: _, tx_schema, rx_schema = ezsp_f.COMMANDS["checkKeyContext"] assert t.serialize_dict((), {"context": context}, tx_schema) == bytes.fromhex( - "04" "00" "0000" "0807060504030201" "00" "02" "00000000" + "040000000807060504030201000200000000" ) assert t.deserialize_dict(b"\x00\x00\x00\x00", rx_schema) == ( {"status": t.sl_Status.OK}, diff --git a/tests/test_ezsp_v14.py b/tests/test_ezsp_v14.py index d5ee91c7b..c2d682dab 100644 --- a/tests/test_ezsp_v14.py +++ b/tests/test_ezsp_v14.py @@ -220,9 +220,7 @@ async def test_get_network_key_without_network(ezsp_f): EUI64_BYTES = bytes.fromhex("0807060504030201") # `sl_zigbee_rx_packet_info_t` -PACKET_INFO_BYTES = bytes.fromhex( - "3412" "0807060504030201" "ff" "03" "aa" "c4" "04030201" -) +PACKET_INFO_BYTES = bytes.fromhex("34120807060504030201ff03aac404030201") PACKET_INFO = t.SlRxPacketInfo( sender_short_id=0x1234, sender_long_id=EUI64, @@ -234,7 +232,7 @@ async def test_get_network_key_without_network(ezsp_f): ) # `sl_zigbee_sec_man_context_t` -CONTEXT_BYTES = bytes.fromhex("04" "00" "0000" "0807060504030201" "00" "02" "00000000") +CONTEXT_BYTES = bytes.fromhex("040000000807060504030201000200000000") CONTEXT = t.SecurityManagerContextV13( core_key_type=t.SecurityManagerKeyType.APP_LINK, key_index=0, @@ -249,7 +247,7 @@ async def test_get_network_key_without_network(ezsp_f): KEY = t.KeyData.convert("000102030405060708090a0b0c0d0e0f") # `sl_zigbee_sec_man_aps_key_metadata_t` -KEY_METADATA_BYTES = bytes.fromhex("1200" "01000000" "02000000" "b400") +KEY_METADATA_BYTES = bytes.fromhex("12000100000002000000b400") KEY_METADATA = t.SecurityManagerAPSKeyMetadata( bitmask=( t.EmberKeyStructBitmask.KEY_HAS_OUTGOING_FRAME_COUNTER @@ -266,13 +264,13 @@ async def test_get_network_key_without_network(ezsp_f): def zll_network_found_handler_data() -> tuple[bytes, dict]: data = ( # `sl_zigbee_zll_network_t` - bytes.fromhex("0b" "3412" "0807060504030201" "01" "02" "00") - + bytes.fromhex("78563412" "21436587" "0100") - + bytes.fromhex("0807060504030201" "cdab" "0000" "02" "01" "00" "00") + bytes.fromhex("0b34120807060504030201010200") + + bytes.fromhex("78563412214365870100") + + bytes.fromhex("0807060504030201cdab000002010000") # `isDeviceInfoNull` + bytes.fromhex("00") # `sl_zigbee_zll_device_info_record_t` - + bytes.fromhex("0807060504030201" "01" "5ec0" "0001" "02" "00") + + bytes.fromhex("0807060504030201015ec000010200") + PACKET_INFO_BYTES ) @@ -391,8 +389,7 @@ def zll_network_found_handler_data() -> tuple[bytes, dict]: ), ( "zllAddressAssignmentHandler", - bytes.fromhex("0100" "0200" "fff7" "0100" "ff00" "0001" "fffe") - + PACKET_INFO_BYTES, + bytes.fromhex("01000200fff70100ff000001fffe") + PACKET_INFO_BYTES, { "addressInfo": t.EmberZllAddressAssignment( nodeId=0x0001, @@ -458,7 +455,7 @@ def test_v14_mac_filter_match_message_handler(version: int) -> None: "reason": 0x03, "nodeType": t.EmberNodeType.ROUTER, }, - bytes.fromhex("01" "00f8ff07" "03" "02"), + bytes.fromhex("0100f8ff070302"), ), ( "setAddressTableInfo", diff --git a/tests/test_ezsp_v19.py b/tests/test_ezsp_v19.py index 5c716750b..454dbf3f5 100644 --- a/tests/test_ezsp_v19.py +++ b/tests/test_ezsp_v19.py @@ -38,7 +38,7 @@ def test_ezsp_frame_rx(ezsp_f): def test_get_token_info(version: int) -> None: _, _, rx_schema = bellows.ezsp.EZSP._BY_VERSION[version].COMMANDS["getTokenInfo"] result, rest = t.deserialize_dict( - bytes.fromhex("00000000" "01000000" "00" "01" "2c010000" "05"), rx_schema + bytes.fromhex("000000000100000000012c01000005"), rx_schema ) assert rest == b"" diff --git a/tests/test_ezsp_v4.py b/tests/test_ezsp_v4.py index 7a8826f8c..f568a75cf 100644 --- a/tests/test_ezsp_v4.py +++ b/tests/test_ezsp_v4.py @@ -41,10 +41,7 @@ async def test_pre_permit(ezsp_f): async def test_read_child_data(ezsp_f): def get_child_data(index): - if index == 0: - status = t.EmberStatus.SUCCESS - else: - status = t.EmberStatus.NOT_JOINED + status = t.EmberStatus.SUCCESS if index == 0 else t.EmberStatus.NOT_JOINED return ( status, @@ -203,7 +200,7 @@ async def test_write_child_data(ezsp_f) -> None: async def test_read_address_table(ezsp_f) -> None: # It's a no-op but still an async generator - async for nwk, eui64 in ezsp_f.read_address_table(): + async for _nwk, _eui64 in ezsp_f.read_address_table(): pass diff --git a/tests/test_ezsp_v7.py b/tests/test_ezsp_v7.py index d8819c53e..217971a27 100644 --- a/tests/test_ezsp_v7.py +++ b/tests/test_ezsp_v7.py @@ -34,10 +34,7 @@ def test_ezsp_frame_rx(ezsp_f): async def test_read_child_data(ezsp_f): def get_child_data(index): - if index == 0: - status = t.EmberStatus.SUCCESS - else: - status = t.EmberStatus.NOT_JOINED + status = t.EmberStatus.SUCCESS if index == 0 else t.EmberStatus.NOT_JOINED return ( status, diff --git a/tests/test_fragmentation.py b/tests/test_fragmentation.py index f73bf016b..d8c38efb2 100644 --- a/tests/test_fragmentation.py +++ b/tests/test_fragmentation.py @@ -6,8 +6,7 @@ async def test_single_fragment_complete(): - """ - If we receive a single-fragment message (fragment_count=1, fragment_index=0), + """If we receive a single-fragment message (fragment_count=1, fragment_index=0), the manager should immediately report completion. """ frag_manager = FragmentManager() @@ -42,9 +41,7 @@ async def test_single_fragment_complete(): async def test_two_fragments_in_order(): - """ - A two-fragment message should remain partial until we've received both pieces. - """ + """A two-fragment message should remain partial until we've received both pieces.""" frag_manager = FragmentManager() key = (0x1111, 0x01, 0x9999, 0x2222) @@ -93,9 +90,7 @@ async def test_two_fragments_in_order(): async def test_out_of_order_fragments(): - """ - Receiving fragments in reverse order should still produce the correct reassembly once all arrive. - """ + """Receiving fragments in reverse order should still produce the correct reassembly once all arrive.""" frag_manager = FragmentManager() key = (0x9999, 0xCD, 0x1234, 0xABCD) @@ -139,9 +134,7 @@ async def test_out_of_order_fragments(): async def test_repeated_fragments_ignored(): - """ - Ensure repeated arrivals of the same fragment index do not double-count or break the logic. - """ + """Ensure repeated arrivals of the same fragment index do not double-count or break the logic.""" frag_manager = FragmentManager() key = (0xAAA, 0xBB, 0xCCC, 0xDDD) diff --git a/tests/test_thread.py b/tests/test_thread.py index 235507f7e..3701b6f88 100644 --- a/tests/test_thread.py +++ b/tests/test_thread.py @@ -172,7 +172,7 @@ async def test_proxy_not_function(): proxy = ThreadsafeProxy(obj, loop) obj.test = mock.sentinel.value with pytest.raises(TypeError): - proxy.test + proxy.test # noqa: B018 async def test_proxy_no_thread(): diff --git a/tests/test_xncp.py b/tests/test_xncp.py index 451f5e8eb..2703d673b 100644 --- a/tests/test_xncp.py +++ b/tests/test_xncp.py @@ -42,7 +42,7 @@ async def test_xncp_failure(ezsp_f: EZSP) -> None: b"\x02\x80\x03", # Simplicity SDK firmware replies with the low octet of an # `sl_status_t`: `SL_STATUS_NOT_FOUND` - b"\x02\x80\x2D", + b"\x02\x80\x2d", ], ) async def test_xncp_missing_mfg_token_override( @@ -52,13 +52,13 @@ async def test_xncp_missing_mfg_token_override( ezsp_f._mock_commands["customFrame"] = AsyncMock( return_value=[t.EmberStatus.SUCCESS, rsp] ) - ezsp_f._mock_commands["getMfgToken"] = AsyncMock(return_value=[b"\xFF" * 8]) + ezsp_f._mock_commands["getMfgToken"] = AsyncMock(return_value=[b"\xff" * 8]) ezsp_f._xncp_features |= xncp.FirmwareFeatures.MFG_TOKEN_OVERRIDES with caplog.at_level(logging.WARNING, logger="bellows"): assert ( await ezsp_f.get_mfg_token(t.EzspMfgTokenId.MFG_CUSTOM_EUI_64) - ) == b"\xFF" * 8 + ) == b"\xff" * 8 # An unsupported override is an expected condition, not a warning assert [ From 0420f1980add8cb5cd037948b392914b8d8ad339 Mon Sep 17 00:00:00 2001 From: zigpy-review-bot <286747149+zigpy-review-bot@users.noreply.github.com> Date: Mon, 28 Sep 2026 03:05:45 +0200 Subject: [PATCH 3/4] Fix test_ezsp tests that could not fail Surfaced by the new ruff rules: - test_write_custom_eui64 and test_write_custom_eui64_rcp compared setTokenData.mock_calls without asserting (B015). Asserting them showed the expected calls used positional arguments while the code passes keywords, and the RCP test's getTokenData mock reported success for every key, so the NCP key was picked. The mock now only knows the RCP key. - test_list_command_initial_failure and test_form_network_fail used t.EmberStatus.FAILURE, which no longer exists, so they passed on an AttributeError raised before the code under test ran (B017). They now use ERR_FATAL and check for the specific error. --- tests/test_ezsp.py | 94 ++++++++++++++++++++++++++-------------------- 1 file changed, 53 insertions(+), 41 deletions(-) diff --git a/tests/test_ezsp.py b/tests/test_ezsp.py index bccf17b39..8764f8486 100644 --- a/tests/test_ezsp.py +++ b/tests/test_ezsp.py @@ -8,6 +8,7 @@ import pytest import zigpy.config +import zigpy.exceptions from bellows import config, uart from bellows.ash import NcpFailure @@ -142,11 +143,11 @@ async def test_list_command_initial_failure(): async def mockcommand(name, *args, **kwargs): assert name == "startScan" - return [t.EmberStatus.FAILURE] + return [t.EmberStatus.ERR_FATAL] ezsp._command = mockcommand - with pytest.raises(Exception): + with pytest.raises(Exception, match="ERR_FATAL"): await ezsp._list_command( "startScan", ["networkFoundHandler"], @@ -168,7 +169,7 @@ async def mockcommand(name, *args, **kwargs): ezsp._command = mockcommand - with pytest.raises(Exception): + with pytest.raises(Exception, match="ERR_FATAL"): await ezsp._list_command( "startScan", ["networkFoundHandler"], @@ -197,8 +198,8 @@ async def test_form_network(): async def test_form_network_fail(): ezsp = await make_connected_ezsp(version=4) - with pytest.raises(Exception): - await _test_form_network(ezsp, [t.EmberStatus.FAILURE], b"\x90") + with pytest.raises(zigpy.exceptions.FormationFailure): + await _test_form_network(ezsp, [t.EmberStatus.ERR_FATAL], b"\x90") @pytest.mark.parametrize( @@ -215,7 +216,7 @@ async def test_form_network_fail_invalid_tx_power(status): async def test_form_network_fail_stack_status(): ezsp = await make_connected_ezsp(version=4) - with pytest.raises(Exception): + with pytest.raises(TimeoutError): await _test_form_network(ezsp, [t.EmberStatus.SUCCESS], b"\x00") @@ -421,17 +422,20 @@ async def replacement(command_name, tokenId=None, valueId=None): if not isinstance(xncp_build_string, InvalidCommandError): ezsp_f._xncp_features |= xncp.FirmwareFeatures.BUILD_STRING - with patch.object( - ezsp_f, - "_command", - new=cmd_mock( - { - ("getMfgToken", t.EzspMfgTokenId.MFG_BOARD_NAME): mfg_board_name, - ("getMfgToken", t.EzspMfgTokenId.MFG_STRING): mfg_string, - ("getValue", t.EzspValueId.VALUE_VERSION_INFO): value_version_info, - } + with ( + patch.object( + ezsp_f, + "_command", + new=cmd_mock( + { + ("getMfgToken", t.EzspMfgTokenId.MFG_BOARD_NAME): mfg_board_name, + ("getMfgToken", t.EzspMfgTokenId.MFG_STRING): mfg_string, + ("getValue", t.EzspValueId.VALUE_VERSION_INFO): value_version_info, + } + ), ), - ), patch.object(ezsp_f, "xncp_get_build_string", side_effect=xncp_build_string): + patch.object(ezsp_f, "xncp_get_build_string", side_effect=xncp_build_string), + ): mfg, brd, ver = await ezsp_f.get_board_info() assert (mfg, brd, ver) == expected @@ -534,7 +538,7 @@ async def test_xncp_token_override(ezsp_f): @pytest.mark.parametrize( "value, expected_result", [ - (b"\xFF" * 8, True), + (b"\xff" * 8, True), (bytes.fromhex("0846b8a11c004b1200"), False), (b"", False), ], @@ -555,12 +559,12 @@ async def test_can_burn_userdata_custom_eui64(ezsp_f, value, expected_result): [ ({}, None, False), ( - {t.NV3KeyId.CREATOR_STACK_RESTORED_EUI64: b"\xAA" * 8}, + {t.NV3KeyId.CREATOR_STACK_RESTORED_EUI64: b"\xaa" * 8}, t.NV3KeyId.CREATOR_STACK_RESTORED_EUI64, True, ), ( - {t.NV3KeyId.NVM3KEY_STACK_RESTORED_EUI64: b"\xAA" * 8}, + {t.NV3KeyId.NVM3KEY_STACK_RESTORED_EUI64: b"\xaa" * 8}, t.NV3KeyId.NVM3KEY_STACK_RESTORED_EUI64, True, ), @@ -617,11 +621,11 @@ async def test_write_custom_eui64(ezsp_f): await ezsp_f.write_custom_eui64(new_eui64, burn_into_userdata=True) ezsp_f.setMfgToken.assert_not_called() - ezsp_f.setTokenData.mock_calls == 2 * [ + assert ezsp_f.setTokenData.mock_calls == 2 * [ call( - t.NV3KeyId.NVM3KEY_STACK_RESTORED_EUI64, - 0, - new_eui64.serialize(), + token=t.NV3KeyId.NVM3KEY_STACK_RESTORED_EUI64, + index=0, + token_data=new_eui64.serialize(), ) ] @@ -672,18 +676,24 @@ async def test_write_custom_eui64_rcp(ezsp_f): # RCP firmware does not support manufacturing tokens ezsp_f.getMfgToken = AsyncMock(return_value=[b""]) - ezsp_f.getTokenData = AsyncMock( - return_value=GetTokenDataRsp(status=t.EmberStatus.SUCCESS, value=b"\xFF" * 8) - ) + + async def get_token_data(token, index): + # Only the RCP NV3 key exists, the NCP one does not + if token == t.NV3KeyId.NVM3KEY_STACK_RESTORED_EUI64: + return GetTokenDataRsp(status=t.EmberStatus.SUCCESS, value=b"\xff" * 8) + + return GetTokenDataRsp(status=t.EmberStatus.NOT_FOUND, value=b"") + + ezsp_f.getTokenData = AsyncMock(side_effect=get_token_data) await ezsp_f.write_custom_eui64(new_eui64) ezsp_f.setMfgToken.assert_not_called() - ezsp_f.setTokenData.mock_calls == [ + assert ezsp_f.setTokenData.mock_calls == [ call( - t.NV3KeyId.NVM3KEY_STACK_RESTORED_EUI64, - 0, - new_eui64.serialize(), + token=t.NV3KeyId.NVM3KEY_STACK_RESTORED_EUI64, + index=0, + token_data=new_eui64.serialize(), ) ] @@ -822,11 +832,13 @@ async def test_wait_for_stack_status(ezsp_f): assert not ezsp_f._stack_status_listeners[t.sl_Status.NETWORK_DOWN] # Cancellation clears handlers - with ezsp_f.wait_for_stack_status(t.sl_Status.NETWORK_DOWN) as stack_status: - with pytest.raises(TimeoutError): - async with asyncio_timeout(0.1): - assert ezsp_f._stack_status_listeners[t.sl_Status.NETWORK_DOWN] - await stack_status + with ( + ezsp_f.wait_for_stack_status(t.sl_Status.NETWORK_DOWN) as stack_status, + pytest.raises(TimeoutError), + ): + async with asyncio_timeout(0.1): + assert ezsp_f._stack_status_listeners[t.sl_Status.NETWORK_DOWN] + await stack_status assert not ezsp_f._stack_status_listeners[t.sl_Status.NETWORK_DOWN] @@ -848,7 +860,7 @@ def test_ezsp_versions(ezsp_f): continue assert version in ezsp_f._BY_VERSION assert ezsp_f._BY_VERSION[version].__name__ == f"EZSPv{version}" - assert ezsp_f._BY_VERSION[version].VERSION == version + assert version == ezsp_f._BY_VERSION[version].VERSION async def test_config_initialize_husbzb1(): @@ -904,7 +916,7 @@ async def test_config_initialize(version: int, caplog): ezsp.networkState = AsyncMock(return_value=(t.EmberNetworkStatus.JOINED_NETWORK,)) ezsp.setValue = AsyncMock(return_value=(t.EzspStatus.SUCCESS,)) - ezsp.getValue = AsyncMock(return_value=(t.EzspStatus.SUCCESS, b"\xFF")) + ezsp.getValue = AsyncMock(return_value=(t.EzspStatus.SUCCESS, b"\xff")) await ezsp.write_config({}) @@ -925,7 +937,7 @@ async def test_config_initialize(version: int, caplog): await ezsp.write_config({}) assert len(ezsp.setValue.mock_calls) == 1 - ezsp.getValue = AsyncMock(return_value=(t.EzspStatus.SUCCESS, b"\xFF")) + ezsp.getValue = AsyncMock(return_value=(t.EzspStatus.SUCCESS, b"\xff")) caplog.clear() with caplog.at_level(logging.DEBUG): @@ -998,7 +1010,7 @@ async def test_unsupported_ezsp_version_startup(caplog): ezsp.getConfigurationValue = AsyncMock(return_value=(t.EzspStatus.SUCCESS, 0)) ezsp.setConfigurationValue = AsyncMock(return_value=(t.EzspStatus.SUCCESS,)) ezsp.setValue = AsyncMock(return_value=(t.EzspStatus.SUCCESS,)) - ezsp.getValue = AsyncMock(return_value=(t.EzspStatus.SUCCESS, b"\xFF")) + ezsp.getValue = AsyncMock(return_value=(t.EzspStatus.SUCCESS, b"\xff")) # Startup should not fail await ezsp.write_config({}) @@ -1016,11 +1028,11 @@ async def test_reset_custom_eui64(ezsp_f): # With NV3 interface ezsp_f.getTokenData = AsyncMock( - return_value=GetTokenDataRsp(status=t.EmberStatus.SUCCESS, value=b"\xAB" * 8) + return_value=GetTokenDataRsp(status=t.EmberStatus.SUCCESS, value=b"\xab" * 8) ) await ezsp_f.reset_custom_eui64() assert ezsp_f.setTokenData.mock_calls == [ - call(t.NV3KeyId.CREATOR_STACK_RESTORED_EUI64, 0, t.LVBytes32(b"\xFF" * 8)) + call(t.NV3KeyId.CREATOR_STACK_RESTORED_EUI64, 0, t.LVBytes32(b"\xff" * 8)) ] From a07bc69414bcb2e4a0970e450766c3d4c97103f9 Mon Sep 17 00:00:00 2001 From: zigpy-review-bot <286747149+zigpy-review-bot@users.noreply.github.com> Date: Mon, 28 Sep 2026 03:48:56 +0200 Subject: [PATCH 4/4] Remove unused tox.ini Nothing references it (CI runs the shared zigpy/workflows pipeline, not tox), it was last changed in 2020, and its py37/py38 environments cannot run against requires-python >= 3.11. --- tox.ini | 27 --------------------------- 1 file changed, 27 deletions(-) delete mode 100644 tox.ini diff --git a/tox.ini b/tox.ini deleted file mode 100644 index 9fc2e1ab7..000000000 --- a/tox.ini +++ /dev/null @@ -1,27 +0,0 @@ -# Tox (http://tox.testrun.org/) is a tool for running tests -# in multiple virtualenvs. This configuration file will run the -# test suite on all supported python versions. To use it, "pip install tox" -# and then run "tox" from this directory. - -[tox] -envlist = py37, py38, lint, format -skip_missing_interpreters = True - -[testenv] -setenv = PYTHONPATH = {toxinidir} -install_command = pip install {opts} {packages} -commands = py.test --cov --cov-report= -deps = -rrequirements_test.txt - -[testenv:lint] -basepython = python3 -commands = - pre-commit run --hook-stage manual ruff-check --all-files --show-diff-on-failure - pre-commit run --hook-stage manual codespell --all-files - -[testenv:format] -setenv = - LC_ALL=C.UTF-8 - LANG=C.UTF-8 -commands= - pre-commit run --hook-stage manual ruff-format --all-files --show-diff-on-failure