Debian Codegraph @

tests/test_bluez.py

raw
1 from typing import Any
2 from unittest.mock import AsyncMock, MagicMock, patch
3
4 import pytest
5 from bleak.backends.bluezdbus import defs
6 from bleak.backends.bluezdbus.manager import DeviceWatcher
7 from bleak.backends.device import BLEDevice
8 from bleak.exc import BleakError
9
10 import bleak_retry_connector
11 from bleak_retry_connector import (
12 AllocationChange,
13 AllocationChangeEvent,
14 Allocations,
15 BleakSlotManager,
16 device_source,
17 )
18 from bleak_retry_connector.bluez import (
19 adapter_path_from_device_path,
20 ble_device_from_properties,
21 clear_cache,
22 get_bluez_device,
23 get_connected_devices,
24 get_device_by_adapter,
25 path_from_ble_device,
26 stop_discovery,
27 wait_for_device_to_reappear,
28 wait_for_disconnect,
29 )
30
31 pytestmark = pytest.mark.asyncio
32
33
34 async def test_slot_manager(mock_linux):
35 """Test the slot manager"""
36
37 class FakeBluezManager:
38 def __init__(self):
39 self.watchers: set[DeviceWatcher] = set()
40 self._properties = {
41 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46": {
42 "UUID": "service",
43 "Primary": True,
44 "Characteristics": [],
45 defs.DEVICE_INTERFACE: {
46 "Address": "FA:23:9D:AA:45:46",
47 "Alias": "FA:23:9D:AA:45:46",
48 "RSSI": -30,
49 },
50 defs.GATT_SERVICE_INTERFACE: True,
51 },
52 "/org/bluez/hci1/dev_FA_23_9D_AA_45_46": {
53 "UUID": "service",
54 "Primary": True,
55 "Characteristics": [],
56 defs.DEVICE_INTERFACE: {
57 "Connected": True,
58 "Address": "FA:23:9D:AA:45:46",
59 "Alias": "FA:23:9D:AA:45:46",
60 "RSSI": -79,
61 },
62 defs.GATT_SERVICE_INTERFACE: True,
63 },
64 "/org/bluez/hci2/dev_FA_23_9D_AA_45_46": {
65 "UUID": "service",
66 "Primary": True,
67 "Characteristics": [],
68 defs.DEVICE_INTERFACE: {
69 "Connected": True,
70 "Address": "FA:23:9D:AA:45:46",
71 "Alias": "FA:23:9D:AA:45:46",
72 "RSSI": -80,
73 },
74 defs.GATT_SERVICE_INTERFACE: True,
75 },
76 "/org/bluez/hci3/dev_FA_23_9D_AA_45_46": {
77 "UUID": "service",
78 "Primary": True,
79 "Characteristics": [],
80 defs.DEVICE_INTERFACE: {
81 "Address": "FA:23:9D:AA:45:46",
82 "Alias": "FA:23:9D:AA:45:46",
83 "RSSI": -31,
84 },
85 defs.GATT_SERVICE_INTERFACE: True,
86 },
87 }
88
89 def add_device_watcher(self, path: str, **kwargs: Any) -> DeviceWatcher:
90 """Add a watcher for device changes."""
91 watcher = DeviceWatcher(path, **kwargs)
92 self.watchers.add(watcher)
93 return watcher
94
95 def remove_device_watcher(self, watcher: DeviceWatcher) -> None:
96 """Remove a watcher for device changes."""
97 self.watchers.remove(watcher)
98
99 def is_connected(self, path: str) -> bool:
100 """Check if device is connected."""
101 return False
102
103 bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock(
104 return_value=FakeBluezManager()
105 )
106 bleak_retry_connector.bluez.defs = defs
107
108 slot_manager = BleakSlotManager()
109
110 await slot_manager.async_setup()
111 slot_manager.register_adapter("hci0", 1)
112 slot_manager.register_adapter("hci1", 2)
113 slot_manager.register_adapter("hci2", 1)
114 changes = []
115
116 def _failing_allocation_callback(event: AllocationChangeEvent) -> None:
117 raise Exception("Test")
118
119 def _allocation_callback(event: AllocationChangeEvent) -> None:
120 change = event.change
121 path = event.path
122 adapter = event.adapter
123 address = event.address
124
125 changes.append((change, path, adapter, address))
126
127 cancel_fail = slot_manager.register_allocation_callback(
128 _failing_allocation_callback
129 )
130 cancel = slot_manager.register_allocation_callback(_allocation_callback)
131
132 ble_device_hci2 = ble_device_from_properties(
133 "/org/bluez/hci2/dev_FA_23_9D_AA_45_45",
134 {
135 "Address": "FA:23:9D:AA:45:45",
136 "Alias": "FA:23:9D:AA:45:45",
137 "RSSI": -30,
138 },
139 )
140 ble_device_hci2_already_connected = ble_device_from_properties(
141 "/org/bluez/hci2/dev_FA_23_9D_AA_45_46",
142 {
143 "Address": "FA:23:9D:AA:45:46",
144 "Alias": "FA:23:9D:AA:45:46",
145 "RSSI": -30,
146 },
147 )
148 ble_device_hci0 = ble_device_from_properties(
149 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
150 {
151 "Address": "FA:23:9D:AA:45:46",
152 "Alias": "FA:23:9D:AA:45:46",
153 "RSSI": -30,
154 },
155 )
156 ble_device_hci0_2 = ble_device_from_properties(
157 "/org/bluez/hci0/dev_FA_23_9D_AA_45_47",
158 {
159 "Address": "FA:23:9D:AA:45:47",
160 "Alias": "FA:23:9D:AA:45:47",
161 "RSSI": -30,
162 },
163 )
164
165 assert slot_manager.allocate_slot(ble_device_hci2) is False
166 assert not changes
167 # Make sure we can allocate an already connected device
168 # since there is always a race condition between the
169 # slot manager and the device connecting
170 assert slot_manager.allocate_slot(ble_device_hci2_already_connected) is True
171 assert not changes
172
173 assert slot_manager.allocate_slot(ble_device_hci0) is True
174 assert changes == [
175 (
176 AllocationChange.ALLOCATED,
177 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
178 "hci0",
179 "FA:23:9D:AA:45:46",
180 )
181 ]
182 assert slot_manager._get_allocations("hci0") == [
183 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"
184 ]
185 assert slot_manager.get_allocations("hci0") == Allocations(
186 "hci0",
187 1,
188 0,
189 ["FA:23:9D:AA:45:46"],
190 )
191
192 # Make sure we can allocate the same device again
193 assert slot_manager.allocate_slot(ble_device_hci0) is True
194 assert changes == [
195 (
196 AllocationChange.ALLOCATED,
197 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
198 "hci0",
199 "FA:23:9D:AA:45:46",
200 ),
201 ]
202 assert slot_manager._get_allocations("hci0") == [
203 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"
204 ]
205 assert slot_manager.get_allocations("hci0") == Allocations(
206 "hci0",
207 1,
208 0,
209 ["FA:23:9D:AA:45:46"],
210 )
211 assert slot_manager.allocate_slot(ble_device_hci0_2) is False
212 assert changes == [
213 (
214 AllocationChange.ALLOCATED,
215 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
216 "hci0",
217 "FA:23:9D:AA:45:46",
218 ),
219 ]
220 assert slot_manager._get_allocations("hci0") == [
221 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"
222 ]
223 assert slot_manager.get_allocations("hci0") == Allocations(
224 "hci0",
225 1,
226 0,
227 ["FA:23:9D:AA:45:46"],
228 )
229 watcher: DeviceWatcher = slot_manager._allocations_by_adapter["hci0"][
230 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"
231 ]
232 watcher.on_connected_changed(True)
233 assert slot_manager._get_allocations("hci0") == [
234 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"
235 ]
236 assert slot_manager.get_allocations("hci0") == Allocations(
237 "hci0",
238 1,
239 0,
240 ["FA:23:9D:AA:45:46"],
241 )
242 assert changes == [
243 (
244 AllocationChange.ALLOCATED,
245 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
246 "hci0",
247 "FA:23:9D:AA:45:46",
248 ),
249 ]
250 watcher.on_connected_changed(False)
251 assert changes == [
252 (
253 AllocationChange.ALLOCATED,
254 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
255 "hci0",
256 "FA:23:9D:AA:45:46",
257 ),
258 (
259 AllocationChange.RELEASED,
260 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
261 "hci0",
262 "FA:23:9D:AA:45:46",
263 ),
264 ]
265 assert slot_manager._get_allocations("hci0") == []
266 assert slot_manager.get_allocations("hci0") == Allocations(
267 "hci0",
268 1,
269 1,
270 [],
271 )
272 assert slot_manager.allocate_slot(ble_device_hci0) is True
273 assert slot_manager._get_allocations("hci0") == [
274 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"
275 ]
276 assert slot_manager.get_allocations("hci0") == Allocations(
277 "hci0",
278 1,
279 0,
280 ["FA:23:9D:AA:45:46"],
281 )
282 assert changes == [
283 (
284 AllocationChange.ALLOCATED,
285 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
286 "hci0",
287 "FA:23:9D:AA:45:46",
288 ),
289 (
290 AllocationChange.RELEASED,
291 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
292 "hci0",
293 "FA:23:9D:AA:45:46",
294 ),
295 (
296 AllocationChange.ALLOCATED,
297 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
298 "hci0",
299 "FA:23:9D:AA:45:46",
300 ),
301 ]
302
303 assert slot_manager.diagnostics() == {
304 "adapter_slots": {"hci0": 1, "hci1": 2, "hci2": 1},
305 "allocations_by_adapter": {
306 "hci0": ["/org/bluez/hci0/dev_FA_23_9D_AA_45_46"],
307 "hci1": ["/org/bluez/hci1/dev_FA_23_9D_AA_45_46"],
308 "hci2": ["/org/bluez/hci2/dev_FA_23_9D_AA_45_46"],
309 },
310 "manager": True,
311 }
312
313 slot_manager.release_slot(ble_device_hci0)
314 assert changes == [
315 (
316 AllocationChange.ALLOCATED,
317 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
318 "hci0",
319 "FA:23:9D:AA:45:46",
320 ),
321 (
322 AllocationChange.RELEASED,
323 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
324 "hci0",
325 "FA:23:9D:AA:45:46",
326 ),
327 (
328 AllocationChange.ALLOCATED,
329 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
330 "hci0",
331 "FA:23:9D:AA:45:46",
332 ),
333 (
334 AllocationChange.RELEASED,
335 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
336 "hci0",
337 "FA:23:9D:AA:45:46",
338 ),
339 ]
340 assert slot_manager._get_allocations("hci0") == []
341 assert slot_manager.get_allocations("hci0") == Allocations(
342 "hci0",
343 1,
344 1,
345 [],
346 )
347 assert slot_manager.allocate_slot(ble_device_hci0) is True
348 assert changes == [
349 (
350 AllocationChange.ALLOCATED,
351 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
352 "hci0",
353 "FA:23:9D:AA:45:46",
354 ),
355 (
356 AllocationChange.RELEASED,
357 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
358 "hci0",
359 "FA:23:9D:AA:45:46",
360 ),
361 (
362 AllocationChange.ALLOCATED,
363 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
364 "hci0",
365 "FA:23:9D:AA:45:46",
366 ),
367 (
368 AllocationChange.RELEASED,
369 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
370 "hci0",
371 "FA:23:9D:AA:45:46",
372 ),
373 (
374 AllocationChange.ALLOCATED,
375 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
376 "hci0",
377 "FA:23:9D:AA:45:46",
378 ),
379 ]
380 assert slot_manager._get_allocations("hci0") == [
381 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"
382 ]
383 assert slot_manager.get_allocations("hci0") == Allocations(
384 "hci0",
385 1,
386 0,
387 ["FA:23:9D:AA:45:46"],
388 )
389 slot_manager.remove_adapter("hci0")
390 assert changes == [
391 (
392 AllocationChange.ALLOCATED,
393 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
394 "hci0",
395 "FA:23:9D:AA:45:46",
396 ),
397 (
398 AllocationChange.RELEASED,
399 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
400 "hci0",
401 "FA:23:9D:AA:45:46",
402 ),
403 (
404 AllocationChange.ALLOCATED,
405 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
406 "hci0",
407 "FA:23:9D:AA:45:46",
408 ),
409 (
410 AllocationChange.RELEASED,
411 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
412 "hci0",
413 "FA:23:9D:AA:45:46",
414 ),
415 (
416 AllocationChange.ALLOCATED,
417 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
418 "hci0",
419 "FA:23:9D:AA:45:46",
420 ),
421 ]
422 assert slot_manager.allocate_slot(ble_device_hci0) is True
423 assert changes == [
424 (
425 AllocationChange.ALLOCATED,
426 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
427 "hci0",
428 "FA:23:9D:AA:45:46",
429 ),
430 (
431 AllocationChange.RELEASED,
432 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
433 "hci0",
434 "FA:23:9D:AA:45:46",
435 ),
436 (
437 AllocationChange.ALLOCATED,
438 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
439 "hci0",
440 "FA:23:9D:AA:45:46",
441 ),
442 (
443 AllocationChange.RELEASED,
444 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
445 "hci0",
446 "FA:23:9D:AA:45:46",
447 ),
448 (
449 AllocationChange.ALLOCATED,
450 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
451 "hci0",
452 "FA:23:9D:AA:45:46",
453 ),
454 ]
455 assert slot_manager.allocate_slot(ble_device_hci0_2) is True
456 assert changes == [
457 (
458 AllocationChange.ALLOCATED,
459 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
460 "hci0",
461 "FA:23:9D:AA:45:46",
462 ),
463 (
464 AllocationChange.RELEASED,
465 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
466 "hci0",
467 "FA:23:9D:AA:45:46",
468 ),
469 (
470 AllocationChange.ALLOCATED,
471 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
472 "hci0",
473 "FA:23:9D:AA:45:46",
474 ),
475 (
476 AllocationChange.RELEASED,
477 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
478 "hci0",
479 "FA:23:9D:AA:45:46",
480 ),
481 (
482 AllocationChange.ALLOCATED,
483 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
484 "hci0",
485 "FA:23:9D:AA:45:46",
486 ),
487 ]
488 cancel_fail()
489 cancel()
490
491
492 async def test_slot_manager_adapter_removal_during_disconnect(mock_linux):
493 """Test that adapter removal during disconnect doesn't cause KeyError."""
494
495 class FakeBluezManager:
496 def __init__(self):
497 self.watchers: set[DeviceWatcher] = set()
498 self._properties = {
499 "/org/bluez/hci1/dev_FA_23_9D_AA_45_46": {
500 defs.DEVICE_INTERFACE: {
501 "Connected": True,
502 "Address": "FA:23:9D:AA:45:46",
503 "Alias": "Test Device",
504 "RSSI": -60,
505 },
506 },
507 }
508
509 def add_device_watcher(self, path: str, **kwargs: Any) -> DeviceWatcher:
510 """Add a watcher for device changes."""
511 watcher = DeviceWatcher(path, **kwargs)
512 self.watchers.add(watcher)
513 return watcher
514
515 def remove_device_watcher(self, watcher: DeviceWatcher) -> None:
516 """Remove a watcher for device changes."""
517 self.watchers.discard(watcher)
518
519 def is_connected(self, path: str) -> bool:
520 """Check if device is connected."""
521 return False
522
523 bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock(
524 return_value=FakeBluezManager()
525 )
526 bleak_retry_connector.bluez.defs = defs
527
528 slot_manager = BleakSlotManager()
529 await slot_manager.async_setup()
530
531 # Register adapter and allocate a slot
532 slot_manager.register_adapter("hci1", 5)
533
534 ble_device = ble_device_from_properties(
535 "/org/bluez/hci1/dev_FA_23_9D_AA_45_46",
536 {
537 "Address": "FA:23:9D:AA:45:46",
538 "Alias": "Test Device",
539 "RSSI": -60,
540 },
541 )
542
543 # Allocate the slot
544 assert slot_manager.allocate_slot(ble_device) is True
545
546 # Store the watcher to simulate disconnect event later
547 watcher: DeviceWatcher = slot_manager._allocations_by_adapter["hci1"][
548 "/org/bluez/hci1/dev_FA_23_9D_AA_45_46"
549 ]
550
551 # Simulate adapter removal (e.g., adapter unplugged)
552 slot_manager.remove_adapter("hci1")
553
554 # Now simulate the disconnect event firing after adapter removal
555 # This should not raise a KeyError
556 watcher.on_connected_changed(False)
557
558 # Verify the adapter is gone and methods handle it gracefully
559 assert slot_manager._get_allocations("hci1") == []
560 assert slot_manager.get_allocations("hci1") == Allocations("hci1", 0, 0, [])
561
562
563 async def test_slot_manager_mac_os():
564 """Test the slot manager"""
565
566 bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock(
567 return_value=None
568 )
569 bleak_retry_connector.bluez.defs = defs
570
571 slot_manager = BleakSlotManager()
572
573 await slot_manager.async_setup()
574 slot_manager.register_adapter("hci0", 1)
575 slot_manager.register_adapter("hci1", 2)
576 slot_manager.register_adapter("hci2", 1)
577
578 ble_device_hci0 = ble_device_from_properties(
579 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
580 {
581 "Address": "FA:23:9D:AA:45:46",
582 "Alias": "FA:23:9D:AA:45:46",
583 "RSSI": -30,
584 },
585 )
586 ble_device_hci0_2 = ble_device_from_properties(
587 "/org/bluez/hci0/dev_FA_23_9D_AA_45_47",
588 {
589 "Address": "FA:23:9D:AA:45:47",
590 "Alias": "FA:23:9D:AA:45:47",
591 "RSSI": -30,
592 },
593 )
594
595 assert slot_manager.allocate_slot(ble_device_hci0) is True
596 assert slot_manager._get_allocations("hci0") == []
597 assert slot_manager.allocate_slot(ble_device_hci0_2) is True
598 assert slot_manager._get_allocations("hci0") == []
599
600 assert slot_manager.allocate_slot(ble_device_hci0) is True
601 assert slot_manager._get_allocations("hci0") == []
602 slot_manager.release_slot(ble_device_hci0)
603 assert slot_manager._get_allocations("hci0") == []
604 slot_manager.remove_adapter("hci0")
605
606
607 async def test_device_source():
608 ble_device_hci0_2 = BLEDevice(
609 "FA:23:9D:AA:45:46",
610 "FA:23:9D:AA:45:46",
611 {
612 "source": "aa:bb:cc:dd:ee:ff",
613 "path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_47",
614 "props": {},
615 },
616 )
617
618 assert device_source(ble_device_hci0_2) == "aa:bb:cc:dd:ee:ff"
619
620
621 async def test_path_from_ble_device():
622 ble_device_hci0_2 = BLEDevice(
623 "FA:23:9D:AA:45:46",
624 "FA:23:9D:AA:45:46",
625 {
626 "source": "aa:bb:cc:dd:ee:ff",
627 "path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_47",
628 "props": {},
629 },
630 )
631
632 assert (
633 path_from_ble_device(ble_device_hci0_2)
634 == "/org/bluez/hci0/dev_FA_23_9D_AA_45_47"
635 )
636
637
638 async def test_wait_for_device_to_reappear(mock_linux):
639 class FakeBluezManager:
640 def __init__(self):
641 self.watchers: set[DeviceWatcher] = set()
642 self._properties = {
643 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46": {
644 "UUID": "service",
645 "Primary": True,
646 "Characteristics": [],
647 defs.DEVICE_INTERFACE: {
648 "Address": "FA:23:9D:AA:45:46",
649 "Alias": "FA:23:9D:AA:45:46",
650 "RSSI": -30,
651 },
652 defs.GATT_SERVICE_INTERFACE: True,
653 },
654 "/org/bluez/hci1/dev_FA_23_9D_AA_45_46": {
655 "UUID": "service",
656 "Primary": True,
657 "Characteristics": [],
658 defs.DEVICE_INTERFACE: {
659 "Connected": True,
660 "Address": "FA:23:9D:AA:45:46",
661 "Alias": "FA:23:9D:AA:45:46",
662 "RSSI": -79,
663 },
664 defs.GATT_SERVICE_INTERFACE: True,
665 },
666 }
667
668 def add_device_watcher(self, path: str, **kwargs: Any) -> DeviceWatcher:
669 """Add a watcher for device changes."""
670 watcher = DeviceWatcher(path, **kwargs)
671 self.watchers.add(watcher)
672 return watcher
673
674 def remove_device_watcher(self, watcher: DeviceWatcher) -> None:
675 """Remove a watcher for device changes."""
676 self.watchers.remove(watcher)
677
678 def is_connected(self, path: str) -> bool:
679 """Check if device is connected."""
680 return False
681
682 bluez_manager = FakeBluezManager()
683 bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock(
684 return_value=bluez_manager
685 )
686 bleak_retry_connector.bluez.defs = defs
687
688 ble_device_hci0 = BLEDevice(
689 "FA:23:9D:AA:45:46",
690 "FA:23:9D:AA:45:46",
691 {
692 "source": "aa:bb:cc:dd:ee:ff",
693 "path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
694 "props": {},
695 },
696 )
697
698 assert await wait_for_device_to_reappear(ble_device_hci0, 1) is True
699 del bluez_manager._properties["/org/bluez/hci0/dev_FA_23_9D_AA_45_46"]
700 assert await wait_for_device_to_reappear(ble_device_hci0, 1) is True
701 del bluez_manager._properties["/org/bluez/hci1/dev_FA_23_9D_AA_45_46"]
702 with patch.object(bleak_retry_connector.bluez, "REAPPEAR_WAIT_INTERVAL", 0.025):
703 assert await wait_for_device_to_reappear(ble_device_hci0, 0.1) is False
704
705
706 async def test_adapter_path_from_device_path(mock_linux):
707 assert (
708 adapter_path_from_device_path("/org/bluez/hci1/dev_FA_23_9D_AA_45_46")
709 == "/org/bluez/hci1"
710 )
711
712
713 async def test_stop_discovery(mock_linux):
714 """Test stopping discovery"""
715
716 class FakeBluezManager:
717 def __init__(self) -> None:
718 """Mock initializer."""
719 self._bus = MagicMock(send=AsyncMock())
720
721 manager = FakeBluezManager()
722
723 bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock(
724 return_value=manager
725 )
726 bleak_retry_connector.bluez.defs = defs
727 bleak_retry_connector.bluez.Message = MagicMock()
728
729 await stop_discovery("hci0")
730 assert manager._bus.send.called
731
732
733 async def test_stop_discovery_no_manager(
734 mock_linux: None, caplog: pytest.LogCaptureFixture
735 ) -> None:
736 """Test stopping discovery no manager."""
737
738 bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock(
739 return_value=None
740 )
741 bleak_retry_connector.bluez.defs = defs
742 bleak_retry_connector.bluez.Message = MagicMock()
743
744 await stop_discovery("hci0")
745 assert "Failed to stop discovery" in caplog.text
746
747
748 async def test_wait_for_disconnect_not_linux(mock_macos):
749 """Non-Linux platforms fall back to a plain sleep."""
750 device = BLEDevice("AA:BB:CC:DD:EE:FF", "name", {"path": "/org/bluez/hci0/dev_x"})
751 sleeps: list[float] = []
752
753 async def fake_sleep(delay: float) -> None:
754 sleeps.append(delay)
755
756 with patch("bleak_retry_connector.bluez.asyncio.sleep", side_effect=fake_sleep):
757 await wait_for_disconnect(device, 0.25)
758
759 assert sleeps == [0.25]
760
761
762 async def test_wait_for_disconnect_no_path(mock_linux):
763 """Devices without a 'path' entry in details fall back to a plain sleep."""
764 device = BLEDevice("AA:BB:CC:DD:EE:FF", "name", {"source": "aa:bb:cc:dd:ee:ff"})
765 sleeps: list[float] = []
766
767 async def fake_sleep(delay: float) -> None:
768 sleeps.append(delay)
769
770 with patch("bleak_retry_connector.bluez.asyncio.sleep", side_effect=fake_sleep):
771 await wait_for_disconnect(device, 0.1)
772
773 assert sleeps == [0.1]
774
775
776 async def test_wait_for_disconnect_no_manager(
777 mock_linux: None, caplog: pytest.LogCaptureFixture
778 ) -> None:
779 """If no BlueZ manager is available, log and return without sleeping."""
780 device = BLEDevice(
781 "FA:23:9D:AA:45:46",
782 "FA:23:9D:AA:45:46",
783 {"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"},
784 )
785 with patch(
786 "bleak_retry_connector.bluez.get_global_bluez_manager_with_timeout",
787 AsyncMock(return_value=None),
788 ):
789 await wait_for_disconnect(device, 1.0)
790
791 assert "Failed to wait for disconnect because no manager" in caplog.text
792
793
794 async def test_wait_for_disconnect_waits_remaining_min_wait_time(mock_linux):
795 """When the device disconnects sooner than min_wait_time, sleep the remainder."""
796 device = BLEDevice(
797 "FA:23:9D:AA:45:46",
798 "FA:23:9D:AA:45:46",
799 {"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"},
800 )
801 manager = MagicMock()
802 manager._wait_condition = AsyncMock()
803 # Only wait_for_disconnect-issued sleeps land here (we don't patch global sleep).
804 sleeps: list[float] = []
805
806 async def fake_sleep(delay: float) -> None:
807 sleeps.append(delay)
808
809 # Patch the time module bound on bluez to return start=100.0, end=100.2
810 # without affecting asyncio internals that read the real clock.
811 fake_time = MagicMock()
812 fake_time.monotonic = MagicMock(side_effect=[100.0, 100.2])
813
814 with (
815 patch(
816 "bleak_retry_connector.bluez.get_global_bluez_manager_with_timeout",
817 AsyncMock(return_value=manager),
818 ),
819 patch.object(bleak_retry_connector.bluez, "time", fake_time),
820 patch("bleak_retry_connector.bluez.asyncio.sleep", side_effect=fake_sleep),
821 ):
822 await wait_for_disconnect(device, 1.0)
823
824 manager._wait_condition.assert_awaited_once_with(
825 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46", "Connected", False
826 )
827 # waited = 0.2, min_wait_time = 1.0, so remaining sleep should be 0.8.
828 assert sleeps == [pytest.approx(0.8)]
829
830
831 async def test_wait_for_disconnect_skips_extra_sleep_when_already_waited(
832 mock_linux: None,
833 ) -> None:
834 """If we already waited long enough, no extra sleep is issued."""
835 device = BLEDevice(
836 "FA:23:9D:AA:45:46",
837 "FA:23:9D:AA:45:46",
838 {"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"},
839 )
840 manager = MagicMock()
841 manager._wait_condition = AsyncMock()
842 sleeps: list[float] = []
843
844 async def fake_sleep(delay: float) -> None:
845 sleeps.append(delay)
846
847 fake_time = MagicMock()
848 fake_time.monotonic = MagicMock(side_effect=[100.0, 105.0])
849
850 with (
851 patch(
852 "bleak_retry_connector.bluez.get_global_bluez_manager_with_timeout",
853 AsyncMock(return_value=manager),
854 ),
855 patch.object(bleak_retry_connector.bluez, "time", fake_time),
856 patch("bleak_retry_connector.bluez.asyncio.sleep", side_effect=fake_sleep),
857 ):
858 await wait_for_disconnect(device, 1.0)
859
860 assert sleeps == []
861
862
863 async def test_wait_for_disconnect_zero_min_wait_time(mock_linux):
864 """min_wait_time=0 bypasses the timing branch entirely."""
865 device = BLEDevice(
866 "FA:23:9D:AA:45:46",
867 "FA:23:9D:AA:45:46",
868 {"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"},
869 )
870 manager = MagicMock()
871 manager._wait_condition = AsyncMock()
872 sleeps: list[float] = []
873
874 async def fake_sleep(delay: float) -> None:
875 sleeps.append(delay)
876
877 with (
878 patch(
879 "bleak_retry_connector.bluez.get_global_bluez_manager_with_timeout",
880 AsyncMock(return_value=manager),
881 ),
882 patch("bleak_retry_connector.bluez.asyncio.sleep", side_effect=fake_sleep),
883 ):
884 await wait_for_disconnect(device, 0)
885
886 manager._wait_condition.assert_awaited_once()
887 assert sleeps == []
888
889
890 async def test_wait_for_disconnect_bleak_error_triggers_reappear(
891 mock_linux: None, caplog: pytest.LogCaptureFixture
892 ) -> None:
893 """A BleakError from _wait_condition routes through wait_for_device_to_reappear."""
894 device = BLEDevice(
895 "FA:23:9D:AA:45:46",
896 "FA:23:9D:AA:45:46",
897 {"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"},
898 )
899 manager = MagicMock()
900 manager._wait_condition = AsyncMock(side_effect=BleakError("gone"))
901 reappear_calls: list[tuple[BLEDevice, float]] = []
902
903 async def fake_reappear(d, t):
904 reappear_calls.append((d, t))
905 return True
906
907 with (
908 patch(
909 "bleak_retry_connector.bluez.get_global_bluez_manager_with_timeout",
910 AsyncMock(return_value=manager),
911 ),
912 patch(
913 "bleak_retry_connector.bluez.wait_for_device_to_reappear",
914 side_effect=fake_reappear,
915 ),
916 ):
917 await wait_for_disconnect(device, 0.5)
918
919 assert reappear_calls == [(device, 0.5)]
920 assert "Device was removed from bus" in caplog.text
921
922
923 async def test_wait_for_disconnect_key_error_triggers_reappear(mock_linux):
924 """KeyError is treated the same as BleakError."""
925 device = BLEDevice(
926 "FA:23:9D:AA:45:46",
927 "FA:23:9D:AA:45:46",
928 {"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"},
929 )
930 manager = MagicMock()
931 manager._wait_condition = AsyncMock(side_effect=KeyError("missing"))
932 called = False
933
934 async def fake_reappear(d, t):
935 nonlocal called
936 called = True
937 return False
938
939 with (
940 patch(
941 "bleak_retry_connector.bluez.get_global_bluez_manager_with_timeout",
942 AsyncMock(return_value=manager),
943 ),
944 patch(
945 "bleak_retry_connector.bluez.wait_for_device_to_reappear",
946 side_effect=fake_reappear,
947 ),
948 ):
949 await wait_for_disconnect(device, 0.1)
950
951 assert called
952
953
954 async def test_wait_for_disconnect_unexpected_exception_swallowed(
955 mock_linux: None, caplog: pytest.LogCaptureFixture
956 ) -> None:
957 """Any other exception is logged and swallowed — no reappear fallback."""
958 device = BLEDevice(
959 "FA:23:9D:AA:45:46",
960 "FA:23:9D:AA:45:46",
961 {"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"},
962 )
963 manager = MagicMock()
964 manager._wait_condition = AsyncMock(side_effect=RuntimeError("boom"))
965 reappear_called = False
966
967 async def fake_reappear(d, t):
968 nonlocal reappear_called
969 reappear_called = True
970
971 with (
972 patch(
973 "bleak_retry_connector.bluez.get_global_bluez_manager_with_timeout",
974 AsyncMock(return_value=manager),
975 ),
976 patch(
977 "bleak_retry_connector.bluez.wait_for_device_to_reappear",
978 side_effect=fake_reappear,
979 ),
980 ):
981 await wait_for_disconnect(device, 0.1)
982
983 assert reappear_called is False
984 assert "Failed waiting for disconnect" in caplog.text
985
986
987 async def test_wait_for_device_to_reappear_debug_logging(mock_linux, caplog):
988 """Debug-level branches in wait_for_device_to_reappear log per iteration."""
989 import logging
990
991 caplog.set_level(logging.DEBUG, logger="bleak_retry_connector.bluez")
992
993 class BluezManager:
994 # Non-empty so _get_properties() returns truthy, but the device path
995 # is intentionally absent so the loop exhausts without finding it.
996 _properties: dict[str, dict[str, dict[str, str]]] = {
997 "/org/bluez/hci0/dev_OTHER": {defs.DEVICE_INTERFACE: {"Address": "x"}}
998 }
999
1000 def is_connected(self, path):
1001 return False
1002
1003 bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock(
1004 return_value=BluezManager()
1005 )
1006 bleak_retry_connector.bluez.defs = defs
1007
1008 device = BLEDevice(
1009 "FA:23:9D:AA:45:46",
1010 "FA:23:9D:AA:45:46",
1011 {"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"},
1012 )
1013 # Force the function-local `debug` flag True even if the logger level
1014 # isn't picked up via caplog (matches how real callers see it).
1015 with (
1016 patch.object(bleak_retry_connector.bluez, "REAPPEAR_WAIT_INTERVAL", 0.01),
1017 patch.object(
1018 bleak_retry_connector.bluez._LOGGER, "isEnabledFor", return_value=True
1019 ),
1020 ):
1021 result = await wait_for_device_to_reappear(device, 0.03)
1022
1023 assert result is False
1024 assert "Waiting" in caplog.text
1025 assert "did not re-appear" in caplog.text
1026
1027
1028 async def test_wait_for_device_to_reappear_no_debug_found(
1029 mock_linux: None,
1030 ) -> None:
1031 """With debug disabled, the success path returns True without logging."""
1032
1033 class BluezManager:
1034 _properties: dict[str, dict[str, dict[str, str]]] = {
1035 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46": {
1036 defs.DEVICE_INTERFACE: {"Address": "FA:23:9D:AA:45:46"}
1037 }
1038 }
1039
1040 def is_connected(self, path: str) -> bool:
1041 return False
1042
1043 bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock(
1044 return_value=BluezManager()
1045 )
1046 bleak_retry_connector.bluez.defs = defs
1047
1048 device = BLEDevice(
1049 "FA:23:9D:AA:45:46",
1050 "FA:23:9D:AA:45:46",
1051 {"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"},
1052 )
1053 with patch.object(
1054 bleak_retry_connector.bluez._LOGGER, "isEnabledFor", return_value=False
1055 ):
1056 assert await wait_for_device_to_reappear(device, 1) is True
1057
1058
1059 async def test_wait_for_device_to_reappear_no_debug_not_found(
1060 mock_linux: None,
1061 ) -> None:
1062 """With debug disabled, the loop exhausts and returns False silently."""
1063
1064 class BluezManager:
1065 _properties: dict[str, dict[str, dict[str, str]]] = {
1066 "/org/bluez/hci0/dev_OTHER": {defs.DEVICE_INTERFACE: {"Address": "x"}}
1067 }
1068
1069 def is_connected(self, path: str) -> bool:
1070 return False
1071
1072 bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock(
1073 return_value=BluezManager()
1074 )
1075 bleak_retry_connector.bluez.defs = defs
1076
1077 device = BLEDevice(
1078 "FA:23:9D:AA:45:46",
1079 "FA:23:9D:AA:45:46",
1080 {"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"},
1081 )
1082 with (
1083 patch.object(bleak_retry_connector.bluez, "REAPPEAR_WAIT_INTERVAL", 0.01),
1084 patch.object(
1085 bleak_retry_connector.bluez._LOGGER, "isEnabledFor", return_value=False
1086 ),
1087 ):
1088 assert await wait_for_device_to_reappear(device, 0.03) is False
1089
1090
1091 async def test_get_services_cache_returns_none_when_no_manager(
1092 mock_linux: None, monkeypatch: pytest.MonkeyPatch
1093 ) -> None:
1094 """When the bluez manager fetch returns None, _get_services_cache returns None."""
1095 from bleak_retry_connector.bluez import _get_services_cache
1096
1097 monkeypatch.setattr(
1098 bleak_retry_connector.bluez,
1099 "get_global_bluez_manager_with_timeout",
1100 AsyncMock(return_value=None),
1101 )
1102 assert await _get_services_cache() is None
1103
1104
1105 async def test_clear_cache_not_linux(mock_macos: None) -> None:
1106 """Non-Linux short-circuits and returns False."""
1107 assert await clear_cache("FA:23:9D:AA:45:46") is False
1108
1109
1110 async def test_clear_cache_no_device(
1111 mock_linux: None, monkeypatch: pytest.MonkeyPatch
1112 ) -> None:
1113 """If get_device returns None, clear_cache returns False without touching cache."""
1114 monkeypatch.setattr(
1115 bleak_retry_connector.bleak_manager,
1116 "get_global_bluez_manager",
1117 AsyncMock(return_value=None),
1118 )
1119 monkeypatch.setattr(
1120 bleak_retry_connector.bleak_manager,
1121 "get_global_bluez_manager_with_timeout",
1122 AsyncMock(return_value=None),
1123 )
1124 assert await clear_cache("FA:23:9D:AA:45:46") is False
1125
1126
1127 async def test_clear_cache_no_services_cache(
1128 mock_linux: None,
1129 monkeypatch: pytest.MonkeyPatch,
1130 caplog: pytest.LogCaptureFixture,
1131 ) -> None:
1132 """get_device succeeds but services cache is unavailable → warn + False."""
1133
1134 class FakeBluezManager:
1135 def __init__(self) -> None:
1136 self._properties = {
1137 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46": {
1138 defs.DEVICE_INTERFACE: {
1139 "Address": "FA:23:9D:AA:45:46",
1140 "Alias": "FA:23:9D:AA:45:46",
1141 },
1142 },
1143 }
1144
1145 manager = FakeBluezManager()
1146 monkeypatch.setattr(
1147 bleak_retry_connector.bleak_manager,
1148 "get_global_bluez_manager",
1149 AsyncMock(return_value=manager),
1150 )
1151 monkeypatch.setattr(
1152 bleak_retry_connector.bleak_manager,
1153 "get_global_bluez_manager_with_timeout",
1154 AsyncMock(return_value=manager),
1155 )
1156 monkeypatch.setattr(bleak_retry_connector.bluez, "defs", defs)
1157 monkeypatch.setattr(
1158 bleak_retry_connector.bluez,
1159 "_get_services_cache",
1160 AsyncMock(return_value=None),
1161 )
1162
1163 assert await clear_cache("FA:23:9D:AA:45:46") is False
1164 assert "no services cache" in caplog.text
1165
1166
1167 async def test_clear_cache_no_manager(
1168 mock_linux: None,
1169 monkeypatch: pytest.MonkeyPatch,
1170 caplog: pytest.LogCaptureFixture,
1171 ) -> None:
1172 """services cache returns dict but the manager fetch fails → warn + False."""
1173 fake_device = BLEDevice(
1174 "FA:23:9D:AA:45:46",
1175 "FA:23:9D:AA:45:46",
1176 {"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"},
1177 )
1178 monkeypatch.setattr(
1179 bleak_retry_connector.bluez,
1180 "get_device",
1181 AsyncMock(return_value=fake_device),
1182 )
1183 monkeypatch.setattr(
1184 bleak_retry_connector.bluez,
1185 "_get_services_cache",
1186 AsyncMock(return_value={}),
1187 )
1188 monkeypatch.setattr(
1189 bleak_retry_connector.bluez,
1190 "get_global_bluez_manager_with_timeout",
1191 AsyncMock(return_value=None),
1192 )
1193
1194 assert await clear_cache("FA:23:9D:AA:45:46") is False
1195 assert "no manager" in caplog.text
1196
1197
1198 async def test_clear_cache_sends_remove_device(
1199 mock_linux: None, monkeypatch: pytest.MonkeyPatch
1200 ) -> None:
1201 """Happy path: matching paths are popped from cache and RemoveDevice is sent."""
1202 sent_kwargs: list[dict[str, Any]] = []
1203
1204 class FakeBus:
1205 async def send(self, message: Any) -> None:
1206 return None
1207
1208 class FakeBluezManager:
1209 def __init__(self) -> None:
1210 self._bus = FakeBus()
1211 self._services_cache = {
1212 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46": "svc0",
1213 "/org/bluez/hci1/dev_FA_23_9D_AA_45_46": "svc1",
1214 }
1215 self._properties = {
1216 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46": {
1217 defs.DEVICE_INTERFACE: {
1218 "Address": "FA:23:9D:AA:45:46",
1219 "Alias": "FA:23:9D:AA:45:46",
1220 "RSSI": -30,
1221 },
1222 },
1223 "/org/bluez/hci1/dev_FA_23_9D_AA_45_46": {
1224 defs.DEVICE_INTERFACE: {
1225 "Address": "FA:23:9D:AA:45:46",
1226 "Alias": "FA:23:9D:AA:45:46",
1227 "RSSI": -60,
1228 },
1229 },
1230 }
1231
1232 manager = FakeBluezManager()
1233
1234 def _record_message(**kw: Any) -> dict[str, Any]:
1235 sent_kwargs.append(kw)
1236 return kw
1237
1238 fake_message = MagicMock(side_effect=_record_message)
1239 monkeypatch.setattr(
1240 bleak_retry_connector.bleak_manager,
1241 "get_global_bluez_manager",
1242 AsyncMock(return_value=manager),
1243 )
1244 monkeypatch.setattr(
1245 bleak_retry_connector.bleak_manager,
1246 "get_global_bluez_manager_with_timeout",
1247 AsyncMock(return_value=manager),
1248 )
1249 monkeypatch.setattr(bleak_retry_connector.bluez, "defs", defs)
1250 monkeypatch.setattr(bleak_retry_connector.bluez, "Message", fake_message)
1251
1252 assert await clear_cache("FA:23:9D:AA:45:46") is True
1253 assert manager._services_cache == {}
1254 assert len(sent_kwargs) == 2
1255 assert {kw["path"] for kw in sent_kwargs} == {"/org/bluez/hci0", "/org/bluez/hci1"}
1256 assert all(kw["member"] == "RemoveDevice" for kw in sent_kwargs)
1257
1258
1259 async def test_clear_cache_swallows_get_device_exception(
1260 mock_linux: None, monkeypatch: pytest.MonkeyPatch
1261 ) -> None:
1262 """A raising get_device must not propagate out of clear_cache.
1263
1264 Callers (e.g. establish_connection's retry loop) rely on clear_cache being
1265 safe to call from failure-handling paths where D-Bus may itself be flaky.
1266 """
1267 monkeypatch.setattr(
1268 bleak_retry_connector.bluez,
1269 "get_device",
1270 AsyncMock(side_effect=RuntimeError("dbus exploded")),
1271 )
1272 assert await clear_cache("FA:23:9D:AA:45:46") is False
1273
1274
1275 async def test_get_device_by_adapter_not_linux(mock_macos: None) -> None:
1276 """Non-Linux returns None immediately."""
1277 assert await get_device_by_adapter("FA:23:9D:AA:45:46", "hci0") is None
1278
1279
1280 async def test_get_device_by_adapter_no_properties(
1281 mock_linux: None, monkeypatch: pytest.MonkeyPatch
1282 ) -> None:
1283 """No bluez manager yields no properties → returns None."""
1284 monkeypatch.setattr(
1285 bleak_retry_connector.bleak_manager,
1286 "get_global_bluez_manager",
1287 AsyncMock(return_value=None),
1288 )
1289 assert await get_device_by_adapter("FA:23:9D:AA:45:46", "hci0") is None
1290
1291
1292 async def test_get_device_by_adapter_path_missing(
1293 mock_linux: None, monkeypatch: pytest.MonkeyPatch
1294 ) -> None:
1295 """Path absent from properties → returns None."""
1296
1297 class FakeBluezManager:
1298 def __init__(self) -> None:
1299 self._properties = {
1300 "/org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF": {
1301 defs.DEVICE_INTERFACE: {
1302 "Address": "AA:BB:CC:DD:EE:FF",
1303 "Alias": "AA:BB:CC:DD:EE:FF",
1304 },
1305 },
1306 }
1307
1308 manager = FakeBluezManager()
1309 monkeypatch.setattr(
1310 bleak_retry_connector.bleak_manager,
1311 "get_global_bluez_manager",
1312 AsyncMock(return_value=manager),
1313 )
1314 monkeypatch.setattr(bleak_retry_connector.bluez, "defs", defs)
1315
1316 assert await get_device_by_adapter("FA:23:9D:AA:45:46", "hci0") is None
1317
1318
1319 async def test_get_device_by_adapter_returns_device(
1320 mock_linux: None, monkeypatch: pytest.MonkeyPatch
1321 ) -> None:
1322 """Matching adapter+address returns the BLEDevice."""
1323
1324 class FakeBluezManager:
1325 def __init__(self) -> None:
1326 self._properties = {
1327 "/org/bluez/hci1/dev_FA_23_9D_AA_45_46": {
1328 defs.DEVICE_INTERFACE: {
1329 "Address": "FA:23:9D:AA:45:46",
1330 "Alias": "Test Device",
1331 "RSSI": -60,
1332 },
1333 },
1334 }
1335
1336 manager = FakeBluezManager()
1337 monkeypatch.setattr(
1338 bleak_retry_connector.bleak_manager,
1339 "get_global_bluez_manager",
1340 AsyncMock(return_value=manager),
1341 )
1342 monkeypatch.setattr(bleak_retry_connector.bluez, "defs", defs)
1343
1344 device = await get_device_by_adapter("FA:23:9D:AA:45:46", "hci1")
1345 assert device is not None
1346 assert device.details["path"] == "/org/bluez/hci1/dev_FA_23_9D_AA_45_46"
1347
1348
1349 async def test_get_bluez_device_no_properties(
1350 mock_linux: None, monkeypatch: pytest.MonkeyPatch
1351 ) -> None:
1352 """No properties → returns None early."""
1353 monkeypatch.setattr(
1354 bleak_retry_connector.bleak_manager,
1355 "get_global_bluez_manager",
1356 AsyncMock(return_value=None),
1357 )
1358 assert (
1359 await get_bluez_device("Test", "/org/bluez/hci0/dev_FA_23_9D_AA_45_46") is None
1360 )
1361
1362
1363 async def test_get_bluez_device_disappeared_logs(
1364 mock_linux: None,
1365 caplog: pytest.LogCaptureFixture,
1366 monkeypatch: pytest.MonkeyPatch,
1367 ) -> None:
1368 """Device path missing from props logs the disappearance and still scans alternates."""
1369
1370 class FakeBluezManager:
1371 def __init__(self) -> None:
1372 self._properties = {
1373 "/org/bluez/hci1/dev_FA_23_9D_AA_45_46": {
1374 defs.DEVICE_INTERFACE: {
1375 "Address": "FA:23:9D:AA:45:46",
1376 "Alias": "Test Device",
1377 "RSSI": -60,
1378 },
1379 },
1380 }
1381
1382 manager = FakeBluezManager()
1383 monkeypatch.setattr(
1384 bleak_retry_connector.bleak_manager,
1385 "get_global_bluez_manager",
1386 AsyncMock(return_value=manager),
1387 )
1388 monkeypatch.setattr(bleak_retry_connector.bluez, "defs", defs)
1389
1390 device = await get_bluez_device("Test", "/org/bluez/hci0/dev_FA_23_9D_AA_45_46")
1391 assert device is not None
1392 assert device.details["path"] == "/org/bluez/hci1/dev_FA_23_9D_AA_45_46"
1393 assert "Device has disappeared" in caplog.text
1394
1395
1396 async def test_get_bluez_device_disappeared_silent_when_flag_false(
1397 mock_linux: None,
1398 caplog: pytest.LogCaptureFixture,
1399 monkeypatch: pytest.MonkeyPatch,
1400 ) -> None:
1401 """`_log_disappearance=False` suppresses the disappearance log."""
1402
1403 class FakeBluezManager:
1404 def __init__(self) -> None:
1405 self._properties = {
1406 "/org/bluez/hci1/dev_FA_23_9D_AA_45_46": {
1407 defs.DEVICE_INTERFACE: {
1408 "Address": "FA:23:9D:AA:45:46",
1409 "Alias": "Test Device",
1410 "RSSI": -60,
1411 },
1412 },
1413 }
1414
1415 manager = FakeBluezManager()
1416 monkeypatch.setattr(
1417 bleak_retry_connector.bleak_manager,
1418 "get_global_bluez_manager",
1419 AsyncMock(return_value=manager),
1420 )
1421 monkeypatch.setattr(bleak_retry_connector.bluez, "defs", defs)
1422
1423 caplog.clear()
1424 await get_bluez_device(
1425 "Test",
1426 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46",
1427 _log_disappearance=False,
1428 )
1429 assert "Device has disappeared" not in caplog.text
1430
1431
1432 async def test_get_bluez_device_connected_at_original_path(
1433 mock_linux: None, monkeypatch: pytest.MonkeyPatch
1434 ) -> None:
1435 """Device already connected at the requested path → returns None (use original)."""
1436
1437 class FakeBluezManager:
1438 def __init__(self) -> None:
1439 self._properties = {
1440 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46": {
1441 defs.DEVICE_INTERFACE: {
1442 "Connected": True,
1443 "Address": "FA:23:9D:AA:45:46",
1444 "Alias": "Test Device",
1445 "RSSI": -30,
1446 },
1447 },
1448 }
1449
1450 manager = FakeBluezManager()
1451 monkeypatch.setattr(
1452 bleak_retry_connector.bleak_manager,
1453 "get_global_bluez_manager",
1454 AsyncMock(return_value=manager),
1455 )
1456 monkeypatch.setattr(bleak_retry_connector.bluez, "defs", defs)
1457
1458 assert (
1459 await get_bluez_device("Test", "/org/bluez/hci0/dev_FA_23_9D_AA_45_46") is None
1460 )
1461
1462
1463 async def test_get_bluez_device_skips_unconnected_original_path(
1464 mock_linux: None, monkeypatch: pytest.MonkeyPatch
1465 ) -> None:
1466 """The original path is skipped during alternate scoring when not connected."""
1467
1468 class FakeBluezManager:
1469 def __init__(self) -> None:
1470 self._properties = {
1471 "/org/bluez/hci0/dev_FA_23_9D_AA_45_46": {
1472 defs.DEVICE_INTERFACE: {
1473 "Address": "FA:23:9D:AA:45:46",
1474 "Alias": "Test Device",
1475 "RSSI": -80,
1476 },
1477 },
1478 "/org/bluez/hci1/dev_FA_23_9D_AA_45_46": {
1479 defs.DEVICE_INTERFACE: {
1480 "Address": "FA:23:9D:AA:45:46",
1481 "Alias": "Test Device",
1482 "RSSI": -30,
1483 },
1484 },
1485 }
1486
1487 manager = FakeBluezManager()
1488 monkeypatch.setattr(
1489 bleak_retry_connector.bleak_manager,
1490 "get_global_bluez_manager",
1491 AsyncMock(return_value=manager),
1492 )
1493 monkeypatch.setattr(bleak_retry_connector.bluez, "defs", defs)
1494
1495 device = await get_bluez_device(
1496 "Test", "/org/bluez/hci0/dev_FA_23_9D_AA_45_46", rssi=-90
1497 )
1498 assert device is not None
1499 assert device.details["path"] == "/org/bluez/hci1/dev_FA_23_9D_AA_45_46"
1500
1501
1502 async def test_get_connected_devices_no_properties(
1503 mock_linux: None, monkeypatch: pytest.MonkeyPatch
1504 ) -> None:
1505 """No properties → returns empty list."""
1506 monkeypatch.setattr(
1507 bleak_retry_connector.bleak_manager,
1508 "get_global_bluez_manager",
1509 AsyncMock(return_value=None),
1510 )
1511 device = BLEDevice(
1512 "FA:23:9D:AA:45:46",
1513 "Test",
1514 {"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"},
1515 )
1516 assert await get_connected_devices(device) == []