From 340034a9a8a81e7d0a7643c784f4e676c938fa71 Mon Sep 17 00:00:00 2001 From: Harry Coureau Date: Sun, 15 Nov 2026 01:36:56 +0000 Subject: [PATCH] fix(v1): report empty trait list replies as parsing errors DefaultConverter, SingleValueConverter, MultiMapsListConverter, LedStatusConverter and DeviceTraitsConverter indexed the first element of a list reply without checking for an empty list, and DeviceTraitsConverter passed a non-dict element to from_dict. These raised IndexError or AttributeError instead of RoborockParsingException. They now raise ValueError, which refresh() wraps as a parsing error, leaving the previous values in place. --- roborock/devices/traits/v1/common.py | 4 ++ roborock/devices/traits/v1/device_features.py | 2 + roborock/devices/traits/v1/led_status.py | 2 + roborock/devices/traits/v1/maps.py | 2 + tests/devices/traits/v1/test_common.py | 27 ++++++++++++- .../devices/traits/v1/test_device_features.py | 30 +++++++++++++++ tests/devices/traits/v1/test_led_status.py | 38 +++++++++++++++++++ tests/devices/traits/v1/test_maps.py | 23 +++++++++++ 8 files changed, 127 insertions(+), 1 deletion(-) create mode 100644 tests/devices/traits/v1/test_led_status.py diff --git a/roborock/devices/traits/v1/common.py b/roborock/devices/traits/v1/common.py index 6e7a5e3bb..b0a046308 100644 --- a/roborock/devices/traits/v1/common.py +++ b/roborock/devices/traits/v1/common.py @@ -113,6 +113,8 @@ def convert(self, response: V1ResponseData) -> RoborockBase: Subclasses can override to implement custom parsing logic """ if isinstance(response, list): + if not response: + raise ValueError(f"Empty {self._dataclass_type.__name__} response") response = response[0] if not isinstance(response, dict): raise ValueError(f"Unexpected {self._dataclass_type.__name__} response format: {response!r}") @@ -136,6 +138,8 @@ def __init__(self, dataclass_type: type[RoborockBase], value_field: str) -> None def convert(self, response: V1ResponseData) -> RoborockBase: """Parse the response from the device into a RoborockValueBase.""" if isinstance(response, list): + if not response: + raise ValueError(f"Empty {self._dataclass_type.__name__} response") response = response[0] if not isinstance(response, int): raise ValueError(f"Unexpected response format: {response!r}") diff --git a/roborock/devices/traits/v1/device_features.py b/roborock/devices/traits/v1/device_features.py index 1f785e65a..4a862a545 100644 --- a/roborock/devices/traits/v1/device_features.py +++ b/roborock/devices/traits/v1/device_features.py @@ -40,6 +40,8 @@ def convert(self, response: common.V1ResponseData) -> DeviceFeatures: """Parse an APP_GET_INIT_STATUS response into a DeviceFeatures instance.""" if not isinstance(response, list): raise ValueError(f"Unexpected AppInitStatus response format: {type(response)}: {response!r}") + if not response or not isinstance(response[0], dict): + raise ValueError(f"Unexpected AppInitStatus response format: {response!r}") app_status = AppInitStatus.from_dict(response[0]) return DeviceFeatures.from_feature_flags( new_feature_info=app_status.new_feature_info, diff --git a/roborock/devices/traits/v1/led_status.py b/roborock/devices/traits/v1/led_status.py index 98cd1cbf2..0e11b4fd9 100644 --- a/roborock/devices/traits/v1/led_status.py +++ b/roborock/devices/traits/v1/led_status.py @@ -16,6 +16,8 @@ def convert(self, response: V1ResponseData) -> LedStatus: """ if not isinstance(response, list): raise ValueError(f"Unexpected LedStatus response format: {response!r}") + if not response: + raise ValueError("Empty LedStatus response") response = response[0] if not isinstance(response, int): raise ValueError(f"Unexpected LedStatus response format: {response!r}") diff --git a/roborock/devices/traits/v1/maps.py b/roborock/devices/traits/v1/maps.py index 4349bd8d8..51af44d4c 100644 --- a/roborock/devices/traits/v1/maps.py +++ b/roborock/devices/traits/v1/maps.py @@ -28,6 +28,8 @@ def convert(self, response: common.V1ResponseData) -> MultiMapsList: """ if not isinstance(response, list): raise ValueError(f"Unexpected MapsTrait response format: {response!r}") + if not response: + raise ValueError("Empty MapsTrait response") response = response[0] if not isinstance(response, dict): raise ValueError(f"Unexpected MapsTrait response format: {response!r}") diff --git a/tests/devices/traits/v1/test_common.py b/tests/devices/traits/v1/test_common.py index aafda2e1d..3c9a73ccb 100644 --- a/tests/devices/traits/v1/test_common.py +++ b/tests/devices/traits/v1/test_common.py @@ -4,7 +4,7 @@ import pytest from roborock.data.containers import RoborockBase -from roborock.devices.traits.v1.common import DefaultConverter, V1TraitMixin +from roborock.devices.traits.v1.common import DefaultConverter, SingleValueConverter, V1TraitMixin from roborock.exceptions import RoborockParsingException from roborock.roborock_typing import RoborockCommand @@ -50,3 +50,28 @@ async def test_valid_payload() -> None: await trait.refresh() assert trait.fake_field == 123 assert trait.other_field == "abc" + + +async def test_empty_list_payload_keeps_state() -> None: + """An empty list raises a parsing error and keeps the previous values.""" + trait = FakeTrait() + trait._rpc_channel.send_command.return_value = [{"fake_field": 123, "other_field": "abc"}] + await trait.refresh() + trait._rpc_channel.send_command.return_value = [] + + with pytest.raises( + RoborockParsingException, + match=r"Failed to parse APP_GET_INIT_STATUS response for FakeTrait. Payload: \[\].*ValueError.*", + ): + await trait.refresh() + + assert trait.fake_field == 123 + assert trait.other_field == "abc" + + +def test_single_value_converter_empty_list() -> None: + """The single-value converter rejects an empty list with ValueError.""" + converter = SingleValueConverter(FakeTraitData, "fake_field") + + with pytest.raises(ValueError, match="Empty FakeTraitData response"): + converter.convert([]) diff --git a/tests/devices/traits/v1/test_device_features.py b/tests/devices/traits/v1/test_device_features.py index f44479ee2..18bfc0f2a 100644 --- a/tests/devices/traits/v1/test_device_features.py +++ b/tests/devices/traits/v1/test_device_features.py @@ -1,13 +1,17 @@ """Tests for the DeviceFeaturesTrait related functionality.""" +from unittest.mock import AsyncMock + import pytest from syrupy import SnapshotAssertion from roborock.data import HomeDataDevice from roborock.data.v1.v1_containers import ConsumableField, StatusField +from roborock.devices.cache import DeviceCache from roborock.devices.device import RoborockDevice from roborock.devices.traits.v1.consumeable import ConsumableTrait from roborock.devices.traits.v1.status import StatusTrait +from roborock.exceptions import RoborockParsingException from tests import mock_data V1_DEVICES = { @@ -57,3 +61,29 @@ async def test_is_consumable_field_supported( field.value: device_features_trait.is_field_supported(ConsumableTrait, field) for field in ConsumableField } assert is_v1_supported == snapshot + + +@pytest.mark.parametrize("payload", [[], ["ok"]], ids=["empty", "non-dict"]) +async def test_refresh_unexpected_list_keeps_state( + device: RoborockDevice, + device_cache: DeviceCache, + mock_rpc_channel: AsyncMock, + payload: list, +) -> None: + """An empty or non-dict init status reply raises a parsing error and keeps the previous features.""" + assert device.v1_properties is not None + device_features_trait = device.v1_properties.device_features + previous = device_features_trait.as_dict() + # Force a device read instead of the cached features from discovery. + cache_data = await device_cache.get() + cache_data.device_features = None + await device_cache.set(cache_data) + mock_rpc_channel.send_command.return_value = payload + + with pytest.raises( + RoborockParsingException, + match=r"Failed to parse APP_GET_INIT_STATUS response for DeviceFeaturesTrait.*ValueError.*", + ): + await device_features_trait.refresh() + + assert device_features_trait.as_dict() == previous diff --git a/tests/devices/traits/v1/test_led_status.py b/tests/devices/traits/v1/test_led_status.py new file mode 100644 index 000000000..7483385ce --- /dev/null +++ b/tests/devices/traits/v1/test_led_status.py @@ -0,0 +1,38 @@ +"""Tests for the LedStatusTrait class.""" + +from unittest.mock import AsyncMock + +import pytest + +from roborock.devices.device import RoborockDevice +from roborock.devices.traits.v1.led_status import LedStatusTrait +from roborock.exceptions import RoborockParsingException + + +@pytest.fixture(name="led_status") +def led_status_trait( + device: RoborockDevice, + discover_features_fixture: None, +) -> LedStatusTrait: + """Create a LedStatusTrait instance with mocked dependencies.""" + assert device.v1_properties + assert device.v1_properties.led_status + return device.v1_properties.led_status + + +async def test_refresh_led_status_empty_list_keeps_state( + led_status: LedStatusTrait, + mock_rpc_channel: AsyncMock, +) -> None: + """An empty reply raises a parsing error and keeps the previous status.""" + mock_rpc_channel.send_command.return_value = [1] + await led_status.refresh() + mock_rpc_channel.send_command.return_value = [] + + with pytest.raises( + RoborockParsingException, + match=r"Failed to parse GET_LED_STATUS response for LedStatusTrait. Payload: \[\].*ValueError.*", + ): + await led_status.refresh() + + assert led_status.status == 1 diff --git a/tests/devices/traits/v1/test_maps.py b/tests/devices/traits/v1/test_maps.py index 660acc3f9..00b3b1328 100644 --- a/tests/devices/traits/v1/test_maps.py +++ b/tests/devices/traits/v1/test_maps.py @@ -7,6 +7,7 @@ from roborock.devices.device import RoborockDevice from roborock.devices.traits.v1.maps import MapsTrait from roborock.devices.traits.v1.status import StatusTrait +from roborock.exceptions import RoborockParsingException from roborock.roborock_typing import RoborockCommand from tests import mock_data @@ -154,3 +155,25 @@ async def test_set_current_map( assert mock_mqtt_rpc_channel.send_command.call_count == 2 mock_mqtt_rpc_channel.send_command.assert_any_call(RoborockCommand.GET_MULTI_MAPS_LIST) mock_mqtt_rpc_channel.send_command.assert_any_call(RoborockCommand.LOAD_MULTI_MAP, params=[123]) + + +async def test_refresh_maps_trait_empty_list_keeps_state( + maps_trait: MapsTrait, + mock_mqtt_rpc_channel: AsyncMock, +) -> None: + """An empty map list raises a parsing error and keeps the previous maps.""" + mock_mqtt_rpc_channel.send_command.side_effect = [ + MULTI_MAP_LIST_DATA, + [], + ] + await maps_trait.refresh() + + with pytest.raises( + RoborockParsingException, + match=r"Failed to parse GET_MULTI_MAPS_LIST response for MapsTrait. Payload: \[\].*ValueError.*", + ): + await maps_trait.refresh() + + assert maps_trait.multi_map_count == 1 + assert maps_trait.map_info + assert [map_info.name for map_info in maps_trait.map_info] == ["Map 1", "Map 2"]