| 1 |
"""Tests for the Bluetooth integration scanners.""" |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import logging |
| 5 |
import platform |
| 6 |
import time |
| 7 |
from collections.abc import Generator, Iterable |
| 8 |
from datetime import timedelta |
| 9 |
from typing import Any |
| 10 |
from unittest.mock import ANY, AsyncMock, MagicMock, Mock, patch |
| 11 |
|
| 12 |
import pytest |
| 13 |
from bleak import BleakError |
| 14 |
from bleak.backends.device import BLEDevice |
| 15 |
from bleak.backends.scanner import AdvertisementData, AdvertisementDataCallback |
| 16 |
from bleak_retry_connector import Allocations, BleakSlotManager |
| 17 |
from bluetooth_adapters import ADAPTER_PASSIVE_SCAN |
| 18 |
|
| 19 |
import habluetooth.scanner as scanner_shim |
| 20 |
from habluetooth import ( |
| 21 |
SCANNER_WATCHDOG_INTERVAL, |
| 22 |
SCANNER_WATCHDOG_TIMEOUT, |
| 23 |
BaseHaScanner, |
| 24 |
BluetoothManager, |
| 25 |
BluetoothScanningMode, |
| 26 |
BluetoothServiceInfoBleak, |
| 27 |
HaScanner, |
| 28 |
HaScannerType, |
| 29 |
ScannerStartError, |
| 30 |
get_manager, |
| 31 |
set_manager, |
| 32 |
) |
| 33 |
from habluetooth import scanner_bleak as scanner |
| 34 |
from habluetooth.channels.bluez import ( |
| 35 |
BluetoothMGMTProtocol, |
| 36 |
MGMTBluetoothCtl, |
| 37 |
bytes_mac_to_str, |
| 38 |
make_bluez_details, |
| 39 |
) |
| 40 |
from habluetooth.scanner_bleak import ( |
| 41 |
InvalidMessageError, |
| 42 |
create_bleak_scanner, |
| 43 |
) |
| 44 |
|
| 45 |
from . import ( |
| 46 |
MockBleakScanner, |
| 47 |
async_fire_time_changed, |
| 48 |
generate_advertisement_data, |
| 49 |
generate_ble_device, |
| 50 |
patch_bleak_scanner_factory, |
| 51 |
patch_bluetooth_time, |
| 52 |
utcnow, |
| 53 |
) |
| 54 |
from .conftest import FakeBluetoothAdapters, MockBluetoothManagerWithCallbacks |
| 55 |
|
| 56 |
DEVICE_FOUND = 0x0012 |
| 57 |
ADV_MONITOR_DEVICE_FOUND = 0x002F |
| 58 |
IS_WINDOWS = 'os.name == "nt"' |
| 59 |
IS_POSIX = 'os.name == "posix"' |
| 60 |
NOT_POSIX = 'os.name != "posix"' |
| 61 |
if platform.system() != "Linux": |
| 62 |
# ``bleak.args.bluez`` may not be importable off Linux; mimic the shape |
| 63 |
# so the production ``if bluez_args:`` truthy check still fires. |
| 64 |
scanner.PASSIVE_SCANNER_ARGS = {"or_patterns": [(0, 0x01, b"\x06")]} |
| 65 |
# If the adapter is in a stuck state the following errors are raised: |
| 66 |
NEED_RESET_ERRORS = [ |
| 67 |
"org.bluez.Error.Failed", |
| 68 |
"org.bluez.Error.InProgress", |
| 69 |
"org.bluez.Error.NotReady", |
| 70 |
"not found", |
| 71 |
] |
| 72 |
|
| 73 |
|
| 74 |
@pytest.fixture(autouse=True, scope="module") |
| 75 |
def disable_stop_discovery(): |
| 76 |
"""Disable stop discovery.""" |
| 77 |
with ( |
| 78 |
patch("habluetooth.scanner_bleak.stop_discovery"), |
| 79 |
patch("habluetooth.scanner_bleak.restore_discoveries"), |
| 80 |
patch("habluetooth.scanner_bleak.restore_discoveries_sync"), |
| 81 |
): |
| 82 |
yield |
| 83 |
|
| 84 |
|
| 85 |
@pytest.fixture |
| 86 |
def force_linux_scanner_mode() -> Generator[None, None, None]: |
| 87 |
""" |
| 88 |
Force scanner.IS_LINUX=True / IS_MACOS=False for AUTO-flow tests. |
| 89 |
|
| 90 |
Lets the active-window toggle path run on any host: the toggle |
| 91 |
is gated on IS_LINUX (BlueZ-only private attribute), and AUTO |
| 92 |
on macOS short-circuits to permanent active. |
| 93 |
""" |
| 94 |
with ( |
| 95 |
patch("habluetooth.scanner_bleak.IS_LINUX", True), |
| 96 |
patch("habluetooth.scanner_bleak.IS_MACOS", False), |
| 97 |
): |
| 98 |
yield |
| 99 |
|
| 100 |
|
| 101 |
@pytest.fixture(autouse=True, scope="module") |
| 102 |
def manager(): |
| 103 |
"""Return the BluetoothManager instance.""" |
| 104 |
adapters = FakeBluetoothAdapters() |
| 105 |
slot_manager = BleakSlotManager() |
| 106 |
manager = BluetoothManager(adapters, slot_manager) |
| 107 |
set_manager(manager) |
| 108 |
return manager |
| 109 |
|
| 110 |
|
| 111 |
@pytest.fixture |
| 112 |
def mock_btmgmt_socket(): |
| 113 |
"""Mock the btmgmt_socket module.""" |
| 114 |
with patch("habluetooth.channels.bluez.btmgmt_socket") as mock_btmgmt: |
| 115 |
mock_socket = Mock() |
| 116 |
# Make the socket look like a real socket with a file descriptor |
| 117 |
mock_socket.fileno.return_value = 99 |
| 118 |
mock_btmgmt.open.return_value = mock_socket |
| 119 |
yield mock_btmgmt |
| 120 |
|
| 121 |
|
| 122 |
def test_scanner_module_aliases_scanner_bleak() -> None: |
| 123 |
"""habluetooth.scanner is a back-compat alias of the scanner_bleak module.""" |
| 124 |
assert scanner_shim is scanner |
| 125 |
|
| 126 |
|
| 127 |
def test_create_bleak_scanner_linux_no_adapter_active() -> None: |
| 128 |
"""Linux + no adapter + active: ``bluez`` kwarg must be absent.""" |
| 129 |
with ( |
| 130 |
patch.object(scanner, "IS_LINUX", True), |
| 131 |
patch.object(scanner, "IS_MACOS", False), |
| 132 |
patch("habluetooth.scanner_bleak.OriginalBleakScanner") as mock_scanner, |
| 133 |
): |
| 134 |
create_bleak_scanner(None, BluetoothScanningMode.ACTIVE, None) |
| 135 |
kwargs = mock_scanner.call_args.kwargs |
| 136 |
assert "bluez" not in kwargs |
| 137 |
assert "adapter" not in kwargs |
| 138 |
|
| 139 |
|
| 140 |
@pytest.mark.skipif(platform.system() != "Linux", reason="Linux only") |
| 141 |
def test_passive_scan_flags_fit_one_monitor() -> None: |
| 142 |
"""The FLAGS list fits one monitor and covers the observed values.""" |
| 143 |
flags = scanner.PASSIVE_SCAN_FLAGS |
| 144 |
assert len(flags) <= 16 |
| 145 |
assert len(set(flags)) == len(flags) |
| 146 |
assert all(0 <= value <= 0xFF for value in flags) |
| 147 |
# Values reported by real networks (#31, #615) must all be covered. |
| 148 |
assert {0x02, 0x04, 0x05, 0x06, 0x18, 0x1A} <= set(flags) |
| 149 |
assert len(scanner.PASSIVE_SCANNER_ARGS["or_patterns"]) == len(flags) |
| 150 |
|
| 151 |
|
| 152 |
def test_create_bleak_scanner_linux_no_adapter_passive() -> None: |
| 153 |
"""Linux + no adapter + passive: ``bluez`` carries passive args only.""" |
| 154 |
with ( |
| 155 |
patch.object(scanner, "IS_LINUX", True), |
| 156 |
patch.object(scanner, "IS_MACOS", False), |
| 157 |
patch("habluetooth.scanner_bleak.OriginalBleakScanner") as mock_scanner, |
| 158 |
): |
| 159 |
create_bleak_scanner(None, BluetoothScanningMode.PASSIVE, None) |
| 160 |
bluez = mock_scanner.call_args.kwargs["bluez"] |
| 161 |
assert "adapter" not in bluez |
| 162 |
# PASSIVE args are copied in — the production dict must not be mutated. |
| 163 |
assert bluez == dict(scanner.PASSIVE_SCANNER_ARGS) |
| 164 |
|
| 165 |
|
| 166 |
def test_create_bleak_scanner_linux_adapter_active() -> None: |
| 167 |
"""Linux + adapter + active: ``bluez`` carries adapter only.""" |
| 168 |
with ( |
| 169 |
patch.object(scanner, "IS_LINUX", True), |
| 170 |
patch.object(scanner, "IS_MACOS", False), |
| 171 |
patch("habluetooth.scanner_bleak.OriginalBleakScanner") as mock_scanner, |
| 172 |
): |
| 173 |
create_bleak_scanner(None, BluetoothScanningMode.ACTIVE, "hci2") |
| 174 |
bluez = mock_scanner.call_args.kwargs["bluez"] |
| 175 |
assert bluez == {"adapter": "hci2"} |
| 176 |
|
| 177 |
|
| 178 |
def test_create_bleak_scanner_linux_adapter_passive() -> None: |
| 179 |
"""Linux + adapter + passive: ``bluez`` merges adapter and passive args.""" |
| 180 |
with ( |
| 181 |
patch.object(scanner, "IS_LINUX", True), |
| 182 |
patch.object(scanner, "IS_MACOS", False), |
| 183 |
patch("habluetooth.scanner_bleak.OriginalBleakScanner") as mock_scanner, |
| 184 |
): |
| 185 |
create_bleak_scanner(None, BluetoothScanningMode.PASSIVE, "hci1") |
| 186 |
bluez = mock_scanner.call_args.kwargs["bluez"] |
| 187 |
assert bluez.get("adapter") == "hci1" |
| 188 |
# The production code must copy PASSIVE_SCANNER_ARGS — assert the source |
| 189 |
# was not mutated by the adapter insertion. |
| 190 |
assert "adapter" not in scanner.PASSIVE_SCANNER_ARGS |
| 191 |
|
| 192 |
|
| 193 |
@pytest.mark.asyncio |
| 194 |
async def test_empty_data_no_scanner() -> None: |
| 195 |
"""Test we handle empty data.""" |
| 196 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 197 |
scanner.async_setup() |
| 198 |
assert scanner.discovered_devices == [] |
| 199 |
assert scanner.discovered_devices_and_advertisement_data == {} |
| 200 |
|
| 201 |
|
| 202 |
@pytest.mark.asyncio |
| 203 |
@pytest.mark.skipif(NOT_POSIX) |
| 204 |
async def test_dbus_socket_missing_in_container( |
| 205 |
caplog: pytest.LogCaptureFixture, |
| 206 |
) -> None: |
| 207 |
"""Test we handle dbus being missing in the container.""" |
| 208 |
with ( |
| 209 |
patch("habluetooth.scanner_bleak.is_docker_env", return_value=True), |
| 210 |
patch( |
| 211 |
"habluetooth.scanner_bleak.OriginalBleakScanner.start", |
| 212 |
side_effect=FileNotFoundError, |
| 213 |
), |
| 214 |
patch( |
| 215 |
"habluetooth.scanner_bleak.OriginalBleakScanner.stop", |
| 216 |
) as mock_stop, |
| 217 |
): |
| 218 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 219 |
scanner.async_setup() |
| 220 |
with pytest.raises( |
| 221 |
ScannerStartError, |
| 222 |
match="DBus service not found; docker config may be missing", |
| 223 |
): |
| 224 |
await scanner.async_start() |
| 225 |
assert mock_stop.called |
| 226 |
|
| 227 |
|
| 228 |
@pytest.mark.asyncio |
| 229 |
@pytest.mark.skipif(NOT_POSIX) |
| 230 |
async def test_dbus_socket_missing(caplog: pytest.LogCaptureFixture) -> None: |
| 231 |
"""Test we handle dbus being missing.""" |
| 232 |
with ( |
| 233 |
patch("habluetooth.scanner_bleak.is_docker_env", return_value=False), |
| 234 |
patch( |
| 235 |
"habluetooth.scanner_bleak.OriginalBleakScanner.start", |
| 236 |
side_effect=FileNotFoundError, |
| 237 |
), |
| 238 |
patch( |
| 239 |
"habluetooth.scanner_bleak.OriginalBleakScanner.stop", |
| 240 |
) as mock_stop, |
| 241 |
): |
| 242 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 243 |
scanner.async_setup() |
| 244 |
with pytest.raises( |
| 245 |
ScannerStartError, |
| 246 |
match="DBus service not found; make sure the DBus socket is available", |
| 247 |
): |
| 248 |
await scanner.async_start() |
| 249 |
assert mock_stop.called |
| 250 |
|
| 251 |
|
| 252 |
@pytest.mark.asyncio |
| 253 |
@pytest.mark.skipif(NOT_POSIX) |
| 254 |
async def test_handle_cancellation(caplog: pytest.LogCaptureFixture) -> None: |
| 255 |
"""Test cancellation stops.""" |
| 256 |
with ( |
| 257 |
patch("habluetooth.scanner_bleak.is_docker_env", return_value=False), |
| 258 |
patch( |
| 259 |
"habluetooth.scanner_bleak.OriginalBleakScanner.start", |
| 260 |
side_effect=asyncio.CancelledError, |
| 261 |
), |
| 262 |
patch( |
| 263 |
"habluetooth.scanner_bleak.OriginalBleakScanner.stop", |
| 264 |
) as mock_stop, |
| 265 |
): |
| 266 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 267 |
scanner.async_setup() |
| 268 |
with pytest.raises(asyncio.CancelledError): |
| 269 |
await scanner.async_start() |
| 270 |
assert mock_stop.called |
| 271 |
|
| 272 |
|
| 273 |
@pytest.mark.asyncio |
| 274 |
@pytest.mark.skipif(NOT_POSIX) |
| 275 |
async def test_handle_stop_while_starting(caplog: pytest.LogCaptureFixture) -> None: |
| 276 |
"""Test stop while starting.""" |
| 277 |
|
| 278 |
async def _start(*args, **kwargs): |
| 279 |
await asyncio.sleep(1000) |
| 280 |
|
| 281 |
with ( |
| 282 |
patch("habluetooth.scanner_bleak.is_docker_env", return_value=False), |
| 283 |
patch("habluetooth.scanner_bleak.OriginalBleakScanner.start", _start), |
| 284 |
patch( |
| 285 |
"habluetooth.scanner_bleak.OriginalBleakScanner.stop", |
| 286 |
) as mock_stop, |
| 287 |
): |
| 288 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 289 |
scanner.async_setup() |
| 290 |
task = asyncio.create_task(scanner.async_start()) |
| 291 |
await asyncio.sleep(0) |
| 292 |
await asyncio.sleep(0) |
| 293 |
await scanner.async_stop() |
| 294 |
with pytest.raises( |
| 295 |
ScannerStartError, match="Starting bluetooth scanner aborted" |
| 296 |
): |
| 297 |
await task |
| 298 |
assert mock_stop.called |
| 299 |
|
| 300 |
|
| 301 |
@pytest.mark.asyncio |
| 302 |
@pytest.mark.skipif(NOT_POSIX) |
| 303 |
async def test_dbus_broken_pipe_in_container(caplog: pytest.LogCaptureFixture) -> None: |
| 304 |
"""Test we handle dbus broken pipe in the container.""" |
| 305 |
with ( |
| 306 |
patch("habluetooth.scanner_bleak.is_docker_env", return_value=True), |
| 307 |
patch( |
| 308 |
"habluetooth.scanner_bleak.OriginalBleakScanner.start", |
| 309 |
side_effect=BrokenPipeError, |
| 310 |
), |
| 311 |
patch( |
| 312 |
"habluetooth.scanner_bleak.OriginalBleakScanner.stop", |
| 313 |
) as mock_stop, |
| 314 |
): |
| 315 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 316 |
scanner.async_setup() |
| 317 |
with pytest.raises(ScannerStartError, match="DBus connection broken"): |
| 318 |
await scanner.async_start() |
| 319 |
assert mock_stop.called |
| 320 |
|
| 321 |
|
| 322 |
@pytest.mark.asyncio |
| 323 |
@pytest.mark.skipif(NOT_POSIX) |
| 324 |
async def test_dbus_broken_pipe(caplog: pytest.LogCaptureFixture) -> None: |
| 325 |
"""Test we handle dbus broken pipe.""" |
| 326 |
with ( |
| 327 |
patch("habluetooth.scanner_bleak.is_docker_env", return_value=False), |
| 328 |
patch( |
| 329 |
"habluetooth.scanner_bleak.OriginalBleakScanner.start", |
| 330 |
side_effect=BrokenPipeError, |
| 331 |
), |
| 332 |
patch( |
| 333 |
"habluetooth.scanner_bleak.OriginalBleakScanner.stop", |
| 334 |
) as mock_stop, |
| 335 |
): |
| 336 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 337 |
scanner.async_setup() |
| 338 |
with pytest.raises(ScannerStartError, match="DBus connection broken:"): |
| 339 |
await scanner.async_start() |
| 340 |
assert mock_stop.called |
| 341 |
|
| 342 |
|
| 343 |
@pytest.mark.asyncio |
| 344 |
@pytest.mark.skipif(NOT_POSIX) |
| 345 |
async def test_invalid_dbus_message(caplog: pytest.LogCaptureFixture) -> None: |
| 346 |
"""Test we handle invalid dbus message.""" |
| 347 |
with patch( |
| 348 |
"habluetooth.scanner_bleak.OriginalBleakScanner.start", |
| 349 |
side_effect=InvalidMessageError, |
| 350 |
): |
| 351 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 352 |
scanner.async_setup() |
| 353 |
with pytest.raises(ScannerStartError, match="Invalid DBus message received"): |
| 354 |
await scanner.async_start() |
| 355 |
|
| 356 |
|
| 357 |
@pytest.mark.asyncio |
| 358 |
@pytest.mark.skipif(IS_WINDOWS) |
| 359 |
@pytest.mark.parametrize("error", NEED_RESET_ERRORS) |
| 360 |
async def test_adapter_needs_reset_at_start( |
| 361 |
caplog: pytest.LogCaptureFixture, error: str |
| 362 |
) -> None: |
| 363 |
"""Test we cycle the adapter when it needs a restart.""" |
| 364 |
called_start = 0 |
| 365 |
called_stop = 0 |
| 366 |
_callback = None |
| 367 |
mock_discovered: list[Any] = [] |
| 368 |
|
| 369 |
class _DBusRecoveryScanner(MockBleakScanner): |
| 370 |
async def start(self, *args: object, **kwargs: object) -> None: |
| 371 |
nonlocal called_start |
| 372 |
called_start += 1 |
| 373 |
if called_start < 3: |
| 374 |
raise BleakError(error) |
| 375 |
|
| 376 |
async def stop(self, *args: object, **kwargs: object) -> None: |
| 377 |
nonlocal called_stop |
| 378 |
called_stop += 1 |
| 379 |
|
| 380 |
@property |
| 381 |
def discovered_devices(self): |
| 382 |
return mock_discovered |
| 383 |
|
| 384 |
def register_detection_callback( |
| 385 |
self, callback: AdvertisementDataCallback |
| 386 |
) -> None: |
| 387 |
nonlocal _callback |
| 388 |
_callback = callback |
| 389 |
|
| 390 |
mock_scanner = _DBusRecoveryScanner() |
| 391 |
|
| 392 |
with ( |
| 393 |
patch( |
| 394 |
"habluetooth.scanner_bleak.OriginalBleakScanner", return_value=mock_scanner |
| 395 |
), |
| 396 |
patch( |
| 397 |
"habluetooth.util.recover_adapter", return_value=True |
| 398 |
) as mock_recover_adapter, |
| 399 |
): |
| 400 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 401 |
scanner.async_setup() |
| 402 |
await scanner.async_start() |
| 403 |
|
| 404 |
assert len(mock_recover_adapter.mock_calls) == 1 |
| 405 |
await scanner.async_stop() |
| 406 |
|
| 407 |
|
| 408 |
@pytest.mark.asyncio |
| 409 |
@pytest.mark.skipif(IS_WINDOWS) |
| 410 |
async def test_recovery_from_dbus_restart() -> None: |
| 411 |
"""Test we can recover when DBus gets restarted out from under us.""" |
| 412 |
called_start = 0 |
| 413 |
called_stop = 0 |
| 414 |
_callback = None |
| 415 |
mock_discovered: list[Any] = [] |
| 416 |
|
| 417 |
class _CallbackCapturingScanner(MockBleakScanner): |
| 418 |
def __init__( |
| 419 |
self, |
| 420 |
detection_callback: AdvertisementDataCallback, |
| 421 |
*args: object, |
| 422 |
**kwargs: object, |
| 423 |
) -> None: |
| 424 |
super().__init__() |
| 425 |
nonlocal _callback |
| 426 |
_callback = detection_callback |
| 427 |
|
| 428 |
async def start(self, *args: object, **kwargs: object) -> None: |
| 429 |
nonlocal called_start |
| 430 |
called_start += 1 |
| 431 |
|
| 432 |
async def stop(self, *args: object, **kwargs: object) -> None: |
| 433 |
nonlocal called_stop |
| 434 |
called_stop += 1 |
| 435 |
|
| 436 |
@property |
| 437 |
def discovered_devices(self): |
| 438 |
return mock_discovered |
| 439 |
|
| 440 |
with patch( |
| 441 |
"habluetooth.scanner_bleak.OriginalBleakScanner", |
| 442 |
_CallbackCapturingScanner, |
| 443 |
): |
| 444 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 445 |
scanner.async_setup() |
| 446 |
await scanner.async_start() |
| 447 |
|
| 448 |
assert called_start == 1 |
| 449 |
|
| 450 |
start_time_monotonic = time.monotonic() |
| 451 |
mock_discovered = [MagicMock()] |
| 452 |
|
| 453 |
# Ensure we don't restart the scanner if we don't need to |
| 454 |
with patch_bluetooth_time( |
| 455 |
start_time_monotonic + 10, |
| 456 |
): |
| 457 |
async_fire_time_changed(utcnow() + SCANNER_WATCHDOG_INTERVAL) |
| 458 |
|
| 459 |
assert called_start == 1 |
| 460 |
|
| 461 |
# Fire a callback to reset the timer |
| 462 |
with patch_bluetooth_time( |
| 463 |
start_time_monotonic, |
| 464 |
): |
| 465 |
_callback( # type: ignore[misc] |
| 466 |
generate_ble_device("44:44:33:11:23:42", "any_name"), |
| 467 |
generate_advertisement_data(local_name="any_name"), |
| 468 |
) |
| 469 |
|
| 470 |
# Ensure we don't restart the scanner if we don't need to |
| 471 |
with patch_bluetooth_time( |
| 472 |
start_time_monotonic + 20, |
| 473 |
): |
| 474 |
async_fire_time_changed(utcnow() + SCANNER_WATCHDOG_INTERVAL) |
| 475 |
await asyncio.sleep(0) |
| 476 |
|
| 477 |
assert called_start == 1 |
| 478 |
|
| 479 |
# We hit the timer, so we restart the scanner |
| 480 |
with patch_bluetooth_time( |
| 481 |
start_time_monotonic + SCANNER_WATCHDOG_TIMEOUT + 20, |
| 482 |
): |
| 483 |
async_fire_time_changed( |
| 484 |
utcnow() + SCANNER_WATCHDOG_INTERVAL + timedelta(seconds=20) |
| 485 |
) |
| 486 |
await asyncio.sleep(0) |
| 487 |
|
| 488 |
assert called_start == 2 |
| 489 |
await scanner.async_stop() |
| 490 |
|
| 491 |
|
| 492 |
@pytest.mark.asyncio |
| 493 |
@pytest.mark.skipif(IS_WINDOWS) |
| 494 |
async def test_adapter_recovery() -> None: |
| 495 |
"""Test we can recover when the adapter stops responding.""" |
| 496 |
called_start = 0 |
| 497 |
called_stop = 0 |
| 498 |
_callback = None |
| 499 |
mock_discovered: list[Any] = [] |
| 500 |
|
| 501 |
class _AdapterRecoveryScanner(MockBleakScanner): |
| 502 |
async def start(self, *args: object, **kwargs: object) -> None: |
| 503 |
nonlocal called_start |
| 504 |
called_start += 1 |
| 505 |
|
| 506 |
async def stop(self, *args: object, **kwargs: object) -> None: |
| 507 |
nonlocal called_stop |
| 508 |
called_stop += 1 |
| 509 |
|
| 510 |
@property |
| 511 |
def discovered_devices(self): |
| 512 |
return mock_discovered |
| 513 |
|
| 514 |
def register_detection_callback( |
| 515 |
self, callback: AdvertisementDataCallback |
| 516 |
) -> None: |
| 517 |
nonlocal _callback |
| 518 |
_callback = callback |
| 519 |
|
| 520 |
mock_scanner = _AdapterRecoveryScanner() |
| 521 |
start_time_monotonic = time.monotonic() |
| 522 |
|
| 523 |
with ( |
| 524 |
patch_bluetooth_time( |
| 525 |
start_time_monotonic, |
| 526 |
), |
| 527 |
patch( |
| 528 |
"habluetooth.scanner_bleak.OriginalBleakScanner", |
| 529 |
return_value=mock_scanner, |
| 530 |
), |
| 531 |
): |
| 532 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 533 |
scanner.async_setup() |
| 534 |
await scanner.async_start() |
| 535 |
|
| 536 |
assert called_start == 1 |
| 537 |
|
| 538 |
mock_discovered = [MagicMock()] |
| 539 |
|
| 540 |
# Ensure we don't restart the scanner if we don't need to |
| 541 |
with patch_bluetooth_time( |
| 542 |
start_time_monotonic + 10, |
| 543 |
): |
| 544 |
async_fire_time_changed(utcnow() + SCANNER_WATCHDOG_INTERVAL) |
| 545 |
await asyncio.sleep(0) |
| 546 |
|
| 547 |
assert called_start == 1 |
| 548 |
|
| 549 |
# Ensure we don't restart the scanner if we don't need to |
| 550 |
with patch_bluetooth_time( |
| 551 |
start_time_monotonic + 20, |
| 552 |
): |
| 553 |
async_fire_time_changed(utcnow() + SCANNER_WATCHDOG_INTERVAL) |
| 554 |
await asyncio.sleep(0) |
| 555 |
|
| 556 |
assert called_start == 1 |
| 557 |
|
| 558 |
# We hit the timer with no detections, so we |
| 559 |
# reset the adapter and restart the scanner |
| 560 |
with ( |
| 561 |
patch_bluetooth_time( |
| 562 |
start_time_monotonic |
| 563 |
+ SCANNER_WATCHDOG_TIMEOUT |
| 564 |
+ SCANNER_WATCHDOG_INTERVAL.total_seconds(), |
| 565 |
), |
| 566 |
patch( |
| 567 |
"habluetooth.util.recover_adapter", return_value=True |
| 568 |
) as mock_recover_adapter, |
| 569 |
): |
| 570 |
async_fire_time_changed(utcnow() + SCANNER_WATCHDOG_INTERVAL) |
| 571 |
await asyncio.sleep(0) |
| 572 |
|
| 573 |
assert len(mock_recover_adapter.mock_calls) == 1 |
| 574 |
assert mock_recover_adapter.call_args_list[0][0] == ( |
| 575 |
0, |
| 576 |
"AA:BB:CC:DD:EE:FF", |
| 577 |
True, |
| 578 |
) |
| 579 |
|
| 580 |
assert called_start == 2 |
| 581 |
await scanner.async_stop() |
| 582 |
|
| 583 |
|
| 584 |
@pytest.mark.asyncio |
| 585 |
async def test_async_start_completes_when_all_attempts_return_false() -> None: |
| 586 |
""" |
| 587 |
All start attempts returning False still finishes the start sequence. |
| 588 |
|
| 589 |
Covers the ``_async_start`` loop fall-through where every attempt reports a |
| 590 |
recoverable failure and the loop is exhausted without breaking. |
| 591 |
""" |
| 592 |
success_calls = 0 |
| 593 |
|
| 594 |
class _AllAttemptsFailScanner(HaScanner): |
| 595 |
async def _async_start_attempt(self, attempt: int) -> bool: |
| 596 |
return False |
| 597 |
|
| 598 |
async def _async_on_successful_start(self) -> None: |
| 599 |
nonlocal success_calls |
| 600 |
success_calls += 1 |
| 601 |
|
| 602 |
ha_scanner = _AllAttemptsFailScanner( |
| 603 |
BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF" |
| 604 |
) |
| 605 |
ha_scanner.async_setup() |
| 606 |
await ha_scanner._async_start() |
| 607 |
assert success_calls == 1 |
| 608 |
|
| 609 |
|
| 610 |
@pytest.mark.asyncio |
| 611 |
@pytest.mark.skipif(IS_WINDOWS) |
| 612 |
async def test_adapter_scanner_fails_to_start_first_time() -> None: |
| 613 |
""" |
| 614 |
Test we can recover when the adapter stops responding. |
| 615 |
|
| 616 |
The first recovery fails. |
| 617 |
""" |
| 618 |
called_start = 0 |
| 619 |
called_stop = 0 |
| 620 |
_callback = None |
| 621 |
mock_discovered: list[Any] = [] |
| 622 |
|
| 623 |
class _RestartFailScanner(MockBleakScanner): |
| 624 |
async def start(self, *args: object, **kwargs: object) -> None: |
| 625 |
nonlocal called_start |
| 626 |
called_start += 1 |
| 627 |
if called_start == 1: |
| 628 |
return |
| 629 |
if called_start < 4: |
| 630 |
msg = "Failed to start" |
| 631 |
raise BleakError(msg) |
| 632 |
|
| 633 |
async def stop(self, *args: object, **kwargs: object) -> None: |
| 634 |
nonlocal called_stop |
| 635 |
called_stop += 1 |
| 636 |
|
| 637 |
@property |
| 638 |
def discovered_devices(self): |
| 639 |
return mock_discovered |
| 640 |
|
| 641 |
def register_detection_callback( |
| 642 |
self, callback: AdvertisementDataCallback |
| 643 |
) -> None: |
| 644 |
nonlocal _callback |
| 645 |
_callback = callback |
| 646 |
|
| 647 |
mock_scanner = _RestartFailScanner() |
| 648 |
start_time_monotonic = time.monotonic() |
| 649 |
|
| 650 |
with ( |
| 651 |
patch_bluetooth_time( |
| 652 |
start_time_monotonic, |
| 653 |
), |
| 654 |
patch( |
| 655 |
"habluetooth.scanner_bleak.OriginalBleakScanner", |
| 656 |
return_value=mock_scanner, |
| 657 |
), |
| 658 |
): |
| 659 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 660 |
scanner.async_setup() |
| 661 |
await scanner.async_start() |
| 662 |
|
| 663 |
assert called_start == 1 |
| 664 |
|
| 665 |
mock_discovered = [MagicMock()] |
| 666 |
|
| 667 |
# Ensure we don't restart the scanner if we don't need to |
| 668 |
with patch_bluetooth_time( |
| 669 |
start_time_monotonic + 10, |
| 670 |
): |
| 671 |
async_fire_time_changed(utcnow() + SCANNER_WATCHDOG_INTERVAL) |
| 672 |
await asyncio.sleep(0) |
| 673 |
|
| 674 |
assert called_start == 1 |
| 675 |
|
| 676 |
# Ensure we don't restart the scanner if we don't need to |
| 677 |
with patch_bluetooth_time( |
| 678 |
start_time_monotonic + 20, |
| 679 |
): |
| 680 |
async_fire_time_changed(utcnow() + SCANNER_WATCHDOG_INTERVAL) |
| 681 |
await asyncio.sleep(0) |
| 682 |
|
| 683 |
assert called_start == 1 |
| 684 |
|
| 685 |
# We hit the timer with no detections, |
| 686 |
# so we reset the adapter and restart the scanner |
| 687 |
with ( |
| 688 |
patch_bluetooth_time( |
| 689 |
start_time_monotonic |
| 690 |
+ SCANNER_WATCHDOG_TIMEOUT |
| 691 |
+ SCANNER_WATCHDOG_INTERVAL.total_seconds(), |
| 692 |
), |
| 693 |
patch( |
| 694 |
"habluetooth.util.recover_adapter", return_value=True |
| 695 |
) as mock_recover_adapter, |
| 696 |
): |
| 697 |
async_fire_time_changed(utcnow() + SCANNER_WATCHDOG_INTERVAL) |
| 698 |
await asyncio.sleep(0) |
| 699 |
|
| 700 |
assert len(mock_recover_adapter.mock_calls) == 1 |
| 701 |
assert called_start == 4 |
| 702 |
assert scanner.scanning is True |
| 703 |
|
| 704 |
now_monotonic = time.monotonic() |
| 705 |
# We hit the timer again the previous start call failed, make sure |
| 706 |
# we try again |
| 707 |
with ( |
| 708 |
patch_bluetooth_time( |
| 709 |
now_monotonic |
| 710 |
+ SCANNER_WATCHDOG_TIMEOUT * 2 |
| 711 |
+ SCANNER_WATCHDOG_INTERVAL.total_seconds(), |
| 712 |
), |
| 713 |
patch( |
| 714 |
"habluetooth.util.recover_adapter", return_value=True |
| 715 |
) as mock_recover_adapter, |
| 716 |
): |
| 717 |
async_fire_time_changed(utcnow() + SCANNER_WATCHDOG_INTERVAL) |
| 718 |
await asyncio.sleep(0) |
| 719 |
|
| 720 |
assert len(mock_recover_adapter.mock_calls) == 1 |
| 721 |
assert called_start == 5 |
| 722 |
await scanner.async_stop() |
| 723 |
|
| 724 |
|
| 725 |
@pytest.mark.asyncio |
| 726 |
async def test_adapter_fails_to_start_and_takes_a_bit_to_init( |
| 727 |
caplog: pytest.LogCaptureFixture, |
| 728 |
) -> None: |
| 729 |
"""Test we can recover the adapter at startup and we wait for Dbus to init.""" |
| 730 |
called_start = 0 |
| 731 |
called_stop = 0 |
| 732 |
_callback = None |
| 733 |
mock_discovered: list[Any] = [] |
| 734 |
|
| 735 |
class _DBusInProgressScanner(MockBleakScanner): |
| 736 |
async def start(self, *args: object, **kwargs: object) -> None: |
| 737 |
nonlocal called_start |
| 738 |
called_start += 1 |
| 739 |
if called_start == 1: |
| 740 |
msg = "org.freedesktop.DBus.Error.UnknownObject" |
| 741 |
raise BleakError(msg) |
| 742 |
if called_start == 2: |
| 743 |
msg = "org.bluez.Error.InProgress" |
| 744 |
raise BleakError(msg) |
| 745 |
if called_start == 3: |
| 746 |
msg = "org.bluez.Error.InProgress" |
| 747 |
raise BleakError(msg) |
| 748 |
|
| 749 |
async def stop(self, *args: object, **kwargs: object) -> None: |
| 750 |
nonlocal called_stop |
| 751 |
called_stop += 1 |
| 752 |
|
| 753 |
@property |
| 754 |
def discovered_devices(self): |
| 755 |
return mock_discovered |
| 756 |
|
| 757 |
def register_detection_callback( |
| 758 |
self, callback: AdvertisementDataCallback |
| 759 |
) -> None: |
| 760 |
nonlocal _callback |
| 761 |
_callback = callback |
| 762 |
|
| 763 |
mock_scanner = _DBusInProgressScanner() |
| 764 |
start_time_monotonic = time.monotonic() |
| 765 |
|
| 766 |
with ( |
| 767 |
patch( |
| 768 |
"habluetooth.scanner_bleak.ADAPTER_INIT_TIME", |
| 769 |
0, |
| 770 |
), |
| 771 |
patch_bluetooth_time( |
| 772 |
start_time_monotonic, |
| 773 |
), |
| 774 |
patch( |
| 775 |
"habluetooth.scanner_bleak.OriginalBleakScanner", |
| 776 |
return_value=mock_scanner, |
| 777 |
), |
| 778 |
patch( |
| 779 |
"habluetooth.util.recover_adapter", return_value=True |
| 780 |
) as mock_recover_adapter, |
| 781 |
): |
| 782 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 783 |
scanner.async_setup() |
| 784 |
await scanner.async_start() |
| 785 |
|
| 786 |
assert called_start == 4 |
| 787 |
|
| 788 |
assert len(mock_recover_adapter.mock_calls) == 1 |
| 789 |
assert "Waiting for adapter to initialize" in caplog.text |
| 790 |
await scanner.async_stop() |
| 791 |
|
| 792 |
|
| 793 |
@pytest.mark.asyncio |
| 794 |
async def test_restart_takes_longer_than_watchdog_time( |
| 795 |
caplog: pytest.LogCaptureFixture, |
| 796 |
) -> None: |
| 797 |
""" |
| 798 |
Test we do not try to recover the adapter again. |
| 799 |
|
| 800 |
If the restart is still in progress. |
| 801 |
""" |
| 802 |
release_start_event = asyncio.Event() |
| 803 |
called_start = 0 |
| 804 |
|
| 805 |
class _ReleaseGatedScanner(MockBleakScanner): |
| 806 |
async def start(self, *args: object, **kwargs: object) -> None: |
| 807 |
nonlocal called_start |
| 808 |
called_start += 1 |
| 809 |
if called_start == 1: |
| 810 |
return |
| 811 |
await release_start_event.wait() |
| 812 |
|
| 813 |
mock_scanner = _ReleaseGatedScanner() |
| 814 |
start_time_monotonic = time.monotonic() |
| 815 |
|
| 816 |
with ( |
| 817 |
patch( |
| 818 |
"habluetooth.scanner_bleak.ADAPTER_INIT_TIME", |
| 819 |
0, |
| 820 |
), |
| 821 |
patch_bluetooth_time( |
| 822 |
start_time_monotonic, |
| 823 |
), |
| 824 |
patch( |
| 825 |
"habluetooth.scanner_bleak.OriginalBleakScanner", |
| 826 |
return_value=mock_scanner, |
| 827 |
), |
| 828 |
patch("habluetooth.util.recover_adapter", return_value=True), |
| 829 |
): |
| 830 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 831 |
scanner.async_setup() |
| 832 |
await scanner.async_start() |
| 833 |
|
| 834 |
assert called_start == 1 |
| 835 |
|
| 836 |
# Now force a recover adapter 2x |
| 837 |
for _ in range(2): |
| 838 |
with patch_bluetooth_time( |
| 839 |
start_time_monotonic |
| 840 |
+ SCANNER_WATCHDOG_TIMEOUT |
| 841 |
+ SCANNER_WATCHDOG_INTERVAL.total_seconds(), |
| 842 |
): |
| 843 |
async_fire_time_changed(utcnow() + SCANNER_WATCHDOG_INTERVAL) |
| 844 |
await asyncio.sleep(0) |
| 845 |
|
| 846 |
# Now release the start event |
| 847 |
release_start_event.set() |
| 848 |
|
| 849 |
assert "already restarting" in caplog.text |
| 850 |
await scanner.async_stop() |
| 851 |
|
| 852 |
|
| 853 |
@pytest.mark.asyncio |
| 854 |
@pytest.mark.skipif("platform.system() != 'Darwin'") |
| 855 |
async def test_setup_and_stop_macos() -> None: |
| 856 |
"""Test we enable use_bdaddr on MacOS.""" |
| 857 |
init_kwargs = None |
| 858 |
|
| 859 |
class _KwargsCapturingScanner(MockBleakScanner): |
| 860 |
def __init__(self, *args: object, **kwargs: object) -> None: |
| 861 |
super().__init__() |
| 862 |
nonlocal init_kwargs |
| 863 |
init_kwargs = kwargs |
| 864 |
|
| 865 |
with patch( |
| 866 |
"habluetooth.scanner_bleak.OriginalBleakScanner", |
| 867 |
_KwargsCapturingScanner, |
| 868 |
): |
| 869 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 870 |
scanner.async_setup() |
| 871 |
await scanner.async_start() |
| 872 |
|
| 873 |
assert init_kwargs == { |
| 874 |
"detection_callback": ANY, |
| 875 |
"scanning_mode": "active", |
| 876 |
"cb": {"use_bdaddr": True}, |
| 877 |
} |
| 878 |
await scanner.async_stop() |
| 879 |
|
| 880 |
|
| 881 |
@pytest.mark.asyncio |
| 882 |
async def test_no_passive_fallback_when_passive_unsupported( |
| 883 |
caplog: pytest.LogCaptureFixture, |
| 884 |
) -> None: |
| 885 |
"""No passive fallback when the adapter cannot scan passively.""" |
| 886 |
called_start = 0 |
| 887 |
|
| 888 |
class _AlwaysFailingScanner(MockBleakScanner): |
| 889 |
async def start(self, *args: object, **kwargs: object) -> None: |
| 890 |
nonlocal called_start |
| 891 |
called_start += 1 |
| 892 |
msg = "org.bluez.Error.InProgress" |
| 893 |
raise BleakError(msg) |
| 894 |
|
| 895 |
async def stop(self, *args: object, **kwargs: object) -> None: |
| 896 |
"""Stop scanning.""" |
| 897 |
|
| 898 |
mock_scanner = _AlwaysFailingScanner() |
| 899 |
|
| 900 |
with ( |
| 901 |
patch.object( |
| 902 |
get_manager(), "_adapters", {"hci0": {ADAPTER_PASSIVE_SCAN: False}} |
| 903 |
), |
| 904 |
patch("habluetooth.scanner_bleak.IS_LINUX", True), |
| 905 |
patch("habluetooth.scanner_bleak.ADAPTER_INIT_TIME", 0), |
| 906 |
patch( |
| 907 |
"habluetooth.scanner_bleak.OriginalBleakScanner", |
| 908 |
return_value=mock_scanner, |
| 909 |
), |
| 910 |
patch("habluetooth.util.recover_adapter", return_value=True), |
| 911 |
): |
| 912 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 913 |
scanner.async_setup() |
| 914 |
with pytest.raises(ScannerStartError): |
| 915 |
await scanner.async_start() |
| 916 |
|
| 917 |
assert called_start == 4 |
| 918 |
assert scanner.current_mode is BluetoothScanningMode.ACTIVE |
| 919 |
assert "Falling back to passive scanning mode" not in caplog.text |
| 920 |
assert "Not falling back to passive scanning" in caplog.text |
| 921 |
|
| 922 |
|
| 923 |
@pytest.mark.asyncio |
| 924 |
async def test_passive_fallback_uses_own_adapter_capability( |
| 925 |
caplog: pytest.LogCaptureFixture, |
| 926 |
) -> None: |
| 927 |
"""The fallback checks the scanner's own adapter, not any adapter.""" |
| 928 |
|
| 929 |
class _AlwaysFailingScanner(MockBleakScanner): |
| 930 |
async def start(self, *args: object, **kwargs: object) -> None: |
| 931 |
msg = "org.bluez.Error.InProgress" |
| 932 |
raise BleakError(msg) |
| 933 |
|
| 934 |
async def stop(self, *args: object, **kwargs: object) -> None: |
| 935 |
"""Stop scanning.""" |
| 936 |
|
| 937 |
mixed_adapters = { |
| 938 |
"hci0": {ADAPTER_PASSIVE_SCAN: False}, |
| 939 |
"hci1": {ADAPTER_PASSIVE_SCAN: True}, |
| 940 |
} |
| 941 |
|
| 942 |
with ( |
| 943 |
patch.object(get_manager(), "_adapters", mixed_adapters), |
| 944 |
patch("habluetooth.scanner_bleak.IS_LINUX", True), |
| 945 |
patch("habluetooth.scanner_bleak.ADAPTER_INIT_TIME", 0), |
| 946 |
patch( |
| 947 |
"habluetooth.scanner_bleak.OriginalBleakScanner", |
| 948 |
return_value=_AlwaysFailingScanner(), |
| 949 |
), |
| 950 |
patch("habluetooth.util.recover_adapter", return_value=True), |
| 951 |
): |
| 952 |
incapable = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 953 |
incapable.async_setup() |
| 954 |
with pytest.raises(ScannerStartError): |
| 955 |
await incapable.async_start() |
| 956 |
|
| 957 |
# Assert before hci1 runs so its fallback log cannot mask this. |
| 958 |
assert incapable.current_mode is BluetoothScanningMode.ACTIVE |
| 959 |
assert "Falling back to passive scanning mode" not in caplog.text |
| 960 |
|
| 961 |
capable = HaScanner(BluetoothScanningMode.ACTIVE, "hci1", "AA:BB:CC:DD:EE:FE") |
| 962 |
capable.async_setup() |
| 963 |
with pytest.raises(ScannerStartError): |
| 964 |
await capable.async_start() |
| 965 |
|
| 966 |
# The capable adapter still takes the fallback. |
| 967 |
assert capable.current_mode is BluetoothScanningMode.PASSIVE |
| 968 |
assert "Falling back to passive scanning mode" in caplog.text |
| 969 |
|
| 970 |
|
| 971 |
@pytest.mark.asyncio |
| 972 |
async def test_adapter_init_fails_fallback_to_passive( |
| 973 |
caplog: pytest.LogCaptureFixture, |
| 974 |
) -> None: |
| 975 |
"""Test we fallback to passive when adapter init fails.""" |
| 976 |
get_manager()._adapters = {"hci0": {ADAPTER_PASSIVE_SCAN: True}} |
| 977 |
called_start = 0 |
| 978 |
called_stop = 0 |
| 979 |
_callback = None |
| 980 |
mock_discovered: list[Any] = [] |
| 981 |
|
| 982 |
class _InProgressFatalScanner(MockBleakScanner): |
| 983 |
async def start(self, *args: object, **kwargs: object) -> None: |
| 984 |
nonlocal called_start |
| 985 |
called_start += 1 |
| 986 |
if called_start == 1: |
| 987 |
msg = "org.freedesktop.DBus.Error.UnknownObject" |
| 988 |
raise BleakError(msg) |
| 989 |
if called_start == 2: |
| 990 |
msg = "org.bluez.Error.InProgress" |
| 991 |
raise BleakError(msg) |
| 992 |
if called_start == 3: |
| 993 |
msg = "org.bluez.Error.InProgress" |
| 994 |
raise BleakError(msg) |
| 995 |
|
| 996 |
async def stop(self, *args: object, **kwargs: object) -> None: |
| 997 |
nonlocal called_stop |
| 998 |
called_stop += 1 |
| 999 |
|
| 1000 |
@property |
| 1001 |
def discovered_devices(self): |
| 1002 |
return mock_discovered |
| 1003 |
|
| 1004 |
def register_detection_callback( |
| 1005 |
self, callback: AdvertisementDataCallback |
| 1006 |
) -> None: |
| 1007 |
nonlocal _callback |
| 1008 |
_callback = callback |
| 1009 |
|
| 1010 |
mock_scanner = _InProgressFatalScanner() |
| 1011 |
start_time_monotonic = time.monotonic() |
| 1012 |
|
| 1013 |
with ( |
| 1014 |
patch( |
| 1015 |
"habluetooth.scanner_bleak.IS_LINUX", |
| 1016 |
True, |
| 1017 |
), |
| 1018 |
patch( |
| 1019 |
"habluetooth.scanner_bleak.ADAPTER_INIT_TIME", |
| 1020 |
0, |
| 1021 |
), |
| 1022 |
patch_bluetooth_time( |
| 1023 |
start_time_monotonic, |
| 1024 |
), |
| 1025 |
patch( |
| 1026 |
"habluetooth.scanner_bleak.OriginalBleakScanner", |
| 1027 |
return_value=mock_scanner, |
| 1028 |
), |
| 1029 |
patch( |
| 1030 |
"habluetooth.util.recover_adapter", return_value=True |
| 1031 |
) as mock_recover_adapter, |
| 1032 |
): |
| 1033 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 1034 |
scanner.async_setup() |
| 1035 |
await scanner.async_start() |
| 1036 |
|
| 1037 |
assert called_start == 4 |
| 1038 |
|
| 1039 |
assert len(mock_recover_adapter.mock_calls) == 1 |
| 1040 |
assert "Waiting for adapter to initialize" in caplog.text |
| 1041 |
assert ( |
| 1042 |
"Successful fall-back to passive scanning mode after active scanning failed" |
| 1043 |
in caplog.text |
| 1044 |
) |
| 1045 |
assert await scanner.async_diagnostics() == { |
| 1046 |
"adapter": "hci0", |
| 1047 |
"connect_failures": {}, |
| 1048 |
"connect_in_progress": {}, |
| 1049 |
"connect_completed_total": 0, |
| 1050 |
"connect_failed_total": 0, |
| 1051 |
"last_connect_completed_time": 0.0, |
| 1052 |
"connectable": True, |
| 1053 |
"current_mode": BluetoothScanningMode.PASSIVE, |
| 1054 |
"discovered_devices_and_advertisement_data": [], |
| 1055 |
"last_detection": ANY, |
| 1056 |
"monotonic_time": ANY, |
| 1057 |
"name": "hci0 (AA:BB:CC:DD:EE:FF)", |
| 1058 |
"requested_mode": BluetoothScanningMode.ACTIVE, |
| 1059 |
"scanning": True, |
| 1060 |
"source": "AA:BB:CC:DD:EE:FF", |
| 1061 |
"start_time": ANY, |
| 1062 |
"type": "HaScanner", |
| 1063 |
} |
| 1064 |
await scanner.async_stop() |
| 1065 |
assert await scanner.async_diagnostics() == { |
| 1066 |
"adapter": "hci0", |
| 1067 |
"connect_failures": {}, |
| 1068 |
"connect_in_progress": {}, |
| 1069 |
"connect_completed_total": 0, |
| 1070 |
"connect_failed_total": 0, |
| 1071 |
"last_connect_completed_time": 0.0, |
| 1072 |
"connectable": True, |
| 1073 |
"current_mode": BluetoothScanningMode.PASSIVE, |
| 1074 |
"discovered_devices_and_advertisement_data": [], |
| 1075 |
"last_detection": ANY, |
| 1076 |
"monotonic_time": ANY, |
| 1077 |
"name": "hci0 (AA:BB:CC:DD:EE:FF)", |
| 1078 |
"requested_mode": BluetoothScanningMode.ACTIVE, |
| 1079 |
"scanning": False, |
| 1080 |
"source": "AA:BB:CC:DD:EE:FF", |
| 1081 |
"start_time": ANY, |
| 1082 |
"type": "HaScanner", |
| 1083 |
} |
| 1084 |
|
| 1085 |
|
| 1086 |
@pytest.mark.asyncio |
| 1087 |
@pytest.mark.skipif(NOT_POSIX) |
| 1088 |
async def test_scanner_with_bluez_mgmt_side_channel(mock_btmgmt_socket: Mock) -> None: |
| 1089 |
"""Test scanner receiving advertisements via BlueZ management side channel.""" |
| 1090 |
# Mock capability check for the entire test |
| 1091 |
with patch.object(MGMTBluetoothCtl, "_check_capabilities", return_value=True): |
| 1092 |
# Create a custom manager that tracks discovered devices |
| 1093 |
class TestBluetoothManager(BluetoothManager): |
| 1094 |
def __init__(self, *args, **kwargs): |
| 1095 |
super().__init__(*args, **kwargs) |
| 1096 |
self.discovered_infos = [] |
| 1097 |
|
| 1098 |
def _discover_service_info( |
| 1099 |
self, service_info: BluetoothServiceInfoBleak |
| 1100 |
) -> None: |
| 1101 |
"""Track discovered service info.""" |
| 1102 |
self.discovered_infos.append(service_info) |
| 1103 |
|
| 1104 |
# Create manager and setup mgmt controller |
| 1105 |
adapters = FakeBluetoothAdapters() |
| 1106 |
slot_manager = BleakSlotManager() |
| 1107 |
manager = TestBluetoothManager(adapters, slot_manager) |
| 1108 |
set_manager(manager) |
| 1109 |
|
| 1110 |
# Set up the manager first |
| 1111 |
await manager.async_setup() |
| 1112 |
|
| 1113 |
# Create and setup the mgmt controller with the manager's side channel scanners |
| 1114 |
mgmt_ctl = MGMTBluetoothCtl( |
| 1115 |
timeout=5.0, scanners=manager._side_channel_scanners |
| 1116 |
) |
| 1117 |
|
| 1118 |
# Mock the protocol setup |
| 1119 |
mock_protocol = Mock(spec=BluetoothMGMTProtocol) |
| 1120 |
mock_transport = Mock() |
| 1121 |
mock_protocol.transport = mock_transport |
| 1122 |
|
| 1123 |
async def mock_setup(): |
| 1124 |
mgmt_ctl.protocol = mock_protocol |
| 1125 |
mgmt_ctl._on_connection_lost_future = ( |
| 1126 |
asyncio.get_running_loop().create_future() |
| 1127 |
) |
| 1128 |
|
| 1129 |
mgmt_ctl.setup = mock_setup # type: ignore[method-assign] |
| 1130 |
|
| 1131 |
# Inject mgmt controller into manager |
| 1132 |
manager._mgmt_ctl = mgmt_ctl |
| 1133 |
manager.has_advertising_side_channel = True |
| 1134 |
|
| 1135 |
# Verify get_bluez_mgmt_ctl returns our controller |
| 1136 |
assert manager.get_bluez_mgmt_ctl() is mgmt_ctl |
| 1137 |
|
| 1138 |
# Register scanner |
| 1139 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 1140 |
scanner.async_setup() |
| 1141 |
manager.async_register_scanner(scanner, connection_slots=2) |
| 1142 |
|
| 1143 |
# Start scanner - should be created without detection callback |
| 1144 |
with patch( |
| 1145 |
"habluetooth.scanner_bleak.OriginalBleakScanner" |
| 1146 |
) as mock_scanner_class: |
| 1147 |
mock_scanner = Mock() |
| 1148 |
mock_scanner.start = AsyncMock() |
| 1149 |
mock_scanner.stop = AsyncMock() |
| 1150 |
mock_scanner.discovered_devices = [] |
| 1151 |
mock_scanner_class.return_value = mock_scanner |
| 1152 |
|
| 1153 |
await scanner.async_start() |
| 1154 |
|
| 1155 |
# Verify scanner was created without detection callback |
| 1156 |
# since side channel is available |
| 1157 |
mock_scanner_class.assert_called_once() |
| 1158 |
call_kwargs = mock_scanner_class.call_args[1] |
| 1159 |
assert ( |
| 1160 |
"detection_callback" not in call_kwargs |
| 1161 |
or call_kwargs["detection_callback"] is None |
| 1162 |
) |
| 1163 |
|
| 1164 |
# Now simulate advertisement data coming through the mgmt protocol |
| 1165 |
# The manager should have registered the scanner with mgmt_ctl |
| 1166 |
assert 0 in mgmt_ctl.scanners # hci0 is index 0 |
| 1167 |
assert mgmt_ctl.scanners[0] is scanner |
| 1168 |
|
| 1169 |
# Simulate the protocol calling the scanner's raw advertisement handler |
| 1170 |
test_address = b"\xaa\xbb\xcc\xdd\xee\xff" |
| 1171 |
test_rssi = -60 |
| 1172 |
# Create valid advertisement data with flags |
| 1173 |
# Each AD structure is: length (1 byte), type (1 byte), data |
| 1174 |
test_data = ( |
| 1175 |
b"\x02\x01\x06" # Length=2, Type=0x01 (Flags), Data=0x06 |
| 1176 |
# Length=8, Type=0x09 (Complete Local Name), Data="TestDev" |
| 1177 |
b"\x08\x09TestDev" |
| 1178 |
) |
| 1179 |
|
| 1180 |
# Replicate what the BlueZ channel does on a raw advertisement: convert |
| 1181 |
# the address and build the details, then call the generic handler. |
| 1182 |
test_address_str = bytes_mac_to_str(test_address) |
| 1183 |
scanner._async_on_raw_advertisement( |
| 1184 |
test_address_str, |
| 1185 |
test_rssi, |
| 1186 |
test_data, |
| 1187 |
make_bluez_details(test_address_str, scanner.adapter), |
| 1188 |
time.monotonic(), |
| 1189 |
) |
| 1190 |
|
| 1191 |
# Allow time for processing |
| 1192 |
await asyncio.sleep(0) |
| 1193 |
|
| 1194 |
# Verify the device was discovered in the base scanner |
| 1195 |
assert len(scanner._previous_service_info) == 1 |
| 1196 |
assert "FF:EE:DD:CC:BB:AA" in scanner._previous_service_info |
| 1197 |
|
| 1198 |
service_info = scanner._previous_service_info["FF:EE:DD:CC:BB:AA"] |
| 1199 |
assert service_info.address == "FF:EE:DD:CC:BB:AA" |
| 1200 |
assert service_info.rssi == test_rssi |
| 1201 |
assert service_info.name == "TestDev" |
| 1202 |
|
| 1203 |
# Verify the manager also received the advertisement |
| 1204 |
assert len(manager.discovered_infos) == 1 |
| 1205 |
assert manager.discovered_infos[0] is service_info |
| 1206 |
|
| 1207 |
await scanner.async_stop() |
| 1208 |
manager.async_stop() |
| 1209 |
|
| 1210 |
|
| 1211 |
@pytest.mark.asyncio |
| 1212 |
@pytest.mark.skipif(NOT_POSIX) |
| 1213 |
async def test_scanner_without_bluez_mgmt_side_channel() -> None: |
| 1214 |
"""Test scanner uses normal detection callback when side channel unavailable.""" |
| 1215 |
|
| 1216 |
# Create manager without BlueZ mgmt support |
| 1217 |
class TestBluetoothManager(BluetoothManager): |
| 1218 |
def __init__(self, *args, **kwargs): |
| 1219 |
super().__init__(*args, **kwargs) |
| 1220 |
self.discovered_infos = [] |
| 1221 |
|
| 1222 |
def _discover_service_info( |
| 1223 |
self, service_info: BluetoothServiceInfoBleak |
| 1224 |
) -> None: |
| 1225 |
"""Track discovered service info.""" |
| 1226 |
self.discovered_infos.append(service_info) |
| 1227 |
|
| 1228 |
adapters = FakeBluetoothAdapters() |
| 1229 |
slot_manager = BleakSlotManager() |
| 1230 |
manager = TestBluetoothManager(adapters, slot_manager) |
| 1231 |
set_manager(manager) |
| 1232 |
|
| 1233 |
# Setup without mgmt controller |
| 1234 |
await manager.async_setup() |
| 1235 |
assert manager.has_advertising_side_channel is False |
| 1236 |
|
| 1237 |
# Register scanner |
| 1238 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 1239 |
scanner.async_setup() |
| 1240 |
manager.async_register_scanner(scanner, connection_slots=2) |
| 1241 |
|
| 1242 |
# Start scanner - should be created with detection callback |
| 1243 |
with patch("habluetooth.scanner_bleak.OriginalBleakScanner") as mock_scanner_class: |
| 1244 |
mock_scanner = Mock() |
| 1245 |
mock_scanner.start = AsyncMock() |
| 1246 |
mock_scanner.stop = AsyncMock() |
| 1247 |
mock_scanner.discovered_devices = [] |
| 1248 |
mock_scanner_class.return_value = mock_scanner |
| 1249 |
|
| 1250 |
await scanner.async_start() |
| 1251 |
|
| 1252 |
# Verify scanner was created with detection callback since no side channel |
| 1253 |
mock_scanner_class.assert_called_once() |
| 1254 |
call_kwargs = mock_scanner_class.call_args[1] |
| 1255 |
assert "detection_callback" in call_kwargs |
| 1256 |
assert call_kwargs["detection_callback"] is not None |
| 1257 |
assert call_kwargs["detection_callback"] == scanner._async_detection_callback |
| 1258 |
|
| 1259 |
await scanner.async_stop() |
| 1260 |
manager.async_stop() |
| 1261 |
|
| 1262 |
|
| 1263 |
@pytest.mark.asyncio |
| 1264 |
@pytest.mark.skipif(NOT_POSIX) |
| 1265 |
async def test_bluez_mgmt_protocol_data_flow(mock_btmgmt_socket: Mock) -> None: |
| 1266 |
"""Test data flow from BlueZ protocol through manager to scanner.""" |
| 1267 |
# Mock capability check for the entire test |
| 1268 |
with patch.object(MGMTBluetoothCtl, "_check_capabilities", return_value=True): |
| 1269 |
# Create manager |
| 1270 |
class TestBluetoothManager(BluetoothManager): |
| 1271 |
def __init__(self, *args, **kwargs): |
| 1272 |
super().__init__(*args, **kwargs) |
| 1273 |
self.discovered_infos = [] |
| 1274 |
|
| 1275 |
def _discover_service_info( |
| 1276 |
self, service_info: BluetoothServiceInfoBleak |
| 1277 |
) -> None: |
| 1278 |
"""Track discovered service info.""" |
| 1279 |
self.discovered_infos.append(service_info) |
| 1280 |
|
| 1281 |
adapters = FakeBluetoothAdapters() |
| 1282 |
slot_manager = BleakSlotManager() |
| 1283 |
manager = TestBluetoothManager(adapters, slot_manager) |
| 1284 |
set_manager(manager) |
| 1285 |
|
| 1286 |
# Set up manager first |
| 1287 |
await manager.async_setup() |
| 1288 |
|
| 1289 |
# Create mgmt controller with the manager's side channel scanners dictionary |
| 1290 |
mgmt_ctl = MGMTBluetoothCtl( |
| 1291 |
timeout=5.0, scanners=manager._side_channel_scanners |
| 1292 |
) |
| 1293 |
|
| 1294 |
# We'll capture the protocol when it's created |
| 1295 |
captured_protocol: BluetoothMGMTProtocol | None = None |
| 1296 |
|
| 1297 |
async def mock_create_connection(sock, protocol_factory, *args, **kwargs): |
| 1298 |
nonlocal captured_protocol |
| 1299 |
captured_protocol = protocol_factory() |
| 1300 |
mock_transport = Mock() |
| 1301 |
captured_protocol.connection_made(mock_transport) |
| 1302 |
return mock_transport, captured_protocol |
| 1303 |
|
| 1304 |
with patch.object( |
| 1305 |
asyncio.get_running_loop(), |
| 1306 |
"_create_connection_transport", |
| 1307 |
mock_create_connection, |
| 1308 |
): |
| 1309 |
await mgmt_ctl.setup() |
| 1310 |
|
| 1311 |
# Set mgmt controller on manager |
| 1312 |
manager._mgmt_ctl = mgmt_ctl |
| 1313 |
manager.has_advertising_side_channel = True |
| 1314 |
|
| 1315 |
# Register scanners for hci0 and hci1 |
| 1316 |
scanner0 = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:00") |
| 1317 |
scanner0.async_setup() |
| 1318 |
manager.async_register_scanner(scanner0, connection_slots=2) |
| 1319 |
|
| 1320 |
scanner1 = HaScanner(BluetoothScanningMode.ACTIVE, "hci1", "AA:BB:CC:DD:EE:01") |
| 1321 |
scanner1.async_setup() |
| 1322 |
manager.async_register_scanner(scanner1, connection_slots=2) |
| 1323 |
|
| 1324 |
# Start scanners |
| 1325 |
with patch( |
| 1326 |
"habluetooth.scanner_bleak.OriginalBleakScanner" |
| 1327 |
) as mock_scanner_class: |
| 1328 |
mock_scanner = Mock() |
| 1329 |
mock_scanner.start = AsyncMock() |
| 1330 |
mock_scanner.stop = AsyncMock() |
| 1331 |
mock_scanner.discovered_devices = [] |
| 1332 |
mock_scanner_class.return_value = mock_scanner |
| 1333 |
await scanner0.async_start() |
| 1334 |
await scanner1.async_start() |
| 1335 |
|
| 1336 |
# Verify scanners are registered in mgmt_ctl |
| 1337 |
assert 0 in mgmt_ctl.scanners |
| 1338 |
assert 1 in mgmt_ctl.scanners |
| 1339 |
assert mgmt_ctl.scanners[0] is scanner0 |
| 1340 |
assert mgmt_ctl.scanners[1] is scanner1 |
| 1341 |
|
| 1342 |
# Test DEVICE_FOUND event for hci0 |
| 1343 |
test_address = b"\x11\x22\x33\x44\x55\x66" |
| 1344 |
rssi_byte = b"\xc4" # -60 in signed byte |
| 1345 |
event_data = ( |
| 1346 |
test_address |
| 1347 |
+ b"\x01" # address_type |
| 1348 |
+ rssi_byte |
| 1349 |
+ b"\x06\x00\x00\x00" # flags |
| 1350 |
+ b"\x03\x00" # data_len |
| 1351 |
+ b"\x02\x01\x06" # minimal adv data |
| 1352 |
) |
| 1353 |
|
| 1354 |
packet = ( |
| 1355 |
DEVICE_FOUND.to_bytes(2, "little") |
| 1356 |
+ b"\x00\x00" # controller_idx 0 (hci0) |
| 1357 |
+ len(event_data).to_bytes(2, "little") |
| 1358 |
+ event_data |
| 1359 |
) |
| 1360 |
|
| 1361 |
# Feed packet to protocol |
| 1362 |
assert captured_protocol is not None |
| 1363 |
captured_protocol.data_received(packet) |
| 1364 |
|
| 1365 |
# Verify device discovered on scanner0 only |
| 1366 |
assert len(scanner0._previous_service_info) == 1 |
| 1367 |
assert "66:55:44:33:22:11" in scanner0._previous_service_info |
| 1368 |
assert len(scanner1._previous_service_info) == 0 |
| 1369 |
|
| 1370 |
# Test ADV_MONITOR_DEVICE_FOUND event for hci1 |
| 1371 |
test_address2 = b"\xaa\xbb\xcc\xdd\xee\x02" |
| 1372 |
monitor_handle = b"\x01\x00" |
| 1373 |
rssi_byte2 = b"\xba" # -70 in signed byte |
| 1374 |
event_data2 = ( |
| 1375 |
monitor_handle |
| 1376 |
+ test_address2 |
| 1377 |
+ b"\x02" # address_type (random) |
| 1378 |
+ rssi_byte2 |
| 1379 |
+ b"\x06\x00\x00\x00" # flags |
| 1380 |
+ b"\x03\x00" # data_len |
| 1381 |
+ b"\x02\x01\x06" # minimal adv data |
| 1382 |
) |
| 1383 |
|
| 1384 |
packet2 = ( |
| 1385 |
ADV_MONITOR_DEVICE_FOUND.to_bytes(2, "little") |
| 1386 |
+ b"\x01\x00" # controller_idx 1 (hci1) |
| 1387 |
+ len(event_data2).to_bytes(2, "little") |
| 1388 |
+ event_data2 |
| 1389 |
) |
| 1390 |
|
| 1391 |
assert captured_protocol is not None |
| 1392 |
captured_protocol.data_received(packet2) |
| 1393 |
|
| 1394 |
# Verify device discovered on scanner1 only |
| 1395 |
assert len(scanner0._previous_service_info) == 1 # Still just the first device |
| 1396 |
assert len(scanner1._previous_service_info) == 1 |
| 1397 |
assert "02:EE:DD:CC:BB:AA" in scanner1._previous_service_info |
| 1398 |
|
| 1399 |
# Verify RSSI values |
| 1400 |
info0 = scanner0._previous_service_info["66:55:44:33:22:11"] |
| 1401 |
assert info0.rssi == -60 |
| 1402 |
|
| 1403 |
info1 = scanner1._previous_service_info["02:EE:DD:CC:BB:AA"] |
| 1404 |
assert info1.rssi == -70 |
| 1405 |
|
| 1406 |
await scanner0.async_stop() |
| 1407 |
await scanner1.async_stop() |
| 1408 |
manager.async_stop() |
| 1409 |
|
| 1410 |
|
| 1411 |
@pytest.mark.asyncio |
| 1412 |
@pytest.mark.skipif(NOT_POSIX) |
| 1413 |
async def test_mgmt_permission_error_fallback() -> None: |
| 1414 |
"""Test that permission errors in MGMT setup fall back to BlueZ-only mode.""" |
| 1415 |
|
| 1416 |
# Create manager |
| 1417 |
class TestBluetoothManager(BluetoothManager): |
| 1418 |
def _discover_service_info( |
| 1419 |
self, service_info: BluetoothServiceInfoBleak |
| 1420 |
) -> None: |
| 1421 |
"""Track discovered service info.""" |
| 1422 |
|
| 1423 |
adapters = FakeBluetoothAdapters() |
| 1424 |
slot_manager = BleakSlotManager() |
| 1425 |
manager = TestBluetoothManager(adapters, slot_manager) |
| 1426 |
|
| 1427 |
# Mock MGMTBluetoothCtl setup to raise PermissionError |
| 1428 |
with ( |
| 1429 |
patch("habluetooth.manager.MGMTBluetoothCtl") as mock_mgmt_cls, |
| 1430 |
patch("habluetooth.manager.IS_LINUX", True), |
| 1431 |
): |
| 1432 |
mock_mgmt = Mock() |
| 1433 |
mock_mgmt.setup = AsyncMock( |
| 1434 |
side_effect=PermissionError( |
| 1435 |
"Missing NET_ADMIN/NET_RAW capabilities for Bluetooth management" |
| 1436 |
) |
| 1437 |
) |
| 1438 |
mock_mgmt_cls.return_value = mock_mgmt |
| 1439 |
|
| 1440 |
# Setup should complete without raising the exception |
| 1441 |
await manager.async_setup() |
| 1442 |
|
| 1443 |
# Verify MGMT was attempted but then set to None |
| 1444 |
mock_mgmt.setup.assert_called_once() |
| 1445 |
assert manager._mgmt_ctl is None |
| 1446 |
assert manager.has_advertising_side_channel is False |
| 1447 |
|
| 1448 |
|
| 1449 |
def test_usb_scanner_type() -> None: |
| 1450 |
"""Test that USB adapters get USB scanner type.""" |
| 1451 |
manager = get_manager() |
| 1452 |
|
| 1453 |
# Mock cached adapters with USB adapter |
| 1454 |
mock_adapters: dict[str, dict[str, Any]] = { |
| 1455 |
"hci0": { |
| 1456 |
"address": "00:1A:7D:DA:71:04", |
| 1457 |
"adapter_type": "usb", |
| 1458 |
"manufacturer": "TestManufacturer", |
| 1459 |
"product": "USB Bluetooth Adapter", |
| 1460 |
} |
| 1461 |
} |
| 1462 |
|
| 1463 |
with patch.object(manager, "_adapters", mock_adapters): |
| 1464 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "00:1A:7D:DA:71:04") |
| 1465 |
assert scanner.details.scanner_type is HaScannerType.USB |
| 1466 |
|
| 1467 |
|
| 1468 |
def test_uart_scanner_type() -> None: |
| 1469 |
"""Test that UART adapters get UART scanner type.""" |
| 1470 |
manager = get_manager() |
| 1471 |
|
| 1472 |
# Mock cached adapters with UART adapter |
| 1473 |
mock_adapters: dict[str, dict[str, Any]] = { |
| 1474 |
"hci0": { |
| 1475 |
"address": "00:1A:7D:DA:71:04", |
| 1476 |
"adapter_type": "uart", |
| 1477 |
"manufacturer": "TestManufacturer", |
| 1478 |
"product": "UART Bluetooth Module", |
| 1479 |
} |
| 1480 |
} |
| 1481 |
|
| 1482 |
with patch.object(manager, "_adapters", mock_adapters): |
| 1483 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "00:1A:7D:DA:71:04") |
| 1484 |
assert scanner.details.scanner_type is HaScannerType.UART |
| 1485 |
|
| 1486 |
|
| 1487 |
def test_unknown_scanner_type_no_cached_adapters() -> None: |
| 1488 |
"""Test that scanners get UNKNOWN type when no adapter info is cached.""" |
| 1489 |
manager = get_manager() |
| 1490 |
|
| 1491 |
# No cached adapters |
| 1492 |
with patch.object(manager, "_adapters", None): |
| 1493 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "00:1A:7D:DA:71:04") |
| 1494 |
assert scanner.details.scanner_type is HaScannerType.UNKNOWN |
| 1495 |
|
| 1496 |
|
| 1497 |
def test_unknown_scanner_type_adapter_not_found() -> None: |
| 1498 |
"""Test that scanners get UNKNOWN type when adapter is not in cache.""" |
| 1499 |
manager = get_manager() |
| 1500 |
|
| 1501 |
# Cached adapters but not the one we're looking for |
| 1502 |
mock_adapters: dict[str, dict[str, Any]] = { |
| 1503 |
"hci1": { |
| 1504 |
"address": "11:22:33:44:55:66", |
| 1505 |
"adapter_type": "usb", |
| 1506 |
} |
| 1507 |
} |
| 1508 |
|
| 1509 |
with patch.object(manager, "_adapters", mock_adapters): |
| 1510 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "00:1A:7D:DA:71:04") |
| 1511 |
assert scanner.details.scanner_type is HaScannerType.UNKNOWN |
| 1512 |
|
| 1513 |
|
| 1514 |
def test_unknown_scanner_type_no_adapter_type() -> None: |
| 1515 |
"""Test that scanners get UNKNOWN type when adapter_type is None.""" |
| 1516 |
manager = get_manager() |
| 1517 |
|
| 1518 |
# Cached adapter without adapter_type field |
| 1519 |
mock_adapters: dict[str, dict[str, Any]] = { |
| 1520 |
"hci0": { |
| 1521 |
"address": "00:1A:7D:DA:71:04", |
| 1522 |
"adapter_type": None, |
| 1523 |
"manufacturer": "TestManufacturer", |
| 1524 |
} |
| 1525 |
} |
| 1526 |
|
| 1527 |
with patch.object(manager, "_adapters", mock_adapters): |
| 1528 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "00:1A:7D:DA:71:04") |
| 1529 |
assert scanner.details.scanner_type is HaScannerType.UNKNOWN |
| 1530 |
|
| 1531 |
|
| 1532 |
@pytest.mark.asyncio |
| 1533 |
async def test_scanner_type_with_real_adapter_data() -> None: |
| 1534 |
"""Test scanner type detection with realistic adapter data.""" |
| 1535 |
# Create a custom manager for this test |
| 1536 |
manager = BluetoothManager(bluetooth_adapters=MagicMock()) |
| 1537 |
set_manager(manager) |
| 1538 |
|
| 1539 |
# Simulate real USB adapter data from Linux |
| 1540 |
usb_adapter_data: dict[str, dict[str, Any]] = { |
| 1541 |
"hci0": { |
| 1542 |
"address": "00:1A:7D:DA:71:04", |
| 1543 |
"sw_version": "homeassistant", |
| 1544 |
"hw_version": "usb:v1D6Bp0246d053F", |
| 1545 |
"passive_scan": False, |
| 1546 |
"manufacturer": "XTech", |
| 1547 |
"product": "Bluetooth 4.0 USB Adapter", |
| 1548 |
"vendor_id": "0a12", |
| 1549 |
"product_id": "0001", |
| 1550 |
"adapter_type": "usb", |
| 1551 |
} |
| 1552 |
} |
| 1553 |
|
| 1554 |
manager._adapters = usb_adapter_data |
| 1555 |
|
| 1556 |
# Create USB scanner |
| 1557 |
usb_scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "00:1A:7D:DA:71:04") |
| 1558 |
assert usb_scanner.details.scanner_type is HaScannerType.USB |
| 1559 |
assert usb_scanner.details.adapter == "hci0" |
| 1560 |
|
| 1561 |
# Simulate real UART adapter data |
| 1562 |
uart_adapter_data: dict[str, dict[str, Any]] = { |
| 1563 |
"hci1": { |
| 1564 |
"address": "AA:BB:CC:DD:EE:FF", |
| 1565 |
"sw_version": "homeassistant", |
| 1566 |
"hw_version": "uart:ttyUSB0", |
| 1567 |
"passive_scan": False, |
| 1568 |
"manufacturer": "cyber-blue(HK)Ltd", |
| 1569 |
"product": "Bluetooth 4.0 UART Module", |
| 1570 |
"vendor_id": None, |
| 1571 |
"product_id": None, |
| 1572 |
"adapter_type": "uart", |
| 1573 |
} |
| 1574 |
} |
| 1575 |
|
| 1576 |
manager._adapters = uart_adapter_data |
| 1577 |
|
| 1578 |
# Create UART scanner |
| 1579 |
uart_scanner = HaScanner(BluetoothScanningMode.PASSIVE, "hci1", "AA:BB:CC:DD:EE:FF") |
| 1580 |
assert uart_scanner.details.scanner_type is HaScannerType.UART |
| 1581 |
assert uart_scanner.details.adapter == "hci1" |
| 1582 |
|
| 1583 |
# Test with macOS/Windows adapter (no adapter_type) |
| 1584 |
macos_adapter_data = { |
| 1585 |
"Core Bluetooth": { |
| 1586 |
"address": "00:00:00:00:00:00", |
| 1587 |
"passive_scan": False, |
| 1588 |
"sw_version": "18.7.0", |
| 1589 |
"manufacturer": "Apple", |
| 1590 |
"product": "Unknown MacOS Model", |
| 1591 |
"vendor_id": "Unknown", |
| 1592 |
"product_id": "Unknown", |
| 1593 |
"adapter_type": None, |
| 1594 |
} |
| 1595 |
} |
| 1596 |
|
| 1597 |
manager._adapters = macos_adapter_data |
| 1598 |
|
| 1599 |
# Create scanner with unknown adapter type |
| 1600 |
macos_scanner = HaScanner( |
| 1601 |
BluetoothScanningMode.ACTIVE, "Core Bluetooth", "00:00:00:00:00:00" |
| 1602 |
) |
| 1603 |
assert macos_scanner.details.scanner_type is HaScannerType.UNKNOWN |
| 1604 |
|
| 1605 |
|
| 1606 |
@pytest.mark.asyncio |
| 1607 |
async def test_scanner_type_updates_after_adapter_refresh() -> None: |
| 1608 |
"""Test scanner type is UNKNOWN initially, determined after adapters load.""" |
| 1609 |
# Create a custom manager for this test |
| 1610 |
manager = BluetoothManager(bluetooth_adapters=MagicMock()) |
| 1611 |
set_manager(manager) |
| 1612 |
|
| 1613 |
# Initially no adapters cached |
| 1614 |
manager._adapters = None # type: ignore[assignment] |
| 1615 |
|
| 1616 |
# Create scanner - should be UNKNOWN |
| 1617 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "00:1A:7D:DA:71:04") |
| 1618 |
assert scanner.details.scanner_type is HaScannerType.UNKNOWN |
| 1619 |
|
| 1620 |
# Now simulate adapter data becoming available |
| 1621 |
manager._adapters = { |
| 1622 |
"hci0": { |
| 1623 |
"address": "00:1A:7D:DA:71:04", |
| 1624 |
"adapter_type": "usb", |
| 1625 |
"manufacturer": "TestManufacturer", |
| 1626 |
} |
| 1627 |
} |
| 1628 |
|
| 1629 |
# Create a new scanner with the same adapter - should now be USB |
| 1630 |
scanner2 = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "00:1A:7D:DA:71:04") |
| 1631 |
assert scanner2.details.scanner_type is HaScannerType.USB |
| 1632 |
|
| 1633 |
# Note: The first scanner still has UNKNOWN since scanner_type is set at init |
| 1634 |
assert scanner.details.scanner_type is HaScannerType.UNKNOWN |
| 1635 |
|
| 1636 |
|
| 1637 |
def test_multiple_scanner_types_simultaneously() -> None: |
| 1638 |
"""Test that multiple scanners can have different types at the same time.""" |
| 1639 |
manager = get_manager() |
| 1640 |
|
| 1641 |
# Set up adapters with different types |
| 1642 |
mock_adapters = { |
| 1643 |
"hci0": { |
| 1644 |
"address": "00:1A:7D:DA:71:04", |
| 1645 |
"adapter_type": "usb", |
| 1646 |
}, |
| 1647 |
"hci1": { |
| 1648 |
"address": "AA:BB:CC:DD:EE:FF", |
| 1649 |
"adapter_type": "uart", |
| 1650 |
}, |
| 1651 |
"hci2": { |
| 1652 |
"address": "11:22:33:44:55:66", |
| 1653 |
"adapter_type": None, |
| 1654 |
}, |
| 1655 |
} |
| 1656 |
|
| 1657 |
with patch.object(manager, "_adapters", mock_adapters): |
| 1658 |
# Create scanners of different types |
| 1659 |
usb_scanner = HaScanner( |
| 1660 |
BluetoothScanningMode.ACTIVE, "hci0", "00:1A:7D:DA:71:04" |
| 1661 |
) |
| 1662 |
uart_scanner = HaScanner( |
| 1663 |
BluetoothScanningMode.ACTIVE, "hci1", "AA:BB:CC:DD:EE:FF" |
| 1664 |
) |
| 1665 |
unknown_scanner = HaScanner( |
| 1666 |
BluetoothScanningMode.ACTIVE, "hci2", "11:22:33:44:55:66" |
| 1667 |
) |
| 1668 |
|
| 1669 |
# Verify each has the correct type |
| 1670 |
assert usb_scanner.details.scanner_type is HaScannerType.USB |
| 1671 |
assert uart_scanner.details.scanner_type is HaScannerType.UART |
| 1672 |
assert unknown_scanner.details.scanner_type is HaScannerType.UNKNOWN |
| 1673 |
|
| 1674 |
# Verify they all have different types |
| 1675 |
types = { |
| 1676 |
usb_scanner.details.scanner_type, |
| 1677 |
uart_scanner.details.scanner_type, |
| 1678 |
unknown_scanner.details.scanner_type, |
| 1679 |
} |
| 1680 |
assert len(types) == 3 # All different |
| 1681 |
|
| 1682 |
|
| 1683 |
def test_ha_scanner_get_allocations_no_slot_manager() -> None: |
| 1684 |
"""Test HaScanner.get_allocations returns None when manager has no slot_manager.""" |
| 1685 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 1686 |
manager = get_manager() |
| 1687 |
|
| 1688 |
# Mock slot_manager as None |
| 1689 |
with patch.object(manager, "slot_manager", None): |
| 1690 |
assert scanner.get_allocations() is None |
| 1691 |
|
| 1692 |
|
| 1693 |
def test_ha_scanner_get_allocations_with_slot_manager() -> None: |
| 1694 |
"""Test HaScanner.get_allocations returns allocation info from BleakSlotManager.""" |
| 1695 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 1696 |
manager = get_manager() |
| 1697 |
|
| 1698 |
# Create mock allocations |
| 1699 |
mock_allocations = Allocations( |
| 1700 |
adapter="hci0", |
| 1701 |
slots=5, |
| 1702 |
free=3, |
| 1703 |
allocated=["11:22:33:44:55:66", "AA:BB:CC:DD:EE:FF"], |
| 1704 |
) |
| 1705 |
|
| 1706 |
# Mock slot_manager |
| 1707 |
mock_slot_manager = Mock(spec=BleakSlotManager) |
| 1708 |
mock_slot_manager.get_allocations.return_value = mock_allocations |
| 1709 |
|
| 1710 |
with patch.object(manager, "slot_manager", mock_slot_manager): |
| 1711 |
allocations = scanner.get_allocations() |
| 1712 |
|
| 1713 |
assert allocations is not None |
| 1714 |
assert allocations == mock_allocations |
| 1715 |
mock_slot_manager.get_allocations.assert_called_once_with("hci0") |
| 1716 |
|
| 1717 |
|
| 1718 |
def test_ha_scanner_get_allocations_updates_dynamically() -> None: |
| 1719 |
"""Test that HaScanner.get_allocations returns current values as they change.""" |
| 1720 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 1721 |
manager = get_manager() |
| 1722 |
|
| 1723 |
# Mock slot_manager |
| 1724 |
mock_slot_manager = Mock(spec=BleakSlotManager) |
| 1725 |
|
| 1726 |
# Initial state - 3 free slots |
| 1727 |
mock_slot_manager.get_allocations.return_value = Allocations( |
| 1728 |
adapter="hci0", slots=3, free=3, allocated=[] |
| 1729 |
) |
| 1730 |
|
| 1731 |
with patch.object(manager, "slot_manager", mock_slot_manager): |
| 1732 |
# Check initial state |
| 1733 |
allocations = scanner.get_allocations() |
| 1734 |
assert allocations is not None |
| 1735 |
assert allocations.free == 3 |
| 1736 |
assert allocations.allocated == [] |
| 1737 |
|
| 1738 |
# Update mock to simulate connection made |
| 1739 |
mock_slot_manager.get_allocations.return_value = Allocations( |
| 1740 |
adapter="hci0", slots=3, free=2, allocated=["11:22:33:44:55:66"] |
| 1741 |
) |
| 1742 |
|
| 1743 |
# Check updated state |
| 1744 |
allocations = scanner.get_allocations() |
| 1745 |
assert allocations is not None |
| 1746 |
assert allocations.free == 2 |
| 1747 |
assert allocations.allocated == ["11:22:33:44:55:66"] |
| 1748 |
|
| 1749 |
# Update mock to simulate another connection |
| 1750 |
mock_slot_manager.get_allocations.return_value = Allocations( |
| 1751 |
adapter="hci0", |
| 1752 |
slots=3, |
| 1753 |
free=1, |
| 1754 |
allocated=["11:22:33:44:55:66", "AA:BB:CC:DD:EE:FF"], |
| 1755 |
) |
| 1756 |
|
| 1757 |
# Check final state |
| 1758 |
allocations = scanner.get_allocations() |
| 1759 |
assert allocations is not None |
| 1760 |
assert allocations.free == 1 |
| 1761 |
assert len(allocations.allocated) == 2 |
| 1762 |
|
| 1763 |
|
| 1764 |
@pytest.mark.asyncio |
| 1765 |
async def test_on_scanner_start_callback( |
| 1766 |
async_mock_manager_with_scanner_callbacks: MockBluetoothManagerWithCallbacks, |
| 1767 |
) -> None: |
| 1768 |
"""Test that on_scanner_start is called when a local scanner starts.""" |
| 1769 |
manager = async_mock_manager_with_scanner_callbacks |
| 1770 |
|
| 1771 |
# Create a local scanner (it will get the manager from get_manager()) |
| 1772 |
scanner = HaScanner( |
| 1773 |
mode=BluetoothScanningMode.ACTIVE, |
| 1774 |
adapter="hci0", |
| 1775 |
address="00:00:00:00:00:00", |
| 1776 |
) |
| 1777 |
|
| 1778 |
# Register scanner with manager |
| 1779 |
manager.async_register_scanner(scanner) |
| 1780 |
|
| 1781 |
# Setup the scanner |
| 1782 |
scanner.async_setup() |
| 1783 |
|
| 1784 |
# Directly call _on_start_success to test the callback |
| 1785 |
# (In real usage, this is called by HaScanner._async_start_attempt |
| 1786 |
# after successful start) |
| 1787 |
scanner._on_start_success() |
| 1788 |
|
| 1789 |
# Verify the callback was called |
| 1790 |
assert len(manager.scanner_start_calls) == 1 |
| 1791 |
assert manager.scanner_start_calls[0] is scanner |
| 1792 |
|
| 1793 |
|
| 1794 |
@pytest.mark.asyncio |
| 1795 |
async def test_async_request_active_window_rejected_when_not_auto() -> None: |
| 1796 |
"""Non-AUTO scanners ignore active-window requests and return False.""" |
| 1797 |
scanner = HaScanner(BluetoothScanningMode.PASSIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 1798 |
scanner.async_setup() |
| 1799 |
assert await scanner.async_request_active_window(1.0) is False |
| 1800 |
assert scanner._scan_mode_override is None |
| 1801 |
|
| 1802 |
|
| 1803 |
@pytest.mark.asyncio |
| 1804 |
@pytest.mark.parametrize("duration", [float("nan"), float("inf"), -1.0, 0.0]) |
| 1805 |
async def test_async_request_active_window_rejects_invalid_duration( |
| 1806 |
duration: float, |
| 1807 |
) -> None: |
| 1808 |
""" |
| 1809 |
NaN/inf/non-positive durations are refused at the entry point. |
| 1810 |
|
| 1811 |
A bad duration would poison ``loop.call_later`` (which raises on |
| 1812 |
NaN) and the extension comparison (NaN ordering is always False, |
| 1813 |
inf would lock the window open). Guard the public entry so a |
| 1814 |
misbehaving subclass / direct caller can't corrupt the scheduler |
| 1815 |
state. |
| 1816 |
""" |
| 1817 |
scanner = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:FF") |
| 1818 |
scanner.async_setup() |
| 1819 |
assert await scanner.async_request_active_window(duration) is False |
| 1820 |
assert scanner._scan_mode_override is None |
| 1821 |
assert scanner._active_window_handle is None |
| 1822 |
|
| 1823 |
|
| 1824 |
@pytest.mark.usefixtures("force_linux_scanner_mode") |
| 1825 |
@pytest.mark.asyncio |
| 1826 |
async def test_async_request_active_window_restarts_scanner_in_active_mode() -> None: |
| 1827 |
"""An AUTO scanner flips to ACTIVE and schedules a return to the prior mode.""" |
| 1828 |
starts: list[str] = [] |
| 1829 |
|
| 1830 |
def _factory(*_args, **kwargs): |
| 1831 |
starts.append(kwargs["scanning_mode"]) |
| 1832 |
return MockBleakScanner() |
| 1833 |
|
| 1834 |
with patch("habluetooth.scanner_bleak.OriginalBleakScanner", side_effect=_factory): |
| 1835 |
scanner = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:FF") |
| 1836 |
scanner.async_setup() |
| 1837 |
await scanner.async_start() |
| 1838 |
# Initial construction: AUTO maps to passive in bleak's |
| 1839 |
# scanning_mode. The active-window toggle path reuses |
| 1840 |
# this single BleakScanner instance and just mutates |
| 1841 |
# _backend._scanning_mode instead of constructing again. |
| 1842 |
assert starts == ["passive"] |
| 1843 |
backend = scanner.scanner._backend # type: ignore[union-attr] |
| 1844 |
backend._scanning_mode = "passive" |
| 1845 |
|
| 1846 |
# Tiny duration so call_later fires on the next loop turn. |
| 1847 |
# async_request_active_window rejects 0/NaN/inf at the boundary, |
| 1848 |
# so we use the smallest positive value that round-trips through |
| 1849 |
# the timer arithmetic. |
| 1850 |
assert await scanner.async_request_active_window(1e-9) is True |
| 1851 |
# The toggle flipped the existing instance to active. |
| 1852 |
assert backend._scanning_mode == "active" |
| 1853 |
assert scanner._scan_mode_override is BluetoothScanningMode.ACTIVE |
| 1854 |
assert scanner._active_window_handle is not None |
| 1855 |
|
| 1856 |
# Let the call_later fire and the background restart task complete. |
| 1857 |
for _ in range(6): |
| 1858 |
await asyncio.sleep(0) |
| 1859 |
# End-of-window toggled the same instance back to passive. |
| 1860 |
assert backend._scanning_mode == "passive" |
| 1861 |
assert scanner._scan_mode_override is None |
| 1862 |
assert scanner._active_window_handle is None # type: ignore[unreachable] |
| 1863 |
|
| 1864 |
await scanner.async_stop() |
| 1865 |
|
| 1866 |
|
| 1867 |
@pytest.mark.asyncio |
| 1868 |
async def test_active_window_restart_does_not_log_fallback_warning( |
| 1869 |
caplog: pytest.LogCaptureFixture, |
| 1870 |
) -> None: |
| 1871 |
""" |
| 1872 |
A successful active-window restart on an AUTO scanner must not warn. |
| 1873 |
|
| 1874 |
Regression: the start-success log compared current_mode against |
| 1875 |
requested_mode. For an AUTO scanner mid-active-window, |
| 1876 |
requested_mode is AUTO but current_mode is ACTIVE (because the |
| 1877 |
restart was triggered by the scheduler with |
| 1878 |
_scan_mode_override=ACTIVE), so the previous code logged a |
| 1879 |
spurious "fell back to passive" warning on every active-window |
| 1880 |
restart. The check now uses effective_mode (the mode we tried to |
| 1881 |
start in) so it only triggers on a real fallback. |
| 1882 |
""" |
| 1883 |
with patch( |
| 1884 |
"habluetooth.scanner_bleak.OriginalBleakScanner", |
| 1885 |
side_effect=lambda *_a, **_kw: MockBleakScanner(), |
| 1886 |
): |
| 1887 |
scanner = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:FF") |
| 1888 |
scanner.async_setup() |
| 1889 |
await scanner.async_start() |
| 1890 |
caplog.clear() |
| 1891 |
with caplog.at_level(logging.WARNING): |
| 1892 |
assert await scanner.async_request_active_window(10.0) is True |
| 1893 |
assert not any( |
| 1894 |
"fall-back to passive" in record.message for record in caplog.records |
| 1895 |
) |
| 1896 |
await scanner.async_stop() |
| 1897 |
|
| 1898 |
|
| 1899 |
@pytest.mark.usefixtures("force_linux_scanner_mode") |
| 1900 |
@pytest.mark.asyncio |
| 1901 |
async def test_async_toggle_active_window_mode_returns_false_when_no_scanner() -> None: |
| 1902 |
"""The toggle helper bails when the scanner instance is gone.""" |
| 1903 |
scanner_obj = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:FF") |
| 1904 |
scanner_obj.async_setup() |
| 1905 |
assert scanner_obj.scanner is None |
| 1906 |
assert await scanner_obj._async_toggle_active_window_mode() is False |
| 1907 |
|
| 1908 |
|
| 1909 |
@pytest.mark.usefixtures("force_linux_scanner_mode") |
| 1910 |
@pytest.mark.asyncio |
| 1911 |
async def test_async_toggle_active_window_mode_returns_false_on_stop_error() -> None: |
| 1912 |
"""The toggle helper logs and bails when scanner.stop() raises.""" |
| 1913 |
|
| 1914 |
class StopErrorMockBleakScanner(MockBleakScanner): |
| 1915 |
async def stop(self) -> None: |
| 1916 |
msg = "simulated stop failure" |
| 1917 |
raise BleakError(msg) |
| 1918 |
|
| 1919 |
with patch_bleak_scanner_factory(StopErrorMockBleakScanner): |
| 1920 |
scanner_obj = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:FF") |
| 1921 |
scanner_obj.async_setup() |
| 1922 |
await scanner_obj.async_start() |
| 1923 |
scanner_obj._scan_mode_override = BluetoothScanningMode.ACTIVE |
| 1924 |
assert scanner_obj.scanning is True |
| 1925 |
assert await scanner_obj._async_toggle_active_window_mode() is False |
| 1926 |
# scanner.stop() raised so the bleak scanner is in an |
| 1927 |
# undefined state; the wrapper must reflect that as not- |
| 1928 |
# scanning so the caller's fallback path treats it correctly. |
| 1929 |
assert scanner_obj.scanning is False |
| 1930 |
|
| 1931 |
|
| 1932 |
@pytest.mark.usefixtures("force_linux_scanner_mode") |
| 1933 |
@pytest.mark.asyncio |
| 1934 |
async def test_async_toggle_active_window_mode_marks_not_scanning_on_start_error() -> ( |
| 1935 |
None |
| 1936 |
): |
| 1937 |
""" |
| 1938 |
Toggle's start-error path also clears self.scanning. |
| 1939 |
|
| 1940 |
The stop succeeded but the post-mode-flip start raised, so the |
| 1941 |
bleak scanner is stopped. self.scanning must follow. |
| 1942 |
""" |
| 1943 |
starts = 0 |
| 1944 |
|
| 1945 |
class StartErrorMockBleakScanner(MockBleakScanner): |
| 1946 |
async def start(self) -> None: |
| 1947 |
nonlocal starts |
| 1948 |
starts += 1 |
| 1949 |
# First start (initial async_start) succeeds; the |
| 1950 |
# post-flip start (second call) raises. |
| 1951 |
if starts > 1: |
| 1952 |
msg = "simulated start failure" |
| 1953 |
raise BleakError(msg) |
| 1954 |
|
| 1955 |
with patch_bleak_scanner_factory(StartErrorMockBleakScanner): |
| 1956 |
scanner_obj = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:FF") |
| 1957 |
scanner_obj.async_setup() |
| 1958 |
await scanner_obj.async_start() |
| 1959 |
scanner_obj._scan_mode_override = BluetoothScanningMode.ACTIVE |
| 1960 |
assert scanner_obj.scanning is True |
| 1961 |
assert await scanner_obj._async_toggle_active_window_mode() is False |
| 1962 |
assert scanner_obj.scanning is False |
| 1963 |
|
| 1964 |
|
| 1965 |
@pytest.mark.usefixtures("force_linux_scanner_mode") |
| 1966 |
@pytest.mark.asyncio |
| 1967 |
async def test_async_toggle_active_window_mode_restores_discoveries() -> None: |
| 1968 |
"""A successful in place toggle re-seeds bleak's discovered map.""" |
| 1969 |
with ( |
| 1970 |
patch_bleak_scanner_factory(MockBleakScanner), |
| 1971 |
patch("habluetooth.scanner_bleak.restore_discoveries", AsyncMock()) as restore, |
| 1972 |
patch("habluetooth.scanner_bleak.restore_discoveries_sync") as restore_sync, |
| 1973 |
): |
| 1974 |
scanner_obj = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:FF") |
| 1975 |
scanner_obj.async_setup() |
| 1976 |
await scanner_obj.async_start() |
| 1977 |
assert restore.await_count == 1 |
| 1978 |
scanner_obj._scan_mode_override = BluetoothScanningMode.ACTIVE |
| 1979 |
assert await scanner_obj._async_toggle_active_window_mode() is True |
| 1980 |
assert restore.await_count == 1 |
| 1981 |
restore_sync.assert_called_once_with(scanner_obj.scanner, "hci0") |
| 1982 |
await scanner_obj.async_stop() |
| 1983 |
|
| 1984 |
|
| 1985 |
@pytest.mark.usefixtures("force_linux_scanner_mode") |
| 1986 |
@pytest.mark.asyncio |
| 1987 |
async def test_async_toggle_active_window_mode_attribute_error_marks_not_scanning() -> ( |
| 1988 |
None |
| 1989 |
): |
| 1990 |
""" |
| 1991 |
Toggle gracefully handles bleak refactoring away ``_scanning_mode``. |
| 1992 |
|
| 1993 |
If a future bleak version drops or renames ``_backend._scanning_mode``, |
| 1994 |
the mutation raises AttributeError. The stop has already completed, |
| 1995 |
so without a guard the scanner would be left stopped and the caller |
| 1996 |
would have no signal to fall back to the full path. The guard logs, |
| 1997 |
clears ``self.scanning``, and returns False so the caller can |
| 1998 |
recover via the full restart path. |
| 1999 |
""" |
| 2000 |
|
| 2001 |
class MockBackend: |
| 2002 |
@property |
| 2003 |
def _scanning_mode(self) -> str: |
| 2004 |
msg = "simulated bleak refactor — attribute removed" |
| 2005 |
raise AttributeError(msg) |
| 2006 |
|
| 2007 |
@_scanning_mode.setter |
| 2008 |
def _scanning_mode(self, value: str) -> None: |
| 2009 |
msg = "simulated bleak refactor — attribute removed" |
| 2010 |
raise AttributeError(msg) |
| 2011 |
|
| 2012 |
class AttrErrorMockBleakScanner(MockBleakScanner): |
| 2013 |
def __init__(self) -> None: |
| 2014 |
self._backend = MockBackend() |
| 2015 |
|
| 2016 |
with patch_bleak_scanner_factory(AttrErrorMockBleakScanner): |
| 2017 |
scanner_obj = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:FF") |
| 2018 |
scanner_obj.async_setup() |
| 2019 |
await scanner_obj.async_start() |
| 2020 |
scanner_obj._scan_mode_override = BluetoothScanningMode.ACTIVE |
| 2021 |
assert scanner_obj.scanning is True |
| 2022 |
assert await scanner_obj._async_toggle_active_window_mode() is False |
| 2023 |
assert scanner_obj.scanning is False |
| 2024 |
|
| 2025 |
|
| 2026 |
@pytest.mark.usefixtures("force_linux_scanner_mode") |
| 2027 |
@pytest.mark.asyncio |
| 2028 |
async def test_arm_active_window_timer_cancels_existing_handle() -> None: |
| 2029 |
""" |
| 2030 |
_arm_active_window_timer cancels any prior handle before arming. |
| 2031 |
|
| 2032 |
Regression for the concurrent-callers race noted in PR review: |
| 2033 |
two concurrent ``async_request_active_window`` calls could both |
| 2034 |
reach _arm_active_window_timer without the second cancelling the |
| 2035 |
first's TimerHandle, leaking a pending timer that would later fire |
| 2036 |
an extra _async_end_active_window. Today only the scheduler drives |
| 2037 |
the public method (and _tick serializes per worker) so the race |
| 2038 |
isn't reachable through normal callers, but the contract on |
| 2039 |
_arm_active_window_timer must defend against it. |
| 2040 |
""" |
| 2041 |
with patch( |
| 2042 |
"habluetooth.scanner_bleak.OriginalBleakScanner", |
| 2043 |
side_effect=lambda *_a, **_kw: MockBleakScanner(), |
| 2044 |
): |
| 2045 |
scanner = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:FF") |
| 2046 |
scanner.async_setup() |
| 2047 |
await scanner.async_start() |
| 2048 |
|
| 2049 |
# Arm a window so there's a handle to potentially leak. |
| 2050 |
assert await scanner.async_request_active_window(100.0) is True |
| 2051 |
first_handle = scanner._active_window_handle |
| 2052 |
assert first_handle is not None |
| 2053 |
# Directly call _arm again (simulating the race-path second |
| 2054 |
# caller). The first handle must be cancelled, not leaked. |
| 2055 |
scanner._arm_active_window_timer(50.0) |
| 2056 |
assert first_handle.cancelled() |
| 2057 |
assert scanner._active_window_handle is not first_handle |
| 2058 |
|
| 2059 |
await scanner.async_stop() |
| 2060 |
|
| 2061 |
|
| 2062 |
@pytest.mark.usefixtures("force_linux_scanner_mode") |
| 2063 |
@pytest.mark.asyncio |
| 2064 |
async def test_async_request_active_window_extends_existing_window() -> None: |
| 2065 |
"""A second request inside an active window extends the timer in place.""" |
| 2066 |
starts: list[str] = [] |
| 2067 |
|
| 2068 |
def _factory(*_args, **kwargs): |
| 2069 |
starts.append(kwargs["scanning_mode"]) |
| 2070 |
return MockBleakScanner() |
| 2071 |
|
| 2072 |
with patch("habluetooth.scanner_bleak.OriginalBleakScanner", side_effect=_factory): |
| 2073 |
scanner = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:FF") |
| 2074 |
scanner.async_setup() |
| 2075 |
await scanner.async_start() |
| 2076 |
|
| 2077 |
assert await scanner.async_request_active_window(100.0) is True |
| 2078 |
first_handle = scanner._active_window_handle |
| 2079 |
first_end = scanner._active_window_end |
| 2080 |
# A longer request extends the existing window without a second restart. |
| 2081 |
assert await scanner.async_request_active_window(200.0) is True |
| 2082 |
assert scanner._active_window_handle is not first_handle |
| 2083 |
assert scanner._active_window_end > first_end |
| 2084 |
# Only one BleakScanner construction happened (the initial |
| 2085 |
# passive one). The active-window flip toggles the existing |
| 2086 |
# instance's _backend._scanning_mode instead of creating a |
| 2087 |
# new scanner. |
| 2088 |
assert starts == ["passive"] |
| 2089 |
assert scanner.current_mode is BluetoothScanningMode.ACTIVE |
| 2090 |
# A shorter follow-up is a no-op on the timer. |
| 2091 |
kept_end = scanner._active_window_end |
| 2092 |
assert await scanner.async_request_active_window(0.001) is True |
| 2093 |
assert scanner._active_window_end == kept_end |
| 2094 |
|
| 2095 |
await scanner.async_stop() |
| 2096 |
|
| 2097 |
|
| 2098 |
@pytest.mark.usefixtures("force_linux_scanner_mode") |
| 2099 |
@pytest.mark.asyncio |
| 2100 |
async def test_async_request_active_window_end_time_matches_real_timer() -> None: |
| 2101 |
""" |
| 2102 |
_active_window_end reflects the post-restart loop.time() + duration. |
| 2103 |
|
| 2104 |
Regression: a slow stop/restart cycle previously left |
| 2105 |
``_active_window_end`` set to ``loop.time() + duration`` captured |
| 2106 |
*before* the restart, so it lagged the real ``call_later`` fire |
| 2107 |
time by the restart duration. The fix moved the |
| 2108 |
``_active_window_end`` computation inside |
| 2109 |
``_arm_active_window_timer`` so it always matches when the timer |
| 2110 |
will actually fire. |
| 2111 |
|
| 2112 |
Uses an asyncio.Event to gate the restart-in-progress |
| 2113 |
deterministically rather than relying on asyncio.sleep precision, |
| 2114 |
which can fire slightly early on busy CI runners. |
| 2115 |
""" |
| 2116 |
duration = 10.0 |
| 2117 |
restart_started = asyncio.Event() |
| 2118 |
gate = asyncio.Event() |
| 2119 |
|
| 2120 |
class GatedMockBleakScanner(MockBleakScanner): |
| 2121 |
_first_start_done = False |
| 2122 |
|
| 2123 |
async def start(self) -> None: |
| 2124 |
if not type(self)._first_start_done: |
| 2125 |
type(self)._first_start_done = True |
| 2126 |
return |
| 2127 |
restart_started.set() |
| 2128 |
await gate.wait() |
| 2129 |
|
| 2130 |
with patch_bleak_scanner_factory(GatedMockBleakScanner): |
| 2131 |
scanner = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:FF") |
| 2132 |
scanner.async_setup() |
| 2133 |
await scanner.async_start() |
| 2134 |
|
| 2135 |
loop = asyncio.get_running_loop() |
| 2136 |
before = loop.time() |
| 2137 |
task = asyncio.create_task(scanner.async_request_active_window(duration)) |
| 2138 |
await restart_started.wait() |
| 2139 |
# Provably advance loop.time() past `before` before the restart |
| 2140 |
# completes; the exact amount doesn't matter for the assertion |
| 2141 |
# below as long as loop.time() has visibly moved. |
| 2142 |
await asyncio.sleep(0.05) |
| 2143 |
elapsed = loop.time() - before |
| 2144 |
gate.set() |
| 2145 |
assert await task is True |
| 2146 |
|
| 2147 |
# Contract: _active_window_end matches loop.time() + duration |
| 2148 |
# measured AFTER the restart, not before. Pre-fix it would be |
| 2149 |
# before + duration. Allow generous tolerance for the small |
| 2150 |
# gap between arming and reading. |
| 2151 |
now = loop.time() |
| 2152 |
assert scanner._active_window_end == pytest.approx(now + duration, abs=0.1) |
| 2153 |
# Reject pre-fix value (before + duration) explicitly with a |
| 2154 |
# margin well above asyncio scheduling jitter: the stored end |
| 2155 |
# is at least ``elapsed`` ahead of before + duration. |
| 2156 |
assert scanner._active_window_end - before - duration >= elapsed / 2 |
| 2157 |
first_handle = scanner._active_window_handle |
| 2158 |
|
| 2159 |
# A follow-up whose new_end lands between the pre-fix stored |
| 2160 |
# end and the real fire time must NOT be treated as an |
| 2161 |
# extension. With the fix this is rejected; without it the |
| 2162 |
# live timer would be cancelled and armed shorter. |
| 2163 |
target_new_end = before + duration + elapsed / 2 |
| 2164 |
shorter_duration = target_new_end - loop.time() |
| 2165 |
assert await scanner.async_request_active_window(shorter_duration) is True |
| 2166 |
assert scanner._active_window_handle is first_handle |
| 2167 |
|
| 2168 |
await scanner.async_stop() |
| 2169 |
|
| 2170 |
|
| 2171 |
@pytest.mark.usefixtures("force_linux_scanner_mode") |
| 2172 |
@pytest.mark.asyncio |
| 2173 |
async def test_async_request_active_window_skips_restart_if_still_active() -> None: |
| 2174 |
""" |
| 2175 |
Re-arm the timer instead of restarting if the scanner is still ACTIVE. |
| 2176 |
|
| 2177 |
A new request arriving after the end-of-window timer fires but |
| 2178 |
before the bg task runs reuses the in-flight ACTIVE mode and just |
| 2179 |
arms a new timer. |
| 2180 |
""" |
| 2181 |
starts: list[str] = [] |
| 2182 |
|
| 2183 |
def _factory(*_args, **kwargs): |
| 2184 |
starts.append(kwargs["scanning_mode"]) |
| 2185 |
return MockBleakScanner() |
| 2186 |
|
| 2187 |
with patch("habluetooth.scanner_bleak.OriginalBleakScanner", side_effect=_factory): |
| 2188 |
scanner = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:FF") |
| 2189 |
scanner.async_setup() |
| 2190 |
await scanner.async_start() |
| 2191 |
# Single construction (passive); toggle reuses the instance. |
| 2192 |
assert starts == ["passive"] |
| 2193 |
backend = scanner.scanner._backend # type: ignore[union-attr] |
| 2194 |
backend._scanning_mode = "passive" |
| 2195 |
|
| 2196 |
assert await scanner.async_request_active_window(100.0) is True |
| 2197 |
# Toggle flipped the existing instance to active. |
| 2198 |
assert backend._scanning_mode == "active" |
| 2199 |
# Simulate the timer firing but the end-window task not having |
| 2200 |
# run yet: clear the handle (like _schedule_end_active_window |
| 2201 |
# does) but leave _scan_mode_override / current_mode == ACTIVE. |
| 2202 |
handle = scanner._active_window_handle |
| 2203 |
assert handle is not None |
| 2204 |
handle.cancel() |
| 2205 |
scanner._active_window_handle = None |
| 2206 |
|
| 2207 |
# Scanner is still ACTIVE; a longer follow-up re-arms the |
| 2208 |
# timer without flipping the radio again. A shorter follow-up |
| 2209 |
# would no-op the timer (covered by |
| 2210 |
# test_async_request_active_window_still_active_does_not_shrink). |
| 2211 |
assert await scanner.async_request_active_window(200.0) is True |
| 2212 |
assert scanner._active_window_handle is not None |
| 2213 |
# Mode unchanged: no toggle happened on the still-ACTIVE path. |
| 2214 |
assert backend._scanning_mode == "active" # type: ignore[unreachable] |
| 2215 |
# Still only one BleakScanner construction. |
| 2216 |
assert starts == ["passive"] |
| 2217 |
|
| 2218 |
await scanner.async_stop() |
| 2219 |
|
| 2220 |
|
| 2221 |
@pytest.mark.usefixtures("force_linux_scanner_mode") |
| 2222 |
@pytest.mark.asyncio |
| 2223 |
async def test_async_request_active_window_still_active_does_not_shrink() -> None: |
| 2224 |
""" |
| 2225 |
Concurrent shorter caller into the still-ACTIVE locked branch is a no-op. |
| 2226 |
|
| 2227 |
Regression: the locked early-return at the top of |
| 2228 |
``async_request_active_window``'s lock block re-armed the timer |
| 2229 |
unconditionally when ``current_mode is ACTIVE``. A second caller |
| 2230 |
with a shorter duration could shrink an in-flight window someone |
| 2231 |
else asked for. Guarded with the same |
| 2232 |
``loop.time() + duration > _active_window_end`` check the |
| 2233 |
lockless fast-path uses. |
| 2234 |
""" |
| 2235 |
with patch( |
| 2236 |
"habluetooth.scanner_bleak.OriginalBleakScanner", |
| 2237 |
side_effect=lambda *_, **__: MockBleakScanner(), |
| 2238 |
): |
| 2239 |
scanner = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:FF") |
| 2240 |
scanner.async_setup() |
| 2241 |
await scanner.async_start() |
| 2242 |
# Open a long window so _active_window_handle is set and |
| 2243 |
# current_mode is ACTIVE. |
| 2244 |
assert await scanner.async_request_active_window(100.0) is True |
| 2245 |
long_end = scanner._active_window_end |
| 2246 |
long_handle = scanner._active_window_handle |
| 2247 |
# Simulate the timer firing without _async_end_active_window |
| 2248 |
# running yet: clear the handle so the locked branch is |
| 2249 |
# reachable (lockless fast path needs handle is not None). |
| 2250 |
assert long_handle is not None |
| 2251 |
long_handle.cancel() |
| 2252 |
scanner._active_window_handle = None |
| 2253 |
# Concurrent shorter caller now hits the locked |
| 2254 |
# current_mode-is-ACTIVE branch. Pre-fix this would re-arm |
| 2255 |
# at end = now + 5 (shrinking the live window); post-fix the |
| 2256 |
# stored end-time stays put and the timer isn't re-armed. |
| 2257 |
assert await scanner.async_request_active_window(5.0) is True |
| 2258 |
assert scanner._active_window_end == long_end |
| 2259 |
|
| 2260 |
await scanner.async_stop() |
| 2261 |
|
| 2262 |
|
| 2263 |
@pytest.mark.usefixtures("force_linux_scanner_mode") |
| 2264 |
@pytest.mark.asyncio |
| 2265 |
async def test_async_stop_clears_active_window_state() -> None: |
| 2266 |
"""Stopping mid-window cancels the timer and clears the override.""" |
| 2267 |
with patch( |
| 2268 |
"habluetooth.scanner_bleak.OriginalBleakScanner", |
| 2269 |
side_effect=lambda *_, **__: MockBleakScanner(), |
| 2270 |
): |
| 2271 |
scanner = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:FF") |
| 2272 |
scanner.async_setup() |
| 2273 |
await scanner.async_start() |
| 2274 |
await scanner.async_request_active_window(100.0) |
| 2275 |
assert scanner._active_window_handle is not None |
| 2276 |
await scanner.async_stop() |
| 2277 |
assert scanner._active_window_handle is None |
| 2278 |
assert scanner._scan_mode_override is None # type: ignore[unreachable] |
| 2279 |
assert scanner._active_window_end == 0.0 |
| 2280 |
|
| 2281 |
|
| 2282 |
@pytest.mark.usefixtures("force_linux_scanner_mode") |
| 2283 |
@pytest.mark.asyncio |
| 2284 |
async def test_async_request_active_window_recovers_on_start_failure() -> None: |
| 2285 |
"""If the ACTIVE restart raises, recovery brings the scanner back up.""" |
| 2286 |
call_count = 0 |
| 2287 |
fail_until = 0 |
| 2288 |
|
| 2289 |
class _CountingFailScanner(MockBleakScanner): |
| 2290 |
async def start(self) -> None: |
| 2291 |
nonlocal call_count |
| 2292 |
call_count += 1 |
| 2293 |
if call_count <= fail_until: |
| 2294 |
msg = "simulated start failure" |
| 2295 |
raise BleakError(msg) |
| 2296 |
|
| 2297 |
with patch_bleak_scanner_factory(_CountingFailScanner): |
| 2298 |
scanner = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:FF") |
| 2299 |
scanner.async_setup() |
| 2300 |
await scanner.async_start() |
| 2301 |
before = call_count |
| 2302 |
# Fail the next 4 start attempts so the ACTIVE swap raises; |
| 2303 |
# then succeed so the recovery restart can come back up. |
| 2304 |
fail_until = call_count + 4 |
| 2305 |
result = await scanner.async_request_active_window(1.0) |
| 2306 |
assert result is False |
| 2307 |
assert scanner._scan_mode_override is None |
| 2308 |
# Recovery restart happened after the failure path. |
| 2309 |
assert call_count > before + 4 |
| 2310 |
await scanner.async_stop() |
| 2311 |
|
| 2312 |
|
| 2313 |
@pytest.mark.usefixtures("force_linux_scanner_mode") |
| 2314 |
@pytest.mark.asyncio |
| 2315 |
async def test_async_request_active_window_clears_override_on_unexpected_error() -> ( |
| 2316 |
None |
| 2317 |
): |
| 2318 |
""" |
| 2319 |
An unexpected exception from the restart clears _scan_mode_override. |
| 2320 |
|
| 2321 |
Regression: only ScannerStartError was caught explicitly, so any |
| 2322 |
other exception propagating from _async_stop_then_start_under_lock |
| 2323 |
would leave _scan_mode_override = ACTIVE. The next |
| 2324 |
_async_start_attempt would then see effective_mode = ACTIVE |
| 2325 |
instead of AUTO, poisoning subsequent starts. |
| 2326 |
""" |
| 2327 |
start_count = 0 |
| 2328 |
|
| 2329 |
class _UnexpectedErrorAfterFirstScanner(MockBleakScanner): |
| 2330 |
async def start(self) -> None: |
| 2331 |
nonlocal start_count |
| 2332 |
start_count += 1 |
| 2333 |
# First start (initial async_start) succeeds; second start |
| 2334 |
# (the ACTIVE restart from async_request_active_window) |
| 2335 |
# raises a non-ScannerStartError so we exercise the |
| 2336 |
# broad-except cleanup path. |
| 2337 |
if start_count > 1: |
| 2338 |
msg = "simulated unexpected error" |
| 2339 |
raise RuntimeError(msg) |
| 2340 |
|
| 2341 |
with patch_bleak_scanner_factory(_UnexpectedErrorAfterFirstScanner): |
| 2342 |
scanner = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:FF") |
| 2343 |
scanner.async_setup() |
| 2344 |
await scanner.async_start() |
| 2345 |
with pytest.raises(RuntimeError, match="simulated unexpected error"): |
| 2346 |
await scanner.async_request_active_window(1.0) |
| 2347 |
# The override must be cleared even though the exception |
| 2348 |
# wasn't a ScannerStartError. |
| 2349 |
assert scanner._scan_mode_override is None |
| 2350 |
await scanner.async_stop() |
| 2351 |
|
| 2352 |
|
| 2353 |
@pytest.mark.asyncio |
| 2354 |
async def test_base_scanner_default_active_window_is_noop( |
| 2355 |
caplog: pytest.LogCaptureFixture, |
| 2356 |
) -> None: |
| 2357 |
"""BaseHaScanner.async_request_active_window default returns False.""" |
| 2358 |
|
| 2359 |
class _PlainScanner(BaseHaScanner): |
| 2360 |
@property |
| 2361 |
def discovered_devices(self) -> list[BLEDevice]: |
| 2362 |
return [] |
| 2363 |
|
| 2364 |
@property |
| 2365 |
def discovered_devices_and_advertisement_data( |
| 2366 |
self, |
| 2367 |
) -> dict[str, tuple[BLEDevice, AdvertisementData]]: |
| 2368 |
return {} |
| 2369 |
|
| 2370 |
def get_discovered_device_advertisement_data( |
| 2371 |
self, address: str |
| 2372 |
) -> tuple[BLEDevice, AdvertisementData] | None: |
| 2373 |
return None |
| 2374 |
|
| 2375 |
@property |
| 2376 |
def discovered_addresses(self) -> Iterable[str]: |
| 2377 |
return () |
| 2378 |
|
| 2379 |
scanner = _PlainScanner("AA:BB:CC:DD:EE:FF", "plain") |
| 2380 |
with caplog.at_level(logging.DEBUG, logger="habluetooth"): |
| 2381 |
result = await scanner.async_request_active_window(1.0) |
| 2382 |
assert result is False |
| 2383 |
assert any( |
| 2384 |
"does not support on-demand active windows" in record.message |
| 2385 |
for record in caplog.records |
| 2386 |
) |
| 2387 |
|
| 2388 |
|
| 2389 |
@pytest.mark.usefixtures("force_linux_scanner_mode") |
| 2390 |
@pytest.mark.asyncio |
| 2391 |
async def test_async_end_active_window_defers_to_new_window() -> None: |
| 2392 |
"""If a new window armed the timer, the end-window task returns early.""" |
| 2393 |
with patch( |
| 2394 |
"habluetooth.scanner_bleak.OriginalBleakScanner", |
| 2395 |
side_effect=lambda *_, **__: MockBleakScanner(), |
| 2396 |
): |
| 2397 |
scanner = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:FF") |
| 2398 |
scanner.async_setup() |
| 2399 |
await scanner.async_start() |
| 2400 |
await scanner.async_request_active_window(3600.0) |
| 2401 |
# Simulate a new window taking over by leaving the handle in place |
| 2402 |
# and call _async_end_active_window directly; it must short-circuit. |
| 2403 |
assert scanner._active_window_handle is not None |
| 2404 |
await scanner._async_end_active_window() |
| 2405 |
# Override and handle untouched because we deferred to the new window. |
| 2406 |
assert scanner._scan_mode_override == BluetoothScanningMode.ACTIVE |
| 2407 |
assert scanner._active_window_handle is not None |
| 2408 |
await scanner.async_stop() |
| 2409 |
|
| 2410 |
|
| 2411 |
@pytest.mark.asyncio |
| 2412 |
async def test_async_end_active_window_skips_when_not_scanning() -> None: |
| 2413 |
"""If the scanner was stopped during the window the restart is skipped.""" |
| 2414 |
with patch( |
| 2415 |
"habluetooth.scanner_bleak.OriginalBleakScanner", |
| 2416 |
side_effect=lambda *_, **__: MockBleakScanner(), |
| 2417 |
): |
| 2418 |
scanner = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:FF") |
| 2419 |
scanner.async_setup() |
| 2420 |
await scanner.async_start() |
| 2421 |
await scanner.async_request_active_window(3600.0) |
| 2422 |
# Pretend the end-window timer just fired (handle cleared) and the |
| 2423 |
# scanner was stopped in the meantime. |
| 2424 |
scanner._active_window_handle = None |
| 2425 |
scanner.scanning = False |
| 2426 |
# Should be a quick no-op: clears override, sees not scanning, returns. |
| 2427 |
await scanner._async_end_active_window() |
| 2428 |
assert scanner._scan_mode_override is None |
| 2429 |
scanner.scanning = True |
| 2430 |
await scanner.async_stop() |
| 2431 |
|
| 2432 |
|
| 2433 |
@pytest.mark.usefixtures("force_linux_scanner_mode") |
| 2434 |
@pytest.mark.asyncio |
| 2435 |
async def test_async_request_active_window_passive_fallback_on_linux() -> None: |
| 2436 |
"""If the swap restart falls back to PASSIVE on Linux, request returns False.""" |
| 2437 |
starts = 0 |
| 2438 |
|
| 2439 |
class _PassiveFallbackScanner(MockBleakScanner): |
| 2440 |
async def start(self) -> None: |
| 2441 |
nonlocal starts |
| 2442 |
starts += 1 |
| 2443 |
# Fail the first three attempts so the 4th-attempt PASSIVE |
| 2444 |
# fallback inside _async_start_attempt kicks in. |
| 2445 |
if 2 <= starts <= 4: |
| 2446 |
msg = "simulated active failure" |
| 2447 |
raise BleakError(msg) |
| 2448 |
|
| 2449 |
with ( |
| 2450 |
patch("habluetooth.scanner_bleak.IS_LINUX", True), |
| 2451 |
patch_bleak_scanner_factory(_PassiveFallbackScanner), |
| 2452 |
patch("habluetooth.scanner_bleak.async_reset_adapter", AsyncMock()), |
| 2453 |
patch("habluetooth.scanner_bleak.ADAPTER_INIT_TIME", 0), |
| 2454 |
): |
| 2455 |
scanner = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:FF") |
| 2456 |
scanner.async_setup() |
| 2457 |
await scanner.async_start() |
| 2458 |
result = await scanner.async_request_active_window(1.0) |
| 2459 |
# The swap ran through to the 4th attempt and fell back to PASSIVE; |
| 2460 |
# the request reports False because the scanner is not ACTIVE. |
| 2461 |
assert result is False |
| 2462 |
assert scanner._scan_mode_override is None |
| 2463 |
await scanner.async_stop() |
| 2464 |
|
| 2465 |
|
| 2466 |
@pytest.mark.usefixtures("force_linux_scanner_mode") |
| 2467 |
@pytest.mark.asyncio |
| 2468 |
async def test_async_end_active_window_handles_start_error( |
| 2469 |
caplog: pytest.LogCaptureFixture, |
| 2470 |
) -> None: |
| 2471 |
"""ScannerStartError during the end-of-window restart logs a warning.""" |
| 2472 |
starts = 0 |
| 2473 |
fail_until = 0 |
| 2474 |
|
| 2475 |
class _FailUntilThresholdScanner(MockBleakScanner): |
| 2476 |
async def start(self) -> None: |
| 2477 |
nonlocal starts |
| 2478 |
starts += 1 |
| 2479 |
if starts <= fail_until: |
| 2480 |
msg = "simulated end-window failure" |
| 2481 |
raise BleakError(msg) |
| 2482 |
|
| 2483 |
with patch_bleak_scanner_factory(_FailUntilThresholdScanner): |
| 2484 |
scanner = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:FF") |
| 2485 |
scanner.async_setup() |
| 2486 |
await scanner.async_start() |
| 2487 |
try: |
| 2488 |
# Open a long active window then drive end-of-window |
| 2489 |
# with the bleak start mocked to fail. |
| 2490 |
await scanner.async_request_active_window(3600.0) |
| 2491 |
assert scanner._active_window_handle is not None |
| 2492 |
# Fail enough start() calls that BOTH the toggle attempt |
| 2493 |
# and every retry in the fallback _async_start cycle |
| 2494 |
# raise, so we exercise the "Failed to restart scanner |
| 2495 |
# after active window" warning. |
| 2496 |
fail_until = starts + 100 |
| 2497 |
scanner._active_window_handle.cancel() |
| 2498 |
scanner._active_window_handle = None |
| 2499 |
caplog.clear() |
| 2500 |
with caplog.at_level(logging.WARNING): |
| 2501 |
await scanner._async_end_active_window() |
| 2502 |
assert any( |
| 2503 |
"Failed to restart scanner after active window" in record.message |
| 2504 |
for record in caplog.records |
| 2505 |
) |
| 2506 |
finally: |
| 2507 |
# Allow the fallback restart to succeed for teardown, |
| 2508 |
# then stop the scanner so we don't leak the watchdog |
| 2509 |
# timer / background tasks into later tests. |
| 2510 |
fail_until = 0 |
| 2511 |
await scanner.async_stop() |
| 2512 |
|
| 2513 |
|
| 2514 |
@pytest.mark.parametrize("exc", [FileNotFoundError("no dbus"), BleakError("nope")]) |
| 2515 |
def test_create_bleak_scanner_wraps_init_error(exc: Exception) -> None: |
| 2516 |
"""``create_bleak_scanner`` wraps FileNotFoundError/BleakError as RuntimeError.""" |
| 2517 |
with ( |
| 2518 |
patch.object(scanner, "IS_LINUX", True), |
| 2519 |
patch.object(scanner, "IS_MACOS", False), |
| 2520 |
patch( |
| 2521 |
"habluetooth.scanner_bleak.OriginalBleakScanner", |
| 2522 |
side_effect=exc, |
| 2523 |
), |
| 2524 |
pytest.raises(RuntimeError, match="Failed to initialize Bluetooth"), |
| 2525 |
): |
| 2526 |
create_bleak_scanner(None, BluetoothScanningMode.ACTIVE, "hci0") |
| 2527 |
|
| 2528 |
|
| 2529 |
@pytest.mark.asyncio |
| 2530 |
@pytest.mark.skipif(NOT_POSIX) |
| 2531 |
@pytest.mark.parametrize("exc", [TimeoutError("slow"), BleakError("nope")]) |
| 2532 |
async def test_async_stop_scanner_logs_when_scanner_stop_raises( |
| 2533 |
caplog: pytest.LogCaptureFixture, exc: Exception |
| 2534 |
) -> None: |
| 2535 |
"""``_async_stop_scanner`` logs and clears the scanner when ``.stop()`` raises.""" |
| 2536 |
mock_scanner = MagicMock() |
| 2537 |
mock_scanner.start = AsyncMock() |
| 2538 |
mock_scanner.stop = AsyncMock(side_effect=exc) |
| 2539 |
with patch( |
| 2540 |
"habluetooth.scanner_bleak.OriginalBleakScanner", return_value=mock_scanner |
| 2541 |
): |
| 2542 |
scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 2543 |
scanner.async_setup() |
| 2544 |
await scanner.async_start() |
| 2545 |
caplog.clear() |
| 2546 |
await scanner.async_stop() |
| 2547 |
assert "Error stopping scanner" in caplog.text |
| 2548 |
assert scanner.scanner is None |
| 2549 |
|
| 2550 |
|
| 2551 |
@pytest.mark.asyncio |
| 2552 |
@pytest.mark.skipif(NOT_POSIX) |
| 2553 |
async def test_async_force_stop_discovery_logs_on_timeout( |
| 2554 |
caplog: pytest.LogCaptureFixture, |
| 2555 |
) -> None: |
| 2556 |
"""Force-stop logs an error when ``stop_discovery`` times out.""" |
| 2557 |
ha_scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 2558 |
ha_scanner.async_setup() |
| 2559 |
with patch( |
| 2560 |
"habluetooth.scanner_bleak.stop_discovery", side_effect=TimeoutError("slow") |
| 2561 |
): |
| 2562 |
await ha_scanner._async_force_stop_discovery() |
| 2563 |
assert "Timeout force stopping scanner" in caplog.text |
| 2564 |
await ha_scanner.async_stop() |
| 2565 |
|
| 2566 |
|
| 2567 |
@pytest.mark.asyncio |
| 2568 |
@pytest.mark.skipif(NOT_POSIX) |
| 2569 |
async def test_async_force_stop_discovery_logs_on_unexpected_error( |
| 2570 |
caplog: pytest.LogCaptureFixture, |
| 2571 |
) -> None: |
| 2572 |
"""Force-stop logs an error when ``stop_discovery`` raises an unexpected error.""" |
| 2573 |
ha_scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 2574 |
ha_scanner.async_setup() |
| 2575 |
with patch( |
| 2576 |
"habluetooth.scanner_bleak.stop_discovery", side_effect=BleakError("boom") |
| 2577 |
): |
| 2578 |
await ha_scanner._async_force_stop_discovery() |
| 2579 |
assert "Failed to force stop scanner" in caplog.text |
| 2580 |
await ha_scanner.async_stop() |
| 2581 |
|
| 2582 |
|
| 2583 |
@pytest.mark.asyncio |
| 2584 |
async def test_get_allocations_returns_none_without_slot_manager() -> None: |
| 2585 |
"""``HaScanner.get_allocations`` returns None when manager has no slot manager.""" |
| 2586 |
ha_scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 2587 |
ha_scanner.async_setup() |
| 2588 |
with patch.object(get_manager(), "slot_manager", None): |
| 2589 |
assert ha_scanner.get_allocations() is None |
| 2590 |
await ha_scanner.async_stop() |
| 2591 |
|
| 2592 |
|
| 2593 |
@pytest.mark.asyncio |
| 2594 |
async def test_discovered_properties_delegate_when_scanner_attached() -> None: |
| 2595 |
"""Discovered* delegate to the underlying bleak scanner when one is attached.""" |
| 2596 |
device = generate_ble_device("AA:BB:CC:DD:EE:01", "x") |
| 2597 |
adv = generate_advertisement_data(local_name="x") |
| 2598 |
|
| 2599 |
class _DiscoveredScanner(MockBleakScanner): |
| 2600 |
@property |
| 2601 |
def discovered_devices(self): |
| 2602 |
return [device] |
| 2603 |
|
| 2604 |
@property |
| 2605 |
def discovered_devices_and_advertisement_data(self): |
| 2606 |
return {device.address: (device, adv)} |
| 2607 |
|
| 2608 |
with patch_bleak_scanner_factory(_DiscoveredScanner): |
| 2609 |
ha_scanner = HaScanner( |
| 2610 |
BluetoothScanningMode.PASSIVE, "hci0", "AA:BB:CC:DD:EE:FF" |
| 2611 |
) |
| 2612 |
ha_scanner.async_setup() |
| 2613 |
await ha_scanner.async_start() |
| 2614 |
try: |
| 2615 |
assert ha_scanner.discovered_devices == [device] |
| 2616 |
assert ha_scanner.discovered_devices_and_advertisement_data == { |
| 2617 |
device.address: (device, adv) |
| 2618 |
} |
| 2619 |
assert ha_scanner.get_discovered_device_advertisement_data( |
| 2620 |
device.address |
| 2621 |
) == (device, adv) |
| 2622 |
assert device.address in list(ha_scanner.discovered_addresses) |
| 2623 |
finally: |
| 2624 |
await ha_scanner.async_stop() |
| 2625 |
|
| 2626 |
|
| 2627 |
@pytest.mark.asyncio |
| 2628 |
async def test_detection_callback_coerces_non_str_name_and_non_int_tx_power() -> None: |
| 2629 |
""" |
| 2630 |
Defensive coercion: bleak occasionally returns non-str names / non-int tx_power. |
| 2631 |
|
| 2632 |
The advertisement path normalizes both so downstream code can rely |
| 2633 |
on plain Python str / int rather than bytes-likes or numpy ints. |
| 2634 |
Inspects ``manager._all_history`` (populated by |
| 2635 |
``_scanner_adv_received``) since the cython method itself isn't |
| 2636 |
monkey-patchable. |
| 2637 |
""" |
| 2638 |
ha_scanner = HaScanner(BluetoothScanningMode.PASSIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 2639 |
ha_scanner.async_setup() |
| 2640 |
|
| 2641 |
class _StrSubclass(str): |
| 2642 |
"""str subclass — `type() is not str` so coercion fires.""" |
| 2643 |
|
| 2644 |
__slots__ = () |
| 2645 |
|
| 2646 |
class _IntLike: |
| 2647 |
"""Non-int that ``int()`` accepts (e.g. numpy.int64 stand-in).""" |
| 2648 |
|
| 2649 |
def __int__(self) -> int: |
| 2650 |
return -7 |
| 2651 |
|
| 2652 |
address = "AA:BB:CC:DD:EE:F0" |
| 2653 |
device = generate_ble_device(address, None) |
| 2654 |
adv = generate_advertisement_data( |
| 2655 |
local_name=_StrSubclass("weird"), |
| 2656 |
tx_power=_IntLike(), |
| 2657 |
) |
| 2658 |
ha_scanner._async_detection_callback(device, adv) |
| 2659 |
info = get_manager()._all_history[address] |
| 2660 |
# Both fields were coerced to the canonical Python type. |
| 2661 |
assert type(info.name) is str |
| 2662 |
assert info.name == "weird" |
| 2663 |
assert type(info.tx_power) is int |
| 2664 |
assert info.tx_power == -7 |
| 2665 |
await ha_scanner.async_stop() |
| 2666 |
|
| 2667 |
|
| 2668 |
@pytest.mark.asyncio |
| 2669 |
async def test_start_attempt_timeout_resets_then_raises_on_exhaustion( |
| 2670 |
caplog: pytest.LogCaptureFixture, |
| 2671 |
) -> None: |
| 2672 |
""" |
| 2673 |
Persistent start TimeoutError: attempt 2 resets the adapter, attempt 4 raises. |
| 2674 |
|
| 2675 |
Covers the in-between `attempt < START_ATTEMPTS` return-False branch |
| 2676 |
(logged as a retry warning) and the `attempt == START_ATTEMPTS` raise. |
| 2677 |
Subclasses HaScanner because the cython type is immutable so a |
| 2678 |
bare patch.object can't override its methods. |
| 2679 |
""" |
| 2680 |
reset_calls: list[bool] = [] |
| 2681 |
|
| 2682 |
class _RecordingResetScanner(HaScanner): |
| 2683 |
async def _async_reset_adapter(self, gone_silent: bool) -> None: |
| 2684 |
reset_calls.append(gone_silent) |
| 2685 |
|
| 2686 |
class TimeoutMockBleakScanner(MockBleakScanner): |
| 2687 |
async def start(self) -> None: |
| 2688 |
msg = "simulated start timeout" |
| 2689 |
raise TimeoutError(msg) |
| 2690 |
|
| 2691 |
with patch_bleak_scanner_factory(TimeoutMockBleakScanner): |
| 2692 |
ha_scanner = _RecordingResetScanner( |
| 2693 |
BluetoothScanningMode.PASSIVE, "hci0", "AA:BB:CC:DD:EE:FF" |
| 2694 |
) |
| 2695 |
ha_scanner.async_setup() |
| 2696 |
with ( |
| 2697 |
caplog.at_level(logging.DEBUG, logger="habluetooth.scanner"), |
| 2698 |
pytest.raises(ScannerStartError, match="Timed out starting Bluetooth"), |
| 2699 |
): |
| 2700 |
await ha_scanner.async_start() |
| 2701 |
# Attempt 2 (gone_silent=False) triggered exactly one adapter reset. |
| 2702 |
assert reset_calls == [False] |
| 2703 |
await ha_scanner.async_stop() |
| 2704 |
|
| 2705 |
|
| 2706 |
@pytest.mark.asyncio |
| 2707 |
async def test_async_restart_scanner_logs_when_start_raises( |
| 2708 |
caplog: pytest.LogCaptureFixture, |
| 2709 |
) -> None: |
| 2710 |
""" |
| 2711 |
Watchdog restart swallows + logs ``ScannerStartError`` from ``_async_start``. |
| 2712 |
|
| 2713 |
Covers the ``except ScannerStartError`` branch in |
| 2714 |
``_async_restart_scanner`` so a single restart failure doesn't |
| 2715 |
propagate out of the background task. Uses a subclass to override |
| 2716 |
methods because cython types are immutable. |
| 2717 |
""" |
| 2718 |
|
| 2719 |
class _RaisingRestartScanner(HaScanner): |
| 2720 |
async def _async_start(self) -> None: |
| 2721 |
msg = "simulated restart failure" |
| 2722 |
raise ScannerStartError(msg) |
| 2723 |
|
| 2724 |
async def _async_stop_scanner(self) -> None: |
| 2725 |
pass |
| 2726 |
|
| 2727 |
async def _async_reset_adapter(self, gone_silent: bool) -> None: |
| 2728 |
pass |
| 2729 |
|
| 2730 |
ha_scanner = _RaisingRestartScanner( |
| 2731 |
BluetoothScanningMode.PASSIVE, "hci0", "AA:BB:CC:DD:EE:FF" |
| 2732 |
) |
| 2733 |
ha_scanner.async_setup() |
| 2734 |
with caplog.at_level(logging.ERROR, logger="habluetooth.scanner"): |
| 2735 |
await ha_scanner._async_restart_scanner() |
| 2736 |
assert "Failed to restart Bluetooth scanner" in caplog.text |
| 2737 |
assert "simulated restart failure" in caplog.text |
| 2738 |
|
| 2739 |
|
| 2740 |
@pytest.fixture |
| 2741 |
def force_non_linux_non_macos_scanner_mode() -> Generator[None, None, None]: |
| 2742 |
"""Force the non-Linux, non-macOS branch of the active-window entry.""" |
| 2743 |
with ( |
| 2744 |
patch("habluetooth.scanner_bleak.IS_LINUX", False), |
| 2745 |
patch("habluetooth.scanner_bleak.IS_MACOS", False), |
| 2746 |
): |
| 2747 |
yield |
| 2748 |
|
| 2749 |
|
| 2750 |
@pytest.mark.usefixtures("force_non_linux_non_macos_scanner_mode") |
| 2751 |
@pytest.mark.asyncio |
| 2752 |
async def test_async_request_active_window_restart_path_happy() -> None: |
| 2753 |
"""Non-Linux active-window entry: full stop+restart leaves scanner in ACTIVE.""" |
| 2754 |
with patch_bleak_scanner_factory(MockBleakScanner): |
| 2755 |
ha_scanner = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:F1") |
| 2756 |
ha_scanner.async_setup() |
| 2757 |
await ha_scanner.async_start() |
| 2758 |
try: |
| 2759 |
assert await ha_scanner.async_request_active_window(0.5) is True |
| 2760 |
assert ha_scanner.current_mode is BluetoothScanningMode.ACTIVE |
| 2761 |
assert ha_scanner._scan_mode_override is BluetoothScanningMode.ACTIVE |
| 2762 |
assert ha_scanner._active_window_handle is not None |
| 2763 |
finally: |
| 2764 |
await ha_scanner.async_stop() |
| 2765 |
|
| 2766 |
|
| 2767 |
@pytest.mark.usefixtures("force_non_linux_non_macos_scanner_mode") |
| 2768 |
@pytest.mark.asyncio |
| 2769 |
async def test_async_request_active_window_restart_path_scanner_start_error() -> None: |
| 2770 |
""" |
| 2771 |
Non-Linux entry: a ``ScannerStartError`` triggers the abort recovery path. |
| 2772 |
|
| 2773 |
``_async_begin_active_window_via_restart`` catches the error and |
| 2774 |
routes through ``_async_abort_active_window`` so the scanner comes |
| 2775 |
back up in its underlying mode instead of being left stopped. |
| 2776 |
""" |
| 2777 |
starts = 0 |
| 2778 |
|
| 2779 |
class AlwaysFailAfterFirstMockBleakScanner(MockBleakScanner): |
| 2780 |
async def start(self) -> None: |
| 2781 |
nonlocal starts |
| 2782 |
starts += 1 |
| 2783 |
# First start (initial async_start) succeeds; every |
| 2784 |
# subsequent start raises so all 4 retries of the |
| 2785 |
# restart attempt exhaust, raising ScannerStartError, |
| 2786 |
# which the abort path then suppresses. |
| 2787 |
if starts > 1: |
| 2788 |
msg = "simulated start failure" |
| 2789 |
raise BleakError(msg) |
| 2790 |
|
| 2791 |
class _NoResetScanner(HaScanner): |
| 2792 |
async def _async_reset_adapter(self, gone_silent: bool) -> None: |
| 2793 |
pass |
| 2794 |
|
| 2795 |
with patch_bleak_scanner_factory(AlwaysFailAfterFirstMockBleakScanner): |
| 2796 |
ha_scanner = _NoResetScanner( |
| 2797 |
BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:F2" |
| 2798 |
) |
| 2799 |
ha_scanner.async_setup() |
| 2800 |
await ha_scanner.async_start() |
| 2801 |
try: |
| 2802 |
assert await ha_scanner.async_request_active_window(0.5) is False |
| 2803 |
# Abort cleared the override; no end-of-window timer armed. |
| 2804 |
assert ha_scanner._scan_mode_override is None |
| 2805 |
assert ha_scanner._active_window_handle is None |
| 2806 |
finally: |
| 2807 |
await ha_scanner.async_stop() |
| 2808 |
|
| 2809 |
|
| 2810 |
@pytest.mark.usefixtures("force_non_linux_non_macos_scanner_mode") |
| 2811 |
@pytest.mark.asyncio |
| 2812 |
async def test_async_request_active_window_restart_path_unexpected_error() -> None: |
| 2813 |
""" |
| 2814 |
Non-Linux entry: unexpected exceptions clear the override and re-raise. |
| 2815 |
|
| 2816 |
Mirrors the toggle-path test for the restart-path |
| 2817 |
``except BaseException`` branch in |
| 2818 |
``_async_begin_active_window_via_restart``: a non-ScannerStartError |
| 2819 |
must not poison ``_scan_mode_override`` for the next start. |
| 2820 |
""" |
| 2821 |
raise_on_restart = False |
| 2822 |
|
| 2823 |
class _MaybeRaiseRestartScanner(HaScanner): |
| 2824 |
async def _async_stop_then_start_under_lock(self) -> None: |
| 2825 |
if raise_on_restart: |
| 2826 |
msg = "simulated unexpected error" |
| 2827 |
raise RuntimeError(msg) |
| 2828 |
|
| 2829 |
with patch_bleak_scanner_factory(MockBleakScanner): |
| 2830 |
ha_scanner = _MaybeRaiseRestartScanner( |
| 2831 |
BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:F4" |
| 2832 |
) |
| 2833 |
ha_scanner.async_setup() |
| 2834 |
await ha_scanner.async_start() |
| 2835 |
try: |
| 2836 |
raise_on_restart = True |
| 2837 |
with pytest.raises(RuntimeError, match="simulated unexpected error"): |
| 2838 |
await ha_scanner.async_request_active_window(0.5) |
| 2839 |
assert ha_scanner._scan_mode_override is None |
| 2840 |
finally: |
| 2841 |
raise_on_restart = False |
| 2842 |
await ha_scanner.async_stop() |
| 2843 |
|
| 2844 |
|
| 2845 |
@pytest.mark.asyncio |
| 2846 |
async def test_detection_callback_skips_last_detection_for_empty_advertisement() -> ( |
| 2847 |
None |
| 2848 |
): |
| 2849 |
""" |
| 2850 |
Empty advertisements don't bump ``_last_detection``. |
| 2851 |
|
| 2852 |
Bleak occasionally hands us a callback with no name / data / |
| 2853 |
service info, which we treat as a heartbeat from a failing |
| 2854 |
adapter rather than a real ping. |
| 2855 |
""" |
| 2856 |
ha_scanner = HaScanner(BluetoothScanningMode.PASSIVE, "hci0", "AA:BB:CC:DD:EE:FF") |
| 2857 |
ha_scanner.async_setup() |
| 2858 |
ha_scanner._last_detection = -1.0 |
| 2859 |
device = generate_ble_device("AA:BB:CC:DD:EE:F5", None) |
| 2860 |
# All four fields explicitly empty so the truthy-check skips the |
| 2861 |
# _last_detection bump (generate_advertisement_data defaults |
| 2862 |
# local_name to "Unknown", which would otherwise trip it). |
| 2863 |
adv = generate_advertisement_data( |
| 2864 |
local_name=None, |
| 2865 |
manufacturer_data={}, |
| 2866 |
service_data={}, |
| 2867 |
service_uuids=[], |
| 2868 |
) |
| 2869 |
ha_scanner._async_detection_callback(device, adv) |
| 2870 |
assert ha_scanner._last_detection == -1.0 |
| 2871 |
await ha_scanner.async_stop() |
| 2872 |
|
| 2873 |
|
| 2874 |
@pytest.mark.usefixtures("force_non_linux_non_macos_scanner_mode") |
| 2875 |
@pytest.mark.asyncio |
| 2876 |
async def test_async_request_active_window_restart_path_mode_mismatch() -> None: |
| 2877 |
""" |
| 2878 |
Non-Linux entry: a restart that doesn't land in ACTIVE clears the override. |
| 2879 |
|
| 2880 |
Simulates a backend that ignores ``_scan_mode_override`` by patching |
| 2881 |
``_async_stop_then_start_under_lock`` at the class level so it |
| 2882 |
leaves ``current_mode`` unchanged at PASSIVE. The branch must clear |
| 2883 |
the override and return False so the public method can report |
| 2884 |
failure to the scheduler. |
| 2885 |
""" |
| 2886 |
noop_restart = False |
| 2887 |
|
| 2888 |
class _NoopRestartScanner(HaScanner): |
| 2889 |
async def _async_stop_then_start_under_lock(self) -> None: |
| 2890 |
if not noop_restart: |
| 2891 |
await HaScanner._async_stop_then_start_under_lock(self) |
| 2892 |
|
| 2893 |
with patch_bleak_scanner_factory(MockBleakScanner): |
| 2894 |
ha_scanner = _NoopRestartScanner( |
| 2895 |
BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:F3" |
| 2896 |
) |
| 2897 |
ha_scanner.async_setup() |
| 2898 |
await ha_scanner.async_start() |
| 2899 |
# Pretend a previous start left current_mode at PASSIVE. |
| 2900 |
ha_scanner.set_current_mode(BluetoothScanningMode.PASSIVE) |
| 2901 |
try: |
| 2902 |
noop_restart = True |
| 2903 |
assert await ha_scanner.async_request_active_window(0.5) is False |
| 2904 |
assert ha_scanner._scan_mode_override is None |
| 2905 |
assert ha_scanner._active_window_handle is None |
| 2906 |
finally: |
| 2907 |
noop_restart = False |
| 2908 |
await ha_scanner.async_stop() |
| 2909 |
|
| 2910 |
|
| 2911 |
@pytest.mark.asyncio |
| 2912 |
async def test_describe_side_channel_state_no_adapter_idx() -> None: |
| 2913 |
"""Non-hci adapter names have no MGMT index so report the fallback path.""" |
| 2914 |
ha_scanner = HaScanner( |
| 2915 |
BluetoothScanningMode.PASSIVE, "Core Bluetooth", "AA:BB:CC:DD:EE:01" |
| 2916 |
) |
| 2917 |
assert ( |
| 2918 |
ha_scanner._describe_side_channel_state() |
| 2919 |
== "no adapter_idx; bleak detection_callback path" |
| 2920 |
) |
| 2921 |
|
| 2922 |
|
| 2923 |
@pytest.mark.asyncio |
| 2924 |
async def test_describe_side_channel_state_no_side_channel() -> None: |
| 2925 |
"""When the manager never brought MGMT up we fall back to bleak's callback.""" |
| 2926 |
manager = get_manager() |
| 2927 |
manager.has_advertising_side_channel = False |
| 2928 |
ha_scanner = HaScanner(BluetoothScanningMode.PASSIVE, "hci0", "AA:BB:CC:DD:EE:02") |
| 2929 |
assert ( |
| 2930 |
ha_scanner._describe_side_channel_state() |
| 2931 |
== "MGMT side channel unavailable; bleak detection_callback path" |
| 2932 |
) |
| 2933 |
|
| 2934 |
|
| 2935 |
@pytest.mark.asyncio |
| 2936 |
async def test_describe_side_channel_state_unregistered() -> None: |
| 2937 |
"""Side channel is alive but the scanner isn't in _side_channel_scanners.""" |
| 2938 |
manager = get_manager() |
| 2939 |
manager.has_advertising_side_channel = True |
| 2940 |
manager._side_channel_scanners.clear() |
| 2941 |
ha_scanner = HaScanner(BluetoothScanningMode.PASSIVE, "hci0", "AA:BB:CC:DD:EE:03") |
| 2942 |
assert ( |
| 2943 |
ha_scanner._describe_side_channel_state() |
| 2944 |
== "MGMT side channel up but hci0 unregistered" |
| 2945 |
) |
| 2946 |
|
| 2947 |
|
| 2948 |
@pytest.mark.asyncio |
| 2949 |
async def test_describe_side_channel_state_bound_to_other_scanner() -> None: |
| 2950 |
"""Another scanner owns the hciN slot in _side_channel_scanners.""" |
| 2951 |
manager = get_manager() |
| 2952 |
manager.has_advertising_side_channel = True |
| 2953 |
other = HaScanner(BluetoothScanningMode.PASSIVE, "hci0", "AA:BB:CC:DD:EE:04") |
| 2954 |
manager._side_channel_scanners[0] = other |
| 2955 |
ha_scanner = HaScanner(BluetoothScanningMode.PASSIVE, "hci0", "AA:BB:CC:DD:EE:05") |
| 2956 |
try: |
| 2957 |
assert ( |
| 2958 |
ha_scanner._describe_side_channel_state() |
| 2959 |
== "MGMT side channel at hci0 bound to a different scanner" |
| 2960 |
) |
| 2961 |
finally: |
| 2962 |
manager._side_channel_scanners.clear() |
| 2963 |
|
| 2964 |
|
| 2965 |
@pytest.mark.asyncio |
| 2966 |
async def test_describe_side_channel_state_protocol_down() -> None: |
| 2967 |
"""Scanner is registered but the MGMT ctl is gone — socket died.""" |
| 2968 |
manager = get_manager() |
| 2969 |
manager.has_advertising_side_channel = True |
| 2970 |
ha_scanner = HaScanner(BluetoothScanningMode.PASSIVE, "hci0", "AA:BB:CC:DD:EE:06") |
| 2971 |
manager._side_channel_scanners[0] = ha_scanner |
| 2972 |
manager._mgmt_ctl = None |
| 2973 |
try: |
| 2974 |
assert ( |
| 2975 |
ha_scanner._describe_side_channel_state() |
| 2976 |
== "MGMT side channel registered at hci0 but protocol down" |
| 2977 |
) |
| 2978 |
finally: |
| 2979 |
manager._side_channel_scanners.clear() |
| 2980 |
|
| 2981 |
|
| 2982 |
@pytest.mark.asyncio |
| 2983 |
async def test_describe_side_channel_state_transport_closed() -> None: |
| 2984 |
"""Scanner is registered, protocol exists, but the transport is gone.""" |
| 2985 |
manager = get_manager() |
| 2986 |
manager.has_advertising_side_channel = True |
| 2987 |
ha_scanner = HaScanner(BluetoothScanningMode.PASSIVE, "hci0", "AA:BB:CC:DD:EE:07") |
| 2988 |
manager._side_channel_scanners[0] = ha_scanner |
| 2989 |
mgmt_ctl = Mock() |
| 2990 |
mgmt_ctl.protocol = Mock(spec=BluetoothMGMTProtocol) |
| 2991 |
mgmt_ctl.protocol.transport = None |
| 2992 |
manager._mgmt_ctl = mgmt_ctl |
| 2993 |
try: |
| 2994 |
assert ( |
| 2995 |
ha_scanner._describe_side_channel_state() |
| 2996 |
== "MGMT side channel registered at hci0 but transport closed" |
| 2997 |
) |
| 2998 |
finally: |
| 2999 |
manager._side_channel_scanners.clear() |
| 3000 |
manager._mgmt_ctl = None |
| 3001 |
|
| 3002 |
|
| 3003 |
@pytest.mark.asyncio |
| 3004 |
async def test_describe_side_channel_state_feeding() -> None: |
| 3005 |
"""Happy path: scanner registered, protocol and transport both live.""" |
| 3006 |
manager = get_manager() |
| 3007 |
manager.has_advertising_side_channel = True |
| 3008 |
ha_scanner = HaScanner(BluetoothScanningMode.PASSIVE, "hci0", "AA:BB:CC:DD:EE:08") |
| 3009 |
manager._side_channel_scanners[0] = ha_scanner |
| 3010 |
mgmt_ctl = Mock() |
| 3011 |
mgmt_ctl.protocol = Mock(spec=BluetoothMGMTProtocol) |
| 3012 |
mgmt_ctl.protocol.transport = Mock() |
| 3013 |
manager._mgmt_ctl = mgmt_ctl |
| 3014 |
try: |
| 3015 |
assert ( |
| 3016 |
ha_scanner._describe_side_channel_state() |
| 3017 |
== "MGMT side channel feeding hci0" |
| 3018 |
) |
| 3019 |
finally: |
| 3020 |
manager._side_channel_scanners.clear() |
| 3021 |
manager._mgmt_ctl = None |
| 3022 |
|
| 3023 |
|
| 3024 |
@pytest.mark.asyncio |
| 3025 |
async def test_scanner_watchdog_log_includes_side_channel_state( |
| 3026 |
caplog: pytest.LogCaptureFixture, |
| 3027 |
) -> None: |
| 3028 |
"""The 'gone quiet' restart log line carries the side-channel diagnostic.""" |
| 3029 |
manager = get_manager() |
| 3030 |
manager.has_advertising_side_channel = True |
| 3031 |
|
| 3032 |
class _NoRestartScanner(HaScanner): |
| 3033 |
# Skip the actual restart so the test just exercises the log path. |
| 3034 |
def _create_background_task(self, coro): |
| 3035 |
coro.close() |
| 3036 |
|
| 3037 |
with patch_bleak_scanner_factory(MockBleakScanner): |
| 3038 |
ha_scanner = _NoRestartScanner( |
| 3039 |
BluetoothScanningMode.PASSIVE, "hci0", "AA:BB:CC:DD:EE:09" |
| 3040 |
) |
| 3041 |
ha_scanner.async_setup() |
| 3042 |
await ha_scanner.async_start() |
| 3043 |
try: |
| 3044 |
# Force the watchdog over its timeout without producing any |
| 3045 |
# advertisements, and clear out the side-channel registration |
| 3046 |
# to make the diagnostic message distinctive. |
| 3047 |
manager._side_channel_scanners.clear() |
| 3048 |
ha_scanner._last_detection = ( |
| 3049 |
ha_scanner._last_detection - SCANNER_WATCHDOG_TIMEOUT - 1.0 |
| 3050 |
) |
| 3051 |
with caplog.at_level(logging.DEBUG, logger="habluetooth.scanner"): |
| 3052 |
ha_scanner._async_scanner_watchdog() |
| 3053 |
assert "MGMT side channel up but hci0 unregistered" in caplog.text |
| 3054 |
finally: |
| 3055 |
await ha_scanner.async_stop() |
| 3056 |
|
| 3057 |
|
| 3058 |
@pytest.mark.usefixtures("force_linux_scanner_mode") |
| 3059 |
@pytest.mark.asyncio |
| 3060 |
async def test_auto_scanner_current_mode_reports_passive_on_linux() -> None: |
| 3061 |
""" |
| 3062 |
AUTO must surface as PASSIVE in current_mode on Linux. |
| 3063 |
|
| 3064 |
AUTO is a habluetooth scheduling concept; the BlueZ radio is |
| 3065 |
actually running in passive until the scheduler opens an active |
| 3066 |
window. Remote scanners (ESPHome) already report the real radio |
| 3067 |
state, and local adapters used to report AUTO and look stuck. |
| 3068 |
""" |
| 3069 |
with patch_bleak_scanner_factory(MockBleakScanner): |
| 3070 |
ha_scanner = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:A0") |
| 3071 |
ha_scanner.async_setup() |
| 3072 |
await ha_scanner.async_start() |
| 3073 |
try: |
| 3074 |
assert ha_scanner.requested_mode is BluetoothScanningMode.AUTO |
| 3075 |
assert ha_scanner.current_mode is BluetoothScanningMode.PASSIVE |
| 3076 |
finally: |
| 3077 |
await ha_scanner.async_stop() |
| 3078 |
|
| 3079 |
|
| 3080 |
@pytest.fixture |
| 3081 |
def force_macos_scanner_mode() -> Generator[None, None, None]: |
| 3082 |
"""Force scanner.IS_LINUX=False / IS_MACOS=True for the AUTO->ACTIVE path.""" |
| 3083 |
with ( |
| 3084 |
patch("habluetooth.scanner_bleak.IS_LINUX", False), |
| 3085 |
patch("habluetooth.scanner_bleak.IS_MACOS", True), |
| 3086 |
): |
| 3087 |
yield |
| 3088 |
|
| 3089 |
|
| 3090 |
@pytest.mark.usefixtures("force_macos_scanner_mode") |
| 3091 |
@pytest.mark.asyncio |
| 3092 |
async def test_auto_scanner_current_mode_reports_active_on_macos() -> None: |
| 3093 |
""" |
| 3094 |
AUTO must surface as ACTIVE in current_mode on macOS. |
| 3095 |
|
| 3096 |
CoreBluetooth has no passive mode so AUTO collapses to permanent |
| 3097 |
active; current_mode should reflect that, not the AUTO scheduling |
| 3098 |
label. |
| 3099 |
""" |
| 3100 |
with patch_bleak_scanner_factory(MockBleakScanner): |
| 3101 |
ha_scanner = HaScanner( |
| 3102 |
BluetoothScanningMode.AUTO, "Core Bluetooth", "AA:BB:CC:DD:EE:A1" |
| 3103 |
) |
| 3104 |
ha_scanner.async_setup() |
| 3105 |
await ha_scanner.async_start() |
| 3106 |
try: |
| 3107 |
assert ha_scanner.requested_mode is BluetoothScanningMode.AUTO |
| 3108 |
assert ha_scanner.current_mode is BluetoothScanningMode.ACTIVE |
| 3109 |
finally: |
| 3110 |
await ha_scanner.async_stop() |
| 3111 |
|
| 3112 |
|
| 3113 |
@pytest.mark.usefixtures("force_linux_scanner_mode") |
| 3114 |
@pytest.mark.asyncio |
| 3115 |
async def test_auto_scanner_current_mode_active_during_active_window() -> None: |
| 3116 |
""" |
| 3117 |
Opening an AUTO active window flips current_mode to ACTIVE. |
| 3118 |
|
| 3119 |
Split from the post-window assertion to avoid mypy narrowing |
| 3120 |
``current_mode`` to a single literal across both transitions. |
| 3121 |
""" |
| 3122 |
with patch( |
| 3123 |
"habluetooth.scanner_bleak.OriginalBleakScanner", |
| 3124 |
side_effect=lambda *_a, **_kw: MockBleakScanner(), |
| 3125 |
): |
| 3126 |
ha_scanner = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:A2") |
| 3127 |
ha_scanner.async_setup() |
| 3128 |
await ha_scanner.async_start() |
| 3129 |
try: |
| 3130 |
assert await ha_scanner.async_request_active_window(10.0) is True |
| 3131 |
assert ha_scanner.current_mode is BluetoothScanningMode.ACTIVE |
| 3132 |
assert ha_scanner._scan_mode_override is BluetoothScanningMode.ACTIVE |
| 3133 |
finally: |
| 3134 |
await ha_scanner.async_stop() |
| 3135 |
|
| 3136 |
|
| 3137 |
@pytest.mark.usefixtures("force_linux_scanner_mode") |
| 3138 |
@pytest.mark.asyncio |
| 3139 |
async def test_auto_scanner_current_mode_passive_after_active_window() -> None: |
| 3140 |
""" |
| 3141 |
After an AUTO active window ends current_mode returns to PASSIVE. |
| 3142 |
|
| 3143 |
The end-of-window toggle restores the real radio state, which on |
| 3144 |
Linux/BlueZ is passive. current_mode must follow the radio rather |
| 3145 |
than reverting to the AUTO label. |
| 3146 |
""" |
| 3147 |
with patch( |
| 3148 |
"habluetooth.scanner_bleak.OriginalBleakScanner", |
| 3149 |
side_effect=lambda *_a, **_kw: MockBleakScanner(), |
| 3150 |
): |
| 3151 |
ha_scanner = HaScanner(BluetoothScanningMode.AUTO, "hci0", "AA:BB:CC:DD:EE:A3") |
| 3152 |
ha_scanner.async_setup() |
| 3153 |
await ha_scanner.async_start() |
| 3154 |
try: |
| 3155 |
assert await ha_scanner.async_request_active_window(1e-9) is True |
| 3156 |
for _ in range(6): |
| 3157 |
await asyncio.sleep(0) |
| 3158 |
assert ha_scanner.current_mode is BluetoothScanningMode.PASSIVE |
| 3159 |
assert ha_scanner._scan_mode_override is None |
| 3160 |
finally: |
| 3161 |
await ha_scanner.async_stop() |