Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions roborock/devices/traits/v1/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand All @@ -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}")
Expand Down
2 changes: 2 additions & 0 deletions roborock/devices/traits/v1/device_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions roborock/devices/traits/v1/led_status.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand Down
2 changes: 2 additions & 0 deletions roborock/devices/traits/v1/maps.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand Down
27 changes: 26 additions & 1 deletion tests/devices/traits/v1/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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([])
30 changes: 30 additions & 0 deletions tests/devices/traits/v1/test_device_features.py
Original file line number Diff line number Diff line change
@@ -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 = {
Expand Down Expand Up @@ -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
38 changes: 38 additions & 0 deletions tests/devices/traits/v1/test_led_status.py
Original file line number Diff line number Diff line change
@@ -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
23 changes: 23 additions & 0 deletions tests/devices/traits/v1/test_maps.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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"]
Loading