Skip to content

Commit 8099f97

Browse files
committed
test: add end-to-end multi-part map content trait tests
Add map_parts and map_part_order support to V1VacuumSimulator and exercise MapContentTrait end-to-end across single-part and multi-part map responses.
1 parent b68ee94 commit 8099f97

3 files changed

Lines changed: 231 additions & 64 deletions

File tree

‎roborock/testing/v1_simulator.py‎

Lines changed: 43 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import logging
1111
import struct
1212
import time
13-
from collections.abc import Callable
13+
from collections.abc import Callable, Sequence
1414
from dataclasses import asdict, replace
1515
from enum import Enum
1616
from typing import Any
@@ -45,6 +45,7 @@
4545
from roborock.roborock_message import RoborockDataProtocol, RoborockMessage, RoborockMessageProtocol
4646
from roborock.testing.channel import FakeChannel
4747
from roborock.testing.simulator import RoborockDeviceSimulator
48+
from roborock.util import get_next_int
4849

4950
_LOGGER = logging.getLogger(__name__)
5051

@@ -255,8 +256,12 @@ def __init__(
255256

256257
# The simulated robot's own view of its map. Tests extend the path
257258
# with advance_path() and move the robot via robot_position.
259+
# Set map_parts > 1 (and optionally map_part_order) to split map
260+
# responses across MAP_RESPONSE_PART (300) and MAP_RESPONSE (301) frames.
258261
self.path_length = 0
259262
self.robot_position = (25000, 24000, 90)
263+
self.map_parts = 1
264+
self.map_part_order: Sequence[int] | None = None
260265

261266
self.device_cache = DeviceCache(self.duid, InMemoryCache())
262267
# The endpoint must fit the eight byte map response header field and the
@@ -416,11 +421,43 @@ def build_map_bytes(self) -> bytes:
416421
data = header + body + digest_header
417422
return data + hashlib.sha1(data, usedforsecurity=False).digest()
418423

419-
def _map_response_message(self, request_id: int, map_bytes: bytes) -> RoborockMessage:
420-
"""Frame the map as the encrypted binary response the device sends."""
424+
def _map_response_messages(self, request_id: int, map_bytes: bytes) -> list[RoborockMessage]:
425+
"""Frame the map as one or more encrypted binary messages as the device sends."""
426+
if self.map_parts < 1:
427+
raise ValueError("map_parts must be at least 1")
421428
body = Utils.encrypt_cbc(gzip.compress(map_bytes), self.security_data.nonce)
422429
header = struct.pack("<8s8sH6s", self.security_data.endpoint.encode(), bytes(8), request_id & 0xFFFF, bytes(6))
423-
return RoborockMessage(protocol=RoborockMessageProtocol.MAP_RESPONSE, payload=header + body)
430+
payload = header + body
431+
if self.map_parts == 1:
432+
if self.map_part_order is not None and list(self.map_part_order) != [0]:
433+
raise ValueError("map_part_order must be a permutation of range(map_parts)")
434+
return [RoborockMessage(protocol=RoborockMessageProtocol.MAP_RESPONSE, payload=payload)]
435+
if self.map_parts > len(payload):
436+
raise ValueError("map_parts cannot exceed encrypted map payload length")
437+
438+
# Split evenly into map_parts non-empty contiguous slices.
439+
total = len(payload)
440+
boundaries = [(i * total) // self.map_parts for i in range(self.map_parts + 1)]
441+
chunks = [payload[boundaries[i] : boundaries[i + 1]] for i in range(self.map_parts)]
442+
random_id = get_next_int(10000, 99999)
443+
timestamp = int(time.time())
444+
messages = [
445+
RoborockMessage(
446+
protocol=RoborockMessageProtocol.MAP_RESPONSE
447+
if idx == len(chunks) - 1
448+
else RoborockMessageProtocol.MAP_RESPONSE_PART,
449+
payload=chunk,
450+
seq=idx + 1,
451+
random=random_id,
452+
timestamp=timestamp,
453+
)
454+
for idx, chunk in enumerate(chunks)
455+
]
456+
if self.map_part_order is not None:
457+
if sorted(self.map_part_order) != list(range(self.map_parts)):
458+
raise ValueError("map_part_order must be a permutation of range(map_parts)")
459+
messages = [messages[i] for i in self.map_part_order]
460+
return messages
424461

425462
async def _handle_publish(self, message: RoborockMessage, channel: FakeChannel) -> None:
426463
if not message.payload:
@@ -455,7 +492,8 @@ async def _handle_publish(self, message: RoborockMessage, channel: FakeChannel)
455492

456493
if method == "get_map_v1" and error is None and isinstance(result, bytes):
457494
# Custom handlers return decompressed map bytes, just like the default.
458-
channel.notify_subscribers(self._map_response_message(msg_id, result))
495+
for map_msg in self._map_response_messages(msg_id, result):
496+
channel.notify_subscribers(map_msg)
459497
return
460498

461499
response_data = {
Lines changed: 164 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,87 +1,192 @@
1-
"""Tests for the MapContentTrait."""
1+
"""End-to-end tests for MapContentTrait backed by V1VacuumSimulator."""
22

3-
from unittest.mock import AsyncMock, MagicMock, patch
3+
from collections.abc import AsyncGenerator
4+
from dataclasses import replace
45

56
import pytest
67

8+
from roborock.data import HomeDataDevice, HomeDataProduct, RoborockDockTypeCode
79
from roborock.devices.device import RoborockDevice
10+
from roborock.devices.rpc.v1_channel import V1Channel
811
from roborock.devices.traits.v1.map_content import MapContentTrait
9-
from roborock.map.map_parser import ParsedMapData
10-
from roborock.roborock_typing import RoborockCommand
12+
from roborock.exceptions import RoborockException
13+
from roborock.protocols.v1_protocol import V1RpcChannel
14+
from roborock.testing import DEFAULT_STATUS, V1VacuumSimulator
15+
16+
17+
@pytest.fixture(name="simulator")
18+
def simulator_fixture(
19+
device_info: HomeDataDevice,
20+
products: list[HomeDataProduct],
21+
dock_type_code: RoborockDockTypeCode | None,
22+
) -> V1VacuumSimulator:
23+
"""Create a connected V1VacuumSimulator backing the device."""
24+
product = next(p for p in products if p.id == device_info.product_id)
25+
sim = V1VacuumSimulator(
26+
duid=device_info.duid,
27+
device_info=device_info,
28+
product=product,
29+
status=replace(DEFAULT_STATUS, dock_type=dock_type_code),
30+
)
31+
sim.connect()
32+
return sim
33+
34+
35+
@pytest.fixture(name="channel")
36+
def simulator_channel_fixture(simulator: V1VacuumSimulator) -> V1Channel:
37+
"""Provide the simulator's real V1Channel."""
38+
return simulator.v1_channel
39+
40+
41+
@pytest.fixture(name="mock_rpc_channel")
42+
def simulator_rpc_channel_fixture(simulator: V1VacuumSimulator) -> V1RpcChannel:
43+
"""Provide the simulator's real combined RPC channel."""
44+
return simulator.v1_channel.rpc_channel
45+
46+
47+
@pytest.fixture(name="mock_mqtt_rpc_channel")
48+
def simulator_mqtt_rpc_channel_fixture(simulator: V1VacuumSimulator) -> V1RpcChannel:
49+
"""Provide the simulator's real MQTT RPC channel."""
50+
return simulator.v1_channel.mqtt_rpc_channel
51+
52+
53+
@pytest.fixture(name="mock_map_rpc_channel")
54+
def simulator_map_rpc_channel_fixture(simulator: V1VacuumSimulator) -> V1RpcChannel:
55+
"""Provide the simulator's real map RPC channel."""
56+
return simulator.v1_channel.map_rpc_channel
57+
58+
59+
@pytest.fixture(name="mock_blob_rpc_channel")
60+
def simulator_blob_rpc_channel_fixture(simulator: V1VacuumSimulator) -> V1RpcChannel:
61+
"""Provide the simulator's real blob RPC channel."""
62+
return simulator.v1_channel.blob_rpc_channel
63+
64+
65+
@pytest.fixture(autouse=True)
66+
async def discover_features_fixture(device: RoborockDevice) -> AsyncGenerator[None, None]:
67+
"""Connect the device against the simulator and tear down cleanly."""
68+
await device.connect()
69+
try:
70+
yield
71+
finally:
72+
await device.close()
1173

1274

13-
@pytest.fixture
14-
def map_content_trait(device: RoborockDevice) -> MapContentTrait:
15-
"""Create a MapContentTrait instance with mocked dependencies."""
75+
@pytest.fixture(name="map_content_trait")
76+
def map_content_trait_fixture(device: RoborockDevice) -> MapContentTrait:
77+
"""Return the device's MapContentTrait."""
1678
assert device.v1_properties
1779
return device.v1_properties.map_content
1880

1981

82+
@pytest.mark.parametrize(
83+
("map_parts", "map_part_order"),
84+
[
85+
(1, None),
86+
(2, [0, 1]),
87+
(2, [1, 0]),
88+
(3, [0, 1, 2]),
89+
(3, [2, 0, 1]),
90+
(4, [3, 1, 2, 0]),
91+
],
92+
ids=[
93+
"single_part",
94+
"two_parts_in_order",
95+
"two_parts_out_of_order",
96+
"three_parts_in_order",
97+
"three_parts_out_of_order",
98+
"four_parts_permuted",
99+
],
100+
)
20101
async def test_refresh_map_content_trait(
102+
simulator: V1VacuumSimulator,
21103
map_content_trait: MapContentTrait,
22-
mock_map_rpc_channel: AsyncMock,
104+
map_parts: int,
105+
map_part_order: list[int] | None,
23106
) -> None:
24-
"""Test successfully getting and parsing map content."""
25-
map_data = b"dummy_map_bytes"
26-
mock_map_rpc_channel.send_command.return_value = map_data
27-
mock_parsed_data = ParsedMapData(
28-
image_content=b"dummy_image_content",
29-
map_data=MagicMock(),
30-
)
107+
"""Test refreshing and parsing single-part and multi-part map responses end-to-end."""
108+
simulator.advance_path(80)
109+
simulator.robot_position = (31000, 32000, 180)
110+
simulator.map_parts = map_parts
111+
simulator.map_part_order = map_part_order
31112

32-
with patch("roborock.devices.traits.v1.map_content.MapParser.parse", return_value=mock_parsed_data) as mock_parse:
33-
await map_content_trait.refresh()
34-
mock_parse.assert_called_once_with(map_data)
113+
await map_content_trait.refresh()
35114

36-
assert map_content_trait.image_content == b"dummy_image_content"
115+
assert map_content_trait.image_content is not None
116+
assert map_content_trait.image_content.startswith(b"\x89PNG")
117+
assert map_content_trait.raw_api_response == simulator.build_map_bytes()
37118
assert map_content_trait.map_data is not None
38-
39-
mock_map_rpc_channel.send_command.assert_called_once_with(RoborockCommand.GET_MAP_V1)
119+
assert map_content_trait.map_data.path is not None
120+
assert len(map_content_trait.map_data.path.path[0]) == 80
121+
assert map_content_trait.map_data.vacuum_position is not None
122+
assert (
123+
map_content_trait.map_data.vacuum_position.x,
124+
map_content_trait.map_data.vacuum_position.y,
125+
) == (31000, 32000)
40126

41127

42128
async def test_refresh_unchanged_content_skips_parsing(
129+
simulator: V1VacuumSimulator,
43130
map_content_trait: MapContentTrait,
44-
mock_map_rpc_channel: AsyncMock,
45131
) -> None:
46-
"""Test that refresh avoids re-parsing when the map content is unchanged."""
47-
map_data = b"dummy_map_bytes"
48-
mock_map_rpc_channel.send_command.return_value = map_data
49-
mock_parsed_data = ParsedMapData(
50-
image_content=b"dummy_image_content",
51-
map_data=MagicMock(),
52-
)
132+
"""Test that refresh avoids re-parsing unchanged maps and updates when map bytes change."""
133+
simulator.advance_path(40)
134+
simulator.robot_position = (28000, 29000, 90)
135+
simulator.map_parts = 3
136+
137+
await map_content_trait.refresh()
138+
initial_image = map_content_trait.image_content
139+
initial_map_data = map_content_trait.map_data
140+
assert initial_image is not None
141+
assert initial_map_data is not None
142+
143+
# Second refresh with identical multi-part map preserves the existing MapData instance
144+
await map_content_trait.refresh()
145+
assert map_content_trait.map_data is initial_map_data
146+
147+
# Third refresh after robot movement re-parses and renders the updated map
148+
simulator.advance_path(40)
149+
simulator.robot_position = (33000, 34000, 270)
150+
simulator.map_part_order = [2, 0, 1]
151+
await map_content_trait.refresh()
152+
153+
assert map_content_trait.map_data is not initial_map_data
154+
assert map_content_trait.image_content != initial_image
155+
assert map_content_trait.map_data is not None
156+
assert map_content_trait.map_data.path is not None
157+
assert len(map_content_trait.map_data.path.path[0]) == 80
158+
assert map_content_trait.map_data.vacuum_position is not None
159+
assert (
160+
map_content_trait.map_data.vacuum_position.x,
161+
map_content_trait.map_data.vacuum_position.y,
162+
) == (33000, 34000)
53163

54-
with patch("roborock.devices.traits.v1.map_content.MapParser.parse", return_value=mock_parsed_data) as mock_parse:
55-
await map_content_trait.refresh()
56-
assert mock_parse.call_count == 1
57-
assert map_content_trait.image_content == b"dummy_image_content"
58164

59-
# Second refresh with identical response should not re-parse
60-
await map_content_trait.refresh()
61-
assert mock_parse.call_count == 1
62-
63-
# Third refresh with new response parses again
64-
new_map_data = b"new_map_bytes"
65-
new_parsed_data = ParsedMapData(
66-
image_content=b"new_image_content",
67-
map_data=MagicMock(),
68-
)
69-
mock_map_rpc_channel.send_command.return_value = new_map_data
70-
mock_parse.return_value = new_parsed_data
165+
async def test_refresh_invalid_map_raises_exception(
166+
simulator: V1VacuumSimulator,
167+
map_content_trait: MapContentTrait,
168+
) -> None:
169+
"""Test malformed map payload raises RoborockException after multi-part reassembly."""
170+
simulator.custom_handlers["get_map_v1"] = lambda _: b"corrupt_map_bytes"
171+
simulator.map_parts = 2
172+
173+
with pytest.raises(RoborockException, match="Failed to parse map data"):
71174
await map_content_trait.refresh()
72-
assert mock_parse.call_count == 2
73-
assert map_content_trait.image_content == b"new_image_content"
74175

75176

76-
async def test_async_parse_map_content(map_content_trait: MapContentTrait) -> None:
77-
"""Test async_parse_map_content on MapContentConverter."""
78-
map_data = b"dummy_map_bytes"
79-
mock_parsed_data = ParsedMapData(
80-
image_content=b"dummy_image_content",
81-
map_data=MagicMock(),
82-
)
83-
with patch("roborock.devices.traits.v1.map_content.MapParser.parse", return_value=mock_parsed_data) as mock_parse:
84-
result = await map_content_trait.converter.async_parse_map_content(map_data)
85-
mock_parse.assert_called_once_with(map_data)
86-
assert result.image_content == b"dummy_image_content"
87-
assert result.raw_api_response == map_data
177+
async def test_async_parse_map_content(
178+
simulator: V1VacuumSimulator,
179+
map_content_trait: MapContentTrait,
180+
) -> None:
181+
"""Test async_parse_map_content on MapContentConverter with real map bytes."""
182+
simulator.advance_path(25)
183+
map_bytes = simulator.build_map_bytes()
184+
185+
result = await map_content_trait.converter.async_parse_map_content(map_bytes)
186+
187+
assert result.image_content is not None
188+
assert result.image_content.startswith(b"\x89PNG")
189+
assert result.raw_api_response == map_bytes
190+
assert result.map_data is not None
191+
assert result.map_data.path is not None
192+
assert len(result.map_data.path.path[0]) == 25

‎tests/testing/test_v1_simulator.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from roborock.devices.traits.v1.consumeable import ConsumableAttribute
1414
from roborock.exceptions import RoborockException
1515
from roborock.map.map_parser import MapParser, MapParserConfig
16+
from roborock.roborock_message import RoborockMessageProtocol
1617
from roborock.testing import (
1718
DEFAULT_NETWORK_INFO,
1819
DEFAULT_STATUS,
@@ -308,6 +309,29 @@ async def test_full_map_refresh_from_simulator():
308309
assert (map_content.map_data.vacuum_position.x, map_content.map_data.vacuum_position.y) == (31000, 32000)
309310

310311

312+
async def test_simulator_multipart_map_framing() -> None:
313+
"""Configuring map_parts and map_part_order frames ordered MAP_RESPONSE_PART + MAP_RESPONSE chunks."""
314+
simulator = V1VacuumSimulator(duid="s7_framing")
315+
simulator.connect()
316+
simulator.advance_path(40)
317+
simulator.map_parts = 3
318+
simulator.map_part_order = [2, 0, 1]
319+
320+
emitted: list[tuple[RoborockMessageProtocol, int]] = []
321+
unsub = await simulator.mqtt_channel.subscribe(lambda msg: emitted.append((msg.protocol, msg.seq)))
322+
try:
323+
raw = await simulator.v1_channel.map_rpc_channel.send_command("get_map_v1")
324+
finally:
325+
unsub()
326+
327+
assert emitted == [
328+
(RoborockMessageProtocol.MAP_RESPONSE, 3),
329+
(RoborockMessageProtocol.MAP_RESPONSE_PART, 1),
330+
(RoborockMessageProtocol.MAP_RESPONSE_PART, 2),
331+
]
332+
assert raw == simulator.build_map_bytes()
333+
334+
311335
@pytest.mark.parametrize("count", [0, 40, 400])
312336
def test_simulated_map_length_and_digest(count: int) -> None:
313337
"""Synthetic maps satisfy the app's full-file length and SHA-1 checks."""

0 commit comments

Comments
 (0)