File: test_home.py

package info (click to toggle)
python-roborock 4.12.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,480 kB
  • sloc: python: 16,602; makefile: 17; sh: 6
file content (692 lines) | stat: -rw-r--r-- 25,944 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
"""Tests for the Home related functionality."""

import base64
from collections.abc import Iterator
from unittest.mock import AsyncMock, MagicMock, patch

import pytest

from roborock.data.containers import CombinedMapInfo, NamedRoomMapping
from roborock.data.v1.v1_code_mappings import RoborockStateCode
from roborock.data.v1.v1_containers import MultiMapsListMapInfo, MultiMapsListRoom
from roborock.devices.cache import DeviceCache, DeviceCacheData, InMemoryCache
from roborock.devices.device import RoborockDevice
from roborock.devices.traits.v1.home import HomeTrait
from roborock.devices.traits.v1.map_content import MapContentTrait
from roborock.devices.traits.v1.maps import MapsTrait
from roborock.devices.traits.v1.rooms import RoomsTrait
from roborock.devices.traits.v1.status import StatusTrait
from roborock.exceptions import RoborockDeviceBusy, RoborockException, RoborockInvalidStatus
from roborock.map.map_parser import ParsedMapData
from roborock.roborock_typing import RoborockCommand
from tests import mock_data

MULTI_MAP_LIST_DATA = [
    {
        "max_multi_map": 2,
        "max_bak_map": 1,
        "multi_map_count": 2,
        "map_info": [
            {
                "mapFlag": 0,
                "add_time": 1747132930,
                "length": 0,
                "name": "Ground Floor",
                "bak_maps": [{"mapFlag": 4, "add_time": 1747132936}],
            },
            {
                "mapFlag": 123,
                "add_time": 1747132940,
                "length": 0,
                "name": "Second Floor",
                "bak_maps": [{"mapFlag": 5, "add_time": 1747132946}],
            },
        ],
    }
]
MULTI_MAP_LIST_SINGLE_MAP_DATA = [
    {
        "max_multi_map": 1,
        "max_bak_map": 0,
        "multi_map_count": 1,
        "map_info": [
            {
                "mapFlag": 0,
                "add_time": 1747132930,
                "length": 0,
                "name": "Only Floor",
                "bak_maps": [],
            },
        ],
    }
]

ROOM_MAPPING_DATA_MAP_0 = [[16, "2362048"], [17, "2362044"]]
ROOM_MAPPING_DATA_MAP_123 = [[18, "2362041"], [19, "2362042"]]

UPDATED_STATUS_MAP_0 = {
    **mock_data.STATUS,
    "map_status": 0 * 4 + 3,  # Set current map to 0
}

UPDATED_STATUS_MAP_123 = {
    **mock_data.STATUS,
    "map_status": 123 * 4 + 3,  # Set current map to 123
}
MAP_BYTES_RESPONSE_1 = b"<map bytes 1>"
MAP_BYTES_RESPONSE_2 = b"<map bytes 2>"
TEST_IMAGE_CONTENT_1 = b"<image bytes 1>"
TEST_IMAGE_CONTENT_2 = b"<image bytes 2>"
TEST_PARSER_MAP = {
    MAP_BYTES_RESPONSE_1: TEST_IMAGE_CONTENT_1,
    MAP_BYTES_RESPONSE_2: TEST_IMAGE_CONTENT_2,
}


@pytest.fixture(autouse=True)
def no_sleep() -> Iterator[None]:
    """Patch sleep to avoid delays in tests."""
    with patch("roborock.devices.traits.v1.home.asyncio.sleep"):
        yield


@pytest.fixture(name="cache")
def cache_fixture():
    """Create an in-memory cache for testing."""
    return InMemoryCache()


@pytest.fixture(name="device_cache")
def device_cache_fixture(cache: InMemoryCache) -> DeviceCache:
    """Create a DeviceCache instance for testing."""
    return DeviceCache(duid="abc123", cache=cache)


@pytest.fixture(autouse=True)
async def status_trait(mock_rpc_channel: AsyncMock, device: RoborockDevice) -> StatusTrait:
    """Create a StatusTrait instance with mocked dependencies."""
    assert device.v1_properties
    status_trait = device.v1_properties.status

    # Verify initial state
    assert status_trait.current_map is None
    mock_rpc_channel.send_command.side_effect = [UPDATED_STATUS_MAP_0]
    await status_trait.refresh()
    assert status_trait.current_map == 0

    mock_rpc_channel.reset_mock()
    return status_trait


@pytest.fixture
def maps_trait(device: RoborockDevice) -> MapsTrait:
    """Create a MapsTrait instance with mocked dependencies."""
    assert device.v1_properties
    return device.v1_properties.maps


@pytest.fixture
def map_content_trait(device: RoborockDevice) -> MapContentTrait:
    """Create a MapContentTrait instance with mocked dependencies."""
    assert device.v1_properties
    return device.v1_properties.map_content


@pytest.fixture
def rooms_trait(device: RoborockDevice) -> RoomsTrait:
    """Create a RoomsTrait instance with mocked dependencies."""
    assert device.v1_properties
    return device.v1_properties.rooms


@pytest.fixture
def home_trait(
    status_trait: StatusTrait,
    maps_trait: MapsTrait,
    map_content_trait: MapContentTrait,
    rooms_trait: RoomsTrait,
    device_cache: DeviceCache,
) -> HomeTrait:
    """Create a HomeTrait instance with mocked dependencies."""
    return HomeTrait(status_trait, maps_trait, map_content_trait, rooms_trait, device_cache)


@pytest.fixture(autouse=True)
def map_parser_fixture() -> Iterator[None]:
    """Mock MapParser.parse to return predefined test map data."""

    def parse_data(response: bytes) -> ParsedMapData:
        if image_content := TEST_PARSER_MAP.get(response):
            return ParsedMapData(
                image_content=image_content,
                map_data=MagicMock(),
            )
        raise ValueError(f"Unexpected map bytes {response!r}")

    with patch("roborock.devices.traits.v1.map_content.MapParser.parse", side_effect=parse_data):
        yield


async def test_discover_home_empty_cache(
    status_trait: StatusTrait,
    home_trait: HomeTrait,
    mock_rpc_channel: AsyncMock,
    mock_mqtt_rpc_channel: AsyncMock,
    mock_map_rpc_channel: AsyncMock,
    device_cache: DeviceCache,
) -> None:
    """Test discovering home when cache is empty."""
    # Setup mocks for the discovery process
    mock_rpc_channel.send_command.side_effect = [
        UPDATED_STATUS_MAP_123,  # Status after switching to map 123
        ROOM_MAPPING_DATA_MAP_123,  # Rooms for map 123
        UPDATED_STATUS_MAP_0,  # Status after switching back to map 0
        ROOM_MAPPING_DATA_MAP_0,  # Rooms for map 0
    ]
    mock_mqtt_rpc_channel.send_command.side_effect = [
        MULTI_MAP_LIST_DATA,  # Multi maps list
        {},  # LOAD_MULTI_MAP response for map 123
        {},  # LOAD_MULTI_MAP response back to map 0
    ]
    mock_map_rpc_channel.send_command.side_effect = [
        MAP_BYTES_RESPONSE_2,  # Map bytes for 123
        MAP_BYTES_RESPONSE_1,  # Map bytes for 0
    ]

    # Before discovery, no cache should exist
    assert home_trait.home_map_info is None
    assert home_trait.current_map_data is None

    # Perform home discovery
    await home_trait.discover_home()

    # Verify cache is populated
    assert home_trait.home_map_info is not None
    assert len(home_trait.home_map_info) == 2

    # Check map 0 data
    map_0_data = home_trait.home_map_info[0]
    assert map_0_data.map_flag == 0
    assert map_0_data.name == "Ground Floor"
    assert len(map_0_data.rooms) == 2
    assert map_0_data.rooms[0].segment_id == 16
    assert map_0_data.rooms[0].name == "Example room 1"
    assert map_0_data.rooms[1].segment_id == 17
    assert map_0_data.rooms[1].name == "Example room 2"

    map_0_content = home_trait.home_map_content[0]
    assert map_0_content is not None
    assert map_0_content.image_content == TEST_IMAGE_CONTENT_1
    assert map_0_content.map_data is not None

    # Check map 123 data
    map_123_data = home_trait.home_map_info[123]
    assert map_123_data.map_flag == 123
    assert map_123_data.name == "Second Floor"
    assert len(map_123_data.rooms) == 2
    assert map_123_data.rooms[0].segment_id == 18
    assert map_123_data.rooms[0].name == "Example room 3"
    assert map_123_data.rooms[1].segment_id == 19
    assert map_123_data.rooms[1].name == "Unknown"  # Not in mock home data

    map_123_content = home_trait.home_map_content[123]
    assert map_123_content is not None
    assert map_123_content.image_content == TEST_IMAGE_CONTENT_2
    assert map_123_content.map_data is not None

    # Verify current map data is accessible
    current_map_data = home_trait.current_map_data
    assert current_map_data is not None
    assert current_map_data.map_flag == 0
    assert current_map_data.name == "Ground Floor"

    # Verify the persistent cache has been updated
    device_cache_data = await device_cache.get()
    assert device_cache_data.home_map_info is not None
    assert len(device_cache_data.home_map_info) == 2
    assert device_cache_data.home_map_content_base64 is not None
    assert len(device_cache_data.home_map_content_base64) == 2


@pytest.mark.parametrize(
    "device_cache_data",
    [
        DeviceCacheData(
            home_map_info={0: CombinedMapInfo(map_flag=0, name="Dummy", rooms=[])},
            home_map_content_base64={0: base64.b64encode(MAP_BYTES_RESPONSE_1).decode("utf-8")},
        ),
    ],
)
async def test_discover_home_with_existing_cache(
    home_trait: HomeTrait,
    mock_rpc_channel: AsyncMock,
    mock_mqtt_rpc_channel: AsyncMock,
    device_cache_data: DeviceCacheData,
    device_cache: DeviceCache,
) -> None:
    """Test that discovery is skipped when cache already exists."""
    # Pre-populate the cache
    await device_cache.set(device_cache_data)

    # Call discover_home
    await home_trait.discover_home()

    # Verify no RPC calls were made (discovery was skipped)
    assert mock_rpc_channel.send_command.call_count == 0
    assert mock_mqtt_rpc_channel.send_command.call_count == 0

    # Verify cache was loaded from storage
    assert home_trait.home_map_info == {0: CombinedMapInfo(map_flag=0, name="Dummy", rooms=[])}
    assert home_trait.home_map_content
    assert home_trait.home_map_content.keys() == {0}
    map_0_content = home_trait.home_map_content[0]
    assert map_0_content is not None
    assert map_0_content.image_content == TEST_IMAGE_CONTENT_1
    assert map_0_content.map_data is not None


async def test_existing_home_cache_invalid_bytes(
    home_trait: HomeTrait,
    device_cache: DeviceCache,
    mock_rpc_channel: AsyncMock,
    mock_mqtt_rpc_channel: AsyncMock,
    mock_map_rpc_channel: AsyncMock,
) -> None:
    """Test that discovery is skipped when cache already exists."""
    # Pre-populate the cache.
    cache_data = await device_cache.get()
    cache_data.home_map_info = {0: CombinedMapInfo(map_flag=0, name="Dummy", rooms=[])}
    # We override the map bytes parser to raise an exception above.
    cache_data.home_map_content_base64 = {0: base64.b64encode(MAP_BYTES_RESPONSE_1).decode("utf-8")}
    await device_cache.set(cache_data)

    # Setup mocks for the discovery process
    mock_rpc_channel.send_command.side_effect = [
        ROOM_MAPPING_DATA_MAP_0,  # Rooms for the single map
    ]
    mock_mqtt_rpc_channel.send_command.side_effect = [
        MULTI_MAP_LIST_SINGLE_MAP_DATA,  # Single map list
    ]
    mock_map_rpc_channel.send_command.side_effect = [
        MAP_BYTES_RESPONSE_1,  # Map bytes for the single map
    ]

    # Call discover_home. First attempt raises an exception then loading from the server
    # produes a valid result.
    with patch(
        "roborock.devices.traits.v1.map_content.MapParser.parse",
        side_effect=[
            RoborockException("Invalid map bytes"),
            ParsedMapData(
                image_content=TEST_IMAGE_CONTENT_2,
                map_data=MagicMock(),
            ),
        ],
    ):
        await home_trait.discover_home()

    # Verify cache was loaded from storage. The map was re-fetched from storage.
    assert home_trait.home_map_info
    assert home_trait.home_map_info.keys() == {0}
    assert home_trait.home_map_info[0].name == "Only Floor"
    assert home_trait.home_map_content
    assert home_trait.home_map_content.keys() == {0}
    map_0_content = home_trait.home_map_content[0]
    assert map_0_content is not None
    assert map_0_content.image_content == TEST_IMAGE_CONTENT_2
    assert map_0_content.map_data is not None


async def test_discover_home_no_maps(
    home_trait: HomeTrait,
    mock_rpc_channel: AsyncMock,
    mock_mqtt_rpc_channel: AsyncMock,
) -> None:
    """Test discovery when no maps are available."""
    # Setup mock to return empty maps list
    mock_mqtt_rpc_channel.send_command.side_effect = [
        [{"max_multi_map": 0, "max_bak_map": 0, "multi_map_count": 0, "map_info": []}]
    ]

    with pytest.raises(Exception, match="Cannot perform home discovery without current map info"):
        await home_trait.discover_home()


async def test_refresh_updates_current_map_cache(
    device_cache: DeviceCache,
    status_trait: StatusTrait,
    home_trait: HomeTrait,
    mock_rpc_channel: AsyncMock,
    mock_mqtt_rpc_channel: AsyncMock,
    mock_map_rpc_channel: AsyncMock,
) -> None:
    """Test that refresh updates the cache for the current map."""
    # Pre-populate cache with some data
    cache_data = await device_cache.get()
    cache_data.home_map_info = {0: CombinedMapInfo(map_flag=0, name="Old Ground Floor", rooms=[])}
    cache_data.home_map_content_base64 = {
        0: base64.b64encode(MAP_BYTES_RESPONSE_2).decode()
    }  # Pre-existing different map bytes
    await device_cache.set(cache_data)
    await home_trait.discover_home()  # Load cache into trait
    # Verify initial cache state
    assert home_trait.home_map_info
    assert home_trait.home_map_info.keys() == {0}
    assert home_trait.home_map_info[0].name == "Old Ground Floor"
    assert len(home_trait.home_map_info[0].rooms) == 0
    assert home_trait.home_map_content
    assert home_trait.home_map_content.keys() == {0}
    assert home_trait.home_map_content[0].image_content == TEST_IMAGE_CONTENT_2

    # Setup mocks for refresh
    mock_rpc_channel.send_command.side_effect = [
        ROOM_MAPPING_DATA_MAP_0,  # Room mapping refresh
    ]
    mock_mqtt_rpc_channel.send_command.side_effect = [
        MULTI_MAP_LIST_DATA,  # Maps refresh
    ]
    mock_map_rpc_channel.send_command.side_effect = [
        MAP_BYTES_RESPONSE_1,  # Map bytes refresh
    ]

    # Perform refresh
    await home_trait.refresh()

    # Verify cache was updated for current map
    assert home_trait.home_map_info
    assert home_trait.home_map_info.keys() == {0}
    assert home_trait.home_map_info[0].name == "Ground Floor"
    assert len(home_trait.home_map_info[0].rooms) == 2
    # Verify map content
    assert home_trait.home_map_content
    assert home_trait.home_map_content.keys() == {0}
    assert home_trait.home_map_content[0].image_content == TEST_IMAGE_CONTENT_1


async def test_current_map_data_property(
    home_trait: HomeTrait,
    mock_rpc_channel: AsyncMock,
    mock_mqtt_rpc_channel: AsyncMock,
    mock_map_rpc_channel: AsyncMock,
) -> None:
    """Test current_map_data property returns correct data."""
    # Setup discovery
    mock_rpc_channel.send_command.side_effect = [
        UPDATED_STATUS_MAP_123,  # Status after switching to map 123
        ROOM_MAPPING_DATA_MAP_123,  # Rooms for map 123
        UPDATED_STATUS_MAP_0,  # Status after switching back to map 0
        ROOM_MAPPING_DATA_MAP_0,  # Rooms for map 0
    ]
    mock_mqtt_rpc_channel.send_command.side_effect = [
        MULTI_MAP_LIST_DATA,  # Multi maps list
        {},  # LOAD_MULTI_MAP response for map 123
        {},  # LOAD_MULTI_MAP response back to map 0
    ]
    mock_map_rpc_channel.send_command.side_effect = [
        MAP_BYTES_RESPONSE_2,  # Map bytes for 123
        MAP_BYTES_RESPONSE_1,  # Map bytes for 0
    ]

    await home_trait.discover_home()

    # Test current map data (should be map 0)
    current_data = home_trait.current_map_data
    assert current_data is not None
    assert current_data.map_flag == 0
    assert current_data.name == "Ground Floor"

    # Test when no cache exists
    home_trait._home_map_info = None
    assert home_trait.current_map_data is None


async def test_discover_home_device_busy_cleaning(
    status_trait: StatusTrait,
    home_trait: HomeTrait,
    mock_rpc_channel: AsyncMock,
    mock_mqtt_rpc_channel: AsyncMock,
    mock_map_rpc_channel: AsyncMock,
    device_cache: DeviceCache,
) -> None:
    """Test that discovery raises RoborockDeviceBusy when device is cleaning.

    This tests the initial failure scenario during discovery where the device
    is busy, then a retry attempt where the device is still busy, then finally
    a successful attempt to run discovery when the device is idle.
    """
    # Set the status trait state to cleaning
    status_trait.state = RoborockStateCode.cleaning

    # Attempt to discover home while cleaning
    with pytest.raises(RoborockDeviceBusy, match="Cannot perform home discovery while the device is cleaning"):
        await home_trait.discover_home()

    # Verify no RPC calls were made (discovery was prevented)
    assert mock_rpc_channel.send_command.call_count == 0
    assert mock_mqtt_rpc_channel.send_command.call_count == 0

    # Setup mocks for refresh
    mock_rpc_channel.send_command.side_effect = [
        ROOM_MAPPING_DATA_MAP_0,  # Room mapping refresh
    ]
    mock_mqtt_rpc_channel.send_command.side_effect = [
        MULTI_MAP_LIST_DATA,  # Maps refresh
    ]
    mock_map_rpc_channel.send_command.side_effect = [
        MAP_BYTES_RESPONSE_1,  # Map bytes refresh
    ]

    # Now attempt to refresh the device while cleaning. This should still fail
    # home discovery but allow refresh to update the current map.
    await home_trait.refresh()

    # Verify the home information is now populated
    current_data = home_trait.current_map_data
    assert current_data is not None
    assert current_data.map_flag == 0
    assert current_data.name == "Ground Floor"
    assert home_trait.home_map_info is not None
    assert home_trait.home_map_info.keys() == {0}
    assert home_trait.home_map_content is not None
    assert home_trait.home_map_content.keys() == {0}
    map_0_content = home_trait.home_map_content[0]
    assert map_0_content is not None
    assert map_0_content.image_content == TEST_IMAGE_CONTENT_1
    assert map_0_content.map_data is not None

    # Verify the persistent cache has not been updated since discovery
    # has not fully completed.
    cache_data = await device_cache.get()
    assert not cache_data.home_map_info
    assert not cache_data.home_map_content_base64

    # Set the status trait state to idle which will mean we can attempt discovery
    # on the next refresh. This should have the result of updating the
    # persistent cache which is verified below.
    status_trait.state = RoborockStateCode.idle

    # Setup mocks for the discovery process
    mock_rpc_channel.send_command.side_effect = [
        UPDATED_STATUS_MAP_123,  # Status after switching to map 123
        ROOM_MAPPING_DATA_MAP_123,  # Rooms for map 123
        UPDATED_STATUS_MAP_0,  # Status after switching back to map 0
        ROOM_MAPPING_DATA_MAP_0,  # Rooms for map 0
    ]
    mock_mqtt_rpc_channel.send_command.side_effect = [
        MULTI_MAP_LIST_DATA,  # Multi maps list
        {},  # LOAD_MULTI_MAP response for map 123
        {},  # LOAD_MULTI_MAP response back to map 0
    ]
    mock_map_rpc_channel.send_command.side_effect = [
        MAP_BYTES_RESPONSE_2,  # Map bytes for 123
        MAP_BYTES_RESPONSE_1,  # Map bytes for 0
    ]

    # Refreshing should now perform discovery successfully
    await home_trait.refresh()

    # Verify we now have all of the information populated from discovery
    assert home_trait.home_map_info is not None
    assert home_trait.home_map_info.keys() == {0, 123}
    assert home_trait.home_map_content is not None
    assert home_trait.home_map_content.keys() == {0, 123}

    # Verify the persistent cache has been updated
    device_cache_data = await device_cache.get()
    assert device_cache_data.home_map_info is not None
    assert len(device_cache_data.home_map_info) == 2
    assert device_cache_data.home_map_content_base64 is not None
    assert len(device_cache_data.home_map_content_base64) == 2


async def test_refresh_falls_back_when_map_switch_action_locked(
    status_trait: StatusTrait,
    home_trait: HomeTrait,
    mock_rpc_channel: AsyncMock,
    mock_mqtt_rpc_channel: AsyncMock,
    mock_map_rpc_channel: AsyncMock,
    device_cache: DeviceCache,
) -> None:
    """Test that refresh falls back to current map when map switching is locked."""
    # Discovery attempt: we can list maps, but switching maps fails with -10007.
    mock_mqtt_rpc_channel.send_command.side_effect = [
        MULTI_MAP_LIST_DATA,  # Maps refresh during discover_home()
        RoborockInvalidStatus({"code": -10007, "message": "invalid status"}),  # LOAD_MULTI_MAP action locked
        MULTI_MAP_LIST_DATA,  # Maps refresh during refresh() fallback
    ]

    # Fallback refresh should still be able to refresh the current map.
    mock_rpc_channel.send_command.side_effect = [
        ROOM_MAPPING_DATA_MAP_0,  # Rooms for current map
    ]
    mock_map_rpc_channel.send_command.side_effect = [
        MAP_BYTES_RESPONSE_1,  # Map bytes for current map
    ]

    await home_trait.refresh()

    current_data = home_trait.current_map_data
    assert current_data is not None
    assert current_data.map_flag == 0
    assert current_data.name == "Ground Floor"

    assert home_trait.home_map_info is not None
    assert home_trait.home_map_info.keys() == {0}
    assert home_trait.home_map_content is not None
    assert home_trait.home_map_content.keys() == {0}
    map_0_content = home_trait.home_map_content[0]
    assert map_0_content.image_content == TEST_IMAGE_CONTENT_1

    # Discovery did not complete, so the persistent cache should not be updated.
    cache_data = await device_cache.get()
    assert not cache_data.home_map_info
    assert not cache_data.home_map_content_base64


async def test_single_map_no_switching(
    home_trait: HomeTrait,
    mock_rpc_channel: AsyncMock,
    mock_mqtt_rpc_channel: AsyncMock,
    mock_map_rpc_channel: AsyncMock,
) -> None:
    """Test that single map discovery doesn't trigger map switching."""
    mock_rpc_channel.send_command.side_effect = [
        ROOM_MAPPING_DATA_MAP_0,  # Rooms for the single map
    ]
    mock_mqtt_rpc_channel.send_command.side_effect = [
        MULTI_MAP_LIST_SINGLE_MAP_DATA,  # Single map list
    ]
    mock_map_rpc_channel.send_command.side_effect = [
        MAP_BYTES_RESPONSE_1,  # Map bytes for the single map
    ]

    await home_trait.discover_home()

    # Verify cache is populated
    assert home_trait.home_map_info is not None
    assert home_trait.home_map_info.keys() == {0}
    assert home_trait.home_map_content is not None
    assert home_trait.home_map_content.keys() == {0}

    # Verify no LOAD_MULTI_MAP commands were sent (no map switching)
    load_map_calls = [
        call
        for call in mock_mqtt_rpc_channel.send_command.call_args_list
        if call[1].get("command") == RoborockCommand.LOAD_MULTI_MAP
    ]
    assert len(load_map_calls) == 0


async def test_refresh_map_info_room_override_and_addition_logic(
    home_trait: HomeTrait,
    rooms_trait: RoomsTrait,
) -> None:
    """Test the room override and addition logic in _refresh_map_info.

    This test verifies:
    1. Room with "Unknown" does not override existing room from map_info
    2. Room with valid name overrides existing room from map_info
    3. Room with "Unknown" is added if not already in rooms
    4. Room with valid name is added if not already in rooms
    """
    map_info = MultiMapsListMapInfo(
        map_flag=0,
        name="Test Map",
        rooms=[
            MultiMapsListRoom(
                id=16,
                iot_name_id="2362048",
                iot_name="Kitchen from map_info",
            ),
            MultiMapsListRoom(
                id=19,
                iot_name_id="2362042",
                iot_name="Bedroom from map_info",
            ),
        ],
    )

    # Mock rooms_trait to return multiple rooms covering all scenarios:
    # - segment_id 16 with "Unknown": exists in map_info, should NOT override
    # - segment_id 19 with valid name: exists in map_info, should override
    # - segment_id 17 with "Unknown": not in map_info, should be added
    # - segment_id 18 with valid name: not in map_info, should be added
    rooms_trait.rooms = [
        NamedRoomMapping(segment_id=16, iot_id="2362048", name="Unknown"),  # Exists in map_info, should not override
        NamedRoomMapping(
            segment_id=19, iot_id="2362042", name="Updated Bedroom Name"
        ),  # Exists in map_info, should override
        NamedRoomMapping(segment_id=17, iot_id="2362044", name="Unknown"),  # Not in map_info, should be added
        NamedRoomMapping(segment_id=18, iot_id="2362041", name="Example room 3"),  # Not in map_info, should be added
    ]

    # Mock rooms_trait.refresh to prevent actual device calls
    with patch.object(rooms_trait, "refresh", new_callable=AsyncMock):
        result = await home_trait._refresh_map_info(map_info)

    assert result.map_flag == 0
    assert result.name == "Test Map"
    assert len(result.rooms) == 4

    # Sort rooms by segment_id for consistent assertions
    sorted_rooms = sorted(result.rooms, key=lambda r: r.segment_id)

    # Room 16: from map_info, kept (not overridden by Unknown)
    assert sorted_rooms[0].segment_id == 16
    assert sorted_rooms[0].name == "Kitchen from map_info"
    assert sorted_rooms[0].iot_id == "2362048"

    # Room 17: from rooms_trait with "Unknown", added because not in map_info
    assert sorted_rooms[1].segment_id == 17
    assert sorted_rooms[1].name == "Unknown"
    assert sorted_rooms[1].iot_id == "2362044"

    # Room 18: from rooms_trait with valid name, added because not in map_info
    assert sorted_rooms[2].segment_id == 18
    assert sorted_rooms[2].name == "Example room 3"
    assert sorted_rooms[2].iot_id == "2362041"

    # Room 19: from map_info, overridden by rooms_trait with valid name
    assert sorted_rooms[3].segment_id == 19
    assert sorted_rooms[3].name == "Updated Bedroom Name"
    assert sorted_rooms[3].iot_id == "2362042"