Skip to content

Commit 85d7514

Browse files
authored
fix(v1): report empty trait list replies as parsing errors (#1056)
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.
1 parent 2527d9a commit 85d7514

8 files changed

Lines changed: 127 additions & 1 deletion

File tree

‎roborock/devices/traits/v1/common.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,8 @@ def convert(self, response: V1ResponseData) -> RoborockBase:
113113
Subclasses can override to implement custom parsing logic
114114
"""
115115
if isinstance(response, list):
116+
if not response:
117+
raise ValueError(f"Empty {self._dataclass_type.__name__} response")
116118
response = response[0]
117119
if not isinstance(response, dict):
118120
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
136138
def convert(self, response: V1ResponseData) -> RoborockBase:
137139
"""Parse the response from the device into a RoborockValueBase."""
138140
if isinstance(response, list):
141+
if not response:
142+
raise ValueError(f"Empty {self._dataclass_type.__name__} response")
139143
response = response[0]
140144
if not isinstance(response, int):
141145
raise ValueError(f"Unexpected response format: {response!r}")

‎roborock/devices/traits/v1/device_features.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ def convert(self, response: common.V1ResponseData) -> DeviceFeatures:
4040
"""Parse an APP_GET_INIT_STATUS response into a DeviceFeatures instance."""
4141
if not isinstance(response, list):
4242
raise ValueError(f"Unexpected AppInitStatus response format: {type(response)}: {response!r}")
43+
if not response or not isinstance(response[0], dict):
44+
raise ValueError(f"Unexpected AppInitStatus response format: {response!r}")
4345
app_status = AppInitStatus.from_dict(response[0])
4446
return DeviceFeatures.from_feature_flags(
4547
new_feature_info=app_status.new_feature_info,

‎roborock/devices/traits/v1/led_status.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ def convert(self, response: V1ResponseData) -> LedStatus:
1616
"""
1717
if not isinstance(response, list):
1818
raise ValueError(f"Unexpected LedStatus response format: {response!r}")
19+
if not response:
20+
raise ValueError("Empty LedStatus response")
1921
response = response[0]
2022
if not isinstance(response, int):
2123
raise ValueError(f"Unexpected LedStatus response format: {response!r}")

‎roborock/devices/traits/v1/maps.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ def convert(self, response: common.V1ResponseData) -> MultiMapsList:
2828
"""
2929
if not isinstance(response, list):
3030
raise ValueError(f"Unexpected MapsTrait response format: {response!r}")
31+
if not response:
32+
raise ValueError("Empty MapsTrait response")
3133
response = response[0]
3234
if not isinstance(response, dict):
3335
raise ValueError(f"Unexpected MapsTrait response format: {response!r}")

‎tests/devices/traits/v1/test_common.py‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import pytest
55

66
from roborock.data.containers import RoborockBase
7-
from roborock.devices.traits.v1.common import DefaultConverter, V1TraitMixin
7+
from roborock.devices.traits.v1.common import DefaultConverter, SingleValueConverter, V1TraitMixin
88
from roborock.exceptions import RoborockParsingException
99
from roborock.roborock_typing import RoborockCommand
1010

@@ -50,3 +50,28 @@ async def test_valid_payload() -> None:
5050
await trait.refresh()
5151
assert trait.fake_field == 123
5252
assert trait.other_field == "abc"
53+
54+
55+
async def test_empty_list_payload_keeps_state() -> None:
56+
"""An empty list raises a parsing error and keeps the previous values."""
57+
trait = FakeTrait()
58+
trait._rpc_channel.send_command.return_value = [{"fake_field": 123, "other_field": "abc"}]
59+
await trait.refresh()
60+
trait._rpc_channel.send_command.return_value = []
61+
62+
with pytest.raises(
63+
RoborockParsingException,
64+
match=r"Failed to parse APP_GET_INIT_STATUS response for FakeTrait. Payload: \[\].*ValueError.*",
65+
):
66+
await trait.refresh()
67+
68+
assert trait.fake_field == 123
69+
assert trait.other_field == "abc"
70+
71+
72+
def test_single_value_converter_empty_list() -> None:
73+
"""The single-value converter rejects an empty list with ValueError."""
74+
converter = SingleValueConverter(FakeTraitData, "fake_field")
75+
76+
with pytest.raises(ValueError, match="Empty FakeTraitData response"):
77+
converter.convert([])

‎tests/devices/traits/v1/test_device_features.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
11
"""Tests for the DeviceFeaturesTrait related functionality."""
22

3+
from unittest.mock import AsyncMock
4+
35
import pytest
46
from syrupy import SnapshotAssertion
57

68
from roborock.data import HomeDataDevice
79
from roborock.data.v1.v1_containers import ConsumableField, StatusField
10+
from roborock.devices.cache import DeviceCache
811
from roborock.devices.device import RoborockDevice
912
from roborock.devices.traits.v1.consumeable import ConsumableTrait
1013
from roborock.devices.traits.v1.status import StatusTrait
14+
from roborock.exceptions import RoborockParsingException
1115
from tests import mock_data
1216

1317
V1_DEVICES = {
@@ -57,3 +61,29 @@ async def test_is_consumable_field_supported(
5761
field.value: device_features_trait.is_field_supported(ConsumableTrait, field) for field in ConsumableField
5862
}
5963
assert is_v1_supported == snapshot
64+
65+
66+
@pytest.mark.parametrize("payload", [[], ["ok"]], ids=["empty", "non-dict"])
67+
async def test_refresh_unexpected_list_keeps_state(
68+
device: RoborockDevice,
69+
device_cache: DeviceCache,
70+
mock_rpc_channel: AsyncMock,
71+
payload: list,
72+
) -> None:
73+
"""An empty or non-dict init status reply raises a parsing error and keeps the previous features."""
74+
assert device.v1_properties is not None
75+
device_features_trait = device.v1_properties.device_features
76+
previous = device_features_trait.as_dict()
77+
# Force a device read instead of the cached features from discovery.
78+
cache_data = await device_cache.get()
79+
cache_data.device_features = None
80+
await device_cache.set(cache_data)
81+
mock_rpc_channel.send_command.return_value = payload
82+
83+
with pytest.raises(
84+
RoborockParsingException,
85+
match=r"Failed to parse APP_GET_INIT_STATUS response for DeviceFeaturesTrait.*ValueError.*",
86+
):
87+
await device_features_trait.refresh()
88+
89+
assert device_features_trait.as_dict() == previous
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"""Tests for the LedStatusTrait class."""
2+
3+
from unittest.mock import AsyncMock
4+
5+
import pytest
6+
7+
from roborock.devices.device import RoborockDevice
8+
from roborock.devices.traits.v1.led_status import LedStatusTrait
9+
from roborock.exceptions import RoborockParsingException
10+
11+
12+
@pytest.fixture(name="led_status")
13+
def led_status_trait(
14+
device: RoborockDevice,
15+
discover_features_fixture: None,
16+
) -> LedStatusTrait:
17+
"""Create a LedStatusTrait instance with mocked dependencies."""
18+
assert device.v1_properties
19+
assert device.v1_properties.led_status
20+
return device.v1_properties.led_status
21+
22+
23+
async def test_refresh_led_status_empty_list_keeps_state(
24+
led_status: LedStatusTrait,
25+
mock_rpc_channel: AsyncMock,
26+
) -> None:
27+
"""An empty reply raises a parsing error and keeps the previous status."""
28+
mock_rpc_channel.send_command.return_value = [1]
29+
await led_status.refresh()
30+
mock_rpc_channel.send_command.return_value = []
31+
32+
with pytest.raises(
33+
RoborockParsingException,
34+
match=r"Failed to parse GET_LED_STATUS response for LedStatusTrait. Payload: \[\].*ValueError.*",
35+
):
36+
await led_status.refresh()
37+
38+
assert led_status.status == 1

‎tests/devices/traits/v1/test_maps.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from roborock.devices.device import RoborockDevice
88
from roborock.devices.traits.v1.maps import MapsTrait
99
from roborock.devices.traits.v1.status import StatusTrait
10+
from roborock.exceptions import RoborockParsingException
1011
from roborock.roborock_typing import RoborockCommand
1112
from tests import mock_data
1213

@@ -154,3 +155,25 @@ async def test_set_current_map(
154155
assert mock_mqtt_rpc_channel.send_command.call_count == 2
155156
mock_mqtt_rpc_channel.send_command.assert_any_call(RoborockCommand.GET_MULTI_MAPS_LIST)
156157
mock_mqtt_rpc_channel.send_command.assert_any_call(RoborockCommand.LOAD_MULTI_MAP, params=[123])
158+
159+
160+
async def test_refresh_maps_trait_empty_list_keeps_state(
161+
maps_trait: MapsTrait,
162+
mock_mqtt_rpc_channel: AsyncMock,
163+
) -> None:
164+
"""An empty map list raises a parsing error and keeps the previous maps."""
165+
mock_mqtt_rpc_channel.send_command.side_effect = [
166+
MULTI_MAP_LIST_DATA,
167+
[],
168+
]
169+
await maps_trait.refresh()
170+
171+
with pytest.raises(
172+
RoborockParsingException,
173+
match=r"Failed to parse GET_MULTI_MAPS_LIST response for MapsTrait. Payload: \[\].*ValueError.*",
174+
):
175+
await maps_trait.refresh()
176+
177+
assert maps_trait.multi_map_count == 1
178+
assert maps_trait.map_info
179+
assert [map_info.name for map_info in maps_trait.map_info] == ["Map 1", "Map 2"]

0 commit comments

Comments
 (0)