Debian Codegraph @

tests/test_scanner_mgmt.py

raw
1 """Tests for the mgmt-based local scanner and the create_local_scanner factory."""
2
3 from __future__ import annotations
4
5 import asyncio
6 from typing import TYPE_CHECKING
7 from unittest.mock import patch
8
9 import pytest
10 from bluetooth_adapters import DEFAULT_ADDRESS
11 from bluetooth_data_tools import monotonic_time_coarse
12
13 from habluetooth import (
14 BluetoothScanningMode,
15 HaScanner,
16 HaScannerMgmt,
17 create_local_scanner,
18 get_manager,
19 )
20 from habluetooth.channels.bluez import LongTermKey
21 from habluetooth.scanner_bleak import ScannerStartError
22
23 if TYPE_CHECKING:
24 from collections.abc import Iterator
25
26 pytestmark = pytest.mark.asyncio
27
28 _ADAPTER = "hci0"
29 _ADAPTER_IDX = 0
30 _ADDRESS = "00:11:22:33:44:55"
31 _PEER = "AA:BB:CC:DD:EE:FF"
32
33
34 class FakeMgmt:
35 """Stand-in for MGMTBluetoothCtl recording the discovery calls made."""
36
37 def __init__(self, *, can_discover: bool = True) -> None:
38 self.can_discover = can_discover
39 self.started: list[int] = []
40 self.stopped: list[int] = []
41 self.monitors_added: list[int] = []
42 self.monitors_removed: list[tuple[int, int]] = []
43 self.start_ok = True
44 self.stop_ok = True
45 self.remove_ok = True
46 self.monitor_handle: int | None = 7
47
48 async def start_discovery(self, idx: int) -> bool:
49 self.started.append(idx)
50 return self.start_ok
51
52 async def stop_discovery(self, idx: int) -> bool:
53 self.stopped.append(idx)
54 return self.stop_ok
55
56 async def add_adv_pattern_monitor(self, idx: int) -> int | None:
57 self.monitors_added.append(idx)
58 return self.monitor_handle
59
60 async def remove_adv_monitor(self, idx: int, handle: int) -> bool:
61 self.monitors_removed.append((idx, handle))
62 return self.remove_ok
63
64
65 @pytest.fixture
66 def use_mgmt() -> Iterator[FakeMgmt]:
67 """Point the manager at a fake mgmt controller that can discover."""
68 fake = FakeMgmt()
69 with patch.object(get_manager(), "get_bluez_mgmt_ctl", return_value=fake):
70 yield fake
71
72
73 def _scanner(
74 mode: BluetoothScanningMode = BluetoothScanningMode.ACTIVE,
75 ) -> HaScannerMgmt:
76 return HaScannerMgmt(mode, _ADAPTER, _ADDRESS)
77
78
79 # -- factory --------------------------------------------------------------
80 async def test_factory_falls_back_without_mgmt() -> None:
81 """With no mgmt controller, the factory returns the bleak scanner."""
82 with patch.object(get_manager(), "get_bluez_mgmt_ctl", return_value=None):
83 scanner = create_local_scanner(BluetoothScanningMode.ACTIVE, _ADAPTER, _ADDRESS)
84 assert type(scanner) is HaScanner
85
86
87 async def test_factory_falls_back_when_cannot_discover() -> None:
88 """A mgmt controller without discovery capability still uses bleak."""
89 fake = FakeMgmt(can_discover=False)
90 with (
91 patch("habluetooth.scanner_mgmt.IS_LINUX", True),
92 patch.object(get_manager(), "get_bluez_mgmt_ctl", return_value=fake),
93 ):
94 scanner = create_local_scanner(BluetoothScanningMode.ACTIVE, _ADAPTER, _ADDRESS)
95 assert type(scanner) is HaScanner
96
97
98 async def test_factory_falls_back_for_non_hci_adapter(use_mgmt: FakeMgmt) -> None:
99 """A non-hci adapter has no controller index, so it uses bleak."""
100 with patch("habluetooth.scanner_mgmt.IS_LINUX", True):
101 scanner = create_local_scanner(
102 BluetoothScanningMode.ACTIVE, "CoreBluetooth", _ADDRESS
103 )
104 assert type(scanner) is HaScanner
105
106
107 async def test_factory_falls_back_without_real_address(use_mgmt: FakeMgmt) -> None:
108 """Without a real adapter BD_ADDR the mgmt scanner cannot pin connects."""
109 with patch("habluetooth.scanner_mgmt.IS_LINUX", True):
110 scanner = create_local_scanner(
111 BluetoothScanningMode.ACTIVE, _ADAPTER, DEFAULT_ADDRESS
112 )
113 assert type(scanner) is HaScanner
114
115
116 async def test_factory_falls_back_for_auto_mode(use_mgmt: FakeMgmt) -> None:
117 """AUTO needs active-window promotion the mgmt scanner lacks, so use bleak."""
118 with patch("habluetooth.scanner_mgmt.IS_LINUX", True):
119 scanner = create_local_scanner(BluetoothScanningMode.AUTO, _ADAPTER, _ADDRESS)
120 assert type(scanner) is HaScanner
121
122
123 async def test_factory_falls_back_without_l2cap(use_mgmt: FakeMgmt) -> None:
124 """Without permission to open L2CAP sockets, connections need the bleak path."""
125 with (
126 patch("habluetooth.scanner_mgmt.IS_LINUX", True),
127 patch("habluetooth.scanner_mgmt.can_use_l2cap", return_value=False),
128 ):
129 scanner = create_local_scanner(BluetoothScanningMode.ACTIVE, _ADAPTER, _ADDRESS)
130 assert type(scanner) is HaScanner
131
132
133 async def test_factory_returns_mgmt_scanner_when_available(
134 use_mgmt: FakeMgmt,
135 ) -> None:
136 """On Linux with a discovering mgmt socket and an hci adapter, use mgmt."""
137 with (
138 patch("habluetooth.scanner_mgmt.IS_LINUX", True),
139 patch("habluetooth.scanner_mgmt.can_use_l2cap", return_value=True),
140 ):
141 scanner = create_local_scanner(BluetoothScanningMode.ACTIVE, _ADAPTER, _ADDRESS)
142 assert type(scanner) is HaScannerMgmt
143
144
145 async def test_init_rejects_default_address() -> None:
146 """Direct construction without a real BD_ADDR fails fast."""
147 with pytest.raises(ValueError, match="real adapter address"):
148 HaScannerMgmt(BluetoothScanningMode.ACTIVE, _ADAPTER, DEFAULT_ADDRESS)
149
150
151 # -- construction ---------------------------------------------------------
152 async def test_init_is_connectable_with_connector() -> None:
153 """The scanner is connectable and routes through a mgmt connector."""
154 scanner = _scanner()
155 assert scanner.connectable is True
156 assert scanner.connector is not None
157 assert scanner.connector.source == _ADDRESS
158 assert scanner.connector.can_connect == scanner._can_connect
159 # The connect path derives the backend id from this; it should read as the
160 # client, not the generic "partial".
161 assert type(scanner.connector.client).__name__ == "HaMgmtClient"
162
163
164 # -- discovery lifecycle --------------------------------------------------
165 async def test_async_start_active_uses_start_discovery(use_mgmt: FakeMgmt) -> None:
166 """Active mode starts kernel discovery and marks the scanner scanning."""
167 scanner = _scanner(BluetoothScanningMode.ACTIVE)
168 scanner.async_setup()
169 await scanner.async_start()
170 assert use_mgmt.started == [_ADAPTER_IDX]
171 assert scanner.scanning is True
172 assert scanner.current_mode is BluetoothScanningMode.ACTIVE
173 await scanner.async_stop()
174
175
176 async def test_start_notifies_mode_change(use_mgmt: FakeMgmt) -> None:
177 """Starting sets the radio mode through the manager notification path."""
178 scanner = _scanner(BluetoothScanningMode.ACTIVE)
179 scanner.async_setup()
180 with patch.object(get_manager(), "scanner_mode_changed") as notify:
181 await scanner.async_start()
182 notify.assert_called_once_with(scanner)
183 await scanner.async_stop()
184
185
186 async def test_async_start_passive_uses_monitor(use_mgmt: FakeMgmt) -> None:
187 """Passive mode adds an advertisement monitor and records its handle."""
188 scanner = _scanner(BluetoothScanningMode.PASSIVE)
189 scanner.async_setup()
190 await scanner.async_start()
191 assert use_mgmt.monitors_added == [_ADAPTER_IDX]
192 assert scanner._monitor_handle == 7
193 assert scanner.scanning is True
194 await scanner.async_stop()
195
196
197 async def test_async_start_raises_when_unavailable() -> None:
198 """Starting without mgmt discovery raises ScannerStartError."""
199 scanner = _scanner()
200 scanner.async_setup()
201 with (
202 patch.object(get_manager(), "get_bluez_mgmt_ctl", return_value=None),
203 pytest.raises(ScannerStartError, match="not available"),
204 ):
205 await scanner.async_start()
206
207
208 async def test_async_start_raises_when_discovery_fails(use_mgmt: FakeMgmt) -> None:
209 """A rejected start_discovery surfaces as ScannerStartError."""
210 use_mgmt.start_ok = False
211 scanner = _scanner(BluetoothScanningMode.ACTIVE)
212 scanner.async_setup()
213 with pytest.raises(ScannerStartError, match="failed to start"):
214 await scanner.async_start()
215
216
217 async def test_async_start_raises_when_monitor_fails(use_mgmt: FakeMgmt) -> None:
218 """A rejected monitor registration surfaces as ScannerStartError."""
219 use_mgmt.monitor_handle = None
220 scanner = _scanner(BluetoothScanningMode.PASSIVE)
221 scanner.async_setup()
222 with pytest.raises(ScannerStartError, match="advertisement monitor"):
223 await scanner.async_start()
224
225
226 async def test_async_stop_active_stops_discovery(use_mgmt: FakeMgmt) -> None:
227 """Stopping an active scanner stops kernel discovery."""
228 scanner = _scanner(BluetoothScanningMode.ACTIVE)
229 scanner.async_setup()
230 await scanner.async_start()
231 await scanner.async_stop()
232 assert use_mgmt.stopped == [_ADAPTER_IDX]
233 assert scanner.scanning is False
234
235
236 async def test_async_stop_passive_removes_monitor(use_mgmt: FakeMgmt) -> None:
237 """Stopping a passive scanner removes its advertisement monitor."""
238 scanner = _scanner(BluetoothScanningMode.PASSIVE)
239 scanner.async_setup()
240 await scanner.async_start()
241 await scanner.async_stop()
242 assert use_mgmt.monitors_removed == [(_ADAPTER_IDX, 7)]
243 assert scanner._monitor_handle is None
244
245
246 # -- connection slots -----------------------------------------------------
247 async def test_can_connect_respects_slot_limit() -> None:
248 """can_connect tracks live connections against the configured slot count."""
249 scanner = _scanner()
250 get_manager().slot_manager.register_adapter(_ADAPTER, 1)
251 assert scanner._can_connect() is True
252 scanner._register_connection(_PEER)
253 assert scanner._can_connect() is False
254 scanner._unregister_connection(_PEER)
255 assert scanner._can_connect() is True
256
257
258 async def test_can_connect_unlimited_without_registered_slots() -> None:
259 """With no slot count registered, connections are not slot-gated."""
260 scanner = _scanner()
261 assert scanner._can_connect() is True
262 scanner._register_connection(_PEER)
263 assert scanner._can_connect() is True
264
265
266 async def test_can_connect_false_when_not_connectable() -> None:
267 """A non-connectable scanner never reports it can connect."""
268 scanner = _scanner()
269 scanner.connectable = False
270 assert scanner._can_connect() is False
271
272
273 async def test_get_allocations_reflects_tracked_connections() -> None:
274 """get_allocations reports free/allocated from the scanner's own tracking."""
275 scanner = _scanner()
276 assert scanner.get_allocations() is None # no slots registered yet
277 get_manager().slot_manager.register_adapter(_ADAPTER, 3)
278 scanner._register_connection(_PEER)
279 allocations = scanner.get_allocations()
280 assert allocations is not None
281 assert allocations.slots == 3
282 assert allocations.free == 2
283 assert allocations.allocated == [_PEER]
284
285
286 async def test_get_allocations_clamps_free_at_zero() -> None:
287 """An overshoot past the advisory gate reports zero free, never negative."""
288 scanner = _scanner()
289 get_manager().slot_manager.register_adapter(_ADAPTER, 1)
290 scanner._register_connection(_PEER)
291 scanner._register_connection("11:22:33:44:55:66") # overshoot the 1 slot
292 allocations = scanner.get_allocations()
293 assert allocations is not None
294 assert allocations.free == 0
295
296
297 async def test_get_allocations_sorts_allocated() -> None:
298 """Allocated addresses are reported in a stable sorted order."""
299 scanner = _scanner()
300 get_manager().slot_manager.register_adapter(_ADAPTER, 5)
301 scanner._register_connection("CC:CC:CC:CC:CC:CC")
302 scanner._register_connection("AA:AA:AA:AA:AA:AA")
303 scanner._register_connection("BB:BB:BB:BB:BB:BB")
304 allocations = scanner.get_allocations()
305 assert allocations is not None
306 assert allocations.allocated == [
307 "AA:AA:AA:AA:AA:AA",
308 "BB:BB:BB:BB:BB:BB",
309 "CC:CC:CC:CC:CC:CC",
310 ]
311
312
313 # -- watchdog -------------------------------------------------------------
314 async def test_watchdog_restarts_discovery_when_quiet(use_mgmt: FakeMgmt) -> None:
315 """The watchdog restarts discovery after the adapter goes quiet."""
316 scanner = _scanner(BluetoothScanningMode.ACTIVE)
317 scanner.async_setup()
318 await scanner.async_start()
319 assert use_mgmt.started == [_ADAPTER_IDX]
320 with patch.object(scanner, "_async_watchdog_triggered", return_value=True):
321 scanner._async_scanner_watchdog()
322 assert scanner.scanning is False
323 # Let the restart background task run to completion.
324 for task in list(scanner._background_tasks):
325 await task
326 assert use_mgmt.stopped == [_ADAPTER_IDX] # stopped during restart
327 assert use_mgmt.started == [_ADAPTER_IDX, _ADAPTER_IDX] # then started again
328 await scanner.async_stop()
329
330
331 async def test_watchdog_noop_when_not_triggered(use_mgmt: FakeMgmt) -> None:
332 """The watchdog does nothing while advertisements are still arriving."""
333 scanner = _scanner(BluetoothScanningMode.ACTIVE)
334 scanner.async_setup()
335 await scanner.async_start()
336 with patch.object(scanner, "_async_watchdog_triggered", return_value=False):
337 scanner._async_scanner_watchdog()
338 assert use_mgmt.stopped == []
339 assert use_mgmt.started == [_ADAPTER_IDX]
340 await scanner.async_stop()
341
342
343 async def test_watchdog_skips_when_restart_in_progress(use_mgmt: FakeMgmt) -> None:
344 """A triggered watchdog does not stack a second restart on the lock."""
345 scanner = _scanner(BluetoothScanningMode.ACTIVE)
346 scanner.async_setup()
347 await scanner.async_start()
348 async with scanner._start_stop_lock:
349 with patch.object(scanner, "_async_watchdog_triggered", return_value=True):
350 scanner._async_scanner_watchdog()
351 assert scanner._background_tasks == set() # no restart scheduled
352 await scanner.async_stop()
353
354
355 async def test_watchdog_restart_logs_on_failure(
356 use_mgmt: FakeMgmt, caplog: pytest.LogCaptureFixture
357 ) -> None:
358 """A failed restart is logged, not raised out of the background task."""
359 scanner = _scanner(BluetoothScanningMode.ACTIVE)
360 scanner.async_setup()
361 await scanner.async_start()
362 use_mgmt.start_ok = False # the restart's start_discovery will fail
363 with (
364 patch.object(scanner, "_async_watchdog_triggered", return_value=True),
365 caplog.at_level("ERROR", logger="habluetooth.scanner_mgmt"),
366 ):
367 scanner._async_scanner_watchdog()
368 for task in list(scanner._background_tasks):
369 await task
370 assert "failed to restart" in caplog.text
371 await scanner.async_stop()
372
373
374 async def test_restart_does_not_stack_monitor_on_failed_removal(
375 use_mgmt: FakeMgmt,
376 ) -> None:
377 """If a passive monitor cannot be removed, the restart does not add another."""
378 use_mgmt.remove_ok = False
379 scanner = _scanner(BluetoothScanningMode.PASSIVE)
380 scanner.async_setup()
381 await scanner.async_start()
382 assert use_mgmt.monitors_added == [_ADAPTER_IDX]
383 with patch.object(scanner, "_async_watchdog_triggered", return_value=True):
384 scanner._async_scanner_watchdog()
385 for task in list(scanner._background_tasks):
386 await task
387 # Removal failed, so no second monitor was registered (no stacking/leak),
388 # and the handle is preserved for a retry on the next tick.
389 assert use_mgmt.monitors_added == [_ADAPTER_IDX]
390 assert scanner._monitor_handle == 7
391 await scanner.async_stop()
392
393
394 async def test_restart_does_not_resurrect_a_stopped_scanner(
395 use_mgmt: FakeMgmt,
396 ) -> None:
397 """A restart queued before a stop must not re-issue discovery afterwards."""
398 scanner = _scanner(BluetoothScanningMode.ACTIVE)
399 scanner.async_setup()
400 await scanner.async_start()
401 await scanner.async_stop()
402 use_mgmt.started.clear()
403 use_mgmt.stopped.clear()
404 # Simulates the queued restart task running after the stop released the lock.
405 await scanner._async_restart()
406 assert use_mgmt.started == [] # discovery was not restarted
407 assert scanner.scanning is False
408
409
410 async def test_unsetup_cancels_pending_background_task(use_mgmt: FakeMgmt) -> None:
411 """Teardown cancels an in-flight restart so it cannot restart discovery."""
412 scanner = _scanner(BluetoothScanningMode.ACTIVE)
413 unsetup = scanner.async_setup()
414 await scanner.async_start()
415 started = asyncio.Event()
416
417 async def _blocker() -> None:
418 started.set()
419 await asyncio.sleep(3600)
420
421 scanner._create_background_task(_blocker())
422 await started.wait()
423 task = next(iter(scanner._background_tasks))
424 unsetup()
425 await asyncio.gather(task, return_exceptions=True)
426 assert task.cancelled()
427 await scanner.async_stop()
428
429
430 async def test_background_task_failure_is_logged(
431 caplog: pytest.LogCaptureFixture,
432 ) -> None:
433 """An exception escaping a background task is logged, not lost at GC."""
434 scanner = _scanner()
435
436 async def boom() -> None:
437 msg = "kaboom"
438 raise RuntimeError(msg)
439
440 with caplog.at_level("ERROR", logger="habluetooth.scanner_mgmt"):
441 scanner._create_background_task(boom())
442 task = next(iter(scanner._background_tasks))
443 await asyncio.gather(task, return_exceptions=True)
444 await asyncio.sleep(0) # let the done-callback run
445 assert "background task failed" in caplog.text
446 assert scanner._background_tasks == set() # reference dropped
447
448
449 async def test_unsetup_stops_watchdog(use_mgmt: FakeMgmt) -> None:
450 """The teardown callback cancels the watchdog timer."""
451 scanner = _scanner(BluetoothScanningMode.ACTIVE)
452 unsetup = scanner.async_setup()
453 await scanner.async_start()
454 armed = scanner._cancel_watchdog # capture before asserting to avoid narrowing
455 assert armed is not None # armed by the start
456 unsetup()
457 assert scanner._cancel_watchdog is None
458 await scanner.async_stop()
459
460
461 async def test_stop_discovery_noop_without_mgmt() -> None:
462 """Stopping with no mgmt controller is a safe no-op."""
463 scanner = _scanner()
464 with patch.object(get_manager(), "get_bluez_mgmt_ctl", return_value=None):
465 await scanner._async_stop_discovery() # does not raise
466
467
468 async def test_stop_active_warns_on_failure(
469 use_mgmt: FakeMgmt, caplog: pytest.LogCaptureFixture
470 ) -> None:
471 """A failed stop_discovery is logged and the scanner still stops scanning."""
472 use_mgmt.stop_ok = False
473 scanner = _scanner(BluetoothScanningMode.ACTIVE)
474 scanner.async_setup()
475 await scanner.async_start()
476 with caplog.at_level("WARNING", logger="habluetooth.scanner_mgmt"):
477 await scanner.async_stop()
478 assert "failed to stop mgmt discovery" in caplog.text
479 assert scanner.scanning is False
480
481
482 async def test_stop_passive_keeps_handle_on_failed_removal(
483 use_mgmt: FakeMgmt, caplog: pytest.LogCaptureFixture
484 ) -> None:
485 """A failed monitor removal keeps the handle so a later stop can retry."""
486 use_mgmt.remove_ok = False
487 scanner = _scanner(BluetoothScanningMode.PASSIVE)
488 scanner.async_setup()
489 await scanner.async_start()
490 with caplog.at_level("WARNING", logger="habluetooth.scanner_mgmt"):
491 await scanner.async_stop()
492 assert "failed to remove advertisement monitor" in caplog.text
493 assert scanner._monitor_handle == 7 # not cleared, so a retry is possible
494
495
496 async def test_registered_scanner_reports_discovered_devices(
497 use_mgmt: FakeMgmt,
498 ) -> None:
499 """Once registered, the inherited ingestion feeds the read-out overrides."""
500 scanner = _scanner()
501 scanner.async_setup()
502 unregister = get_manager().async_register_scanner(scanner)
503 try:
504 assert list(scanner.discovered_addresses) == []
505 assert scanner.discovered_devices == []
506 assert scanner.discovered_devices_and_advertisement_data == {}
507 assert scanner.get_discovered_device_advertisement_data(_PEER) is None
508 scanner._async_on_advertisement(
509 _PEER, -60, "dev", [], {}, {}, None, {}, monotonic_time_coarse()
510 )
511 assert _PEER in scanner.discovered_addresses
512 assert _PEER in scanner.discovered_devices_and_advertisement_data
513 result = scanner.get_discovered_device_advertisement_data(_PEER)
514 assert result is not None
515 assert result[0].address == _PEER
516 assert scanner.discovered_devices[0].address == _PEER
517 finally:
518 unregister()
519
520
521 async def test_long_term_key_store() -> None:
522 """The scanner stores, lists, and forgets bonded keys per peer."""
523 scanner = _scanner()
524 key_a = LongTermKey(_PEER, 1, 0x05, False, 16, 0x1234, bytes(8), bytes(16))
525 # Same peer, distinct (central, ediv) so both survive rather than clobber.
526 key_a2 = LongTermKey(_PEER, 1, 0x05, True, 16, 0x5678, bytes(8), bytes(16))
527 other = LongTermKey(
528 "11:22:33:44:55:66", 1, 0x05, False, 16, 0x1, bytes(8), bytes(16)
529 )
530 scanner._store_long_term_key(key_a)
531 scanner._store_long_term_key(key_a2)
532 scanner._store_long_term_key(other)
533 assert set(scanner.export_long_term_keys()) == {key_a, key_a2, other}
534 # Forget is case-insensitive: stored addresses are canonical upper-case.
535 scanner._forget_long_term_keys(_PEER.lower())
536 assert scanner.export_long_term_keys() == [other]
537 scanner._forget_long_term_keys(_PEER) # idempotent
538
539
540 async def test_long_term_key_export_and_restore() -> None:
541 """Keys can be exported for persistence and seeded back on startup."""
542 scanner = _scanner()
543 key = LongTermKey(_PEER, 1, 0x05, False, 16, 0x1234, bytes(8), bytes(16))
544 scanner.restore_long_term_keys([key])
545 assert scanner.export_long_term_keys() == [key]
546
547
548 async def test_long_term_keys_changed_callback() -> None:
549 """The change callback fires on store and on an actual forget, not a no-op."""
550 scanner = _scanner()
551 changes: list[int] = []
552 scanner.set_long_term_keys_changed_callback(lambda: changes.append(1))
553 key = LongTermKey(_PEER, 1, 0x05, False, 16, 0x1234, bytes(8), bytes(16))
554 scanner._store_long_term_key(key)
555 assert len(changes) == 1
556 scanner._store_long_term_key(key) # identical -> no fire (symmetric with forget)
557 assert len(changes) == 1
558 updated = LongTermKey(_PEER, 1, 0x05, False, 16, 0x1234, bytes(8), bytes(range(16)))
559 scanner._store_long_term_key(updated) # same tuple, new value -> fires
560 assert len(changes) == 2
561 scanner._forget_long_term_keys("00:00:00:00:00:00") # nothing removed -> no fire
562 assert len(changes) == 2
563 scanner._forget_long_term_keys(_PEER) # removes -> fires
564 assert len(changes) == 3
565 scanner.set_long_term_keys_changed_callback(None) # cleared
566 scanner._store_long_term_key(key)
567 assert len(changes) == 3
568
569
570 async def test_long_term_keys_changed_callback_failure_is_isolated(
571 caplog: pytest.LogCaptureFixture,
572 ) -> None:
573 """A raising persistence callback is logged, not propagated into pairing."""
574 scanner = _scanner()
575
576 def boom() -> None:
577 msg = "persistence broke"
578 raise RuntimeError(msg)
579
580 scanner.set_long_term_keys_changed_callback(boom)
581 key = LongTermKey(_PEER, 1, 0x05, False, 16, 0x1234, bytes(8), bytes(16))
582 with caplog.at_level("ERROR", logger="habluetooth.scanner_mgmt"):
583 scanner._store_long_term_key(key) # must not raise
584 assert "change callback failed" in caplog.text
585
586
587 async def test_slot_limit_zero_when_adapter_unregistered() -> None:
588 """An adapter with no registered slot count reports 0 (unlimited)."""
589 scanner = _scanner()
590 assert scanner._slot_limit() == 0
591 assert scanner._can_connect() is True