| 1 |
"""Tests for bluetooth wrappers.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import asyncio |
| 6 |
import gc |
| 7 |
import logging |
| 8 |
import sys |
| 9 |
from contextlib import contextmanager, suppress |
| 10 |
from typing import TYPE_CHECKING, Any |
| 11 |
from unittest.mock import AsyncMock, MagicMock, Mock, patch |
| 12 |
from unittest.mock import call as mock_call |
| 13 |
|
| 14 |
import bleak |
| 15 |
import pytest |
| 16 |
import pytest_asyncio |
| 17 |
from bleak.backends.device import BLEDevice |
| 18 |
from bleak.exc import BleakError |
| 19 |
from bleak_retry_connector import Allocations |
| 20 |
|
| 21 |
from habluetooth import HaBluetoothConnector |
| 22 |
from habluetooth import get_manager as _get_manager |
| 23 |
from habluetooth.const import ( |
| 24 |
BDADDR_LE_PUBLIC, |
| 25 |
BDADDR_LE_RANDOM, |
| 26 |
CLIENT_DISCONNECT_TIMEOUT, |
| 27 |
) |
| 28 |
from habluetooth.usage import ( |
| 29 |
install_multiple_bleak_catcher, |
| 30 |
uninstall_multiple_bleak_catcher, |
| 31 |
) |
| 32 |
from habluetooth.wrappers import ( |
| 33 |
FILTER_UUIDS, |
| 34 |
HaBleakClientWrapper, |
| 35 |
HaBleakScannerWrapper, |
| 36 |
_get_device_address_type, |
| 37 |
) |
| 38 |
|
| 39 |
from . import ( |
| 40 |
HCI0_SOURCE_ADDRESS, |
| 41 |
InjectableRemoteScanner, |
| 42 |
generate_advertisement_data, |
| 43 |
generate_ble_device, |
| 44 |
inject_advertisement, |
| 45 |
patch_discovered_devices, |
| 46 |
) |
| 47 |
|
| 48 |
if TYPE_CHECKING: |
| 49 |
from collections.abc import AsyncGenerator, Awaitable, Callable, Generator |
| 50 |
|
| 51 |
from bleak.backends.scanner import AdvertisementData |
| 52 |
|
| 53 |
from habluetooth.manager import BluetoothManager |
| 54 |
|
| 55 |
ConnectedClient = tuple[ |
| 56 |
bleak.BleakClient, dict[str, Any], dict[str, Callable[[], None]] |
| 57 |
] |
| 58 |
|
| 59 |
|
| 60 |
@contextmanager |
| 61 |
def mock_shutdown(manager: BluetoothManager) -> Generator[None, None, None]: |
| 62 |
"""Mock shutdown of the HomeAssistantBluetoothManager.""" |
| 63 |
manager.shutdown = True |
| 64 |
yield |
| 65 |
manager.shutdown = False |
| 66 |
|
| 67 |
|
| 68 |
class FakeScanner(InjectableRemoteScanner): |
| 69 |
"""Wrappers-test scanner that empties _details for routing tests.""" |
| 70 |
|
| 71 |
def __init__( |
| 72 |
self, |
| 73 |
scanner_id: str, |
| 74 |
name: str, |
| 75 |
connector: Any, |
| 76 |
connectable: bool, |
| 77 |
) -> None: |
| 78 |
"""Initialize the scanner.""" |
| 79 |
super().__init__(scanner_id, name, connector, connectable) |
| 80 |
self._details: dict[str, str | HaBluetoothConnector] = {} |
| 81 |
|
| 82 |
def __repr__(self) -> str: |
| 83 |
"""Return the representation.""" |
| 84 |
return f"FakeScanner({self.name})" |
| 85 |
|
| 86 |
|
| 87 |
class BaseFakeBleakClient: |
| 88 |
"""Base class for fake bleak clients.""" |
| 89 |
|
| 90 |
def __init__(self, address_or_ble_device: BLEDevice | str, **kwargs: Any) -> None: |
| 91 |
"""Initialize the fake bleak client.""" |
| 92 |
self._device_path = "/dev/test" |
| 93 |
self._device = address_or_ble_device |
| 94 |
assert isinstance(address_or_ble_device, BLEDevice) |
| 95 |
self._address = address_or_ble_device.address |
| 96 |
|
| 97 |
async def disconnect(self, *args, **kwargs): |
| 98 |
"""Disconnect.""" |
| 99 |
|
| 100 |
async def get_services(self, *args, **kwargs): |
| 101 |
"""Get services.""" |
| 102 |
return [] |
| 103 |
|
| 104 |
|
| 105 |
class FakeBleakClient(BaseFakeBleakClient): |
| 106 |
"""Fake bleak client.""" |
| 107 |
|
| 108 |
async def connect(self, *args, **kwargs): |
| 109 |
"""Connect.""" |
| 110 |
return True |
| 111 |
|
| 112 |
@property |
| 113 |
def is_connected(self): |
| 114 |
return False |
| 115 |
|
| 116 |
|
| 117 |
class FakeBleakClientFailsToConnect(BaseFakeBleakClient): |
| 118 |
"""Fake bleak client that fails to connect.""" |
| 119 |
|
| 120 |
async def connect(self, *args, **kwargs): |
| 121 |
"""Connect.""" |
| 122 |
return |
| 123 |
|
| 124 |
@property |
| 125 |
def is_connected(self): |
| 126 |
return False |
| 127 |
|
| 128 |
|
| 129 |
class FakeBleakClientRaisesOnConnect(BaseFakeBleakClient): |
| 130 |
"""Fake bleak client that raises on connect.""" |
| 131 |
|
| 132 |
async def connect(self, *args, **kwargs): |
| 133 |
"""Connect.""" |
| 134 |
msg = "Test exception" |
| 135 |
raise ConnectionError(msg) |
| 136 |
|
| 137 |
|
| 138 |
class FakeBleakClientCancelledOnConnect(BaseFakeBleakClient): |
| 139 |
"""Fake bleak client that raises CancelledError on connect.""" |
| 140 |
|
| 141 |
async def connect(self, *args, **kwargs): |
| 142 |
"""Connect.""" |
| 143 |
raise asyncio.CancelledError |
| 144 |
|
| 145 |
|
| 146 |
def _generate_ble_device_and_adv_data( |
| 147 |
interface: str, mac: str, rssi: int |
| 148 |
) -> tuple[BLEDevice, AdvertisementData]: |
| 149 |
"""Generate a BLE device with adv data.""" |
| 150 |
return ( |
| 151 |
generate_ble_device( |
| 152 |
mac, |
| 153 |
"any", |
| 154 |
delegate="", |
| 155 |
details={"path": f"/org/bluez/{interface}/dev_{mac}"}, |
| 156 |
), |
| 157 |
generate_advertisement_data(rssi=rssi), |
| 158 |
) |
| 159 |
|
| 160 |
|
| 161 |
def _make_detection_recorder() -> tuple[ |
| 162 |
list[tuple[BLEDevice, AdvertisementData]], |
| 163 |
Callable[[BLEDevice, AdvertisementData], None], |
| 164 |
]: |
| 165 |
"""Return ``(recorded, callback)``; callback appends ``(device, adv)``.""" |
| 166 |
recorded: list[tuple[BLEDevice, AdvertisementData]] = [] |
| 167 |
|
| 168 |
def _record(device: BLEDevice, advertisement_data: AdvertisementData) -> None: |
| 169 |
recorded.append((device, advertisement_data)) |
| 170 |
|
| 171 |
return recorded, _record |
| 172 |
|
| 173 |
|
| 174 |
def _make_async_detection_recorder() -> tuple[ |
| 175 |
list[tuple[BLEDevice, AdvertisementData]], |
| 176 |
Callable[[BLEDevice, AdvertisementData], Awaitable[None]], |
| 177 |
]: |
| 178 |
"""Async variant of :func:`_make_detection_recorder`.""" |
| 179 |
recorded: list[tuple[BLEDevice, AdvertisementData]] = [] |
| 180 |
|
| 181 |
async def _record(device: BLEDevice, advertisement_data: AdvertisementData) -> None: |
| 182 |
recorded.append((device, advertisement_data)) |
| 183 |
|
| 184 |
return recorded, _record |
| 185 |
|
| 186 |
|
| 187 |
@pytest.fixture(name="install_bleak_catcher") |
| 188 |
def install_bleak_catcher_fixture(): |
| 189 |
"""Fixture that installs the bleak catcher.""" |
| 190 |
install_multiple_bleak_catcher() |
| 191 |
yield |
| 192 |
uninstall_multiple_bleak_catcher() |
| 193 |
|
| 194 |
|
| 195 |
@pytest.fixture(name="mock_platform_client") |
| 196 |
def mock_platform_client_fixture(): |
| 197 |
"""Fixture that mocks the platform client.""" |
| 198 |
with patch( |
| 199 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 200 |
return_value=FakeBleakClient, |
| 201 |
): |
| 202 |
yield |
| 203 |
|
| 204 |
|
| 205 |
@pytest.fixture(name="mock_platform_client_that_fails_to_connect") |
| 206 |
def mock_platform_client_that_fails_to_connect_fixture(): |
| 207 |
"""Fixture that mocks the platform client that fails to connect.""" |
| 208 |
with patch( |
| 209 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 210 |
return_value=FakeBleakClientFailsToConnect, |
| 211 |
): |
| 212 |
yield |
| 213 |
|
| 214 |
|
| 215 |
@pytest.fixture(name="mock_platform_client_that_raises_on_connect") |
| 216 |
def mock_platform_client_that_raises_on_connect_fixture(): |
| 217 |
"""Fixture that mocks the platform client that fails to connect.""" |
| 218 |
with patch( |
| 219 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 220 |
return_value=FakeBleakClientRaisesOnConnect, |
| 221 |
): |
| 222 |
yield |
| 223 |
|
| 224 |
|
| 225 |
@pytest.fixture(name="mock_platform_client_that_cancels_on_connect") |
| 226 |
def mock_platform_client_that_cancels_on_connect_fixture(): |
| 227 |
"""Fixture that mocks the platform client that raises CancelledError.""" |
| 228 |
with patch( |
| 229 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 230 |
return_value=FakeBleakClientCancelledOnConnect, |
| 231 |
): |
| 232 |
yield |
| 233 |
|
| 234 |
|
| 235 |
def _generate_scanners_with_fake_devices(): |
| 236 |
"""Generate scanners with fake devices.""" |
| 237 |
manager = _get_manager() |
| 238 |
hci0_device_advs = {} |
| 239 |
for i in range(10): |
| 240 |
device, adv_data = _generate_ble_device_and_adv_data( |
| 241 |
"hci0", f"00:00:00:00:00:{i:02x}", rssi=-60 |
| 242 |
) |
| 243 |
hci0_device_advs[device.address] = (device, adv_data) |
| 244 |
hci1_device_advs = {} |
| 245 |
for i in range(10): |
| 246 |
device, adv_data = _generate_ble_device_and_adv_data( |
| 247 |
"hci1", f"00:00:00:00:00:{i:02x}", rssi=-80 |
| 248 |
) |
| 249 |
hci1_device_advs[device.address] = (device, adv_data) |
| 250 |
|
| 251 |
scanner_hci0 = FakeScanner("00:00:00:00:00:01", "hci0", None, True) |
| 252 |
scanner_hci1 = FakeScanner("00:00:00:00:00:02", "hci1", None, True) |
| 253 |
|
| 254 |
for device, adv_data in hci0_device_advs.values(): |
| 255 |
scanner_hci0.inject_advertisement(device, adv_data) |
| 256 |
|
| 257 |
for device, adv_data in hci1_device_advs.values(): |
| 258 |
scanner_hci1.inject_advertisement(device, adv_data) |
| 259 |
|
| 260 |
cancel_hci0 = manager.async_register_scanner(scanner_hci0, connection_slots=2) |
| 261 |
cancel_hci1 = manager.async_register_scanner(scanner_hci1, connection_slots=1) |
| 262 |
|
| 263 |
return hci0_device_advs, cancel_hci0, cancel_hci1 |
| 264 |
|
| 265 |
|
| 266 |
@pytest_asyncio.fixture |
| 267 |
async def connected_client( |
| 268 |
two_adapters: None, |
| 269 |
enable_bluetooth: None, |
| 270 |
install_bleak_catcher: None, |
| 271 |
mock_platform_client: None, |
| 272 |
) -> AsyncGenerator[ConnectedClient, None]: |
| 273 |
"""A client connected through hci0 plus the scanner cancel callbacks.""" |
| 274 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 275 |
with patch.object(FakeBleakClient, "is_connected", return_value=True): |
| 276 |
client = bleak.BleakClient(hci0_device_advs["00:00:00:00:00:01"][0]) |
| 277 |
await client.connect() |
| 278 |
yield client, hci0_device_advs, {"hci0": cancel_hci0, "hci1": cancel_hci1} |
| 279 |
cancel_hci0() |
| 280 |
cancel_hci1() |
| 281 |
|
| 282 |
|
| 283 |
async def _settle_disconnects() -> None: |
| 284 |
"""Wait for the manager's background tasks to finish.""" |
| 285 |
await asyncio.gather(*_get_manager()._background_tasks, return_exceptions=True) |
| 286 |
await asyncio.sleep(0) |
| 287 |
|
| 288 |
|
| 289 |
async def _hang() -> None: |
| 290 |
await asyncio.Event().wait() |
| 291 |
|
| 292 |
|
| 293 |
@pytest.mark.asyncio |
| 294 |
@pytest.mark.parametrize(("removed", "disconnects"), [("hci0", 1), ("hci1", 0)]) |
| 295 |
async def test_unregister_scanner_disconnects_only_its_clients( |
| 296 |
connected_client: ConnectedClient, removed: str, disconnects: int |
| 297 |
) -> None: |
| 298 |
"""Removing a scanner disconnects its clients and nobody else's.""" |
| 299 |
_, _, cancel = connected_client |
| 300 |
with patch.object( |
| 301 |
FakeBleakClient, "disconnect", new_callable=AsyncMock |
| 302 |
) as disconnect_mock: |
| 303 |
cancel[removed]() |
| 304 |
await _settle_disconnects() |
| 305 |
assert disconnect_mock.call_count == disconnects |
| 306 |
|
| 307 |
|
| 308 |
@pytest.mark.asyncio |
| 309 |
async def test_disconnected_client_is_not_disconnected_again( |
| 310 |
connected_client: ConnectedClient, |
| 311 |
) -> None: |
| 312 |
"""A client that already disconnected is no longer tracked.""" |
| 313 |
client, _, cancel = connected_client |
| 314 |
scanner = client._connected_scanner |
| 315 |
with patch.object(FakeBleakClient, "is_connected", False): |
| 316 |
await client.disconnect() |
| 317 |
assert client not in scanner._clients |
| 318 |
with patch.object( |
| 319 |
FakeBleakClient, "disconnect", new_callable=AsyncMock |
| 320 |
) as disconnect_mock: |
| 321 |
cancel["hci0"]() |
| 322 |
await _settle_disconnects() |
| 323 |
assert disconnect_mock.call_count == 0 |
| 324 |
|
| 325 |
|
| 326 |
@pytest.mark.asyncio |
| 327 |
async def test_client_tracking_does_not_keep_client_alive( |
| 328 |
two_adapters: None, |
| 329 |
enable_bluetooth: None, |
| 330 |
install_bleak_catcher: None, |
| 331 |
mock_platform_client: None, |
| 332 |
) -> None: |
| 333 |
"""Tracked clients are held weakly so a dropped client cannot leak.""" |
| 334 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 335 |
with patch.object(FakeBleakClient, "is_connected", return_value=True): |
| 336 |
client = bleak.BleakClient(hci0_device_advs["00:00:00:00:00:01"][0]) |
| 337 |
await client.connect() |
| 338 |
scanner = client._connected_scanner |
| 339 |
assert len(scanner._clients) == 1 |
| 340 |
del client |
| 341 |
gc.collect() |
| 342 |
assert len(scanner._clients) == 0 |
| 343 |
cancel_hci0() |
| 344 |
cancel_hci1() |
| 345 |
|
| 346 |
|
| 347 |
@pytest.mark.asyncio |
| 348 |
@pytest.mark.parametrize("reconnected_elsewhere", [False, True]) |
| 349 |
async def test_disconnect_error_on_unregister_is_logged_not_raised( |
| 350 |
connected_client: ConnectedClient, |
| 351 |
caplog: pytest.LogCaptureFixture, |
| 352 |
reconnected_elsewhere: bool, |
| 353 |
) -> None: |
| 354 |
"""A failed disconnect is logged; give up re-checks identity first.""" |
| 355 |
client, _, cancel = connected_client |
| 356 |
|
| 357 |
async def _fail_mid_disconnect(*args: Any, **kwargs: Any) -> None: |
| 358 |
if reconnected_elsewhere: |
| 359 |
# The client moves on while its disconnect is failing; the |
| 360 |
# handler must not give up the fresh backend. |
| 361 |
client._connected_scanner = MagicMock() |
| 362 |
msg = "nope" |
| 363 |
raise BleakError(msg) |
| 364 |
|
| 365 |
with patch.object( |
| 366 |
FakeBleakClient, |
| 367 |
"disconnect", |
| 368 |
new_callable=AsyncMock, |
| 369 |
side_effect=_fail_mid_disconnect, |
| 370 |
): |
| 371 |
cancel["hci0"]() |
| 372 |
await _settle_disconnects() |
| 373 |
assert (client._backend is None) is not reconnected_elsewhere |
| 374 |
if not reconnected_elsewhere: |
| 375 |
assert client._connected_scanner is None |
| 376 |
assert "from removed scanner" in caplog.text |
| 377 |
|
| 378 |
|
| 379 |
@pytest.mark.asyncio |
| 380 |
async def test_client_reconnected_elsewhere_is_not_disconnected( |
| 381 |
connected_client: ConnectedClient, |
| 382 |
) -> None: |
| 383 |
"""A client that moved to another scanner survives the old one's removal.""" |
| 384 |
client, _, cancel = connected_client |
| 385 |
other_scanner = MagicMock() |
| 386 |
with ( |
| 387 |
patch.object(client, "_connected_scanner", other_scanner), |
| 388 |
patch.object( |
| 389 |
FakeBleakClient, "disconnect", new_callable=AsyncMock |
| 390 |
) as disconnect_mock, |
| 391 |
): |
| 392 |
cancel["hci0"]() |
| 393 |
await _settle_disconnects() |
| 394 |
assert disconnect_mock.call_count == 0 |
| 395 |
|
| 396 |
|
| 397 |
@pytest.mark.asyncio |
| 398 |
async def test_reconnect_untracks_from_previous_scanner( |
| 399 |
connected_client: ConnectedClient, |
| 400 |
) -> None: |
| 401 |
"""Reconnecting drops the stale entry on the previous scanner.""" |
| 402 |
client, _, cancel = connected_client |
| 403 |
first_scanner = client._connected_scanner |
| 404 |
assert client in first_scanner._clients |
| 405 |
cancel["hci0"]() |
| 406 |
await _settle_disconnects() |
| 407 |
# The old link is gone; reconnect resolves to the remaining scanner. |
| 408 |
with patch.object(FakeBleakClient, "is_connected", False): |
| 409 |
await client.connect() |
| 410 |
second_scanner = client._connected_scanner |
| 411 |
assert second_scanner is not first_scanner |
| 412 |
assert client not in first_scanner._clients |
| 413 |
assert client in second_scanner._clients |
| 414 |
|
| 415 |
|
| 416 |
@pytest.mark.asyncio |
| 417 |
async def test_disconnect_timeout_on_unregister_is_logged( |
| 418 |
connected_client: ConnectedClient, caplog: pytest.LogCaptureFixture |
| 419 |
) -> None: |
| 420 |
"""A hanging disconnect is bounded and logged, not pending forever.""" |
| 421 |
client, _, cancel = connected_client |
| 422 |
|
| 423 |
disconnected: list[bleak.BleakClient] = [] |
| 424 |
with patch.object( |
| 425 |
FakeBleakClient, "set_disconnected_callback", Mock(), create=True |
| 426 |
): |
| 427 |
client.set_disconnected_callback(disconnected.append) |
| 428 |
with ( |
| 429 |
patch("habluetooth.manager.CLIENT_DISCONNECT_TIMEOUT", 0.0), |
| 430 |
patch.object(FakeBleakClient, "disconnect", side_effect=_hang), |
| 431 |
): |
| 432 |
cancel["hci0"]() |
| 433 |
await _settle_disconnects() |
| 434 |
assert client._backend is None |
| 435 |
assert client._connected_scanner is None |
| 436 |
assert not client.is_connected |
| 437 |
await asyncio.sleep(0) |
| 438 |
assert disconnected == [client] |
| 439 |
assert "Timed out disconnecting client 00:00:00:00:00:01" in caplog.text |
| 440 |
|
| 441 |
|
| 442 |
@pytest.mark.asyncio |
| 443 |
async def test_stop_cancels_pending_disconnects( |
| 444 |
connected_client: ConnectedClient, caplog: pytest.LogCaptureFixture |
| 445 |
) -> None: |
| 446 |
"""async_stop cancels disconnect tasks still in flight.""" |
| 447 |
_, _, cancel = connected_client |
| 448 |
manager = _get_manager() |
| 449 |
|
| 450 |
with patch.object(FakeBleakClient, "disconnect", side_effect=_hang): |
| 451 |
cancel["hci0"]() |
| 452 |
tasks = list(manager._background_tasks) |
| 453 |
assert tasks |
| 454 |
# Let the disconnect task start and block on the hung disconnect. |
| 455 |
await asyncio.sleep(0) |
| 456 |
manager.async_stop() |
| 457 |
await asyncio.wait(tasks, timeout=1) |
| 458 |
assert all(task.cancelled() for task in tasks) |
| 459 |
assert "Cancelling 1 background task(s) at stop" in caplog.text |
| 460 |
assert "Cancelled disconnecting 1 client(s)" in caplog.text |
| 461 |
|
| 462 |
|
| 463 |
@pytest.mark.asyncio |
| 464 |
async def test_manager_backend_timeout_is_not_misreported( |
| 465 |
connected_client: ConnectedClient, caplog: pytest.LogCaptureFixture |
| 466 |
) -> None: |
| 467 |
"""A backend raised TimeoutError logs as an error, not the deadline.""" |
| 468 |
_, _, cancel = connected_client |
| 469 |
with patch.object( |
| 470 |
FakeBleakClient, |
| 471 |
"disconnect", |
| 472 |
new_callable=AsyncMock, |
| 473 |
side_effect=TimeoutError("backend"), |
| 474 |
): |
| 475 |
cancel["hci0"]() |
| 476 |
await _settle_disconnects() |
| 477 |
assert "Error disconnecting client" in caplog.text |
| 478 |
assert "Timed out disconnecting client" not in caplog.text |
| 479 |
|
| 480 |
|
| 481 |
@pytest.mark.asyncio |
| 482 |
async def test_give_up_detaches_the_disconnected_callback( |
| 483 |
install_bleak_catcher: None, |
| 484 |
) -> None: |
| 485 |
"""Give up silences the orphaned backend's disconnected callback.""" |
| 486 |
client = HaBleakClientWrapper(generate_ble_device("00:00:00:00:00:0E", "x")) |
| 487 |
backend: Any = Mock() |
| 488 |
client._backend = backend |
| 489 |
client._give_up() |
| 490 |
backend.set_disconnected_callback.assert_called_once_with(None) |
| 491 |
assert client._backend is None |
| 492 |
assert client._connected_scanner is None |
| 493 |
# Idempotent with no backend left. |
| 494 |
client._give_up() |
| 495 |
backend.set_disconnected_callback.assert_called_once_with(None) |
| 496 |
|
| 497 |
|
| 498 |
@pytest.mark.asyncio |
| 499 |
async def test_give_up_survives_a_backend_that_refuses_to_detach( |
| 500 |
install_bleak_catcher: None, caplog: pytest.LogCaptureFixture |
| 501 |
) -> None: |
| 502 |
"""A backend that refuses to detach is logged, not fatal.""" |
| 503 |
client = HaBleakClientWrapper(generate_ble_device("00:00:00:00:00:0E", "x")) |
| 504 |
refusing: Any = Mock() |
| 505 |
refusing.set_disconnected_callback.side_effect = ValueError("no") |
| 506 |
client._backend = refusing |
| 507 |
client._give_up() |
| 508 |
assert client._backend is None |
| 509 |
assert "could not detach the disconnected callback" in caplog.text |
| 510 |
assert caplog.records[-1].levelname == "WARNING" |
| 511 |
|
| 512 |
|
| 513 |
@pytest.mark.asyncio |
| 514 |
async def test_abort_detaches_the_callback_before_disconnecting( |
| 515 |
install_bleak_catcher: None, |
| 516 |
) -> None: |
| 517 |
"""A clean abort cannot fire the consumer callback mid connect.""" |
| 518 |
client = HaBleakClientWrapper(generate_ble_device("00:00:00:00:00:0E", "x")) |
| 519 |
backend: Any = Mock() |
| 520 |
backend.disconnect = AsyncMock() |
| 521 |
backend.is_connected = False |
| 522 |
client._backend = backend |
| 523 |
aborted = False |
| 524 |
try: |
| 525 |
await client._async_abort_unregistered_mid_connect(MagicMock()) |
| 526 |
except BleakError as err: |
| 527 |
aborted = "unregistered during connect" in str(err) |
| 528 |
assert aborted |
| 529 |
assert backend.mock_calls[0] == mock_call.set_disconnected_callback(None) |
| 530 |
assert mock_call.disconnect() in backend.mock_calls |
| 531 |
|
| 532 |
|
| 533 |
@pytest.mark.asyncio |
| 534 |
@pytest.mark.parametrize(("link_up", "notified"), [(True, True), (False, False)]) |
| 535 |
async def test_give_up_notifies_only_when_the_link_was_up( |
| 536 |
install_bleak_catcher: None, link_up: bool, notified: bool |
| 537 |
) -> None: |
| 538 |
"""The consumer hears about a give up once, not twice.""" |
| 539 |
client = HaBleakClientWrapper(generate_ble_device("00:00:00:00:00:0E", "x")) |
| 540 |
disconnected: list[bleak.BleakClient] = [] |
| 541 |
client.set_disconnected_callback(disconnected.append) |
| 542 |
backend: Any = Mock() |
| 543 |
backend.is_connected = link_up |
| 544 |
client._backend = backend |
| 545 |
client._give_up(notify=True) |
| 546 |
await asyncio.sleep(0) |
| 547 |
assert (disconnected == [client]) is notified |
| 548 |
|
| 549 |
|
| 550 |
@pytest.mark.asyncio |
| 551 |
async def test_failed_disconnect_with_link_down_untracks( |
| 552 |
connected_client: ConnectedClient, |
| 553 |
) -> None: |
| 554 |
"""A raising disconnect still untracks when the link actually dropped.""" |
| 555 |
client, _, _ = connected_client |
| 556 |
scanner = client._connected_scanner |
| 557 |
with ( |
| 558 |
patch.object(FakeBleakClient, "is_connected", False), |
| 559 |
patch.object( |
| 560 |
FakeBleakClient, |
| 561 |
"disconnect", |
| 562 |
new_callable=AsyncMock, |
| 563 |
side_effect=BleakError("nope"), |
| 564 |
), |
| 565 |
pytest.raises(BleakError), |
| 566 |
): |
| 567 |
await client.disconnect() |
| 568 |
assert client not in scanner._clients |
| 569 |
assert client._connected_scanner is None |
| 570 |
|
| 571 |
|
| 572 |
@pytest.mark.asyncio |
| 573 |
async def test_failed_disconnect_keeps_client_tracked( |
| 574 |
connected_client: ConnectedClient, |
| 575 |
) -> None: |
| 576 |
"""A disconnect that raises with the link still up keeps the client tracked.""" |
| 577 |
client, _, _ = connected_client |
| 578 |
scanner = client._connected_scanner |
| 579 |
with ( |
| 580 |
patch.object( |
| 581 |
FakeBleakClient, |
| 582 |
"disconnect", |
| 583 |
new_callable=AsyncMock, |
| 584 |
side_effect=BleakError("nope"), |
| 585 |
), |
| 586 |
pytest.raises(BleakError), |
| 587 |
): |
| 588 |
await client.disconnect() |
| 589 |
assert client in scanner._clients |
| 590 |
|
| 591 |
|
| 592 |
@pytest.mark.asyncio |
| 593 |
@pytest.mark.parametrize( |
| 594 |
("disconnect_effect", "zero_timeout", "expected_exc", "log_fragment"), |
| 595 |
[ |
| 596 |
(None, False, BleakError, None), |
| 597 |
(BleakError("nope"), False, BleakError, "error disconnecting after scanner"), |
| 598 |
( |
| 599 |
TimeoutError("backend"), |
| 600 |
False, |
| 601 |
BleakError, |
| 602 |
"error disconnecting after scanner", |
| 603 |
), |
| 604 |
( |
| 605 |
asyncio.CancelledError, |
| 606 |
False, |
| 607 |
asyncio.CancelledError, |
| 608 |
"cancelled disconnecting after scanner", |
| 609 |
), |
| 610 |
(_hang, True, BleakError, "timed out disconnecting after scanner"), |
| 611 |
], |
| 612 |
ids=["clean", "error", "backend_timeout", "cancelled", "timeout"], |
| 613 |
) |
| 614 |
async def test_connect_in_flight_when_scanner_unregisters( |
| 615 |
two_adapters: None, |
| 616 |
enable_bluetooth: None, |
| 617 |
install_bleak_catcher: None, |
| 618 |
mock_platform_client: None, |
| 619 |
caplog: pytest.LogCaptureFixture, |
| 620 |
disconnect_effect: Any, |
| 621 |
zero_timeout: bool, |
| 622 |
expected_exc: type[BaseException], |
| 623 |
log_fragment: str | None, |
| 624 |
) -> None: |
| 625 |
"""A connect that finishes after its scanner unregistered is torn down.""" |
| 626 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 627 |
original_connect = FakeBleakClient.connect |
| 628 |
|
| 629 |
async def _connect_and_unregister( |
| 630 |
self: FakeBleakClient, *args: Any, **kwargs: Any |
| 631 |
) -> None: |
| 632 |
await original_connect(self, *args, **kwargs) |
| 633 |
# The scanner goes away while the connect is still in flight. |
| 634 |
cancel_hci0() |
| 635 |
|
| 636 |
timeout = 0.0 if zero_timeout else CLIENT_DISCONNECT_TIMEOUT |
| 637 |
with ( |
| 638 |
patch("habluetooth.wrappers.CLIENT_DISCONNECT_TIMEOUT", timeout), |
| 639 |
patch.object(FakeBleakClient, "is_connected", return_value=True), |
| 640 |
patch.object(FakeBleakClient, "connect", _connect_and_unregister), |
| 641 |
patch.object( |
| 642 |
FakeBleakClient, |
| 643 |
"disconnect", |
| 644 |
new_callable=AsyncMock, |
| 645 |
side_effect=disconnect_effect, |
| 646 |
) as disconnect_mock, |
| 647 |
): |
| 648 |
client = bleak.BleakClient(hci0_device_advs["00:00:00:00:00:01"][0]) |
| 649 |
with pytest.raises(expected_exc): |
| 650 |
await client.connect() |
| 651 |
assert client._backend is None |
| 652 |
assert disconnect_mock.call_count == 1 |
| 653 |
if log_fragment is not None: |
| 654 |
assert log_fragment in caplog.text |
| 655 |
cancel_hci1() |
| 656 |
|
| 657 |
|
| 658 |
@pytest.mark.asyncio |
| 659 |
async def test_dropped_link_is_not_disconnected_on_unregister( |
| 660 |
connected_client: ConnectedClient, caplog: pytest.LogCaptureFixture |
| 661 |
) -> None: |
| 662 |
"""A client whose link already dropped is untracked, not disconnected.""" |
| 663 |
client, _, cancel = connected_client |
| 664 |
with ( |
| 665 |
patch.object(FakeBleakClient, "is_connected", False), |
| 666 |
patch.object( |
| 667 |
FakeBleakClient, "disconnect", new_callable=AsyncMock |
| 668 |
) as disconnect_mock, |
| 669 |
): |
| 670 |
cancel["hci0"]() |
| 671 |
await _settle_disconnects() |
| 672 |
assert client._connected_scanner is None |
| 673 |
assert disconnect_mock.call_count == 0 |
| 674 |
assert "already down; not disconnecting" in caplog.text |
| 675 |
|
| 676 |
|
| 677 |
@pytest.mark.asyncio |
| 678 |
async def test_track_moves_client_between_scanners( |
| 679 |
connected_client: ConnectedClient, |
| 680 |
) -> None: |
| 681 |
"""Tracking follows the client when it roams to another scanner.""" |
| 682 |
client, _, _ = connected_client |
| 683 |
manager = _get_manager() |
| 684 |
first = client._connected_scanner |
| 685 |
second = next(s for s in manager._sources.values() if s is not first) |
| 686 |
client._track(second, client._connected_device) |
| 687 |
assert client not in first._clients |
| 688 |
assert client in second._clients |
| 689 |
assert client._connected_scanner is second |
| 690 |
|
| 691 |
|
| 692 |
@pytest.mark.asyncio |
| 693 |
async def test_no_disconnects_scheduled_after_stop( |
| 694 |
connected_client: ConnectedClient, caplog: pytest.LogCaptureFixture |
| 695 |
) -> None: |
| 696 |
"""A scanner unregistering after async_stop schedules nothing.""" |
| 697 |
_, _, cancel = connected_client |
| 698 |
manager = _get_manager() |
| 699 |
manager.async_stop() |
| 700 |
cancel["hci0"]() |
| 701 |
assert not manager._background_tasks |
| 702 |
assert "Shutdown; not disconnecting 1 client(s)" in caplog.text |
| 703 |
|
| 704 |
|
| 705 |
@pytest.mark.asyncio |
| 706 |
async def test_background_task_exception_is_logged( |
| 707 |
two_adapters: None, |
| 708 |
enable_bluetooth: None, |
| 709 |
caplog: pytest.LogCaptureFixture, |
| 710 |
) -> None: |
| 711 |
"""An exception escaping a background task is logged, not lost.""" |
| 712 |
manager = _get_manager() |
| 713 |
|
| 714 |
async def _boom() -> None: |
| 715 |
msg = "boom" |
| 716 |
raise ValueError(msg) |
| 717 |
|
| 718 |
manager._async_add_background_task(_boom(), "boom task") |
| 719 |
await _settle_disconnects() |
| 720 |
assert "Background task boom task failed" in caplog.text |
| 721 |
|
| 722 |
|
| 723 |
@pytest.mark.asyncio |
| 724 |
async def test_disconnect_untracks_even_if_backend_still_reports_connected( |
| 725 |
connected_client: ConnectedClient, |
| 726 |
) -> None: |
| 727 |
"""A clean disconnect untracks even when the backend clears state late.""" |
| 728 |
client, _, _ = connected_client |
| 729 |
scanner = client._connected_scanner |
| 730 |
# The fixture pins is_connected True, simulating a backend that only |
| 731 |
# clears its state asynchronously; the clean return must still untrack. |
| 732 |
with patch.object(FakeBleakClient, "disconnect", new_callable=AsyncMock): |
| 733 |
await client.disconnect() |
| 734 |
assert client not in scanner._clients |
| 735 |
assert client._connected_scanner is None |
| 736 |
|
| 737 |
|
| 738 |
@pytest.mark.asyncio |
| 739 |
@pytest.mark.parametrize("reconnected_elsewhere", [False, True]) |
| 740 |
async def test_base_exception_from_disconnect_gives_up_client( |
| 741 |
connected_client: ConnectedClient, |
| 742 |
caplog: pytest.LogCaptureFixture, |
| 743 |
reconnected_elsewhere: bool, |
| 744 |
) -> None: |
| 745 |
"""A BaseException escaping a child is logged; give up re-checks identity.""" |
| 746 |
client, _, cancel = connected_client |
| 747 |
|
| 748 |
async def _cancel_mid_disconnect(*args: Any, **kwargs: Any) -> None: |
| 749 |
if reconnected_elsewhere: |
| 750 |
# The client moves on while the gather is still settling; the |
| 751 |
# late results pass must not give it up. |
| 752 |
client._connected_scanner = MagicMock() |
| 753 |
raise asyncio.CancelledError |
| 754 |
|
| 755 |
with patch.object( |
| 756 |
FakeBleakClient, |
| 757 |
"disconnect", |
| 758 |
new_callable=AsyncMock, |
| 759 |
side_effect=_cancel_mid_disconnect, |
| 760 |
): |
| 761 |
cancel["hci0"]() |
| 762 |
await _settle_disconnects() |
| 763 |
assert (client._backend is None) is not reconnected_elsewhere |
| 764 |
assert "Unexpected error disconnecting client" in caplog.text |
| 765 |
|
| 766 |
|
| 767 |
@pytest.mark.asyncio |
| 768 |
async def test_set_connection_params_disconnected_is_quiet( |
| 769 |
connected_client: ConnectedClient, caplog: pytest.LogCaptureFixture |
| 770 |
) -> None: |
| 771 |
"""No upgrade-the-backend warning for a client that is not connected.""" |
| 772 |
client, _, _ = connected_client |
| 773 |
with patch.object(FakeBleakClient, "is_connected", False): |
| 774 |
await client.disconnect() |
| 775 |
await client.set_connection_params(6, 6, 0, 1000) |
| 776 |
assert "Upgrade the backend library" not in caplog.text |
| 777 |
assert "not setting connection params" in caplog.text |
| 778 |
|
| 779 |
|
| 780 |
@pytest.mark.asyncio |
| 781 |
async def test_disconnect_without_backend_untracks_stale_pointers( |
| 782 |
connected_client: ConnectedClient, |
| 783 |
) -> None: |
| 784 |
"""Disconnect with no backend clears pointers left by a failed teardown.""" |
| 785 |
client, _, _ = connected_client |
| 786 |
scanner = client._connected_scanner |
| 787 |
assert client in scanner._clients |
| 788 |
with patch.object(FakeBleakClient, "is_connected", False): |
| 789 |
client._backend = None |
| 790 |
await client.disconnect() |
| 791 |
assert client not in scanner._clients |
| 792 |
assert client._connected_scanner is None |
| 793 |
assert client._connected_device is None |
| 794 |
|
| 795 |
|
| 796 |
@pytest.mark.asyncio |
| 797 |
async def test_disconnect_without_connected_scanner( |
| 798 |
install_bleak_catcher: None, |
| 799 |
) -> None: |
| 800 |
"""Disconnect with a backend but no recorded scanner is a no-op untrack.""" |
| 801 |
client = HaBleakClientWrapper(generate_ble_device("00:00:00:00:00:0F", "x")) |
| 802 |
client._backend = FakeBleakClient(generate_ble_device("00:00:00:00:00:0F", "x")) |
| 803 |
assert client._connected_scanner is None |
| 804 |
await client.disconnect() |
| 805 |
|
| 806 |
|
| 807 |
@pytest.mark.asyncio |
| 808 |
async def test_disconnect_keeps_other_clients_tracked( |
| 809 |
connected_client: ConnectedClient, |
| 810 |
) -> None: |
| 811 |
"""Untracking one client leaves the scanner's other clients tracked.""" |
| 812 |
first, hci0_device_advs, _ = connected_client |
| 813 |
second = bleak.BleakClient(hci0_device_advs["00:00:00:00:00:02"][0]) |
| 814 |
await second.connect() |
| 815 |
scanner = first._connected_scanner |
| 816 |
assert len(scanner._clients) == 2 |
| 817 |
with patch.object(FakeBleakClient, "is_connected", False): |
| 818 |
await first.disconnect() |
| 819 |
assert set(scanner._clients) == {second} |
| 820 |
|
| 821 |
|
| 822 |
@pytest.mark.asyncio |
| 823 |
async def test_test_switch_adapters_when_out_of_slots( |
| 824 |
two_adapters: None, |
| 825 |
enable_bluetooth: None, |
| 826 |
install_bleak_catcher: None, |
| 827 |
mock_platform_client: None, |
| 828 |
) -> None: |
| 829 |
"""Ensure we try another scanner when one runs out of slots.""" |
| 830 |
manager = _get_manager() |
| 831 |
# hci0 has an rssi of -60, hci1 has an rssi of -80 |
| 832 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 833 |
# hci0 has 2 slots, hci1 has 1 slot |
| 834 |
with ( |
| 835 |
patch.object(manager.slot_manager, "release_slot") as release_slot_mock, |
| 836 |
patch.object( |
| 837 |
manager.slot_manager, "allocate_slot", return_value=True |
| 838 |
) as allocate_slot_mock, |
| 839 |
): |
| 840 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 841 |
with patch.object(FakeBleakClient, "is_connected", return_value=True): |
| 842 |
client = bleak.BleakClient(ble_device) |
| 843 |
await client.connect() |
| 844 |
assert allocate_slot_mock.call_count == 1 |
| 845 |
assert release_slot_mock.call_count == 0 |
| 846 |
|
| 847 |
# All adapters are out of slots |
| 848 |
with ( |
| 849 |
patch.object(manager.slot_manager, "release_slot") as release_slot_mock, |
| 850 |
patch.object( |
| 851 |
manager.slot_manager, "allocate_slot", return_value=False |
| 852 |
) as allocate_slot_mock, |
| 853 |
): |
| 854 |
ble_device = hci0_device_advs["00:00:00:00:00:02"][0] |
| 855 |
client = bleak.BleakClient(ble_device) |
| 856 |
with pytest.raises( |
| 857 |
bleak.exc.BleakError, |
| 858 |
match=( |
| 859 |
r"No backend with an available connection slot that can reach " |
| 860 |
r"address .* was found:.*connectable=True" |
| 861 |
), |
| 862 |
): |
| 863 |
await client.connect() |
| 864 |
assert allocate_slot_mock.call_count == 2 |
| 865 |
assert release_slot_mock.call_count == 0 |
| 866 |
|
| 867 |
# When hci0 runs out of slots, we should try hci1 |
| 868 |
def _allocate_slot_mock(ble_device: BLEDevice) -> bool: |
| 869 |
return "hci1" in ble_device.details["path"] |
| 870 |
|
| 871 |
with ( |
| 872 |
patch.object(manager.slot_manager, "release_slot") as release_slot_mock, |
| 873 |
patch.object( # type: ignore[assignment] |
| 874 |
manager.slot_manager, "allocate_slot", _allocate_slot_mock |
| 875 |
) as allocate_slot_mock, |
| 876 |
): |
| 877 |
ble_device = hci0_device_advs["00:00:00:00:00:03"][0] |
| 878 |
with patch.object(FakeBleakClient, "is_connected", return_value=True): |
| 879 |
client = bleak.BleakClient(ble_device) |
| 880 |
await client.connect() |
| 881 |
assert release_slot_mock.call_count == 0 |
| 882 |
|
| 883 |
cancel_hci0() |
| 884 |
cancel_hci1() |
| 885 |
|
| 886 |
|
| 887 |
@pytest.mark.asyncio |
| 888 |
async def test_no_backend_error_survives_diagnostics_failure( |
| 889 |
two_adapters: None, |
| 890 |
enable_bluetooth: None, |
| 891 |
install_bleak_catcher: None, |
| 892 |
mock_platform_client: None, |
| 893 |
) -> None: |
| 894 |
"""A failing diagnostics builder must not mask the no-backend BleakError.""" |
| 895 |
manager = _get_manager() |
| 896 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 897 |
with ( |
| 898 |
patch.object(manager.slot_manager, "allocate_slot", return_value=False), |
| 899 |
patch.object( |
| 900 |
manager, |
| 901 |
"async_address_reachability_diagnostics", |
| 902 |
side_effect=RuntimeError("boom"), |
| 903 |
), |
| 904 |
): |
| 905 |
ble_device = hci0_device_advs["00:00:00:00:00:02"][0] |
| 906 |
client = bleak.BleakClient(ble_device) |
| 907 |
with pytest.raises( |
| 908 |
bleak.exc.BleakError, |
| 909 |
match=( |
| 910 |
r"No backend with an available connection slot that can reach " |
| 911 |
r"address .* was found$" |
| 912 |
), |
| 913 |
): |
| 914 |
await client.connect() |
| 915 |
|
| 916 |
cancel_hci0() |
| 917 |
cancel_hci1() |
| 918 |
|
| 919 |
|
| 920 |
@pytest.mark.asyncio |
| 921 |
async def test_backend_id_property( |
| 922 |
two_adapters: None, |
| 923 |
enable_bluetooth: None, |
| 924 |
install_bleak_catcher: None, |
| 925 |
mock_platform_client: None, |
| 926 |
) -> None: |
| 927 |
"""Ensure BleakClient.backend_id is readable before and after connect.""" |
| 928 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 929 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 930 |
client = bleak.BleakClient(ble_device) |
| 931 |
# Before connect(), backend_id must be readable (regression for #399). |
| 932 |
assert client.backend_id == "" |
| 933 |
with patch.object(FakeBleakClient, "is_connected", return_value=True): |
| 934 |
await client.connect() |
| 935 |
# After connect(), backend_id reflects the selected backend. |
| 936 |
assert client.backend_id |
| 937 |
cancel_hci0() |
| 938 |
cancel_hci1() |
| 939 |
|
| 940 |
|
| 941 |
@pytest.mark.asyncio |
| 942 |
async def test_release_slot_on_connect_failure( |
| 943 |
two_adapters: None, |
| 944 |
enable_bluetooth: None, |
| 945 |
install_bleak_catcher: None, |
| 946 |
mock_platform_client_that_raises_on_connect: None, |
| 947 |
) -> None: |
| 948 |
"""Ensure the slot gets released on connection failure.""" |
| 949 |
manager = _get_manager() |
| 950 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 951 |
# hci0 has 2 slots, hci1 has 1 slot |
| 952 |
with ( |
| 953 |
patch.object(manager.slot_manager, "release_slot") as release_slot_mock, |
| 954 |
patch.object( |
| 955 |
manager.slot_manager, "allocate_slot", return_value=True |
| 956 |
) as allocate_slot_mock, |
| 957 |
): |
| 958 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 959 |
client = bleak.BleakClient(ble_device) |
| 960 |
with pytest.raises(ConnectionError): |
| 961 |
await client.connect() |
| 962 |
assert allocate_slot_mock.call_count == 1 |
| 963 |
assert release_slot_mock.call_count == 1 |
| 964 |
|
| 965 |
cancel_hci0() |
| 966 |
cancel_hci1() |
| 967 |
|
| 968 |
|
| 969 |
@pytest.mark.asyncio |
| 970 |
async def test_release_slot_on_connect_exception( |
| 971 |
two_adapters: None, |
| 972 |
enable_bluetooth: None, |
| 973 |
install_bleak_catcher: None, |
| 974 |
mock_platform_client_that_raises_on_connect: None, |
| 975 |
) -> None: |
| 976 |
"""Ensure the slot gets released on connection exception.""" |
| 977 |
manager = _get_manager() |
| 978 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 979 |
# hci0 has 2 slots, hci1 has 1 slot |
| 980 |
with ( |
| 981 |
patch.object(manager.slot_manager, "release_slot") as release_slot_mock, |
| 982 |
patch.object( |
| 983 |
manager.slot_manager, "allocate_slot", return_value=True |
| 984 |
) as allocate_slot_mock, |
| 985 |
): |
| 986 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 987 |
client = bleak.BleakClient(ble_device) |
| 988 |
with pytest.raises(ConnectionError) as exc_info: |
| 989 |
await client.connect() |
| 990 |
assert str(exc_info.value) == "Test exception" |
| 991 |
assert allocate_slot_mock.call_count == 1 |
| 992 |
assert release_slot_mock.call_count == 1 |
| 993 |
|
| 994 |
cancel_hci0() |
| 995 |
cancel_hci1() |
| 996 |
|
| 997 |
|
| 998 |
@pytest.mark.asyncio |
| 999 |
async def test_release_slot_and_clear_backend_on_cancelled( |
| 1000 |
two_adapters: None, |
| 1001 |
enable_bluetooth: None, |
| 1002 |
install_bleak_catcher: None, |
| 1003 |
mock_platform_client_that_cancels_on_connect: None, |
| 1004 |
) -> None: |
| 1005 |
"""Ensure CancelledError still releases the slot and clears _backend.""" |
| 1006 |
manager = _get_manager() |
| 1007 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 1008 |
with ( |
| 1009 |
patch.object(manager.slot_manager, "release_slot") as release_slot_mock, |
| 1010 |
patch.object( |
| 1011 |
manager.slot_manager, "allocate_slot", return_value=True |
| 1012 |
) as allocate_slot_mock, |
| 1013 |
): |
| 1014 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 1015 |
client = bleak.BleakClient(ble_device) |
| 1016 |
with pytest.raises(asyncio.CancelledError): |
| 1017 |
await client.connect() |
| 1018 |
assert allocate_slot_mock.call_count == 1 |
| 1019 |
assert release_slot_mock.call_count == 1 |
| 1020 |
# Regression: CancelledError used to leave _backend set because the |
| 1021 |
# cleanup ran in `except Exception` rather than `finally`. |
| 1022 |
assert client._backend is None |
| 1023 |
|
| 1024 |
cancel_hci0() |
| 1025 |
cancel_hci1() |
| 1026 |
|
| 1027 |
|
| 1028 |
@pytest.mark.asyncio |
| 1029 |
async def test_remote_scanner_connect_failure_skips_local_slot_release( |
| 1030 |
enable_bluetooth: None, |
| 1031 |
install_bleak_catcher: None, |
| 1032 |
) -> None: |
| 1033 |
""" |
| 1034 |
Ensure remote-scanner connect failure clears _backend without slot release. |
| 1035 |
|
| 1036 |
Covers the not-taken branch of ``if not wrapped_backend.source:`` in |
| 1037 |
``HaBleakClientWrapper.connect()``. When the chosen backend belongs to a |
| 1038 |
remote (proxy) scanner, ``wrapped_backend.source`` is truthy and |
| 1039 |
``manager.async_release_connection_slot`` must not run — slot accounting |
| 1040 |
for proxies is owned by the firmware and reported via |
| 1041 |
``async_on_allocation_changed``. |
| 1042 |
""" |
| 1043 |
manager = _get_manager() |
| 1044 |
|
| 1045 |
fake_connector = HaBluetoothConnector( |
| 1046 |
client=FakeBleakClientRaisesOnConnect, |
| 1047 |
source="remote_scanner", |
| 1048 |
can_connect=lambda: True, |
| 1049 |
) |
| 1050 |
remote_scanner = FakeScanner( |
| 1051 |
"remote_scanner", "ESPHome Device", fake_connector, True |
| 1052 |
) |
| 1053 |
cancel_remote = manager.async_register_scanner(remote_scanner) |
| 1054 |
|
| 1055 |
device = generate_ble_device( |
| 1056 |
"AA:BB:CC:DD:EE:FF", "Test Device", {"source": "remote_scanner"} |
| 1057 |
) |
| 1058 |
adv_data = generate_advertisement_data(local_name="Test Device", rssi=-50) |
| 1059 |
remote_scanner.inject_advertisement(device, adv_data) |
| 1060 |
await asyncio.sleep(0) |
| 1061 |
|
| 1062 |
with ( |
| 1063 |
patch.object(manager.slot_manager, "release_slot") as release_slot_mock, |
| 1064 |
patch.object( |
| 1065 |
manager.slot_manager, "allocate_slot", return_value=True |
| 1066 |
) as allocate_slot_mock, |
| 1067 |
): |
| 1068 |
client = bleak.BleakClient("AA:BB:CC:DD:EE:FF") |
| 1069 |
with pytest.raises(ConnectionError): |
| 1070 |
await client.connect() |
| 1071 |
# Local-adapter slot manager must not be touched on the remote path. |
| 1072 |
assert allocate_slot_mock.call_count == 0 |
| 1073 |
assert release_slot_mock.call_count == 0 |
| 1074 |
# Backend is cleared on every failure path. |
| 1075 |
assert client._backend is None |
| 1076 |
# _finished_connecting still runs, so the in-progress counter is empty. |
| 1077 |
assert remote_scanner._connect_in_progress == {} |
| 1078 |
|
| 1079 |
cancel_remote() |
| 1080 |
|
| 1081 |
|
| 1082 |
@pytest.mark.asyncio |
| 1083 |
async def test_switch_adapters_on_failure( |
| 1084 |
two_adapters: None, |
| 1085 |
enable_bluetooth: None, |
| 1086 |
install_bleak_catcher: None, |
| 1087 |
) -> None: |
| 1088 |
"""Ensure we try the next best adapter after a failure.""" |
| 1089 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 1090 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 1091 |
client = bleak.BleakClient(ble_device) |
| 1092 |
|
| 1093 |
class FakeBleakClientFailsHCI0Only(BaseFakeBleakClient): |
| 1094 |
"""Fake bleak client that fails to connect on hci0.""" |
| 1095 |
|
| 1096 |
async def connect(self, *args: Any, **kwargs: Any) -> None: |
| 1097 |
"""Connect.""" |
| 1098 |
assert isinstance(self._device, BLEDevice) |
| 1099 |
if "/hci0/" in self._device.details["path"]: |
| 1100 |
msg = "Failed to connect on hci0" |
| 1101 |
raise BleakError(msg) |
| 1102 |
|
| 1103 |
@property |
| 1104 |
def is_connected(self) -> bool: |
| 1105 |
return True |
| 1106 |
|
| 1107 |
class FakeBleakClientFailsHCI1Only(BaseFakeBleakClient): |
| 1108 |
"""Fake bleak client that fails to connect on hci1.""" |
| 1109 |
|
| 1110 |
async def connect(self, *args: Any, **kwargs: Any) -> None: |
| 1111 |
"""Connect.""" |
| 1112 |
assert isinstance(self._device, BLEDevice) |
| 1113 |
if "/hci1/" in self._device.details["path"]: |
| 1114 |
msg = "Failed to connect on hci1" |
| 1115 |
raise BleakError(msg) |
| 1116 |
|
| 1117 |
@property |
| 1118 |
def is_connected(self) -> bool: |
| 1119 |
return True |
| 1120 |
|
| 1121 |
with patch( |
| 1122 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 1123 |
return_value=FakeBleakClientFailsHCI0Only, |
| 1124 |
): |
| 1125 |
# Should try to connect to hci0 first |
| 1126 |
with pytest.raises(BleakError): |
| 1127 |
await client.connect() |
| 1128 |
assert not client.is_connected |
| 1129 |
# Should try to connect with hci0 again |
| 1130 |
with pytest.raises(BleakError): |
| 1131 |
await client.connect() |
| 1132 |
assert not client.is_connected |
| 1133 |
|
| 1134 |
# After two tries we should switch to hci1 |
| 1135 |
await client.connect() |
| 1136 |
assert client.is_connected |
| 1137 |
|
| 1138 |
# ..and we remember that hci1 works as long as the client doesn't change |
| 1139 |
await client.connect() |
| 1140 |
assert client.is_connected |
| 1141 |
|
| 1142 |
# If we replace the client, we should remember hci0 is failing |
| 1143 |
client = bleak.BleakClient(ble_device) |
| 1144 |
|
| 1145 |
await client.connect() |
| 1146 |
assert client.is_connected |
| 1147 |
|
| 1148 |
with patch( |
| 1149 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 1150 |
return_value=FakeBleakClientFailsHCI1Only, |
| 1151 |
): |
| 1152 |
# Should try to connect to hci1 first |
| 1153 |
await client.connect() |
| 1154 |
assert client.is_connected |
| 1155 |
# Should work with hci0 on next attempt |
| 1156 |
await client.connect() |
| 1157 |
assert client.is_connected |
| 1158 |
# Next attempt should also use hci0 |
| 1159 |
await client.connect() |
| 1160 |
assert client.is_connected |
| 1161 |
|
| 1162 |
cancel_hci0() |
| 1163 |
cancel_hci1() |
| 1164 |
|
| 1165 |
|
| 1166 |
@pytest.mark.asyncio |
| 1167 |
async def test_switch_adapters_on_connecting( |
| 1168 |
two_adapters: None, |
| 1169 |
enable_bluetooth: None, |
| 1170 |
install_bleak_catcher: None, |
| 1171 |
) -> None: |
| 1172 |
"""Ensure we try the next best adapter after a failure.""" |
| 1173 |
# hci0 has an rssi of -60, hci1 has an rssi of -80 |
| 1174 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 1175 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 1176 |
client = bleak.BleakClient(ble_device) |
| 1177 |
|
| 1178 |
class FakeBleakClientSlowHCI0Connnect(BaseFakeBleakClient): |
| 1179 |
"""Fake bleak client that connects instantly on hci1 and slow on hci0.""" |
| 1180 |
|
| 1181 |
valid = False |
| 1182 |
|
| 1183 |
async def connect(self, *args: Any, **kwargs: Any) -> None: |
| 1184 |
"""Connect.""" |
| 1185 |
assert isinstance(self._device, BLEDevice) |
| 1186 |
if "/hci0/" in self._device.details["path"]: |
| 1187 |
await asyncio.sleep(0.4) |
| 1188 |
self.valid = True |
| 1189 |
else: |
| 1190 |
self.valid = True |
| 1191 |
|
| 1192 |
@property |
| 1193 |
def is_connected(self) -> bool: |
| 1194 |
return self.valid |
| 1195 |
|
| 1196 |
with patch( |
| 1197 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 1198 |
return_value=FakeBleakClientSlowHCI0Connnect, |
| 1199 |
): |
| 1200 |
task = asyncio.create_task(client.connect()) |
| 1201 |
await asyncio.sleep(0.1) |
| 1202 |
assert not task.done() |
| 1203 |
|
| 1204 |
task2 = asyncio.create_task(client.connect()) |
| 1205 |
await asyncio.sleep(0.1) |
| 1206 |
assert task2.done() |
| 1207 |
await task2 |
| 1208 |
assert client.is_connected |
| 1209 |
|
| 1210 |
task3 = asyncio.create_task(client.connect()) |
| 1211 |
await asyncio.sleep(0.1) |
| 1212 |
assert task3.done() |
| 1213 |
await task3 |
| 1214 |
assert client.is_connected |
| 1215 |
|
| 1216 |
await task |
| 1217 |
assert client.is_connected |
| 1218 |
|
| 1219 |
cancel_hci0() |
| 1220 |
cancel_hci1() |
| 1221 |
|
| 1222 |
|
| 1223 |
@pytest.mark.asyncio |
| 1224 |
@pytest.mark.usefixtures("enable_bluetooth", "install_bleak_catcher") |
| 1225 |
async def test_single_adapter_connection_history( |
| 1226 |
caplog: pytest.LogCaptureFixture, |
| 1227 |
) -> None: |
| 1228 |
"""Test connection history failure count.""" |
| 1229 |
manager = _get_manager() |
| 1230 |
scanner_hci0 = FakeScanner(HCI0_SOURCE_ADDRESS, "hci0", None, True) |
| 1231 |
unsub_hci0 = manager.async_register_scanner(scanner_hci0, connection_slots=2) |
| 1232 |
ble_device, adv_data = _generate_ble_device_and_adv_data( |
| 1233 |
"hci0", "00:00:00:00:00:11", rssi=-60 |
| 1234 |
) |
| 1235 |
scanner_hci0.inject_advertisement(ble_device, adv_data) |
| 1236 |
service_info = manager.async_last_service_info( |
| 1237 |
ble_device.address, connectable=False |
| 1238 |
) |
| 1239 |
assert service_info is not None |
| 1240 |
assert service_info.source == HCI0_SOURCE_ADDRESS |
| 1241 |
|
| 1242 |
client = bleak.BleakClient(ble_device) |
| 1243 |
|
| 1244 |
class FakeBleakClientFastConnect(BaseFakeBleakClient): |
| 1245 |
"""Fake bleak client that connects instantly on hci1 and slow on hci0.""" |
| 1246 |
|
| 1247 |
valid = False |
| 1248 |
|
| 1249 |
async def connect(self, *args: Any, **kwargs: Any) -> None: |
| 1250 |
"""Connect.""" |
| 1251 |
assert isinstance(self._device, BLEDevice) |
| 1252 |
self.valid = "/hci0/" in self._device.details["path"] |
| 1253 |
|
| 1254 |
@property |
| 1255 |
def is_connected(self) -> bool: |
| 1256 |
return self.valid |
| 1257 |
|
| 1258 |
with patch( |
| 1259 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 1260 |
return_value=FakeBleakClientFastConnect, |
| 1261 |
): |
| 1262 |
await client.connect() |
| 1263 |
unsub_hci0() |
| 1264 |
|
| 1265 |
|
| 1266 |
@pytest.mark.asyncio |
| 1267 |
async def test_passing_subclassed_str_as_address( |
| 1268 |
two_adapters: None, |
| 1269 |
enable_bluetooth: None, |
| 1270 |
install_bleak_catcher: None, |
| 1271 |
) -> None: |
| 1272 |
"""Ensure the client wrapper can handle a subclassed str as the address.""" |
| 1273 |
_, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 1274 |
|
| 1275 |
class SubclassedStr(str): |
| 1276 |
__slots__ = () |
| 1277 |
|
| 1278 |
address = SubclassedStr("00:00:00:00:00:01") |
| 1279 |
client = bleak.BleakClient(address) |
| 1280 |
|
| 1281 |
class FakeBleakClient(BaseFakeBleakClient): |
| 1282 |
"""Fake bleak client.""" |
| 1283 |
|
| 1284 |
async def connect(self, *args, **kwargs): |
| 1285 |
"""Connect.""" |
| 1286 |
return |
| 1287 |
|
| 1288 |
@property |
| 1289 |
def is_connected(self) -> bool: |
| 1290 |
return True |
| 1291 |
|
| 1292 |
with patch( |
| 1293 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 1294 |
return_value=FakeBleakClient, |
| 1295 |
): |
| 1296 |
await client.connect() |
| 1297 |
|
| 1298 |
cancel_hci0() |
| 1299 |
cancel_hci1() |
| 1300 |
|
| 1301 |
|
| 1302 |
@pytest.mark.asyncio |
| 1303 |
async def test_find_device_by_address( |
| 1304 |
two_adapters: None, |
| 1305 |
enable_bluetooth: None, |
| 1306 |
install_bleak_catcher: None, |
| 1307 |
) -> None: |
| 1308 |
"""Ensure the client wrapper can handle a subclassed str as the address.""" |
| 1309 |
_, _cancel_hci0, _cancel_hci1 = _generate_scanners_with_fake_devices() |
| 1310 |
device = await bleak.BleakScanner.find_device_by_address("00:00:00:00:00:01") |
| 1311 |
assert device.address == "00:00:00:00:00:01" |
| 1312 |
device = await bleak.BleakScanner().find_device_by_address("00:00:00:00:00:01") |
| 1313 |
assert device.address == "00:00:00:00:00:01" |
| 1314 |
|
| 1315 |
|
| 1316 |
@pytest.mark.asyncio |
| 1317 |
async def test_find_device_by_filter( |
| 1318 |
two_adapters: None, |
| 1319 |
enable_bluetooth: None, |
| 1320 |
install_bleak_catcher: None, |
| 1321 |
) -> None: |
| 1322 |
"""Ensure find_device_by_filter finds a device matching the filter.""" |
| 1323 |
_, _cancel_hci0, _cancel_hci1 = _generate_scanners_with_fake_devices() |
| 1324 |
device = await bleak.BleakScanner.find_device_by_filter( |
| 1325 |
lambda d, ad: d.address == "00:00:00:00:00:01" |
| 1326 |
) |
| 1327 |
assert device is not None |
| 1328 |
assert device.address == "00:00:00:00:00:01" |
| 1329 |
|
| 1330 |
|
| 1331 |
@pytest.mark.asyncio |
| 1332 |
async def test_find_device_by_filter_no_match( |
| 1333 |
two_adapters: None, |
| 1334 |
enable_bluetooth: None, |
| 1335 |
install_bleak_catcher: None, |
| 1336 |
) -> None: |
| 1337 |
"""Ensure find_device_by_filter returns None when no device matches.""" |
| 1338 |
_, _cancel_hci0, _cancel_hci1 = _generate_scanners_with_fake_devices() |
| 1339 |
device = await bleak.BleakScanner.find_device_by_filter( |
| 1340 |
lambda d, ad: d.address == "DE:AD:BE:EF:00:00" |
| 1341 |
) |
| 1342 |
assert device is None |
| 1343 |
|
| 1344 |
|
| 1345 |
@pytest.mark.asyncio |
| 1346 |
async def test_find_device_by_name( |
| 1347 |
two_adapters: None, |
| 1348 |
enable_bluetooth: None, |
| 1349 |
install_bleak_catcher: None, |
| 1350 |
) -> None: |
| 1351 |
"""Ensure find_device_by_name finds a device matching the name.""" |
| 1352 |
_, _cancel_hci0, _cancel_hci1 = _generate_scanners_with_fake_devices() |
| 1353 |
device = await bleak.BleakScanner.find_device_by_name("any") |
| 1354 |
assert device is not None |
| 1355 |
|
| 1356 |
|
| 1357 |
@pytest.mark.asyncio |
| 1358 |
async def test_find_device_by_name_no_match( |
| 1359 |
two_adapters: None, |
| 1360 |
enable_bluetooth: None, |
| 1361 |
install_bleak_catcher: None, |
| 1362 |
) -> None: |
| 1363 |
"""Ensure find_device_by_name returns None when no device matches.""" |
| 1364 |
_, _cancel_hci0, _cancel_hci1 = _generate_scanners_with_fake_devices() |
| 1365 |
device = await bleak.BleakScanner.find_device_by_name("nonexistent") |
| 1366 |
assert device is None |
| 1367 |
|
| 1368 |
|
| 1369 |
@pytest.mark.asyncio |
| 1370 |
async def test_async_context_manager( |
| 1371 |
two_adapters: None, |
| 1372 |
enable_bluetooth: None, |
| 1373 |
install_bleak_catcher: None, |
| 1374 |
) -> None: |
| 1375 |
"""Ensure HaBleakScannerWrapper supports async context manager protocol.""" |
| 1376 |
_, _cancel_hci0, _cancel_hci1 = _generate_scanners_with_fake_devices() |
| 1377 |
async with bleak.BleakScanner() as scanner: |
| 1378 |
assert scanner.discovered_devices |
| 1379 |
|
| 1380 |
|
| 1381 |
@pytest.mark.asyncio |
| 1382 |
async def test_discovered_devices_and_advertisement_data( |
| 1383 |
two_adapters: None, |
| 1384 |
enable_bluetooth: None, |
| 1385 |
install_bleak_catcher: None, |
| 1386 |
) -> None: |
| 1387 |
"""Ensure discovered_devices_and_advertisement_data works.""" |
| 1388 |
_, _cancel_hci0, _cancel_hci1 = _generate_scanners_with_fake_devices() |
| 1389 |
scanner = bleak.BleakScanner() |
| 1390 |
result = scanner.discovered_devices_and_advertisement_data |
| 1391 |
assert "00:00:00:00:00:01" in result |
| 1392 |
device, adv_data = result["00:00:00:00:00:01"] |
| 1393 |
assert device.address == "00:00:00:00:00:01" |
| 1394 |
assert adv_data is not None |
| 1395 |
|
| 1396 |
|
| 1397 |
@pytest.mark.asyncio |
| 1398 |
async def test_advertisement_data_iterator( |
| 1399 |
two_adapters: None, |
| 1400 |
enable_bluetooth: None, |
| 1401 |
install_bleak_catcher: None, |
| 1402 |
) -> None: |
| 1403 |
"""Ensure advertisement_data async iterator yields devices.""" |
| 1404 |
_, _cancel_hci0, _cancel_hci1 = _generate_scanners_with_fake_devices() |
| 1405 |
scanner = bleak.BleakScanner() |
| 1406 |
devices_found: dict[str, tuple[BLEDevice, AdvertisementData]] = {} |
| 1407 |
async for device, adv_data in scanner.advertisement_data(): |
| 1408 |
devices_found[device.address] = (device, adv_data) |
| 1409 |
if "00:00:00:00:00:01" in devices_found: |
| 1410 |
break |
| 1411 |
assert "00:00:00:00:00:01" in devices_found |
| 1412 |
assert devices_found["00:00:00:00:00:01"][1] is not None |
| 1413 |
|
| 1414 |
|
| 1415 |
@pytest.mark.asyncio |
| 1416 |
async def test_discover( |
| 1417 |
two_adapters: None, |
| 1418 |
enable_bluetooth: None, |
| 1419 |
install_bleak_catcher: None, |
| 1420 |
) -> None: |
| 1421 |
"""Ensure the discover is implemented.""" |
| 1422 |
_, _cancel_hci0, _cancel_hci1 = _generate_scanners_with_fake_devices() |
| 1423 |
devices = await bleak.BleakScanner.discover() |
| 1424 |
assert any(device.address == "00:00:00:00:00:01" for device in devices) |
| 1425 |
devices_adv = await bleak.BleakScanner.discover(return_adv=True) |
| 1426 |
assert "00:00:00:00:00:01" in devices_adv |
| 1427 |
|
| 1428 |
|
| 1429 |
@pytest.mark.asyncio |
| 1430 |
async def test_raise_after_shutdown( |
| 1431 |
two_adapters: None, |
| 1432 |
enable_bluetooth: None, |
| 1433 |
install_bleak_catcher: None, |
| 1434 |
mock_platform_client_that_raises_on_connect: None, |
| 1435 |
) -> None: |
| 1436 |
"""Ensure the slot gets released on connection exception.""" |
| 1437 |
manager = _get_manager() |
| 1438 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 1439 |
# hci0 has 2 slots, hci1 has 1 slot |
| 1440 |
with mock_shutdown(manager): |
| 1441 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 1442 |
client = bleak.BleakClient(ble_device) |
| 1443 |
with pytest.raises(BleakError, match="shutdown"): |
| 1444 |
await client.connect() |
| 1445 |
cancel_hci0() |
| 1446 |
cancel_hci1() |
| 1447 |
|
| 1448 |
|
| 1449 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 1450 |
@pytest.mark.asyncio |
| 1451 |
async def test_wrapped_instance_with_filter( |
| 1452 |
register_hci0_scanner: None, |
| 1453 |
) -> None: |
| 1454 |
"""Test wrapped instance with a filter as if it was normal BleakScanner.""" |
| 1455 |
detected, _device_detected = _make_detection_recorder() |
| 1456 |
|
| 1457 |
switchbot_device = generate_ble_device("44:44:33:11:23:45", "wohand") |
| 1458 |
switchbot_adv = generate_advertisement_data( |
| 1459 |
local_name="wohand", |
| 1460 |
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1461 |
manufacturer_data={89: b"\xd8.\xad\xcd\r\x85"}, |
| 1462 |
service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"}, |
| 1463 |
) |
| 1464 |
switchbot_adv_2 = generate_advertisement_data( |
| 1465 |
local_name="wohand", |
| 1466 |
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1467 |
manufacturer_data={89: b"\xd8.\xad\xcd\r\x84"}, |
| 1468 |
service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"}, |
| 1469 |
) |
| 1470 |
empty_device = generate_ble_device("11:22:33:44:55:66", "empty") |
| 1471 |
empty_adv = generate_advertisement_data(local_name="empty") |
| 1472 |
|
| 1473 |
assert _get_manager() is not None |
| 1474 |
scanner = HaBleakScannerWrapper( |
| 1475 |
detection_callback=_device_detected, |
| 1476 |
filters={"UUIDs": ["cba20d00-224d-11e6-9fb8-0002a5d5c51b"]}, |
| 1477 |
) |
| 1478 |
await scanner.start() |
| 1479 |
|
| 1480 |
inject_advertisement(switchbot_device, switchbot_adv_2) |
| 1481 |
await asyncio.sleep(0) |
| 1482 |
|
| 1483 |
discovered = await scanner.discover(timeout=0) |
| 1484 |
assert len(discovered) == 1 |
| 1485 |
assert discovered == [switchbot_device] |
| 1486 |
assert len(detected) == 1 |
| 1487 |
|
| 1488 |
with patch_discovered_devices([]): |
| 1489 |
discovered = await scanner.discover(timeout=0) |
| 1490 |
assert len(discovered) == 0 |
| 1491 |
assert discovered == [] |
| 1492 |
|
| 1493 |
inject_advertisement(switchbot_device, switchbot_adv) |
| 1494 |
assert len(detected) == 2 |
| 1495 |
|
| 1496 |
# The filter we created in the wrapped scanner with should be respected |
| 1497 |
# and we should not get another callback |
| 1498 |
inject_advertisement(empty_device, empty_adv) |
| 1499 |
assert len(detected) == 2 |
| 1500 |
|
| 1501 |
|
| 1502 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 1503 |
@pytest.mark.asyncio |
| 1504 |
async def test_register_detection_callback_deprecated( |
| 1505 |
register_hci0_scanner: None, |
| 1506 |
) -> None: |
| 1507 |
"""Test the deprecated register_detection_callback still works and warns.""" |
| 1508 |
detected, _device_detected = _make_detection_recorder() |
| 1509 |
|
| 1510 |
switchbot_device = generate_ble_device("44:44:33:11:23:45", "wohand") |
| 1511 |
switchbot_adv = generate_advertisement_data( |
| 1512 |
local_name="wohand", |
| 1513 |
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1514 |
manufacturer_data={89: b"\xd8.\xad\xcd\r\x85"}, |
| 1515 |
service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"}, |
| 1516 |
) |
| 1517 |
|
| 1518 |
assert _get_manager() is not None |
| 1519 |
scanner = HaBleakScannerWrapper( |
| 1520 |
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1521 |
) |
| 1522 |
|
| 1523 |
with pytest.warns(DeprecationWarning, match="register_detection_callback"): |
| 1524 |
cancel = scanner.register_detection_callback(_device_detected) |
| 1525 |
|
| 1526 |
inject_advertisement(switchbot_device, switchbot_adv) |
| 1527 |
await asyncio.sleep(0) |
| 1528 |
assert len(detected) == 1 |
| 1529 |
|
| 1530 |
cancel() |
| 1531 |
inject_advertisement(switchbot_device, switchbot_adv) |
| 1532 |
await asyncio.sleep(0) |
| 1533 |
assert len(detected) == 1 |
| 1534 |
|
| 1535 |
|
| 1536 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 1537 |
@pytest.mark.asyncio |
| 1538 |
async def test_wrapped_instance_with_service_uuids( |
| 1539 |
register_hci0_scanner: None, |
| 1540 |
) -> None: |
| 1541 |
"""Test wrapped instance with a service_uuids list as normal BleakScanner.""" |
| 1542 |
detected, _device_detected = _make_detection_recorder() |
| 1543 |
|
| 1544 |
switchbot_device = generate_ble_device("44:44:33:11:23:45", "wohand") |
| 1545 |
switchbot_adv = generate_advertisement_data( |
| 1546 |
local_name="wohand", |
| 1547 |
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1548 |
manufacturer_data={89: b"\xd8.\xad\xcd\r\x85"}, |
| 1549 |
service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"}, |
| 1550 |
) |
| 1551 |
switchbot_adv_2 = generate_advertisement_data( |
| 1552 |
local_name="wohand", |
| 1553 |
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1554 |
manufacturer_data={89: b"\xd8.\xad\xcd\r\x84"}, |
| 1555 |
service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"}, |
| 1556 |
) |
| 1557 |
empty_device = generate_ble_device("11:22:33:44:55:66", "empty") |
| 1558 |
empty_adv = generate_advertisement_data(local_name="empty") |
| 1559 |
|
| 1560 |
assert _get_manager() is not None |
| 1561 |
_scanner = HaBleakScannerWrapper( |
| 1562 |
detection_callback=_device_detected, |
| 1563 |
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1564 |
) |
| 1565 |
await _scanner.start() |
| 1566 |
|
| 1567 |
inject_advertisement(switchbot_device, switchbot_adv) |
| 1568 |
inject_advertisement(switchbot_device, switchbot_adv_2) |
| 1569 |
|
| 1570 |
await asyncio.sleep(0) |
| 1571 |
|
| 1572 |
assert len(detected) == 2 |
| 1573 |
|
| 1574 |
# The UUIDs list we created in the wrapped scanner with should be respected |
| 1575 |
# and we should not get another callback |
| 1576 |
inject_advertisement(empty_device, empty_adv) |
| 1577 |
assert len(detected) == 2 |
| 1578 |
|
| 1579 |
|
| 1580 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 1581 |
@pytest.mark.asyncio |
| 1582 |
async def test_callback_not_registered_until_start( |
| 1583 |
register_hci0_scanner: None, |
| 1584 |
) -> None: |
| 1585 |
"""Detections are only delivered between start() and stop().""" |
| 1586 |
detected, _device_detected = _make_detection_recorder() |
| 1587 |
|
| 1588 |
switchbot_device = generate_ble_device("44:44:33:11:23:45", "wohand") |
| 1589 |
switchbot_adv = generate_advertisement_data( |
| 1590 |
local_name="wohand", |
| 1591 |
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1592 |
manufacturer_data={89: b"\xd8.\xad\xcd\r\x85"}, |
| 1593 |
service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"}, |
| 1594 |
) |
| 1595 |
|
| 1596 |
assert _get_manager() is not None |
| 1597 |
scanner = HaBleakScannerWrapper( |
| 1598 |
detection_callback=_device_detected, |
| 1599 |
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1600 |
) |
| 1601 |
|
| 1602 |
# Before start() no callbacks should fire even though a callback was |
| 1603 |
# provided to the constructor. |
| 1604 |
inject_advertisement(switchbot_device, switchbot_adv) |
| 1605 |
await asyncio.sleep(0) |
| 1606 |
assert len(detected) == 0 |
| 1607 |
|
| 1608 |
# After start() detections are delivered. |
| 1609 |
await scanner.start() |
| 1610 |
inject_advertisement(switchbot_device, switchbot_adv) |
| 1611 |
await asyncio.sleep(0) |
| 1612 |
assert len(detected) == 1 |
| 1613 |
|
| 1614 |
# After stop() the callback is deregistered and no longer fires. |
| 1615 |
await scanner.stop() |
| 1616 |
inject_advertisement(switchbot_device, switchbot_adv) |
| 1617 |
await asyncio.sleep(0) |
| 1618 |
assert len(detected) == 1 |
| 1619 |
|
| 1620 |
# start() again re-registers the callback. |
| 1621 |
await scanner.start() |
| 1622 |
inject_advertisement(switchbot_device, switchbot_adv) |
| 1623 |
await asyncio.sleep(0) |
| 1624 |
assert len(detected) == 2 |
| 1625 |
|
| 1626 |
|
| 1627 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 1628 |
@pytest.mark.asyncio |
| 1629 |
async def test_set_scanning_filter_reregisters_when_started( |
| 1630 |
register_hci0_scanner: None, |
| 1631 |
) -> None: |
| 1632 |
"""set_scanning_filter re-registers and applies the new filter when started.""" |
| 1633 |
detected, _device_detected = _make_detection_recorder() |
| 1634 |
|
| 1635 |
switchbot_device = generate_ble_device("44:44:33:11:23:45", "wohand") |
| 1636 |
switchbot_adv = generate_advertisement_data( |
| 1637 |
local_name="wohand", |
| 1638 |
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1639 |
manufacturer_data={89: b"\xd8.\xad\xcd\r\x85"}, |
| 1640 |
service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"}, |
| 1641 |
) |
| 1642 |
empty_device = generate_ble_device("11:22:33:44:55:66", "empty") |
| 1643 |
empty_adv = generate_advertisement_data(local_name="empty") |
| 1644 |
|
| 1645 |
assert _get_manager() is not None |
| 1646 |
# No initial filter, so the started scanner matches everything. |
| 1647 |
scanner = HaBleakScannerWrapper(detection_callback=_device_detected) |
| 1648 |
await scanner.start() |
| 1649 |
|
| 1650 |
inject_advertisement(switchbot_device, switchbot_adv) |
| 1651 |
inject_advertisement(empty_device, empty_adv) |
| 1652 |
await asyncio.sleep(0) |
| 1653 |
assert len(detected) == 2 |
| 1654 |
|
| 1655 |
# An effective filter change while started re-registers the callback with |
| 1656 |
# the new filter, so only matching advertisements are delivered afterwards. |
| 1657 |
scanner.set_scanning_filter(service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"]) |
| 1658 |
inject_advertisement(switchbot_device, switchbot_adv) |
| 1659 |
inject_advertisement(empty_device, empty_adv) |
| 1660 |
await asyncio.sleep(0) |
| 1661 |
assert len(detected) == 3 |
| 1662 |
|
| 1663 |
|
| 1664 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 1665 |
@pytest.mark.asyncio |
| 1666 |
async def test_start_without_detection_callback( |
| 1667 |
register_hci0_scanner: None, |
| 1668 |
) -> None: |
| 1669 |
"""start() is a no-op when no detection callback was provided.""" |
| 1670 |
switchbot_device = generate_ble_device("44:44:33:11:23:45", "wohand") |
| 1671 |
switchbot_adv = generate_advertisement_data(local_name="wohand") |
| 1672 |
|
| 1673 |
assert _get_manager() is not None |
| 1674 |
scanner = HaBleakScannerWrapper() |
| 1675 |
|
| 1676 |
# start() reaches the detection-callback setup path but no callback was |
| 1677 |
# registered, so it short-circuits without raising and nothing is delivered. |
| 1678 |
await scanner.start() |
| 1679 |
inject_advertisement(switchbot_device, switchbot_adv) |
| 1680 |
await asyncio.sleep(0) |
| 1681 |
await scanner.stop() |
| 1682 |
|
| 1683 |
|
| 1684 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 1685 |
@pytest.mark.asyncio |
| 1686 |
async def test_wrapped_instance_with_service_uuids_with_coro_callback( |
| 1687 |
register_hci0_scanner: None, |
| 1688 |
) -> None: |
| 1689 |
""" |
| 1690 |
Test wrapped instance with a service_uuids list as normal BleakScanner. |
| 1691 |
|
| 1692 |
Verify that coro callbacks are supported. |
| 1693 |
""" |
| 1694 |
detected, _device_detected = _make_async_detection_recorder() |
| 1695 |
|
| 1696 |
switchbot_device = generate_ble_device("44:44:33:11:23:45", "wohand") |
| 1697 |
switchbot_adv = generate_advertisement_data( |
| 1698 |
local_name="wohand", |
| 1699 |
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1700 |
manufacturer_data={89: b"\xd8.\xad\xcd\r\x85"}, |
| 1701 |
service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"}, |
| 1702 |
) |
| 1703 |
switchbot_adv_2 = generate_advertisement_data( |
| 1704 |
local_name="wohand", |
| 1705 |
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1706 |
manufacturer_data={89: b"\xd8.\xad\xcd\r\x84"}, |
| 1707 |
service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"}, |
| 1708 |
) |
| 1709 |
empty_device = generate_ble_device("11:22:33:44:55:66", "empty") |
| 1710 |
empty_adv = generate_advertisement_data(local_name="empty") |
| 1711 |
|
| 1712 |
assert _get_manager() is not None |
| 1713 |
_scanner = HaBleakScannerWrapper( |
| 1714 |
detection_callback=_device_detected, |
| 1715 |
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1716 |
) |
| 1717 |
await _scanner.start() |
| 1718 |
|
| 1719 |
inject_advertisement(switchbot_device, switchbot_adv) |
| 1720 |
inject_advertisement(switchbot_device, switchbot_adv_2) |
| 1721 |
|
| 1722 |
await asyncio.sleep(0) |
| 1723 |
|
| 1724 |
assert len(detected) == 2 |
| 1725 |
|
| 1726 |
# The UUIDs list we created in the wrapped scanner with should be respected |
| 1727 |
# and we should not get another callback |
| 1728 |
inject_advertisement(empty_device, empty_adv) |
| 1729 |
assert len(detected) == 2 |
| 1730 |
|
| 1731 |
|
| 1732 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 1733 |
@pytest.mark.asyncio |
| 1734 |
async def test_wrapped_instance_with_broken_callbacks( |
| 1735 |
register_hci0_scanner: None, |
| 1736 |
) -> None: |
| 1737 |
"""Test broken callbacks do not cause the scanner to fail.""" |
| 1738 |
detected: list[tuple[BLEDevice, AdvertisementData]] = [] |
| 1739 |
|
| 1740 |
def _device_detected( |
| 1741 |
device: BLEDevice, advertisement_data: AdvertisementData |
| 1742 |
) -> None: |
| 1743 |
"""Handle a detected device.""" |
| 1744 |
if detected: |
| 1745 |
raise ValueError |
| 1746 |
detected.append((device, advertisement_data)) |
| 1747 |
|
| 1748 |
switchbot_device = generate_ble_device("44:44:33:11:23:45", "wohand") |
| 1749 |
switchbot_adv = generate_advertisement_data( |
| 1750 |
local_name="wohand", |
| 1751 |
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1752 |
manufacturer_data={89: b"\xd8.\xad\xcd\r\x85"}, |
| 1753 |
service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"}, |
| 1754 |
) |
| 1755 |
|
| 1756 |
assert _get_manager() is not None |
| 1757 |
_scanner = HaBleakScannerWrapper( |
| 1758 |
detection_callback=_device_detected, |
| 1759 |
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1760 |
) |
| 1761 |
await _scanner.start() |
| 1762 |
|
| 1763 |
inject_advertisement(switchbot_device, switchbot_adv) |
| 1764 |
await asyncio.sleep(0) |
| 1765 |
inject_advertisement(switchbot_device, switchbot_adv) |
| 1766 |
await asyncio.sleep(0) |
| 1767 |
assert len(detected) == 1 |
| 1768 |
|
| 1769 |
|
| 1770 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 1771 |
@pytest.mark.asyncio |
| 1772 |
async def test_wrapped_instance_changes_uuids( |
| 1773 |
register_hci0_scanner: None, |
| 1774 |
) -> None: |
| 1775 |
"""Test consumers can use the wrapped instance can change the uuids later.""" |
| 1776 |
detected, _device_detected = _make_detection_recorder() |
| 1777 |
|
| 1778 |
switchbot_device = generate_ble_device("44:44:33:11:23:45", "wohand") |
| 1779 |
switchbot_adv = generate_advertisement_data( |
| 1780 |
local_name="wohand", |
| 1781 |
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1782 |
manufacturer_data={89: b"\xd8.\xad\xcd\r\x85"}, |
| 1783 |
service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"}, |
| 1784 |
) |
| 1785 |
switchbot_adv_2 = generate_advertisement_data( |
| 1786 |
local_name="wohand", |
| 1787 |
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1788 |
manufacturer_data={89: b"\xd8.\xad\xcd\r\x84"}, |
| 1789 |
service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"}, |
| 1790 |
) |
| 1791 |
empty_device = generate_ble_device("11:22:33:44:55:66", "empty") |
| 1792 |
empty_adv = generate_advertisement_data(local_name="empty") |
| 1793 |
|
| 1794 |
assert _get_manager() is not None |
| 1795 |
_scanner = HaBleakScannerWrapper( |
| 1796 |
detection_callback=_device_detected, |
| 1797 |
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1798 |
) |
| 1799 |
await _scanner.start() |
| 1800 |
|
| 1801 |
inject_advertisement(switchbot_device, switchbot_adv) |
| 1802 |
inject_advertisement(switchbot_device, switchbot_adv_2) |
| 1803 |
await asyncio.sleep(0) |
| 1804 |
|
| 1805 |
assert len(detected) == 2 |
| 1806 |
|
| 1807 |
# The UUIDs list we created in the wrapped scanner with should be respected |
| 1808 |
# and we should not get another callback |
| 1809 |
inject_advertisement(empty_device, empty_adv) |
| 1810 |
assert len(detected) == 2 |
| 1811 |
|
| 1812 |
|
| 1813 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 1814 |
@pytest.mark.asyncio |
| 1815 |
async def test_wrapped_instance_changes_filters( |
| 1816 |
register_hci0_scanner: None, |
| 1817 |
) -> None: |
| 1818 |
"""Test consumers can use the wrapped instance can change the filter later.""" |
| 1819 |
detected, _device_detected = _make_detection_recorder() |
| 1820 |
|
| 1821 |
switchbot_device = generate_ble_device("44:44:33:11:23:42", "wohand") |
| 1822 |
switchbot_adv = generate_advertisement_data( |
| 1823 |
local_name="wohand", |
| 1824 |
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1825 |
manufacturer_data={89: b"\xd8.\xad\xcd\r\x85"}, |
| 1826 |
service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"}, |
| 1827 |
) |
| 1828 |
switchbot_adv_2 = generate_advertisement_data( |
| 1829 |
local_name="wohand", |
| 1830 |
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1831 |
manufacturer_data={89: b"\xd8.\xad\xcd\r\x84"}, |
| 1832 |
service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"}, |
| 1833 |
) |
| 1834 |
empty_device = generate_ble_device("11:22:33:44:55:62", "empty") |
| 1835 |
empty_adv = generate_advertisement_data(local_name="empty") |
| 1836 |
|
| 1837 |
assert _get_manager() is not None |
| 1838 |
_scanner = HaBleakScannerWrapper( |
| 1839 |
detection_callback=_device_detected, |
| 1840 |
filters={"UUIDs": ["cba20d00-224d-11e6-9fb8-0002a5d5c51b"]}, |
| 1841 |
) |
| 1842 |
await _scanner.start() |
| 1843 |
|
| 1844 |
inject_advertisement(switchbot_device, switchbot_adv) |
| 1845 |
inject_advertisement(switchbot_device, switchbot_adv_2) |
| 1846 |
|
| 1847 |
await asyncio.sleep(0) |
| 1848 |
|
| 1849 |
assert len(detected) == 2 |
| 1850 |
|
| 1851 |
# The UUIDs list we created in the wrapped scanner with should be respected |
| 1852 |
# and we should not get another callback |
| 1853 |
inject_advertisement(empty_device, empty_adv) |
| 1854 |
assert len(detected) == 2 |
| 1855 |
|
| 1856 |
|
| 1857 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 1858 |
@pytest.mark.asyncio |
| 1859 |
async def test_wrapped_instance_unsupported_filter( |
| 1860 |
register_hci0_scanner: None, |
| 1861 |
caplog: pytest.LogCaptureFixture, |
| 1862 |
) -> None: |
| 1863 |
"""Test we want when their filter is ineffective.""" |
| 1864 |
assert _get_manager() is not None |
| 1865 |
scanner = HaBleakScannerWrapper() |
| 1866 |
scanner.set_scanning_filter( |
| 1867 |
filters={ |
| 1868 |
"unsupported": ["cba20d00-224d-11e6-9fb8-0002a5d5c51b"], |
| 1869 |
"DuplicateData": True, |
| 1870 |
} |
| 1871 |
) |
| 1872 |
assert "Only UUIDs filters are supported" in caplog.text |
| 1873 |
|
| 1874 |
|
| 1875 |
@pytest.mark.asyncio |
| 1876 |
async def test_client_with_services_parameter( |
| 1877 |
two_adapters: None, |
| 1878 |
enable_bluetooth: None, |
| 1879 |
install_bleak_catcher: None, |
| 1880 |
mock_platform_client: None, |
| 1881 |
) -> None: |
| 1882 |
"""Test that services parameter is passed correctly to the backend.""" |
| 1883 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 1884 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 1885 |
|
| 1886 |
test_services = [ |
| 1887 |
"00001800-0000-1000-8000-00805f9b34fb", |
| 1888 |
"00001801-0000-1000-8000-00805f9b34fb", |
| 1889 |
] |
| 1890 |
|
| 1891 |
# Track what services were passed to the backend |
| 1892 |
services_passed_to_backend = None |
| 1893 |
|
| 1894 |
class FakeBleakClientTracksServices(BaseFakeBleakClient): |
| 1895 |
"""Fake bleak client that tracks services parameter.""" |
| 1896 |
|
| 1897 |
def __init__( |
| 1898 |
self, address_or_ble_device: BLEDevice | str, **kwargs: Any |
| 1899 |
) -> None: |
| 1900 |
"""Initialize and capture services.""" |
| 1901 |
super().__init__(address_or_ble_device, **kwargs) |
| 1902 |
nonlocal services_passed_to_backend |
| 1903 |
services_passed_to_backend = kwargs.get("services") |
| 1904 |
|
| 1905 |
async def connect(self, *args, **kwargs): |
| 1906 |
"""Connect.""" |
| 1907 |
return True |
| 1908 |
|
| 1909 |
@property |
| 1910 |
def is_connected(self): |
| 1911 |
return True |
| 1912 |
|
| 1913 |
with patch( |
| 1914 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 1915 |
return_value=FakeBleakClientTracksServices, |
| 1916 |
): |
| 1917 |
client = bleak.BleakClient(ble_device, services=test_services) |
| 1918 |
await client.connect() |
| 1919 |
|
| 1920 |
# Verify services were normalized and passed as a set |
| 1921 |
assert services_passed_to_backend is not None |
| 1922 |
assert isinstance(services_passed_to_backend, set) |
| 1923 |
assert services_passed_to_backend == { |
| 1924 |
"00001800-0000-1000-8000-00805f9b34fb", |
| 1925 |
"00001801-0000-1000-8000-00805f9b34fb", |
| 1926 |
} |
| 1927 |
|
| 1928 |
cancel_hci0() |
| 1929 |
cancel_hci1() |
| 1930 |
|
| 1931 |
|
| 1932 |
@pytest.mark.asyncio |
| 1933 |
async def test_client_with_pair_parameter( |
| 1934 |
two_adapters: None, |
| 1935 |
enable_bluetooth: None, |
| 1936 |
install_bleak_catcher: None, |
| 1937 |
mock_platform_client: None, |
| 1938 |
) -> None: |
| 1939 |
"""Test that pair parameter is set correctly on the wrapper.""" |
| 1940 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 1941 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 1942 |
|
| 1943 |
# Test default pair=False |
| 1944 |
client = bleak.BleakClient(ble_device) |
| 1945 |
assert client._pair_before_connect is False |
| 1946 |
|
| 1947 |
# Test pair=True |
| 1948 |
client = bleak.BleakClient(ble_device, pair=True) |
| 1949 |
assert client._pair_before_connect is True |
| 1950 |
|
| 1951 |
cancel_hci0() |
| 1952 |
cancel_hci1() |
| 1953 |
|
| 1954 |
|
| 1955 |
@pytest.mark.asyncio |
| 1956 |
async def test_client_services_normalization( |
| 1957 |
two_adapters: None, |
| 1958 |
enable_bluetooth: None, |
| 1959 |
install_bleak_catcher: None, |
| 1960 |
mock_platform_client: None, |
| 1961 |
) -> None: |
| 1962 |
"""Test that service UUIDs are normalized correctly.""" |
| 1963 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 1964 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 1965 |
|
| 1966 |
# Test with short UUIDs that need normalization |
| 1967 |
test_services = ["1800", "1801", "CBA20D00-224D-11E6-9FB8-0002A5D5C51B"] |
| 1968 |
|
| 1969 |
services_passed_to_backend = None |
| 1970 |
|
| 1971 |
class FakeBleakClientTracksServices(BaseFakeBleakClient): |
| 1972 |
"""Fake bleak client that tracks services parameter.""" |
| 1973 |
|
| 1974 |
def __init__( |
| 1975 |
self, address_or_ble_device: BLEDevice | str, **kwargs: Any |
| 1976 |
) -> None: |
| 1977 |
"""Initialize and capture services.""" |
| 1978 |
super().__init__(address_or_ble_device, **kwargs) |
| 1979 |
nonlocal services_passed_to_backend |
| 1980 |
services_passed_to_backend = kwargs.get("services") |
| 1981 |
|
| 1982 |
async def connect(self, *args, **kwargs): |
| 1983 |
"""Connect.""" |
| 1984 |
return True |
| 1985 |
|
| 1986 |
@property |
| 1987 |
def is_connected(self): |
| 1988 |
return True |
| 1989 |
|
| 1990 |
with patch( |
| 1991 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 1992 |
return_value=FakeBleakClientTracksServices, |
| 1993 |
): |
| 1994 |
client = bleak.BleakClient(ble_device, services=test_services) |
| 1995 |
await client.connect() |
| 1996 |
|
| 1997 |
# Verify services were normalized |
| 1998 |
assert services_passed_to_backend is not None |
| 1999 |
assert isinstance(services_passed_to_backend, set) |
| 2000 |
assert services_passed_to_backend == { |
| 2001 |
"00001800-0000-1000-8000-00805f9b34fb", |
| 2002 |
"00001801-0000-1000-8000-00805f9b34fb", |
| 2003 |
"cba20d00-224d-11e6-9fb8-0002a5d5c51b", # Should be lowercased |
| 2004 |
} |
| 2005 |
|
| 2006 |
cancel_hci0() |
| 2007 |
cancel_hci1() |
| 2008 |
|
| 2009 |
|
| 2010 |
@pytest.mark.asyncio |
| 2011 |
async def test_client_with_none_services( |
| 2012 |
two_adapters: None, |
| 2013 |
enable_bluetooth: None, |
| 2014 |
install_bleak_catcher: None, |
| 2015 |
mock_platform_client: None, |
| 2016 |
) -> None: |
| 2017 |
"""Test that None services parameter is handled correctly.""" |
| 2018 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 2019 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 2020 |
|
| 2021 |
services_passed_to_backend = "not_set" |
| 2022 |
|
| 2023 |
class FakeBleakClientTracksServices(BaseFakeBleakClient): |
| 2024 |
"""Fake bleak client that tracks services parameter.""" |
| 2025 |
|
| 2026 |
def __init__( |
| 2027 |
self, address_or_ble_device: BLEDevice | str, **kwargs: Any |
| 2028 |
) -> None: |
| 2029 |
"""Initialize and capture services.""" |
| 2030 |
super().__init__(address_or_ble_device, **kwargs) |
| 2031 |
nonlocal services_passed_to_backend |
| 2032 |
services_passed_to_backend = kwargs.get("services", "not_set") |
| 2033 |
|
| 2034 |
async def connect(self, *args, **kwargs): |
| 2035 |
"""Connect.""" |
| 2036 |
return True |
| 2037 |
|
| 2038 |
@property |
| 2039 |
def is_connected(self): |
| 2040 |
return True |
| 2041 |
|
| 2042 |
with patch( |
| 2043 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 2044 |
return_value=FakeBleakClientTracksServices, |
| 2045 |
): |
| 2046 |
# Test with no services parameter (default None) |
| 2047 |
client = bleak.BleakClient(ble_device) |
| 2048 |
await client.connect() |
| 2049 |
assert services_passed_to_backend is None |
| 2050 |
|
| 2051 |
# Reset the captured value |
| 2052 |
services_passed_to_backend = "not_set" # type: ignore[unreachable] |
| 2053 |
|
| 2054 |
with patch( |
| 2055 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 2056 |
return_value=FakeBleakClientTracksServices, |
| 2057 |
): |
| 2058 |
# Test with explicit None |
| 2059 |
client = bleak.BleakClient(ble_device, services=None) |
| 2060 |
await client.connect() |
| 2061 |
assert services_passed_to_backend is None |
| 2062 |
|
| 2063 |
cancel_hci0() |
| 2064 |
cancel_hci1() |
| 2065 |
|
| 2066 |
|
| 2067 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 2068 |
@pytest.mark.asyncio |
| 2069 |
async def test_passive_only_scanner_error_message() -> None: |
| 2070 |
"""Test error message when all scanners are passive-only (like Shelly).""" |
| 2071 |
manager = _get_manager() |
| 2072 |
# Register a passive-only scanner (connectable=False) |
| 2073 |
scanner = FakeScanner( |
| 2074 |
"passive_scanner_1", "shelly_plus1pm_e86bea01020c", None, False |
| 2075 |
) |
| 2076 |
cancel = manager.async_register_scanner(scanner) |
| 2077 |
|
| 2078 |
# Inject an advertisement from this passive scanner |
| 2079 |
device = generate_ble_device( |
| 2080 |
"00:00:00:00:00:01", "Test Device", {"source": "passive_scanner_1"} |
| 2081 |
) |
| 2082 |
adv_data = generate_advertisement_data( |
| 2083 |
local_name="Test Device", |
| 2084 |
service_uuids=[], |
| 2085 |
rssi=-50, |
| 2086 |
) |
| 2087 |
scanner.inject_advertisement(device, adv_data) |
| 2088 |
await asyncio.sleep(0) # Let the advertisement be processed |
| 2089 |
|
| 2090 |
# Try to connect - should fail with our custom error message |
| 2091 |
client = bleak.BleakClient("00:00:00:00:00:01") |
| 2092 |
with pytest.raises( |
| 2093 |
BleakError, |
| 2094 |
match=r"00:00:00:00:00:01: No connectable Bluetooth adapters\. " |
| 2095 |
r"Shelly devices are passive-only and cannot connect\. " |
| 2096 |
r"Need local Bluetooth adapter or ESPHome proxy\. " |
| 2097 |
r"Available: shelly_plus1pm_e86bea01020c \(passive_scanner_1\)", |
| 2098 |
): |
| 2099 |
await client.connect() |
| 2100 |
|
| 2101 |
cancel() |
| 2102 |
|
| 2103 |
|
| 2104 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 2105 |
@pytest.mark.asyncio |
| 2106 |
async def test_passive_scanner_with_active_scanner() -> None: |
| 2107 |
"""Test normal error when there's a mix of passive and active scanners.""" |
| 2108 |
manager = _get_manager() |
| 2109 |
# Register a passive-only scanner |
| 2110 |
passive_scanner = FakeScanner("passive_scanner", "shelly_device", None, False) |
| 2111 |
cancel_passive = manager.async_register_scanner(passive_scanner) |
| 2112 |
|
| 2113 |
# Register an active scanner with no available slots |
| 2114 |
active_scanner = FakeScanner("active_scanner", "esphome_device", None, True) |
| 2115 |
cancel_active = manager.async_register_scanner(active_scanner) |
| 2116 |
|
| 2117 |
# Inject advertisements from both scanners |
| 2118 |
device1 = generate_ble_device( |
| 2119 |
"00:00:00:00:00:02", "Test Device", {"source": "passive_scanner"} |
| 2120 |
) |
| 2121 |
device2 = generate_ble_device( |
| 2122 |
"00:00:00:00:00:02", "Test Device", {"source": "active_scanner"} |
| 2123 |
) |
| 2124 |
adv_data = generate_advertisement_data( |
| 2125 |
local_name="Test Device", |
| 2126 |
service_uuids=[], |
| 2127 |
rssi=-50, |
| 2128 |
) |
| 2129 |
passive_scanner.inject_advertisement(device1, adv_data) |
| 2130 |
active_scanner.inject_advertisement(device2, adv_data) |
| 2131 |
await asyncio.sleep(0) # Let the advertisements be processed |
| 2132 |
|
| 2133 |
# Mock the slot allocation to fail (simulating no available slots) |
| 2134 |
with patch.object(manager.slot_manager, "allocate_slot", return_value=False): |
| 2135 |
# Should get the normal "no available slot" error, not the passive-only error |
| 2136 |
client = bleak.BleakClient("00:00:00:00:00:02") |
| 2137 |
with pytest.raises( |
| 2138 |
BleakError, |
| 2139 |
match=( |
| 2140 |
"No backend with an available connection slot that can reach " |
| 2141 |
"address 00:00:00:00:00:02 was found" |
| 2142 |
), |
| 2143 |
): |
| 2144 |
await client.connect() |
| 2145 |
|
| 2146 |
cancel_passive() |
| 2147 |
cancel_active() |
| 2148 |
|
| 2149 |
|
| 2150 |
@pytest.mark.asyncio |
| 2151 |
async def test_connection_params_loading_with_bluez_mgmt( |
| 2152 |
two_adapters: None, |
| 2153 |
enable_bluetooth: None, |
| 2154 |
install_bleak_catcher: None, |
| 2155 |
caplog: pytest.LogCaptureFixture, |
| 2156 |
) -> None: |
| 2157 |
"""Test that connection parameters are loaded when mgmt API is available.""" |
| 2158 |
manager = _get_manager() |
| 2159 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 2160 |
|
| 2161 |
# Mock the bluez mgmt controller |
| 2162 |
mock_mgmt_ctl = Mock() |
| 2163 |
mock_mgmt_ctl.load_conn_params.return_value = True |
| 2164 |
|
| 2165 |
class FakeBleakClientTracksConnect(BaseFakeBleakClient): |
| 2166 |
"""Fake bleak client that tracks connect.""" |
| 2167 |
|
| 2168 |
connected = False |
| 2169 |
|
| 2170 |
async def connect(self, *args, **kwargs): |
| 2171 |
"""Connect.""" |
| 2172 |
self.connected = True |
| 2173 |
# Simulate service discovery |
| 2174 |
await asyncio.sleep(0) |
| 2175 |
|
| 2176 |
@property |
| 2177 |
def is_connected(self) -> bool: |
| 2178 |
return self.connected |
| 2179 |
|
| 2180 |
# Test with debug logging enabled |
| 2181 |
with ( |
| 2182 |
caplog.at_level(logging.DEBUG), |
| 2183 |
patch.object(manager, "get_bluez_mgmt_ctl", return_value=mock_mgmt_ctl), |
| 2184 |
patch( |
| 2185 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 2186 |
return_value=FakeBleakClientTracksConnect, |
| 2187 |
), |
| 2188 |
): |
| 2189 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 2190 |
client = bleak.BleakClient(ble_device) |
| 2191 |
await client.connect() |
| 2192 |
|
| 2193 |
# Verify load_conn_params was called twice (fast before connect, medium after) |
| 2194 |
assert mock_mgmt_ctl.load_conn_params.call_count == 2 |
| 2195 |
|
| 2196 |
# First call should be for FAST params |
| 2197 |
first_call = mock_mgmt_ctl.load_conn_params.call_args_list[0] |
| 2198 |
assert first_call[0][0] == 0 # adapter_idx |
| 2199 |
assert first_call[0][1] == "00:00:00:00:00:01" # address |
| 2200 |
assert first_call[0][2] == 1 # BDADDR_LE_PUBLIC (default) |
| 2201 |
assert first_call[0][3].value == "fast" # ConnectParams.FAST |
| 2202 |
|
| 2203 |
# Second call should be for MEDIUM params |
| 2204 |
second_call = mock_mgmt_ctl.load_conn_params.call_args_list[1] |
| 2205 |
assert second_call[0][0] == 0 # adapter_idx |
| 2206 |
assert second_call[0][1] == "00:00:00:00:00:01" # address |
| 2207 |
assert second_call[0][2] == 1 # BDADDR_LE_PUBLIC |
| 2208 |
assert second_call[0][3].value == "medium" # ConnectParams.MEDIUM |
| 2209 |
|
| 2210 |
# Verify debug logging |
| 2211 |
assert "Loaded ConnectParams.FAST connection parameters" in caplog.text |
| 2212 |
assert "Loaded ConnectParams.MEDIUM connection parameters" in caplog.text |
| 2213 |
|
| 2214 |
cancel_hci0() |
| 2215 |
cancel_hci1() |
| 2216 |
|
| 2217 |
|
| 2218 |
@pytest.mark.asyncio |
| 2219 |
async def test_connection_params_not_loaded_without_mgmt( |
| 2220 |
two_adapters: None, |
| 2221 |
enable_bluetooth: None, |
| 2222 |
install_bleak_catcher: None, |
| 2223 |
caplog: pytest.LogCaptureFixture, |
| 2224 |
) -> None: |
| 2225 |
"""Test that connection parameters are not loaded when mgmt API is unavailable.""" |
| 2226 |
manager = _get_manager() |
| 2227 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 2228 |
|
| 2229 |
class FakeBleakClientTracksConnect(BaseFakeBleakClient): |
| 2230 |
"""Fake bleak client that tracks connect.""" |
| 2231 |
|
| 2232 |
connected = False |
| 2233 |
|
| 2234 |
async def connect(self, *args, **kwargs): |
| 2235 |
"""Connect.""" |
| 2236 |
self.connected = True |
| 2237 |
await asyncio.sleep(0) |
| 2238 |
|
| 2239 |
@property |
| 2240 |
def is_connected(self) -> bool: |
| 2241 |
return self.connected |
| 2242 |
|
| 2243 |
with ( |
| 2244 |
caplog.at_level(logging.DEBUG), |
| 2245 |
patch.object(manager, "get_bluez_mgmt_ctl", return_value=None), |
| 2246 |
patch( |
| 2247 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 2248 |
return_value=FakeBleakClientTracksConnect, |
| 2249 |
), |
| 2250 |
): |
| 2251 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 2252 |
client = bleak.BleakClient(ble_device) |
| 2253 |
await client.connect() |
| 2254 |
|
| 2255 |
# Verify no connection parameters were loaded |
| 2256 |
assert "connection parameters" not in caplog.text |
| 2257 |
|
| 2258 |
cancel_hci0() |
| 2259 |
cancel_hci1() |
| 2260 |
|
| 2261 |
|
| 2262 |
@pytest.mark.asyncio |
| 2263 |
async def test_get_device_address_type_random( |
| 2264 |
two_adapters: None, |
| 2265 |
enable_bluetooth: None, |
| 2266 |
install_bleak_catcher: None, |
| 2267 |
) -> None: |
| 2268 |
"""Test _get_device_address_type returns BDADDR_LE_RANDOM for random address.""" |
| 2269 |
_hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 2270 |
|
| 2271 |
# Create a device with random address type |
| 2272 |
device = generate_ble_device( |
| 2273 |
"00:00:00:00:00:02", |
| 2274 |
"Test Device", |
| 2275 |
{ |
| 2276 |
"path": "/org/bluez/hci0/dev_00_00_00_00_00_02", |
| 2277 |
"props": {"AddressType": "random"}, |
| 2278 |
}, |
| 2279 |
) |
| 2280 |
|
| 2281 |
assert _get_device_address_type(device) == BDADDR_LE_RANDOM |
| 2282 |
|
| 2283 |
cancel_hci0() |
| 2284 |
cancel_hci1() |
| 2285 |
|
| 2286 |
|
| 2287 |
@pytest.mark.asyncio |
| 2288 |
async def test_get_device_address_type_public( |
| 2289 |
two_adapters: None, |
| 2290 |
enable_bluetooth: None, |
| 2291 |
install_bleak_catcher: None, |
| 2292 |
) -> None: |
| 2293 |
"""Test _get_device_address_type returns BDADDR_LE_PUBLIC for public address.""" |
| 2294 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 2295 |
|
| 2296 |
# Create a device with public address type (default) |
| 2297 |
device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 2298 |
|
| 2299 |
assert _get_device_address_type(device) == BDADDR_LE_PUBLIC |
| 2300 |
|
| 2301 |
cancel_hci0() |
| 2302 |
cancel_hci1() |
| 2303 |
|
| 2304 |
|
| 2305 |
@pytest.mark.asyncio |
| 2306 |
async def test_connection_params_loading_fails_silently( |
| 2307 |
two_adapters: None, |
| 2308 |
enable_bluetooth: None, |
| 2309 |
install_bleak_catcher: None, |
| 2310 |
caplog: pytest.LogCaptureFixture, |
| 2311 |
) -> None: |
| 2312 |
"""Test that connection still succeeds even if loading params fails.""" |
| 2313 |
manager = _get_manager() |
| 2314 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 2315 |
|
| 2316 |
# Mock the bluez mgmt controller to fail loading params |
| 2317 |
mock_mgmt_ctl = Mock() |
| 2318 |
mock_mgmt_ctl.load_conn_params.return_value = False |
| 2319 |
|
| 2320 |
class FakeBleakClientTracksConnect(BaseFakeBleakClient): |
| 2321 |
"""Fake bleak client that tracks connect.""" |
| 2322 |
|
| 2323 |
connected = False |
| 2324 |
|
| 2325 |
async def connect(self, *args, **kwargs): |
| 2326 |
"""Connect.""" |
| 2327 |
self.connected = True |
| 2328 |
await asyncio.sleep(0) |
| 2329 |
|
| 2330 |
@property |
| 2331 |
def is_connected(self) -> bool: |
| 2332 |
return self.connected |
| 2333 |
|
| 2334 |
with ( |
| 2335 |
caplog.at_level(logging.DEBUG), |
| 2336 |
patch.object(manager, "get_bluez_mgmt_ctl", return_value=mock_mgmt_ctl), |
| 2337 |
patch( |
| 2338 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 2339 |
return_value=FakeBleakClientTracksConnect, |
| 2340 |
), |
| 2341 |
): |
| 2342 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 2343 |
client = bleak.BleakClient(ble_device) |
| 2344 |
# Connection should succeed even though param loading failed |
| 2345 |
await client.connect() |
| 2346 |
|
| 2347 |
# Verify load_conn_params was called |
| 2348 |
assert mock_mgmt_ctl.load_conn_params.call_count == 2 |
| 2349 |
|
| 2350 |
# But no success message should be logged |
| 2351 |
assert "Loaded" not in caplog.text |
| 2352 |
|
| 2353 |
cancel_hci0() |
| 2354 |
cancel_hci1() |
| 2355 |
|
| 2356 |
|
| 2357 |
@pytest.mark.asyncio |
| 2358 |
async def test_connection_params_no_adapter_idx( |
| 2359 |
two_adapters: None, |
| 2360 |
enable_bluetooth: None, |
| 2361 |
install_bleak_catcher: None, |
| 2362 |
caplog: pytest.LogCaptureFixture, |
| 2363 |
) -> None: |
| 2364 |
"""Test that connection params are not loaded if scanner has no adapter_idx.""" |
| 2365 |
manager = _get_manager() |
| 2366 |
|
| 2367 |
# Mock the bluez mgmt controller |
| 2368 |
mock_mgmt_ctl = Mock() |
| 2369 |
mock_mgmt_ctl.load_conn_params.return_value = True |
| 2370 |
|
| 2371 |
class FakeBleakClientTracksConnect(BaseFakeBleakClient): |
| 2372 |
"""Fake bleak client that tracks connect.""" |
| 2373 |
|
| 2374 |
connected = False |
| 2375 |
|
| 2376 |
async def connect(self, *args, **kwargs): |
| 2377 |
"""Connect.""" |
| 2378 |
self.connected = True |
| 2379 |
await asyncio.sleep(0) |
| 2380 |
|
| 2381 |
@property |
| 2382 |
def is_connected(self) -> bool: |
| 2383 |
return self.connected |
| 2384 |
|
| 2385 |
# Create a fake connector for the remote scanner |
| 2386 |
fake_connector = HaBluetoothConnector( |
| 2387 |
client=FakeBleakClientTracksConnect, source="any", can_connect=lambda: True |
| 2388 |
) |
| 2389 |
|
| 2390 |
# Create a scanner without adapter_idx (e.g., remote scanner) |
| 2391 |
remote_scanner = FakeScanner( |
| 2392 |
"remote_scanner", "ESPHome Device", fake_connector, True |
| 2393 |
) |
| 2394 |
cancel_remote = manager.async_register_scanner(remote_scanner) |
| 2395 |
|
| 2396 |
# Inject advertisement |
| 2397 |
device = generate_ble_device( |
| 2398 |
"00:00:00:00:00:03", "Test Device", {"source": "remote_scanner"} |
| 2399 |
) |
| 2400 |
adv_data = generate_advertisement_data( |
| 2401 |
local_name="Test Device", |
| 2402 |
service_uuids=[], |
| 2403 |
rssi=-50, |
| 2404 |
) |
| 2405 |
remote_scanner.inject_advertisement(device, adv_data) |
| 2406 |
await asyncio.sleep(0) |
| 2407 |
|
| 2408 |
# Remote scanner should already have adapter_idx returning None |
| 2409 |
with ( |
| 2410 |
caplog.at_level(logging.DEBUG), |
| 2411 |
patch.object(manager, "get_bluez_mgmt_ctl", return_value=mock_mgmt_ctl), |
| 2412 |
): |
| 2413 |
client = bleak.BleakClient("00:00:00:00:00:03") |
| 2414 |
await client.connect() |
| 2415 |
|
| 2416 |
# Verify load_conn_params was NOT called since adapter_idx is None |
| 2417 |
assert mock_mgmt_ctl.load_conn_params.call_count == 0 |
| 2418 |
|
| 2419 |
cancel_remote() |
| 2420 |
|
| 2421 |
|
| 2422 |
@pytest.mark.asyncio |
| 2423 |
async def test_connection_path_scoring_with_slots_and_logging( |
| 2424 |
caplog: pytest.LogCaptureFixture, |
| 2425 |
) -> None: |
| 2426 |
"""Test connection path scoring and logging reflects slot availability.""" |
| 2427 |
manager = _get_manager() |
| 2428 |
|
| 2429 |
class FakeBleakClientNoConnect(BaseFakeBleakClient): |
| 2430 |
"""Fake bleak client that doesn't connect.""" |
| 2431 |
|
| 2432 |
async def connect(self, *args, **kwargs): |
| 2433 |
"""Don't actually connect.""" |
| 2434 |
msg = "Test - connection not needed" |
| 2435 |
raise BleakError(msg) |
| 2436 |
|
| 2437 |
# Create fake connectors |
| 2438 |
fake_connector_1 = HaBluetoothConnector( |
| 2439 |
client=FakeBleakClientNoConnect, source="scanner1", can_connect=lambda: True |
| 2440 |
) |
| 2441 |
fake_connector_2 = HaBluetoothConnector( |
| 2442 |
client=FakeBleakClientNoConnect, source="scanner2", can_connect=lambda: True |
| 2443 |
) |
| 2444 |
fake_connector_3 = HaBluetoothConnector( |
| 2445 |
client=FakeBleakClientNoConnect, source="scanner3", can_connect=lambda: True |
| 2446 |
) |
| 2447 |
|
| 2448 |
# Create scanners with different sources |
| 2449 |
scanner1 = FakeScanner("scanner1", "Scanner 1", fake_connector_1, True) |
| 2450 |
scanner2 = FakeScanner("scanner2", "Scanner 2", fake_connector_2, True) |
| 2451 |
scanner3 = FakeScanner("scanner3", "Scanner 3", fake_connector_3, True) |
| 2452 |
|
| 2453 |
# Mock get_allocations for each scanner using patch.object |
| 2454 |
with ( |
| 2455 |
patch.object( |
| 2456 |
scanner1, |
| 2457 |
"get_allocations", |
| 2458 |
return_value=Allocations( |
| 2459 |
adapter="scanner1", |
| 2460 |
slots=3, |
| 2461 |
free=1, # Only 1 slot free - should get penalty |
| 2462 |
allocated=["AA:BB:CC:DD:EE:01", "AA:BB:CC:DD:EE:02"], |
| 2463 |
), |
| 2464 |
), |
| 2465 |
patch.object( |
| 2466 |
scanner2, |
| 2467 |
"get_allocations", |
| 2468 |
return_value=Allocations( |
| 2469 |
adapter="scanner2", |
| 2470 |
slots=3, |
| 2471 |
free=2, # 2 slots free - no penalty |
| 2472 |
allocated=["AA:BB:CC:DD:EE:03"], |
| 2473 |
), |
| 2474 |
), |
| 2475 |
patch.object( |
| 2476 |
scanner3, |
| 2477 |
"get_allocations", |
| 2478 |
return_value=Allocations( |
| 2479 |
adapter="scanner3", |
| 2480 |
slots=3, |
| 2481 |
free=3, # All slots free - no penalty |
| 2482 |
allocated=[], |
| 2483 |
), |
| 2484 |
), |
| 2485 |
): |
| 2486 |
cancel1 = manager.async_register_scanner(scanner1) |
| 2487 |
cancel2 = manager.async_register_scanner(scanner2) |
| 2488 |
cancel3 = manager.async_register_scanner(scanner3) |
| 2489 |
|
| 2490 |
# Inject advertisements with different RSSI values |
| 2491 |
device1 = generate_ble_device( |
| 2492 |
"00:00:00:00:00:01", "Test Device", {"source": "scanner1"} |
| 2493 |
) |
| 2494 |
adv_data1 = generate_advertisement_data(local_name="Test Device", rssi=-60) |
| 2495 |
scanner1.inject_advertisement(device1, adv_data1) |
| 2496 |
|
| 2497 |
device2 = generate_ble_device( |
| 2498 |
"00:00:00:00:00:01", "Test Device", {"source": "scanner2"} |
| 2499 |
) |
| 2500 |
adv_data2 = generate_advertisement_data(local_name="Test Device", rssi=-65) |
| 2501 |
scanner2.inject_advertisement(device2, adv_data2) |
| 2502 |
|
| 2503 |
device3 = generate_ble_device( |
| 2504 |
"00:00:00:00:00:01", "Test Device", {"source": "scanner3"} |
| 2505 |
) |
| 2506 |
adv_data3 = generate_advertisement_data(local_name="Test Device", rssi=-70) |
| 2507 |
scanner3.inject_advertisement(device3, adv_data3) |
| 2508 |
|
| 2509 |
await asyncio.sleep(0) |
| 2510 |
|
| 2511 |
# Try to connect with logging enabled |
| 2512 |
with caplog.at_level(logging.INFO): |
| 2513 |
client = bleak.BleakClient("00:00:00:00:00:01") |
| 2514 |
with suppress(BleakError): |
| 2515 |
await client.connect() |
| 2516 |
|
| 2517 |
# Check that the log contains the connection paths with correct scoring |
| 2518 |
log_text = caplog.text |
| 2519 |
assert "Found 3 connection path(s)" in log_text |
| 2520 |
|
| 2521 |
# Extract the log line with connection paths |
| 2522 |
for line in caplog.text.splitlines(): |
| 2523 |
if "Found 3 connection path(s)" in line: |
| 2524 |
# rssi_diff = best_rssi - second_best_rssi = -60 - (-65) = 5 |
| 2525 |
# Scanner 1 has best RSSI (-60) but only 1 slot free, so with penalty: |
| 2526 |
# score = -60 - (5 * 0.76) = -63.8 |
| 2527 |
assert "Scanner 1" in line |
| 2528 |
assert "(slots=1/3 free)" in line |
| 2529 |
assert "(score=-63.8)" in line |
| 2530 |
|
| 2531 |
# Scanner 2 has RSSI -65 with 2 slots free, no penalty, so |
| 2532 |
# the score is just -65. |
| 2533 |
assert "Scanner 2" in line |
| 2534 |
assert "(slots=2/3 free)" in line |
| 2535 |
# Check for both -65 and -65.0 |
| 2536 |
assert ("(score=-65)" in line) or ("(score=-65.0)" in line) |
| 2537 |
|
| 2538 |
# Scanner 3 has RSSI -70 with all slots free, no penalty, so |
| 2539 |
# the score is just -70. |
| 2540 |
assert "Scanner 3" in line |
| 2541 |
assert "(slots=3/3 free)" in line |
| 2542 |
# Check for both -70 and -70.0 |
| 2543 |
assert ("(score=-70)" in line) or ("(score=-70.0)" in line) |
| 2544 |
|
| 2545 |
# Verify order: Scanner 1 should be first (best score -63.8), |
| 2546 |
# then Scanner 2 (-65), then Scanner 3 (-70) |
| 2547 |
scanner1_pos = line.find("Scanner 1") |
| 2548 |
scanner2_pos = line.find("Scanner 2") |
| 2549 |
scanner3_pos = line.find("Scanner 3") |
| 2550 |
|
| 2551 |
assert scanner1_pos < scanner2_pos < scanner3_pos, ( |
| 2552 |
f"Expected Scanner 1 before Scanner 2 before Scanner 3, " |
| 2553 |
f"but got positions {scanner1_pos}, {scanner2_pos}, {scanner3_pos}" |
| 2554 |
) |
| 2555 |
break |
| 2556 |
else: |
| 2557 |
pytest.fail("Could not find connection path log line") |
| 2558 |
|
| 2559 |
cancel1() |
| 2560 |
cancel2() |
| 2561 |
cancel3() |
| 2562 |
|
| 2563 |
|
| 2564 |
@pytest.mark.asyncio |
| 2565 |
async def test_connection_path_scoring_no_slots_available( |
| 2566 |
caplog: pytest.LogCaptureFixture, |
| 2567 |
) -> None: |
| 2568 |
"""Test that scanners with no free slots are excluded.""" |
| 2569 |
manager = _get_manager() |
| 2570 |
|
| 2571 |
class FakeBleakClientNoConnect(BaseFakeBleakClient): |
| 2572 |
"""Fake bleak client that doesn't connect.""" |
| 2573 |
|
| 2574 |
async def connect(self, *args, **kwargs): |
| 2575 |
"""Don't actually connect.""" |
| 2576 |
msg = "Test - connection not needed" |
| 2577 |
raise BleakError(msg) |
| 2578 |
|
| 2579 |
# Create fake connectors |
| 2580 |
fake_connector_1 = HaBluetoothConnector( |
| 2581 |
client=FakeBleakClientNoConnect, source="scanner1", can_connect=lambda: True |
| 2582 |
) |
| 2583 |
fake_connector_2 = HaBluetoothConnector( |
| 2584 |
client=FakeBleakClientNoConnect, source="scanner2", can_connect=lambda: True |
| 2585 |
) |
| 2586 |
|
| 2587 |
# Create scanners |
| 2588 |
scanner1 = FakeScanner("scanner1", "Scanner 1", fake_connector_1, True) |
| 2589 |
scanner2 = FakeScanner("scanner2", "Scanner 2", fake_connector_2, True) |
| 2590 |
|
| 2591 |
# Mock get_allocations - scanner1 has no free slots |
| 2592 |
with ( |
| 2593 |
patch.object( |
| 2594 |
scanner1, |
| 2595 |
"get_allocations", |
| 2596 |
return_value=Allocations( |
| 2597 |
adapter="scanner1", |
| 2598 |
slots=3, |
| 2599 |
free=0, # No slots available - should be excluded |
| 2600 |
allocated=[ |
| 2601 |
"AA:BB:CC:DD:EE:01", |
| 2602 |
"AA:BB:CC:DD:EE:02", |
| 2603 |
"AA:BB:CC:DD:EE:03", |
| 2604 |
], |
| 2605 |
), |
| 2606 |
), |
| 2607 |
patch.object( |
| 2608 |
scanner2, |
| 2609 |
"get_allocations", |
| 2610 |
return_value=Allocations( |
| 2611 |
adapter="scanner2", |
| 2612 |
slots=3, |
| 2613 |
free=3, |
| 2614 |
allocated=[], # All slots free |
| 2615 |
), |
| 2616 |
), |
| 2617 |
): |
| 2618 |
cancel1 = manager.async_register_scanner(scanner1) |
| 2619 |
cancel2 = manager.async_register_scanner(scanner2) |
| 2620 |
|
| 2621 |
# Inject advertisements |
| 2622 |
device1 = generate_ble_device( |
| 2623 |
"00:00:00:00:00:02", "Test Device", {"source": "scanner1"} |
| 2624 |
) |
| 2625 |
adv_data1 = generate_advertisement_data( |
| 2626 |
local_name="Test Device", rssi=-50 |
| 2627 |
) # Better RSSI |
| 2628 |
scanner1.inject_advertisement(device1, adv_data1) |
| 2629 |
|
| 2630 |
device2 = generate_ble_device( |
| 2631 |
"00:00:00:00:00:02", "Test Device", {"source": "scanner2"} |
| 2632 |
) |
| 2633 |
adv_data2 = generate_advertisement_data( |
| 2634 |
local_name="Test Device", rssi=-70 |
| 2635 |
) # Worse RSSI |
| 2636 |
scanner2.inject_advertisement(device2, adv_data2) |
| 2637 |
|
| 2638 |
await asyncio.sleep(0) |
| 2639 |
|
| 2640 |
# Try to connect with logging enabled |
| 2641 |
with caplog.at_level(logging.INFO): |
| 2642 |
client = bleak.BleakClient("00:00:00:00:00:02") |
| 2643 |
with suppress(BleakError): |
| 2644 |
await client.connect() |
| 2645 |
|
| 2646 |
# Check that only scanner2 is in the connection paths |
| 2647 |
log_text = caplog.text |
| 2648 |
assert ( |
| 2649 |
"Found 1 connection path(s)" in log_text |
| 2650 |
or "Found 2 connection path(s)" in log_text |
| 2651 |
) |
| 2652 |
|
| 2653 |
# If both are shown, scanner1 should have bad score (NO_RSSI_VALUE = -127) |
| 2654 |
for line in caplog.text.splitlines(): |
| 2655 |
if "connection path(s)" in line: |
| 2656 |
if "Scanner 1" in line: |
| 2657 |
# Scanner 1 should show 0 free slots and bad score |
| 2658 |
assert "(slots=0/3 free)" in line |
| 2659 |
assert "(score=-127)" in line # NO_RSSI_VALUE |
| 2660 |
|
| 2661 |
# Scanner 2 should be present with normal score |
| 2662 |
assert "Scanner 2" in line |
| 2663 |
assert "(slots=3/3 free)" in line |
| 2664 |
# Check for both -70 and -70.0 |
| 2665 |
assert ("(score=-70)" in line) or ("(score=-70.0)" in line) |
| 2666 |
break |
| 2667 |
|
| 2668 |
cancel1() |
| 2669 |
cancel2() |
| 2670 |
|
| 2671 |
|
| 2672 |
@pytest.mark.asyncio |
| 2673 |
async def test_thundering_herd_connection_slots() -> None: # noqa: C901 |
| 2674 |
""" |
| 2675 |
Test thundering herd scenario with limited connection slots. |
| 2676 |
|
| 2677 |
Simulates 7 devices trying to connect simultaneously to 3 proxies: |
| 2678 |
- Proxy 1 & 2: Good signal (-60 RSSI), 3 slots each |
| 2679 |
- Proxy 3: Bad signal (-95 RSSI), 3 slots each |
| 2680 |
|
| 2681 |
Expected behavior: |
| 2682 |
- First 6 devices should connect to proxy1 and proxy2 (3 each) |
| 2683 |
- 7th device should connect to proxy3 (bad signal) when others are full |
| 2684 |
""" |
| 2685 |
manager = _get_manager() |
| 2686 |
|
| 2687 |
# Track which backend each device connected to |
| 2688 |
connection_tracker = {} |
| 2689 |
|
| 2690 |
class FakeBleakClientThunderingHerd(BaseFakeBleakClient): |
| 2691 |
"""Fake bleak client for thundering herd test.""" |
| 2692 |
|
| 2693 |
def __init__(self, address_or_ble_device, *args, **kwargs): |
| 2694 |
"""Initialize with tracking.""" |
| 2695 |
super().__init__(address_or_ble_device, *args, **kwargs) |
| 2696 |
self._connected = False |
| 2697 |
# Track the device and source |
| 2698 |
if isinstance(address_or_ble_device, BLEDevice): |
| 2699 |
self._address = address_or_ble_device.address |
| 2700 |
self._source = address_or_ble_device.details.get("source") |
| 2701 |
else: |
| 2702 |
self._address = str(address_or_ble_device) |
| 2703 |
self._source = None |
| 2704 |
|
| 2705 |
async def connect(self, *args, **kwargs): |
| 2706 |
"""Simulate connection and record which backend was used.""" |
| 2707 |
# Small delay to simulate connection time |
| 2708 |
await asyncio.sleep(0.01) |
| 2709 |
self._connected = True |
| 2710 |
# Record which backend this device connected to |
| 2711 |
if self._address and self._source: |
| 2712 |
connection_tracker[self._address] = self._source |
| 2713 |
return True |
| 2714 |
|
| 2715 |
@property |
| 2716 |
def is_connected(self) -> bool: |
| 2717 |
"""Return connection state.""" |
| 2718 |
return self._connected |
| 2719 |
|
| 2720 |
# Create fake connectors for 3 proxies |
| 2721 |
fake_connector_1 = HaBluetoothConnector( |
| 2722 |
client=FakeBleakClientThunderingHerd, |
| 2723 |
source="proxy1", |
| 2724 |
can_connect=lambda: True, |
| 2725 |
) |
| 2726 |
fake_connector_2 = HaBluetoothConnector( |
| 2727 |
client=FakeBleakClientThunderingHerd, |
| 2728 |
source="proxy2", |
| 2729 |
can_connect=lambda: True, |
| 2730 |
) |
| 2731 |
fake_connector_3 = HaBluetoothConnector( |
| 2732 |
client=FakeBleakClientThunderingHerd, |
| 2733 |
source="proxy3", |
| 2734 |
can_connect=lambda: True, |
| 2735 |
) |
| 2736 |
|
| 2737 |
# Create 3 scanners (proxies) with 3 connection slots each |
| 2738 |
proxy1 = FakeScanner("proxy1", "Proxy 1 (Good)", fake_connector_1, True) |
| 2739 |
proxy2 = FakeScanner("proxy2", "Proxy 2 (Good)", fake_connector_2, True) |
| 2740 |
proxy3 = FakeScanner("proxy3", "Proxy 3 (Bad)", fake_connector_3, True) |
| 2741 |
|
| 2742 |
# Track actual slot allocations dynamically |
| 2743 |
proxy_allocations: dict[str, set[str]] = { |
| 2744 |
"proxy1": set(), |
| 2745 |
"proxy2": set(), |
| 2746 |
"proxy3": set(), |
| 2747 |
} |
| 2748 |
|
| 2749 |
def get_proxy_allocations(proxy_name: str) -> Allocations: |
| 2750 |
"""Get allocations for a specific proxy.""" |
| 2751 |
allocated = proxy_allocations[proxy_name] |
| 2752 |
return Allocations( |
| 2753 |
adapter=proxy_name, |
| 2754 |
slots=3, |
| 2755 |
free=3 - len(allocated), |
| 2756 |
allocated=list(allocated), |
| 2757 |
) |
| 2758 |
|
| 2759 |
# Mock methods to track allocations |
| 2760 |
def make_add_connecting(proxy_name: str) -> Callable[[str], None]: |
| 2761 |
def _add_connecting(addr: str) -> None: |
| 2762 |
proxy_allocations[proxy_name].add(addr) |
| 2763 |
|
| 2764 |
return _add_connecting |
| 2765 |
|
| 2766 |
def make_finished_connecting(proxy_name: str) -> Callable[[str, bool], None]: |
| 2767 |
def _finished_connecting(addr: str, success: bool) -> None: |
| 2768 |
if not success: |
| 2769 |
proxy_allocations[proxy_name].discard(addr) |
| 2770 |
|
| 2771 |
return _finished_connecting |
| 2772 |
|
| 2773 |
# Mock get_allocations and connection tracking |
| 2774 |
with ( |
| 2775 |
patch.object( |
| 2776 |
proxy1, "get_allocations", lambda: get_proxy_allocations("proxy1") |
| 2777 |
), |
| 2778 |
patch.object( |
| 2779 |
proxy2, "get_allocations", lambda: get_proxy_allocations("proxy2") |
| 2780 |
), |
| 2781 |
patch.object( |
| 2782 |
proxy3, "get_allocations", lambda: get_proxy_allocations("proxy3") |
| 2783 |
), |
| 2784 |
patch.object(proxy1, "_add_connecting", make_add_connecting("proxy1")), |
| 2785 |
patch.object(proxy2, "_add_connecting", make_add_connecting("proxy2")), |
| 2786 |
patch.object(proxy3, "_add_connecting", make_add_connecting("proxy3")), |
| 2787 |
patch.object( |
| 2788 |
proxy1, "_finished_connecting", make_finished_connecting("proxy1") |
| 2789 |
), |
| 2790 |
patch.object( |
| 2791 |
proxy2, "_finished_connecting", make_finished_connecting("proxy2") |
| 2792 |
), |
| 2793 |
patch.object( |
| 2794 |
proxy3, "_finished_connecting", make_finished_connecting("proxy3") |
| 2795 |
), |
| 2796 |
): |
| 2797 |
cancel1 = manager.async_register_scanner(proxy1) |
| 2798 |
cancel2 = manager.async_register_scanner(proxy2) |
| 2799 |
cancel3 = manager.async_register_scanner(proxy3) |
| 2800 |
|
| 2801 |
# Create 7 devices to connect |
| 2802 |
device_addresses = [f"AA:BB:CC:DD:EE:0{i}" for i in range(1, 8)] |
| 2803 |
|
| 2804 |
# Inject advertisements for all devices on all proxies |
| 2805 |
for i, address in enumerate(device_addresses, 1): |
| 2806 |
# Good signal on proxy1 |
| 2807 |
device1 = generate_ble_device(address, f"Device {i}", {"source": "proxy1"}) |
| 2808 |
adv_data1 = generate_advertisement_data(local_name=f"Device {i}", rssi=-60) |
| 2809 |
proxy1.inject_advertisement(device1, adv_data1) |
| 2810 |
|
| 2811 |
# Good signal on proxy2 (exactly same as proxy1) |
| 2812 |
device2 = generate_ble_device(address, f"Device {i}", {"source": "proxy2"}) |
| 2813 |
adv_data2 = generate_advertisement_data(local_name=f"Device {i}", rssi=-60) |
| 2814 |
proxy2.inject_advertisement(device2, adv_data2) |
| 2815 |
|
| 2816 |
# Bad signal on proxy3 |
| 2817 |
device3 = generate_ble_device(address, f"Device {i}", {"source": "proxy3"}) |
| 2818 |
adv_data3 = generate_advertisement_data(local_name=f"Device {i}", rssi=-95) |
| 2819 |
proxy3.inject_advertisement(device3, adv_data3) |
| 2820 |
|
| 2821 |
await asyncio.sleep(0) |
| 2822 |
|
| 2823 |
# Clear the connection tracker before starting |
| 2824 |
connection_tracker.clear() |
| 2825 |
|
| 2826 |
async def connect_device(address: str) -> tuple[str, str | None]: |
| 2827 |
"""Try to connect to a device.""" |
| 2828 |
client = bleak.BleakClient(address) |
| 2829 |
try: |
| 2830 |
await client.connect() |
| 2831 |
# The connection tracker should have recorded which backend was used |
| 2832 |
return address, connection_tracker.get(address, "unknown") |
| 2833 |
except BleakError: |
| 2834 |
# Connection failed (no available backend) |
| 2835 |
return address, None |
| 2836 |
|
| 2837 |
# Simulate thundering herd - all devices try to connect at once |
| 2838 |
tasks = [connect_device(addr) for addr in device_addresses] |
| 2839 |
results = await asyncio.gather(*tasks, return_exceptions=True) |
| 2840 |
|
| 2841 |
# Process results |
| 2842 |
connection_results = {} |
| 2843 |
for result in results: |
| 2844 |
if isinstance(result, tuple): |
| 2845 |
address, proxy = result |
| 2846 |
connection_results[address] = proxy |
| 2847 |
|
| 2848 |
# Count connections per proxy |
| 2849 |
proxy1_connections = [ |
| 2850 |
addr for addr, p in connection_results.items() if p == "proxy1" |
| 2851 |
] |
| 2852 |
proxy2_connections = [ |
| 2853 |
addr for addr, p in connection_results.items() if p == "proxy2" |
| 2854 |
] |
| 2855 |
proxy3_connections = [ |
| 2856 |
addr for addr, p in connection_results.items() if p == "proxy3" |
| 2857 |
] |
| 2858 |
failed_connections = [ |
| 2859 |
addr for addr, p in connection_results.items() if p is None |
| 2860 |
] |
| 2861 |
|
| 2862 |
# Verify constraints |
| 2863 |
# 1. No proxy should exceed its slot limit |
| 2864 |
assert len(proxy1_connections) <= 3, ( |
| 2865 |
f"Proxy1 exceeded slot limit: {len(proxy1_connections)} > 3" |
| 2866 |
) |
| 2867 |
assert len(proxy2_connections) <= 3, ( |
| 2868 |
f"Proxy2 exceeded slot limit: {len(proxy2_connections)} > 3" |
| 2869 |
) |
| 2870 |
assert len(proxy3_connections) <= 3, ( |
| 2871 |
f"Proxy3 exceeded slot limit: {len(proxy3_connections)} > 3" |
| 2872 |
) |
| 2873 |
|
| 2874 |
# 2. Good signal proxies should be preferred and fill up first |
| 2875 |
good_proxy_total = len(proxy1_connections) + len(proxy2_connections) |
| 2876 |
assert good_proxy_total == 6, ( |
| 2877 |
f"Expected exactly 6 connections on good proxies, got {good_proxy_total}" |
| 2878 |
) |
| 2879 |
|
| 2880 |
# 3. All 7 devices should connect (6 to good proxies, 1 to bad proxy) |
| 2881 |
total_connected = ( |
| 2882 |
len(proxy1_connections) + len(proxy2_connections) + len(proxy3_connections) |
| 2883 |
) |
| 2884 |
assert total_connected == 7, ( |
| 2885 |
f"Expected all 7 devices to connect, but only {total_connected} did" |
| 2886 |
) |
| 2887 |
|
| 2888 |
# 4. The 7th device should go to proxy3 since good ones are full |
| 2889 |
assert len(proxy3_connections) == 1, ( |
| 2890 |
f"Expected exactly 1 connection on proxy3, got {len(proxy3_connections)}" |
| 2891 |
) |
| 2892 |
|
| 2893 |
# 5. Verify good distribution across proxy1 and proxy2 |
| 2894 |
# Both should have roughly equal load (3 connections each) |
| 2895 |
assert len(proxy1_connections) == 3, ( |
| 2896 |
f"Expected proxy1 to have 3 connections, got {len(proxy1_connections)}" |
| 2897 |
) |
| 2898 |
assert len(proxy2_connections) == 3, ( |
| 2899 |
f"Expected proxy2 to have 3 connections, got {len(proxy2_connections)}" |
| 2900 |
) |
| 2901 |
|
| 2902 |
# 6. No connections should fail |
| 2903 |
assert len(failed_connections) == 0, ( |
| 2904 |
f"Expected no failed connections, but {len(failed_connections)} failed" |
| 2905 |
) |
| 2906 |
|
| 2907 |
# Clean up |
| 2908 |
cancel1() |
| 2909 |
cancel2() |
| 2910 |
cancel3() |
| 2911 |
|
| 2912 |
|
| 2913 |
@pytest.mark.asyncio |
| 2914 |
async def test_backend_name_from_tuple( |
| 2915 |
enable_bluetooth: None, |
| 2916 |
install_bleak_catcher: None, |
| 2917 |
mock_platform_client: None, |
| 2918 |
) -> None: |
| 2919 |
"""Test that backend name is extracted from tuple (bleak 2.0.0+).""" |
| 2920 |
manager = _get_manager() |
| 2921 |
hci0_device_advs, cancel_hci0, _ = _generate_scanners_with_fake_devices() |
| 2922 |
|
| 2923 |
with patch( |
| 2924 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 2925 |
return_value=(FakeBleakClient, "TestBackend"), |
| 2926 |
): |
| 2927 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 2928 |
client = bleak.BleakClient(ble_device) |
| 2929 |
|
| 2930 |
# Access the wrapped backend through the client |
| 2931 |
# The backend name should be extracted from the tuple |
| 2932 |
wrapped_backend = client._async_get_best_available_backend_and_device(manager) |
| 2933 |
assert wrapped_backend.backend_name == "TestBackend" |
| 2934 |
assert wrapped_backend.client == FakeBleakClient |
| 2935 |
|
| 2936 |
cancel_hci0() |
| 2937 |
|
| 2938 |
|
| 2939 |
@pytest.mark.asyncio |
| 2940 |
async def test_backend_name_from_class( |
| 2941 |
enable_bluetooth: None, |
| 2942 |
install_bleak_catcher: None, |
| 2943 |
mock_platform_client: None, |
| 2944 |
) -> None: |
| 2945 |
"""Test that backend name is derived from class name (pre-bleak 2.0.0).""" |
| 2946 |
manager = _get_manager() |
| 2947 |
hci0_device_advs, cancel_hci0, _ = _generate_scanners_with_fake_devices() |
| 2948 |
|
| 2949 |
with patch( |
| 2950 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 2951 |
return_value=FakeBleakClient, |
| 2952 |
): |
| 2953 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 2954 |
client = bleak.BleakClient(ble_device) |
| 2955 |
|
| 2956 |
# Access the wrapped backend through the client |
| 2957 |
# The backend name should be derived from the class name |
| 2958 |
wrapped_backend = client._async_get_best_available_backend_and_device(manager) |
| 2959 |
assert wrapped_backend.backend_name == "type" |
| 2960 |
assert wrapped_backend.client == FakeBleakClient |
| 2961 |
|
| 2962 |
cancel_hci0() |
| 2963 |
|
| 2964 |
|
| 2965 |
@pytest.mark.skipif( |
| 2966 |
sys.platform == "win32", |
| 2967 |
reason="dbus_fast (BlueZ backend) does not import on Windows", |
| 2968 |
) |
| 2969 |
@pytest.mark.asyncio |
| 2970 |
async def test_connect_uses_real_bluez_backend_signature( |
| 2971 |
enable_bluetooth: None, |
| 2972 |
install_bleak_catcher: None, |
| 2973 |
) -> None: |
| 2974 |
""" |
| 2975 |
Ensure backend kwargs satisfy the real bleak BlueZ signature. |
| 2976 |
|
| 2977 |
Regression: kwargs passed to the backend client must satisfy the |
| 2978 |
real bleak backend signature, not just FakeBleakClient's ``**kwargs``. |
| 2979 |
|
| 2980 |
bleak 3.0 made ``bluez`` a required keyword-only arg on |
| 2981 |
``BleakClientBlueZDBus.__init__``; because HaBleakClientWrapper bypasses |
| 2982 |
``BleakClient.__init__`` and constructs the backend directly, the default |
| 2983 |
supplied by the high-level constructor never reaches the backend. The |
| 2984 |
rest of the suite mocks the platform backend with FakeBleakClient (which |
| 2985 |
accepts ``**kwargs``) so signature drift slips through. This test wires |
| 2986 |
in the real BlueZ backend class so a future required kwarg fails here. |
| 2987 |
""" |
| 2988 |
from bleak.backends.bluezdbus.client import ( # noqa: PLC0415 |
| 2989 |
BleakClientBlueZDBus, |
| 2990 |
) |
| 2991 |
|
| 2992 |
hci0_device_advs, cancel_hci0, _ = _generate_scanners_with_fake_devices() |
| 2993 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 2994 |
|
| 2995 |
with ( |
| 2996 |
patch( |
| 2997 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 2998 |
return_value=BleakClientBlueZDBus, |
| 2999 |
), |
| 3000 |
patch.object(BleakClientBlueZDBus, "connect", AsyncMock(return_value=True)), |
| 3001 |
patch.object(BleakClientBlueZDBus, "is_connected", True), |
| 3002 |
patch.object(BleakClientBlueZDBus, "disconnect", AsyncMock(return_value=True)), |
| 3003 |
): |
| 3004 |
client = bleak.BleakClient(ble_device) |
| 3005 |
await client.connect() |
| 3006 |
assert isinstance(client._backend, BleakClientBlueZDBus) |
| 3007 |
await client.disconnect() |
| 3008 |
|
| 3009 |
cancel_hci0() |
| 3010 |
|
| 3011 |
|
| 3012 |
@pytest.mark.asyncio |
| 3013 |
async def test_backend_name_in_logs( |
| 3014 |
enable_bluetooth: None, |
| 3015 |
install_bleak_catcher: None, |
| 3016 |
mock_platform_client: None, |
| 3017 |
caplog: pytest.LogCaptureFixture, |
| 3018 |
) -> None: |
| 3019 |
"""Test that backend name appears in debug logs.""" |
| 3020 |
caplog.set_level(logging.DEBUG) |
| 3021 |
|
| 3022 |
hci0_device_advs, cancel_hci0, _ = _generate_scanners_with_fake_devices() |
| 3023 |
|
| 3024 |
with patch( |
| 3025 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 3026 |
return_value=(FakeBleakClient, "TestBackend"), |
| 3027 |
): |
| 3028 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 3029 |
with patch.object(FakeBleakClient, "is_connected", return_value=True): |
| 3030 |
client = bleak.BleakClient(ble_device) |
| 3031 |
await client.connect() |
| 3032 |
|
| 3033 |
# Check that the backend name appears in the logs |
| 3034 |
assert any( |
| 3035 |
"[TestBackend]" in record.message |
| 3036 |
for record in caplog.records |
| 3037 |
if "Connecting via" in record.message |
| 3038 |
), f"Backend name not found in logs: {[r.message for r in caplog.records]}" |
| 3039 |
assert any( |
| 3040 |
"[TestBackend]" in record.message |
| 3041 |
for record in caplog.records |
| 3042 |
if "Connected via" in record.message |
| 3043 |
), f"Backend name not found in logs: {[r.message for r in caplog.records]}" |
| 3044 |
|
| 3045 |
await client.disconnect() |
| 3046 |
|
| 3047 |
cancel_hci0() |
| 3048 |
|
| 3049 |
|
| 3050 |
@pytest.mark.asyncio |
| 3051 |
async def test_set_connection_params_with_backend( |
| 3052 |
two_adapters: None, |
| 3053 |
enable_bluetooth: None, |
| 3054 |
install_bleak_catcher: None, |
| 3055 |
caplog: pytest.LogCaptureFixture, |
| 3056 |
) -> None: |
| 3057 |
"""Test that set_connection_params delegates to backend when it has the method.""" |
| 3058 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 3059 |
|
| 3060 |
class FakeBleakClientWithConnParams(BaseFakeBleakClient): |
| 3061 |
"""Fake bleak client that supports set_connection_params.""" |
| 3062 |
|
| 3063 |
connected = False |
| 3064 |
set_connection_params = AsyncMock() |
| 3065 |
|
| 3066 |
async def connect(self, *args, **kwargs): |
| 3067 |
"""Connect.""" |
| 3068 |
self.connected = True |
| 3069 |
await asyncio.sleep(0) |
| 3070 |
|
| 3071 |
@property |
| 3072 |
def is_connected(self) -> bool: |
| 3073 |
return self.connected |
| 3074 |
|
| 3075 |
with patch( |
| 3076 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 3077 |
return_value=FakeBleakClientWithConnParams, |
| 3078 |
): |
| 3079 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 3080 |
client = bleak.BleakClient(ble_device) |
| 3081 |
await client.connect() |
| 3082 |
|
| 3083 |
await client.set_connection_params(800, 800, 0, 300) |
| 3084 |
|
| 3085 |
FakeBleakClientWithConnParams.set_connection_params.assert_called_once_with( |
| 3086 |
800, 800, 0, 300 |
| 3087 |
) |
| 3088 |
|
| 3089 |
cancel_hci0() |
| 3090 |
cancel_hci1() |
| 3091 |
|
| 3092 |
|
| 3093 |
@pytest.mark.asyncio |
| 3094 |
async def test_set_connection_params_with_bluez_mgmt( |
| 3095 |
two_adapters: None, |
| 3096 |
enable_bluetooth: None, |
| 3097 |
install_bleak_catcher: None, |
| 3098 |
caplog: pytest.LogCaptureFixture, |
| 3099 |
) -> None: |
| 3100 |
"""Test that set_connection_params routes to mgmt_ctl when no backend method.""" |
| 3101 |
manager = _get_manager() |
| 3102 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 3103 |
|
| 3104 |
mock_mgmt_ctl = Mock() |
| 3105 |
mock_mgmt_ctl.load_conn_params.return_value = True |
| 3106 |
|
| 3107 |
class FakeBleakClientTracksConnect(BaseFakeBleakClient): |
| 3108 |
"""Fake bleak client that tracks connect.""" |
| 3109 |
|
| 3110 |
connected = False |
| 3111 |
|
| 3112 |
async def connect(self, *args, **kwargs): |
| 3113 |
"""Connect.""" |
| 3114 |
self.connected = True |
| 3115 |
await asyncio.sleep(0) |
| 3116 |
|
| 3117 |
@property |
| 3118 |
def is_connected(self) -> bool: |
| 3119 |
return self.connected |
| 3120 |
|
| 3121 |
with ( |
| 3122 |
patch.object(manager, "get_bluez_mgmt_ctl", return_value=mock_mgmt_ctl), |
| 3123 |
patch( |
| 3124 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 3125 |
return_value=FakeBleakClientTracksConnect, |
| 3126 |
), |
| 3127 |
): |
| 3128 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 3129 |
client = bleak.BleakClient(ble_device) |
| 3130 |
await client.connect() |
| 3131 |
|
| 3132 |
# Reset mock to isolate set_connection_params call from connect-time calls |
| 3133 |
mock_mgmt_ctl.reset_mock() |
| 3134 |
|
| 3135 |
await client.set_connection_params(800, 800, 0, 300) |
| 3136 |
|
| 3137 |
mock_mgmt_ctl.load_conn_params_explicit.assert_called_once_with( |
| 3138 |
0, # adapter_idx for hci0 |
| 3139 |
"00:00:00:00:00:01", # address |
| 3140 |
1, # BDADDR_LE_PUBLIC (default) |
| 3141 |
800, |
| 3142 |
800, |
| 3143 |
0, |
| 3144 |
300, |
| 3145 |
) |
| 3146 |
|
| 3147 |
cancel_hci0() |
| 3148 |
cancel_hci1() |
| 3149 |
|
| 3150 |
|
| 3151 |
@pytest.mark.asyncio |
| 3152 |
async def test_set_connection_params_no_mgmt_no_backend( |
| 3153 |
two_adapters: None, |
| 3154 |
enable_bluetooth: None, |
| 3155 |
install_bleak_catcher: None, |
| 3156 |
caplog: pytest.LogCaptureFixture, |
| 3157 |
) -> None: |
| 3158 |
"""Test set_connection_params no-ops without mgmt or backend.""" |
| 3159 |
manager = _get_manager() |
| 3160 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 3161 |
|
| 3162 |
class FakeBleakClientTracksConnect(BaseFakeBleakClient): |
| 3163 |
"""Fake bleak client that tracks connect.""" |
| 3164 |
|
| 3165 |
connected = False |
| 3166 |
|
| 3167 |
async def connect(self, *args, **kwargs): |
| 3168 |
"""Connect.""" |
| 3169 |
self.connected = True |
| 3170 |
await asyncio.sleep(0) |
| 3171 |
|
| 3172 |
@property |
| 3173 |
def is_connected(self) -> bool: |
| 3174 |
return self.connected |
| 3175 |
|
| 3176 |
with ( |
| 3177 |
patch.object(manager, "get_bluez_mgmt_ctl", return_value=None), |
| 3178 |
patch( |
| 3179 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 3180 |
return_value=FakeBleakClientTracksConnect, |
| 3181 |
), |
| 3182 |
): |
| 3183 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 3184 |
client = bleak.BleakClient(ble_device) |
| 3185 |
await client.connect() |
| 3186 |
|
| 3187 |
# Should not raise any error |
| 3188 |
await client.set_connection_params(800, 800, 0, 300) |
| 3189 |
|
| 3190 |
assert "does not support setting connection parameters" in caplog.text |
| 3191 |
|
| 3192 |
cancel_hci0() |
| 3193 |
cancel_hci1() |
| 3194 |
|
| 3195 |
|
| 3196 |
@pytest.mark.asyncio |
| 3197 |
async def test_clear_cache_with_backend( |
| 3198 |
two_adapters: None, |
| 3199 |
enable_bluetooth: None, |
| 3200 |
install_bleak_catcher: None, |
| 3201 |
) -> None: |
| 3202 |
"""Test clear_cache delegates to the backend when it supports clear_cache.""" |
| 3203 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 3204 |
|
| 3205 |
class FakeBleakClientWithClearCache(BaseFakeBleakClient): |
| 3206 |
"""Fake bleak client that supports clear_cache.""" |
| 3207 |
|
| 3208 |
connected = False |
| 3209 |
clear_cache = AsyncMock(return_value=True) |
| 3210 |
|
| 3211 |
async def connect(self, *args, **kwargs): |
| 3212 |
"""Connect.""" |
| 3213 |
self.connected = True |
| 3214 |
await asyncio.sleep(0) |
| 3215 |
|
| 3216 |
@property |
| 3217 |
def is_connected(self) -> bool: |
| 3218 |
return self.connected |
| 3219 |
|
| 3220 |
with patch( |
| 3221 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 3222 |
return_value=FakeBleakClientWithClearCache, |
| 3223 |
): |
| 3224 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 3225 |
client = bleak.BleakClient(ble_device) |
| 3226 |
await client.connect() |
| 3227 |
|
| 3228 |
assert await client.clear_cache() is True |
| 3229 |
FakeBleakClientWithClearCache.clear_cache.assert_called_once_with() |
| 3230 |
|
| 3231 |
cancel_hci0() |
| 3232 |
cancel_hci1() |
| 3233 |
|
| 3234 |
|
| 3235 |
@pytest.mark.asyncio |
| 3236 |
async def test_clear_cache_without_backend( |
| 3237 |
enable_bluetooth: None, |
| 3238 |
install_bleak_catcher: None, |
| 3239 |
) -> None: |
| 3240 |
"""Test clear_cache falls back to the library helper without a backend.""" |
| 3241 |
client = bleak.BleakClient("00:00:00:00:00:01") |
| 3242 |
|
| 3243 |
with patch( |
| 3244 |
"habluetooth.wrappers.clear_cache", |
| 3245 |
AsyncMock(return_value=True), |
| 3246 |
) as mock_clear_cache: |
| 3247 |
assert await client.clear_cache() is True |
| 3248 |
|
| 3249 |
mock_clear_cache.assert_awaited_once_with("00:00:00:00:00:01") |
| 3250 |
|
| 3251 |
|
| 3252 |
@pytest.mark.asyncio |
| 3253 |
async def test_set_disconnected_callback_with_backend( |
| 3254 |
two_adapters: None, |
| 3255 |
enable_bluetooth: None, |
| 3256 |
install_bleak_catcher: None, |
| 3257 |
) -> None: |
| 3258 |
"""Test set_disconnected_callback forwards to the backend once connected.""" |
| 3259 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 3260 |
|
| 3261 |
class FakeBleakClientTracksDisconnectCb(BaseFakeBleakClient): |
| 3262 |
"""Fake bleak client that records set_disconnected_callback.""" |
| 3263 |
|
| 3264 |
connected = False |
| 3265 |
set_disconnected_callback = Mock() |
| 3266 |
|
| 3267 |
async def connect(self, *args, **kwargs): |
| 3268 |
"""Connect.""" |
| 3269 |
self.connected = True |
| 3270 |
await asyncio.sleep(0) |
| 3271 |
|
| 3272 |
@property |
| 3273 |
def is_connected(self) -> bool: |
| 3274 |
return self.connected |
| 3275 |
|
| 3276 |
with patch( |
| 3277 |
"habluetooth.wrappers.get_platform_client_backend_type", |
| 3278 |
return_value=FakeBleakClientTracksDisconnectCb, |
| 3279 |
): |
| 3280 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 3281 |
client = bleak.BleakClient(ble_device) |
| 3282 |
await client.connect() |
| 3283 |
|
| 3284 |
callback = Mock() |
| 3285 |
client.set_disconnected_callback(callback) |
| 3286 |
|
| 3287 |
FakeBleakClientTracksDisconnectCb.set_disconnected_callback.assert_called_once() |
| 3288 |
|
| 3289 |
cancel_hci0() |
| 3290 |
cancel_hci1() |
| 3291 |
|
| 3292 |
|
| 3293 |
@pytest.mark.asyncio |
| 3294 |
async def test_disconnect_without_backend( |
| 3295 |
enable_bluetooth: None, |
| 3296 |
install_bleak_catcher: None, |
| 3297 |
) -> None: |
| 3298 |
"""Test disconnect is a no-op when no backend has been connected.""" |
| 3299 |
client = bleak.BleakClient("00:00:00:00:00:01") |
| 3300 |
|
| 3301 |
# Should return cleanly without raising even though connect() never ran. |
| 3302 |
assert await client.disconnect() is None |
| 3303 |
|
| 3304 |
|
| 3305 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 3306 |
def test_set_scanning_filter_applies_uuid_filter( |
| 3307 |
caplog: pytest.LogCaptureFixture, |
| 3308 |
) -> None: |
| 3309 |
"""Test set_scanning_filter stores an effective UUID filter change.""" |
| 3310 |
scanner = HaBleakScannerWrapper() |
| 3311 |
uuid = "cba20d00-224d-11e6-9fb8-0002a5d5c51b" |
| 3312 |
|
| 3313 |
# A real UUID filter is an effective change (_map_filters returns True), |
| 3314 |
# but the scanner is not started, so set_scanning_filter short-circuits on |
| 3315 |
# the _started guard and only stores the mapped filter. |
| 3316 |
scanner.set_scanning_filter(service_uuids=[uuid]) |
| 3317 |
|
| 3318 |
assert scanner._mapped_filters == {FILTER_UUIDS: {uuid}} |
| 3319 |
assert "Only UUIDs filters are supported" not in caplog.text |
| 3320 |
|
| 3321 |
|
| 3322 |
@pytest.mark.asyncio |
| 3323 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 3324 |
async def test_set_connection_params_no_backend_no_scanner_noop( |
| 3325 |
caplog: pytest.LogCaptureFixture, |
| 3326 |
) -> None: |
| 3327 |
""" |
| 3328 |
set_connection_params is a silent no-op before any backend is chosen. |
| 3329 |
|
| 3330 |
Before connect() runs there is no backend, no connected scanner/device, and |
| 3331 |
no mgmt path, so the call must return without raising and without emitting |
| 3332 |
the unsupported-backend warning (that warning is only for a connected |
| 3333 |
backend that lacks the capability). |
| 3334 |
""" |
| 3335 |
client = bleak.BleakClient("00:00:00:00:00:01") |
| 3336 |
|
| 3337 |
await client.set_connection_params(800, 800, 0, 300) |
| 3338 |
|
| 3339 |
assert "does not support setting connection parameters" not in caplog.text |
| 3340 |
|
| 3341 |
|
| 3342 |
@pytest.mark.asyncio |
| 3343 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 3344 |
async def test_set_disconnected_callback_without_backend() -> None: |
| 3345 |
""" |
| 3346 |
set_disconnected_callback stores the callback before a backend exists. |
| 3347 |
|
| 3348 |
Called prior to connect(), there is no backend to forward to, so the wrapper |
| 3349 |
must accept and retain the callback without raising. |
| 3350 |
""" |
| 3351 |
client = bleak.BleakClient("00:00:00:00:00:01") |
| 3352 |
callback = Mock() |
| 3353 |
|
| 3354 |
# Must not raise even though connect() never ran. |
| 3355 |
client.set_disconnected_callback(callback) |
| 3356 |
|
| 3357 |
# The callback is retained for later (pre-backend) use. |
| 3358 |
assert client._HaBleakClientWrapper__disconnected_callback is callback |
| 3359 |
|
| 3360 |
|
| 3361 |
@pytest.mark.asyncio |
| 3362 |
async def test_connect_as_retry_client_skips_warning( |
| 3363 |
two_adapters: None, |
| 3364 |
enable_bluetooth: None, |
| 3365 |
install_bleak_catcher: None, |
| 3366 |
mock_platform_client: None, |
| 3367 |
caplog: pytest.LogCaptureFixture, |
| 3368 |
) -> None: |
| 3369 |
""" |
| 3370 |
A retry-client connect skips the bleak-retry-connector warning. |
| 3371 |
|
| 3372 |
Passing ``_is_retry_client=True`` marks the wrapper as driven by |
| 3373 |
bleak-retry-connector's establish_connection, so the "called without |
| 3374 |
bleak-retry-connector" guidance warning must not fire. Pinning the logger |
| 3375 |
above DEBUG also exercises the non-debug connect path (the debug-only |
| 3376 |
description lookup and connect/connected log lines are skipped). |
| 3377 |
""" |
| 3378 |
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices() |
| 3379 |
ble_device = hci0_device_advs["00:00:00:00:00:01"][0] |
| 3380 |
client = bleak.BleakClient(ble_device, _is_retry_client=True) |
| 3381 |
|
| 3382 |
wrappers_logger = logging.getLogger("habluetooth.wrappers") |
| 3383 |
previous_level = wrappers_logger.level |
| 3384 |
wrappers_logger.setLevel(logging.INFO) |
| 3385 |
try: |
| 3386 |
with patch.object(FakeBleakClient, "is_connected", return_value=True): |
| 3387 |
await client.connect() |
| 3388 |
assert client.is_connected |
| 3389 |
finally: |
| 3390 |
wrappers_logger.setLevel(previous_level) |
| 3391 |
|
| 3392 |
assert "without bleak-retry-connector" not in caplog.text |
| 3393 |
|
| 3394 |
cancel_hci0() |
| 3395 |
cancel_hci1() |
| 3396 |
|
| 3397 |
|
| 3398 |
@pytest.mark.asyncio |
| 3399 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 3400 |
async def test_connect_no_scanners_raises_no_backend() -> None: |
| 3401 |
""" |
| 3402 |
connect() raises the generic no-backend error when no scanners exist. |
| 3403 |
|
| 3404 |
With no scanners registered at all, the passive-only diagnostic branch is |
| 3405 |
skipped (it only applies when scanners exist but none are connectable) and |
| 3406 |
the wrapper falls through to the generic no-available-slot error. |
| 3407 |
""" |
| 3408 |
client = bleak.BleakClient("00:00:00:00:00:01") |
| 3409 |
|
| 3410 |
with pytest.raises( |
| 3411 |
BleakError, |
| 3412 |
match=( |
| 3413 |
"No backend with an available connection slot that can reach " |
| 3414 |
"address 00:00:00:00:00:01 was found" |
| 3415 |
), |
| 3416 |
): |
| 3417 |
await client.connect() |