Detect offline hub children and fail fast on writes to them (#1830)
Some checks failed
CI / Perform Lint Checks (3.15) (push) Has been cancelled
CodeQL Checks / Analyze (python) (push) Has been cancelled
CI / Python 3.11 on macos-latest (push) Has been cancelled
CI / Python 3.12 on macos-latest (push) Has been cancelled
CI / Python 3.13 on macos-latest (push) Has been cancelled
CI / Python 3.14 on macos-latest (push) Has been cancelled
CI / Python 3.15 on macos-latest (push) Has been cancelled
CI / Python 3.11 on ubuntu-latest (push) Has been cancelled
CI / Python 3.12 on ubuntu-latest (push) Has been cancelled
CI / Python 3.13 on ubuntu-latest (push) Has been cancelled
CI / Python 3.14 on ubuntu-latest (push) Has been cancelled
CI / Python 3.15 on ubuntu-latest (push) Has been cancelled
CI / Python 3.11 on windows-latest (push) Has been cancelled
CI / Python 3.12 on windows-latest (push) Has been cancelled
CI / Python 3.13 on windows-latest (push) Has been cancelled
CI / Python 3.14 on windows-latest (push) Has been cancelled
CI / Python 3.15 on windows-latest (push) Has been cancelled
Stale / stale (push) Has been cancelled

Hubs keep reporting for children they have lost contact with, so callers
see stale values as if they were live. Trying to write to such devices
fail after timeouts with a generic error.
This PR exposes the offline/online information as reported by the hub,
and refuses writes to unreachable child devices without waiting for
device errors.

In details:
- Add new API: `Device.is_available`; hub children report unavailable
when the hub marks them offline or no longer lists them.
- New feature `available` for child devices to make it visible to the
CLI.
- Refuse writes to unavailable children with the new
`DeviceUnavailableError` instead of waiting for the hub to time out.
This commit is contained in:
Teemu R.
2026-11-01 18:18:03 +01:00
committed by GitHub
parent 81243ed87f
commit a68f2b3304
13 changed files with 229 additions and 16 deletions

View File

@@ -5,7 +5,8 @@ from pytest_mock import MockerFixture
from kasa import Device, DeviceType, Module
from kasa.cli.hub import hub
from ..device_fixtures import hubs, plug_iot
from ..device_fixtures import hubs, hubs_smart, plug_iot
from ..fakeprotocol_smart import FakeSmartTransport
@hubs
@@ -51,6 +52,28 @@ async def test_hub_unpair(
assert res.exit_code == 0
@hubs_smart
@pytest.mark.requires_dummy
async def test_hub_list(dev: Device, runner: CliRunner) -> None:
"""Test that list shows each child with its index and availability."""
if not dev.children:
pytest.skip("Cannot test without child devices")
assert isinstance(dev.protocol._transport, FakeSmartTransport)
child_list = dev.protocol._transport.info["get_child_device_list"]
child_list["child_device_list"][0]["status"] = "offline"
await dev.update()
res = await runner.invoke(hub, ["list"], obj=dev, catch_exceptions=False)
rows = {line.split()[1]: line.split() for line in res.output.splitlines()[1:]}
for index, child in enumerate(dev.children):
row = rows[child.device_id]
assert row[0] == str(index)
assert row[3] == str(index != 0)
assert res.exit_code == 0
@plug_iot
async def test_non_hub(dev: Device, mocker: MockerFixture, runner: CliRunner) -> None:
"""Test that hub commands return an error if executed on a non-hub."""

View File

@@ -14,11 +14,17 @@ from freezegun.api import FrozenDateTimeFactory
from kasa import Credentials, Device, DeviceType, Module
from kasa.credentials import DEFAULT_CREDENTIALS, get_default_credentials
from kasa.exceptions import AuthenticationError, DeviceError, KasaException
from kasa.smartcam import SmartCamDevice
from kasa.exceptions import (
AuthenticationError,
DeviceError,
DeviceUnavailableError,
KasaException,
)
from kasa.smartcam import SmartCamChild, SmartCamDevice
from kasa.smartcam.modules.time import Time
from ..conftest import device_smartcam, hub_smartcam
from ..fakeprotocol_smartcam import FakeSmartCamTransport
class _ChangeAdminPasswordPayload(TypedDict):
@@ -96,6 +102,28 @@ async def test_hub(dev: Device) -> None:
assert child.device_id
@hub_smartcam
@pytest.mark.requires_dummy
@pytest.mark.parametrize("online", [True, False])
async def test_camera_child_is_available(dev: Device, online: bool) -> None:
"""Test a camera child reports the reachability the hub reports for it."""
child = next((c for c in dev.children if isinstance(c, SmartCamChild)), None)
if child is None:
pytest.skip(f"Device {dev} fixture does not have camera children")
assert isinstance(dev.protocol._transport, FakeSmartCamTransport)
for info in dev.protocol._transport.info["getChildDeviceList"]["child_device_list"]:
if info["device_id"] == child.device_id:
info["online"] = online
await dev.update()
assert child.is_available is online
assert child.features["available"].value is online
if not online:
with pytest.raises(DeviceUnavailableError):
await child.set_alias("new")
@device_smartcam
async def test_wifi_scan(dev: SmartCamDevice) -> None:
fake_scan_data = {

View File

@@ -1,11 +1,12 @@
import inspect
import logging
from datetime import UTC, datetime
import pytest
from freezegun.api import FrozenDateTimeFactory
from pytest_mock import MockerFixture
from kasa import Device
from kasa import Device, DeviceUnavailableError
from kasa.device_type import DeviceType
from kasa.protocols.smartprotocol import SmartProtocol, _ChildProtocolWrapper
from kasa.smart.smartchilddevice import SmartChildDevice
@@ -18,6 +19,7 @@ from .conftest import (
strip_iot,
strip_smart,
)
from .fakeprotocol_smart import FakeSmartTransport
has_children_smart = parametrize(
"has children", component_filter="control_child", protocol_filter={"SMART"}
@@ -126,6 +128,104 @@ async def test_parent_property(dev: Device) -> None:
assert child.parent == dev
@hub_smart
@pytest.mark.requires_dummy
@pytest.mark.parametrize(
("status", "is_available"), [("online", True), ("offline", False)]
)
async def test_child_is_available(dev: Device, status: str, is_available: bool) -> None:
"""Test a hub child reports the reachability status from the hub."""
if not dev.children:
pytest.skip(f"Device {dev} fixture does not have any children")
assert isinstance(dev.protocol._transport, FakeSmartTransport)
child_list = dev.protocol._transport.info["get_child_device_list"]
child_list["child_device_list"][0]["status"] = status
await dev.update()
child = dev.children[0]
assert child.is_available is is_available
assert child.features["available"].value is is_available
assert dev.is_available is True
@hub_smart
@pytest.mark.requires_dummy
@pytest.mark.parametrize(
"write",
[
pytest.param(lambda child: child.set_alias("new"), id="set_alias"),
pytest.param(lambda child: child.reboot(), id="reboot"),
pytest.param(
lambda child: next(iter(child.modules.values())).call(
"set_device_info", {"a": 1}
),
id="module_call",
),
],
)
@pytest.mark.parametrize("removed", [False, True], ids=["offline", "removed"])
async def test_unavailable_child_refuses_writes(
dev: Device, write, removed: bool, mocker: MockerFixture
) -> None:
"""Test writes to an unreachable hub child fail without contacting the hub."""
if not dev.children:
pytest.skip(f"Device {dev} fixture does not have any children")
child = dev.children[0]
assert isinstance(child, SmartChildDevice)
assert isinstance(dev.protocol._transport, FakeSmartTransport)
info = dev.protocol._transport.info
child_list = info["get_child_device_list"]
if removed:
child_list["child_device_list"].pop(0)
child_list["sum"] -= 1
info["get_child_device_component_list"]["child_component_list"] = [
c
for c in info["get_child_device_component_list"]["child_component_list"]
if c["device_id"] != child.device_id
]
else:
child_list["child_device_list"][0]["status"] = "offline"
await dev.update()
query = mocker.spy(dev.protocol, "query")
assert child.is_available is False
with pytest.raises(DeviceUnavailableError):
await write(child)
query.assert_not_called()
await child._query_helper("get_device_info")
query.assert_called_once()
@hub_smart
@pytest.mark.requires_dummy
@pytest.mark.xdist_group(name="caplog")
async def test_child_availability_change_logged_once(
dev: Device, caplog: pytest.LogCaptureFixture
) -> None:
"""Test going offline and coming back are each logged once."""
if not dev.children:
pytest.skip(f"Device {dev} fixture does not have any children")
assert isinstance(dev.protocol._transport, FakeSmartTransport)
child_info = dev.protocol._transport.info["get_child_device_list"]
child_id = child_info["child_device_list"][0]["device_id"]
caplog.set_level(logging.DEBUG)
child_info["child_device_list"][0]["status"] = "offline"
await dev.update()
await dev.update()
assert caplog.text.count(f"({child_id}) available: False") == 1
child_info["child_device_list"][0]["status"] = "online"
await dev.update()
await dev.update()
assert caplog.text.count(f"({child_id}) available: True") == 1
@has_children_smart
@pytest.mark.requires_dummy
async def test_child_time(dev: Device, freezer: FrozenDateTimeFactory) -> None: