| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import itertools |
| 5 |
from typing import Any |
| 6 |
from unittest.mock import AsyncMock, MagicMock, Mock, patch |
| 7 |
|
| 8 |
import bleak |
| 9 |
import pytest |
| 10 |
from bleak import BleakClient, BleakError |
| 11 |
from bleak.backends.bluezdbus import defs |
| 12 |
from bleak.backends.bluezdbus.manager import DeviceWatcher |
| 13 |
from bleak.backends.device import BLEDevice |
| 14 |
from bleak.backends.scanner import AdvertisementData |
| 15 |
from bleak.backends.service import BleakGATTService, BleakGATTServiceCollection |
| 16 |
from bleak.exc import BleakDBusError, BleakDeviceNotFoundError |
| 17 |
|
| 18 |
import bleak_retry_connector |
| 19 |
from bleak_retry_connector import ( |
| 20 |
BLEAK_BACKOFF_TIME, |
| 21 |
BLEAK_DBUS_BACKOFF_TIME, |
| 22 |
BLEAK_DISCONNECTED_BACKOFF_TIME, |
| 23 |
BLEAK_OUT_OF_SLOTS_BACKOFF_TIME, |
| 24 |
BLEAK_TRANSIENT_BACKOFF_TIME, |
| 25 |
BLEAK_TRANSIENT_LONG_BACKOFF_TIME, |
| 26 |
BLEAK_TRANSIENT_MEDIUM_BACKOFF_TIME, |
| 27 |
MAX_TRANSIENT_ERRORS, |
| 28 |
BleakAbortedError, |
| 29 |
BleakClientWithServiceCache, |
| 30 |
BleakConnectionError, |
| 31 |
BleakNotFoundError, |
| 32 |
BleakOutOfConnectionSlotsError, |
| 33 |
ble_device_description, |
| 34 |
ble_device_has_changed, |
| 35 |
calculate_backoff_time, |
| 36 |
clear_cache, |
| 37 |
close_stale_connections, |
| 38 |
close_stale_connections_by_address, |
| 39 |
establish_connection, |
| 40 |
get_connected_devices, |
| 41 |
get_device, |
| 42 |
get_device_by_adapter, |
| 43 |
restore_discoveries, |
| 44 |
restore_discoveries_sync, |
| 45 |
retry_bluetooth_connection_error, |
| 46 |
) |
| 47 |
from bleak_retry_connector.bleak_manager import _reset_dbus_socket_cache |
| 48 |
|
| 49 |
|
| 50 |
def make_scripted_client( |
| 51 |
script: list[BaseException | None], |
| 52 |
) -> tuple[type[BleakClient], dict[str, int]]: |
| 53 |
"""Build a ``BleakClient`` subclass whose ``connect()`` replays ``script``. |
| 54 |
|
| 55 |
Each call pops the next entry from ``script`` (by index): ``None`` means |
| 56 |
a successful connect, an exception instance is raised. Returns the class |
| 57 |
paired with an ``attempts`` counter dict that callers can read to assert |
| 58 |
on how many times ``connect()`` was invoked. |
| 59 |
""" |
| 60 |
attempts = {"n": 0} |
| 61 |
|
| 62 |
class _ScriptedClient(BleakClient): |
| 63 |
def __init__(self, *args: Any, **kwargs: Any) -> None: |
| 64 |
pass |
| 65 |
|
| 66 |
async def connect(self, *args: Any, **kwargs: Any) -> None: |
| 67 |
exc = script[attempts["n"]] |
| 68 |
attempts["n"] += 1 |
| 69 |
if exc is not None: |
| 70 |
raise exc |
| 71 |
|
| 72 |
async def disconnect(self, *args: Any, **kwargs: Any) -> None: |
| 73 |
pass |
| 74 |
|
| 75 |
return _ScriptedClient, attempts |
| 76 |
|
| 77 |
|
| 78 |
@pytest.mark.asyncio |
| 79 |
async def test_establish_connection_works_first_time(): |
| 80 |
class FakeBleakClient(BleakClient): |
| 81 |
async def connect(self, *args, **kwargs): |
| 82 |
pass |
| 83 |
|
| 84 |
async def disconnect(self, *args, **kwargs): |
| 85 |
pass |
| 86 |
|
| 87 |
client = await establish_connection( |
| 88 |
FakeBleakClient, MagicMock(), "test", disconnected_callback=MagicMock() |
| 89 |
) |
| 90 |
assert isinstance(client, FakeBleakClient) |
| 91 |
|
| 92 |
|
| 93 |
@pytest.mark.asyncio |
| 94 |
async def test_establish_connection_passes_retry_client_flag(): |
| 95 |
"""Test that establish_connection passes _is_retry_client=True to the client.""" |
| 96 |
received_kwargs = {} |
| 97 |
|
| 98 |
class FakeBleakClient(BleakClient): |
| 99 |
def __init__(self, *args, **kwargs): |
| 100 |
# Capture the kwargs passed to __init__ |
| 101 |
received_kwargs.update(kwargs) |
| 102 |
# Remove _is_retry_client before calling super() if it exists |
| 103 |
# since the base BleakClient doesn't expect it |
| 104 |
kwargs.pop("_is_retry_client", None) |
| 105 |
# Don't call super().__init__ to avoid platform-specific initialization |
| 106 |
self._device_path = None |
| 107 |
self._device_info = None |
| 108 |
self._backend = None |
| 109 |
|
| 110 |
async def connect(self, *args, **kwargs): |
| 111 |
pass |
| 112 |
|
| 113 |
async def disconnect(self, *args, **kwargs): |
| 114 |
pass |
| 115 |
|
| 116 |
device = MagicMock(spec=BLEDevice) |
| 117 |
device.address = "00:00:00:00:00:01" |
| 118 |
|
| 119 |
client = await establish_connection( |
| 120 |
FakeBleakClient, device, "test", disconnected_callback=MagicMock() |
| 121 |
) |
| 122 |
|
| 123 |
assert isinstance(client, FakeBleakClient) |
| 124 |
assert "_is_retry_client" in received_kwargs |
| 125 |
assert received_kwargs["_is_retry_client"] is True |
| 126 |
|
| 127 |
|
| 128 |
@pytest.mark.asyncio |
| 129 |
async def test_establish_connection_passes_pair_flag(): |
| 130 |
"""Test that establish_connection passes pair=True to the client.""" |
| 131 |
received_kwargs = {} |
| 132 |
|
| 133 |
class FakeBleakClient(BleakClient): |
| 134 |
def __init__(self, *args, **kwargs): |
| 135 |
# Capture the kwargs passed to __init__ |
| 136 |
received_kwargs.update(kwargs) |
| 137 |
# Remove kwargs that base BleakClient doesn't expect |
| 138 |
kwargs.pop("_is_retry_client", None) |
| 139 |
# Don't call super().__init__ to avoid platform-specific initialization |
| 140 |
self._device_path = None |
| 141 |
self._device_info = None |
| 142 |
self._backend = None |
| 143 |
|
| 144 |
async def connect(self, *args, **kwargs): |
| 145 |
pass |
| 146 |
|
| 147 |
async def disconnect(self, *args, **kwargs): |
| 148 |
pass |
| 149 |
|
| 150 |
device = MagicMock(spec=BLEDevice) |
| 151 |
device.address = "00:00:00:00:00:01" |
| 152 |
|
| 153 |
client = await establish_connection( |
| 154 |
FakeBleakClient, device, "test", disconnected_callback=MagicMock(), pair=True |
| 155 |
) |
| 156 |
|
| 157 |
assert isinstance(client, FakeBleakClient) |
| 158 |
assert "pair" in received_kwargs |
| 159 |
assert received_kwargs["pair"] is True |
| 160 |
|
| 161 |
|
| 162 |
@pytest.mark.asyncio |
| 163 |
async def test_establish_connection_with_cached_services(): |
| 164 |
class FakeBleakClient(BleakClient): |
| 165 |
def __init__(self, *args, **kwargs): |
| 166 |
super().__init__(*args, **kwargs) |
| 167 |
self._device_path = "/dev/test" |
| 168 |
|
| 169 |
async def connect(self, *args, **kwargs): |
| 170 |
return True |
| 171 |
|
| 172 |
async def disconnect(self, *args, **kwargs): |
| 173 |
pass |
| 174 |
|
| 175 |
async def get_services(self, *args, **kwargs): |
| 176 |
return [] |
| 177 |
|
| 178 |
class FakeBleakClientWithServiceCache(BleakClientWithServiceCache, FakeBleakClient): |
| 179 |
"""Fake BleakClientWithServiceCache.""" |
| 180 |
|
| 181 |
async def get_services(self, *args, **kwargs): |
| 182 |
return [] |
| 183 |
|
| 184 |
collection = BleakGATTServiceCollection() |
| 185 |
|
| 186 |
class FakeBluezManager: |
| 187 |
def __init__(self): |
| 188 |
self._services_cache = {} |
| 189 |
self._properties = { |
| 190 |
"/dev/test/service/1": { |
| 191 |
"UUID": "service", |
| 192 |
"Primary": True, |
| 193 |
"Characteristics": [], |
| 194 |
defs.GATT_SERVICE_INTERFACE: True, |
| 195 |
}, |
| 196 |
} |
| 197 |
|
| 198 |
bluez_manager = FakeBluezManager() |
| 199 |
|
| 200 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock( |
| 201 |
return_value=bluez_manager |
| 202 |
) |
| 203 |
|
| 204 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager_with_timeout = ( |
| 205 |
AsyncMock(return_value=bluez_manager) |
| 206 |
) |
| 207 |
bleak_retry_connector.bluez.defs = defs |
| 208 |
|
| 209 |
client = await establish_connection( |
| 210 |
FakeBleakClientWithServiceCache, |
| 211 |
MagicMock(), |
| 212 |
"test", |
| 213 |
disconnected_callback=MagicMock(), |
| 214 |
cached_services=collection, |
| 215 |
) |
| 216 |
|
| 217 |
assert isinstance(client, FakeBleakClientWithServiceCache) |
| 218 |
await client.get_services() is collection |
| 219 |
|
| 220 |
|
| 221 |
@pytest.mark.asyncio |
| 222 |
async def test_establish_connection_with_cached_services_that_have_vanished(): |
| 223 |
class FakeBleakClient(BleakClient): |
| 224 |
def __init__(self, *args, **kwargs): |
| 225 |
super().__init__(*args, **kwargs) |
| 226 |
self._device_path = "/dev/test" |
| 227 |
|
| 228 |
async def connect(self, *args, **kwargs): |
| 229 |
return True |
| 230 |
|
| 231 |
async def disconnect(self, *args, **kwargs): |
| 232 |
pass |
| 233 |
|
| 234 |
async def get_services(self, *args, **kwargs): |
| 235 |
return [] |
| 236 |
|
| 237 |
class FakeBleakClientWithServiceCache(BleakClientWithServiceCache, FakeBleakClient): |
| 238 |
"""Fake BleakClientWithServiceCache.""" |
| 239 |
|
| 240 |
async def get_services(self, *args, **kwargs): |
| 241 |
return [] |
| 242 |
|
| 243 |
collection = BleakGATTServiceCollection() |
| 244 |
|
| 245 |
class FakeBluezManager: |
| 246 |
def __init__(self): |
| 247 |
self._services_cache = {} |
| 248 |
self._properties = {} |
| 249 |
|
| 250 |
bluez_manager = FakeBluezManager() |
| 251 |
|
| 252 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock( |
| 253 |
return_value=bluez_manager |
| 254 |
) |
| 255 |
|
| 256 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager_with_timeout = ( |
| 257 |
AsyncMock(return_value=bluez_manager) |
| 258 |
) |
| 259 |
bleak_retry_connector.bluez.defs = defs |
| 260 |
|
| 261 |
client = await establish_connection( |
| 262 |
FakeBleakClientWithServiceCache, |
| 263 |
MagicMock(), |
| 264 |
"test", |
| 265 |
disconnected_callback=MagicMock(), |
| 266 |
cached_services=collection, |
| 267 |
) |
| 268 |
|
| 269 |
assert isinstance(client, FakeBleakClientWithServiceCache) |
| 270 |
await client.get_services() is collection |
| 271 |
|
| 272 |
|
| 273 |
@pytest.mark.asyncio |
| 274 |
async def test_establish_connection_can_cache_services_always_patched(): |
| 275 |
class FakeBleakClient(BleakClient): |
| 276 |
def __init__(self, *args, **kwargs): |
| 277 |
super().__init__(*args, **kwargs) |
| 278 |
self._device_path = "/dev/test" |
| 279 |
|
| 280 |
async def connect(self, *args, **kwargs): |
| 281 |
return True |
| 282 |
|
| 283 |
async def disconnect(self, *args, **kwargs): |
| 284 |
pass |
| 285 |
|
| 286 |
async def get_services(self, *args, **kwargs): |
| 287 |
return [] |
| 288 |
|
| 289 |
class FakeBleakClientWithServiceCache(BleakClientWithServiceCache, FakeBleakClient): |
| 290 |
"""Fake BleakClientWithServiceCache.""" |
| 291 |
|
| 292 |
collection = BleakGATTServiceCollection() |
| 293 |
|
| 294 |
class FakeBluezManager: |
| 295 |
def __init__(self): |
| 296 |
self._services_cache = {} |
| 297 |
self._properties = { |
| 298 |
"/dev/test/service/1": { |
| 299 |
"UUID": "service", |
| 300 |
"Primary": True, |
| 301 |
"Characteristics": [], |
| 302 |
defs.GATT_SERVICE_INTERFACE: True, |
| 303 |
}, |
| 304 |
} |
| 305 |
|
| 306 |
bluez_manager = FakeBluezManager() |
| 307 |
|
| 308 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock( |
| 309 |
return_value=bluez_manager |
| 310 |
) |
| 311 |
|
| 312 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager_with_timeout = ( |
| 313 |
AsyncMock(return_value=bluez_manager) |
| 314 |
) |
| 315 |
bleak_retry_connector.bluez.defs = defs |
| 316 |
|
| 317 |
client = await establish_connection( |
| 318 |
FakeBleakClientWithServiceCache, |
| 319 |
MagicMock(), |
| 320 |
"test", |
| 321 |
disconnected_callback=MagicMock(), |
| 322 |
cached_services=collection, |
| 323 |
) |
| 324 |
|
| 325 |
assert isinstance(client, FakeBleakClientWithServiceCache) |
| 326 |
await client.get_services() is collection |
| 327 |
|
| 328 |
|
| 329 |
@pytest.mark.asyncio |
| 330 |
async def test_establish_connection_can_cache_services_services_missing(): |
| 331 |
class FakeBleakClient(BleakClient): |
| 332 |
def __init__(self, *args, **kwargs): |
| 333 |
super().__init__(*args, **kwargs) |
| 334 |
self._device_path = "/dev/test" |
| 335 |
|
| 336 |
async def connect(self, *args, **kwargs): |
| 337 |
return True |
| 338 |
|
| 339 |
async def disconnect(self, *args, **kwargs): |
| 340 |
pass |
| 341 |
|
| 342 |
async def get_services(self, *args, **kwargs): |
| 343 |
return [] |
| 344 |
|
| 345 |
class FakeBleakClientWithServiceCache(BleakClientWithServiceCache, FakeBleakClient): |
| 346 |
"""Fake BleakClientWithServiceCache.""" |
| 347 |
|
| 348 |
collection = BleakGATTServiceCollection() |
| 349 |
|
| 350 |
class FakeBluezManager: |
| 351 |
def __init__(self): |
| 352 |
self._services_cache = {} |
| 353 |
self._properties = { |
| 354 |
"/dev/test2/service/1": { |
| 355 |
"UUID": "service", |
| 356 |
"Primary": True, |
| 357 |
"Characteristics": [], |
| 358 |
}, |
| 359 |
} |
| 360 |
|
| 361 |
bluez_manager = FakeBluezManager() |
| 362 |
|
| 363 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock( |
| 364 |
return_value=bluez_manager |
| 365 |
) |
| 366 |
|
| 367 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager_with_timeout = ( |
| 368 |
AsyncMock(return_value=bluez_manager) |
| 369 |
) |
| 370 |
bleak_retry_connector.bluez.defs = defs |
| 371 |
|
| 372 |
client = await establish_connection( |
| 373 |
FakeBleakClientWithServiceCache, |
| 374 |
MagicMock(), |
| 375 |
"test", |
| 376 |
disconnected_callback=MagicMock(), |
| 377 |
cached_services=collection, |
| 378 |
) |
| 379 |
|
| 380 |
assert isinstance(client, FakeBleakClientWithServiceCache) |
| 381 |
await client.get_services() is collection |
| 382 |
|
| 383 |
|
| 384 |
@pytest.mark.asyncio |
| 385 |
async def test_establish_connection_can_cache_services_newer_bleak(): |
| 386 |
class FakeBleakClient(BleakClient): |
| 387 |
async def connect(self, *args, **kwargs): |
| 388 |
return True |
| 389 |
|
| 390 |
async def disconnect(self, *args, **kwargs): |
| 391 |
pass |
| 392 |
|
| 393 |
async def get_services(self, *args, **kwargs): |
| 394 |
return [] |
| 395 |
|
| 396 |
class FakeBleakClientWithServiceCache(BleakClientWithServiceCache, FakeBleakClient): |
| 397 |
"""Fake BleakClientWithServiceCache.""" |
| 398 |
|
| 399 |
collection = BleakGATTServiceCollection() |
| 400 |
|
| 401 |
client = await establish_connection( |
| 402 |
FakeBleakClientWithServiceCache, |
| 403 |
MagicMock(), |
| 404 |
"test", |
| 405 |
disconnected_callback=MagicMock(), |
| 406 |
cached_services=collection, |
| 407 |
) |
| 408 |
|
| 409 |
assert isinstance(client, FakeBleakClientWithServiceCache) |
| 410 |
await client.get_services() is collection |
| 411 |
|
| 412 |
|
| 413 |
@pytest.mark.asyncio |
| 414 |
async def test_establish_connection_with_dangerous_use_cached_services(): |
| 415 |
class FakeBleakClient(BleakClient): |
| 416 |
async def connect(self, *args, **kwargs): |
| 417 |
return True |
| 418 |
|
| 419 |
async def disconnect(self, *args, **kwargs): |
| 420 |
pass |
| 421 |
|
| 422 |
async def get_services(self, *args, **kwargs): |
| 423 |
return [] |
| 424 |
|
| 425 |
class FakeBleakClientWithServiceCache(BleakClientWithServiceCache, FakeBleakClient): |
| 426 |
"""Fake BleakClientWithServiceCache.""" |
| 427 |
|
| 428 |
client = await establish_connection( |
| 429 |
FakeBleakClientWithServiceCache, |
| 430 |
MagicMock(), |
| 431 |
"test", |
| 432 |
disconnected_callback=MagicMock(), |
| 433 |
) |
| 434 |
|
| 435 |
assert isinstance(client, FakeBleakClientWithServiceCache) |
| 436 |
|
| 437 |
|
| 438 |
@pytest.mark.asyncio |
| 439 |
async def test_establish_connection_without_dangerous_use_cached_services(): |
| 440 |
class FakeBleakClient(BleakClient): |
| 441 |
async def connect(self, *args, **kwargs): |
| 442 |
return True |
| 443 |
|
| 444 |
async def disconnect(self, *args, **kwargs): |
| 445 |
pass |
| 446 |
|
| 447 |
async def get_services(self, *args, **kwargs): |
| 448 |
return [] |
| 449 |
|
| 450 |
class FakeBleakClientWithServiceCache(BleakClientWithServiceCache, FakeBleakClient): |
| 451 |
"""Fake BleakClientWithServiceCache.""" |
| 452 |
|
| 453 |
client = await establish_connection( |
| 454 |
FakeBleakClientWithServiceCache, |
| 455 |
MagicMock(), |
| 456 |
"test", |
| 457 |
disconnected_callback=MagicMock(), |
| 458 |
) |
| 459 |
|
| 460 |
assert isinstance(client, FakeBleakClientWithServiceCache) |
| 461 |
|
| 462 |
|
| 463 |
@pytest.mark.asyncio |
| 464 |
async def test_establish_connection_fails(): |
| 465 |
class FakeBleakClient(BleakClient): |
| 466 |
def __init__(self, *args, **kwargs): |
| 467 |
pass |
| 468 |
|
| 469 |
async def connect(self, *args, **kwargs): |
| 470 |
raise BleakError("test") |
| 471 |
|
| 472 |
async def disconnect(self, *args, **kwargs): |
| 473 |
pass |
| 474 |
|
| 475 |
with ( |
| 476 |
patch("bleak_retry_connector.calculate_backoff_time", return_value=0), |
| 477 |
pytest.raises(BleakConnectionError), |
| 478 |
): |
| 479 |
await establish_connection(FakeBleakClient, MagicMock(), "test") |
| 480 |
|
| 481 |
|
| 482 |
@pytest.mark.asyncio |
| 483 |
async def test_establish_connection_times_out(): |
| 484 |
class FakeBleakClient(BleakClient): |
| 485 |
def __init__(self, *args, **kwargs): |
| 486 |
pass |
| 487 |
|
| 488 |
async def connect(self, *args, **kwargs): |
| 489 |
raise asyncio.TimeoutError() |
| 490 |
|
| 491 |
async def disconnect(self, *args, **kwargs): |
| 492 |
pass |
| 493 |
|
| 494 |
with ( |
| 495 |
patch("bleak_retry_connector.calculate_backoff_time", return_value=0), |
| 496 |
pytest.raises(BleakNotFoundError), |
| 497 |
): |
| 498 |
await establish_connection(FakeBleakClient, MagicMock(), "test") |
| 499 |
|
| 500 |
|
| 501 |
@pytest.mark.asyncio |
| 502 |
async def test_establish_connection_has_transient_error(): |
| 503 |
attempts = 0 |
| 504 |
|
| 505 |
class FakeBleakClient(BleakClient): |
| 506 |
def __init__(self, *args, **kwargs): |
| 507 |
pass |
| 508 |
|
| 509 |
async def connect(self, *args, **kwargs): |
| 510 |
nonlocal attempts |
| 511 |
attempts += 1 |
| 512 |
if attempts < MAX_TRANSIENT_ERRORS: |
| 513 |
raise BleakError("le-connection-abort-by-local") |
| 514 |
pass |
| 515 |
|
| 516 |
async def disconnect(self, *args, **kwargs): |
| 517 |
pass |
| 518 |
|
| 519 |
with patch("bleak_retry_connector.calculate_backoff_time", return_value=0): |
| 520 |
client = await establish_connection(FakeBleakClient, MagicMock(), "test") |
| 521 |
assert isinstance(client, FakeBleakClient) |
| 522 |
assert attempts == 9 |
| 523 |
|
| 524 |
|
| 525 |
@pytest.mark.asyncio |
| 526 |
async def test_establish_connection_has_transient_broken_pipe_error(): |
| 527 |
attempts = 0 |
| 528 |
|
| 529 |
class FakeBleakClient(BleakClient): |
| 530 |
def __init__(self, *args, **kwargs): |
| 531 |
pass |
| 532 |
|
| 533 |
async def connect(self, *args, **kwargs): |
| 534 |
nonlocal attempts |
| 535 |
attempts += 1 |
| 536 |
if attempts < MAX_TRANSIENT_ERRORS: |
| 537 |
raise BrokenPipeError |
| 538 |
pass |
| 539 |
|
| 540 |
async def disconnect(self, *args, **kwargs): |
| 541 |
pass |
| 542 |
|
| 543 |
client = await establish_connection(FakeBleakClient, MagicMock(), "test") |
| 544 |
assert isinstance(client, FakeBleakClient) |
| 545 |
assert attempts == 9 |
| 546 |
|
| 547 |
|
| 548 |
@pytest.mark.asyncio |
| 549 |
async def test_establish_connection_has_transient_eof_error(): |
| 550 |
"""EOFError raised during connect is treated as transient and retried.""" |
| 551 |
attempts = 0 |
| 552 |
wait_calls: list[float] = [] |
| 553 |
|
| 554 |
class FakeBleakClient(BleakClient): |
| 555 |
def __init__(self, *args, **kwargs): |
| 556 |
pass |
| 557 |
|
| 558 |
async def connect(self, *args, **kwargs): |
| 559 |
nonlocal attempts |
| 560 |
attempts += 1 |
| 561 |
if attempts < MAX_TRANSIENT_ERRORS: |
| 562 |
raise EOFError |
| 563 |
|
| 564 |
async def disconnect(self, *args, **kwargs): |
| 565 |
pass |
| 566 |
|
| 567 |
async def fake_wait_for_disconnect(device, backoff_time): |
| 568 |
wait_calls.append(backoff_time) |
| 569 |
|
| 570 |
with ( |
| 571 |
patch( |
| 572 |
"bleak_retry_connector.wait_for_disconnect", |
| 573 |
side_effect=fake_wait_for_disconnect, |
| 574 |
), |
| 575 |
patch("bleak_retry_connector.calculate_backoff_time", return_value=0), |
| 576 |
): |
| 577 |
client = await establish_connection(FakeBleakClient, MagicMock(), "test") |
| 578 |
|
| 579 |
assert isinstance(client, FakeBleakClient) |
| 580 |
assert attempts == 9 |
| 581 |
assert wait_calls == [0] * 8 |
| 582 |
|
| 583 |
|
| 584 |
@pytest.mark.asyncio |
| 585 |
async def test_establish_connection_eof_error_exhausts_retries( |
| 586 |
caplog: pytest.LogCaptureFixture, |
| 587 |
) -> None: |
| 588 |
"""EOFError exceeding MAX_TRANSIENT_ERRORS raises BleakConnectionError and logs.""" |
| 589 |
attempts = 0 |
| 590 |
|
| 591 |
class FakeBleakClient(BleakClient): |
| 592 |
def __init__(self, *args, **kwargs): |
| 593 |
pass |
| 594 |
|
| 595 |
async def connect(self, *args, **kwargs): |
| 596 |
nonlocal attempts |
| 597 |
attempts += 1 |
| 598 |
raise EOFError("broken bus") |
| 599 |
|
| 600 |
async def disconnect(self, *args, **kwargs): |
| 601 |
pass |
| 602 |
|
| 603 |
with ( |
| 604 |
patch("bleak_retry_connector.wait_for_disconnect", AsyncMock()), |
| 605 |
patch("bleak_retry_connector.calculate_backoff_time", return_value=0), |
| 606 |
): |
| 607 |
with pytest.raises(BleakConnectionError): |
| 608 |
await establish_connection(FakeBleakClient, MagicMock(), "test") |
| 609 |
|
| 610 |
assert attempts == MAX_TRANSIENT_ERRORS |
| 611 |
assert "broken bus" in caplog.text |
| 612 |
assert "backing off" in caplog.text |
| 613 |
|
| 614 |
|
| 615 |
@pytest.mark.asyncio |
| 616 |
async def test_establish_connection_services_changed(): |
| 617 |
attempts = 0 |
| 618 |
disconnect_calls = 0 |
| 619 |
clear_cache_calls = 0 |
| 620 |
|
| 621 |
class FakeBleakClient(BleakClientWithServiceCache): |
| 622 |
def __init__(self, *args, **kwargs): |
| 623 |
pass |
| 624 |
|
| 625 |
async def connect(self, *args, **kwargs): |
| 626 |
nonlocal attempts |
| 627 |
attempts += 1 |
| 628 |
if attempts < MAX_TRANSIENT_ERRORS: |
| 629 |
raise KeyError |
| 630 |
|
| 631 |
async def disconnect(self, *args, **kwargs): |
| 632 |
nonlocal disconnect_calls |
| 633 |
disconnect_calls += 1 |
| 634 |
|
| 635 |
async def clear_cache(self) -> bool: |
| 636 |
nonlocal clear_cache_calls |
| 637 |
clear_cache_calls += 1 |
| 638 |
return True |
| 639 |
|
| 640 |
client = await establish_connection(FakeBleakClient, MagicMock(), "test") |
| 641 |
assert isinstance(client, FakeBleakClient) |
| 642 |
assert attempts == 9 |
| 643 |
assert disconnect_calls == 8 |
| 644 |
assert clear_cache_calls == 8 |
| 645 |
|
| 646 |
|
| 647 |
@pytest.mark.asyncio |
| 648 |
async def test_establish_connection_has_transient_error_had_advice(): |
| 649 |
class FakeBleakClient(BleakClient): |
| 650 |
def __init__(self, *args, **kwargs): |
| 651 |
pass |
| 652 |
|
| 653 |
async def connect(self, *args, **kwargs): |
| 654 |
raise BleakError("le-connection-abort-by-local") |
| 655 |
|
| 656 |
async def disconnect(self, *args, **kwargs): |
| 657 |
pass |
| 658 |
|
| 659 |
with patch("bleak_retry_connector.calculate_backoff_time", return_value=0): |
| 660 |
try: |
| 661 |
await establish_connection( |
| 662 |
FakeBleakClient, |
| 663 |
BLEDevice( |
| 664 |
"aa:bb:cc:dd:ee:ff", |
| 665 |
"name", |
| 666 |
{"path": "/org/bluez/hci2/dev_FA_23_9D_AA_45_46"}, |
| 667 |
), |
| 668 |
"test", |
| 669 |
) |
| 670 |
except BleakError as e: |
| 671 |
exc = e |
| 672 |
|
| 673 |
assert isinstance(exc, BleakAbortedError) |
| 674 |
assert str(exc) == ( |
| 675 |
"test - aa:bb:cc:dd:ee:ff: " |
| 676 |
"Failed to connect after 9 attempt(s): " |
| 677 |
"le-connection-abort-by-local: " |
| 678 |
"Interference/range; " |
| 679 |
"External Bluetooth adapter w/extension may help; " |
| 680 |
"Extension cables reduce USB 3 port interference" |
| 681 |
) |
| 682 |
|
| 683 |
|
| 684 |
@pytest.mark.asyncio |
| 685 |
async def test_establish_connection_out_of_slots_advice(): |
| 686 |
class FakeBleakClient(BleakClient): |
| 687 |
def __init__(self, *args, **kwargs): |
| 688 |
pass |
| 689 |
|
| 690 |
async def connect(self, *args, **kwargs): |
| 691 |
raise BleakError("out of connection slots") |
| 692 |
|
| 693 |
async def disconnect(self, *args, **kwargs): |
| 694 |
pass |
| 695 |
|
| 696 |
with patch("bleak_retry_connector.calculate_backoff_time", return_value=0): |
| 697 |
try: |
| 698 |
await establish_connection( |
| 699 |
FakeBleakClient, |
| 700 |
BLEDevice("aa:bb:cc:dd:ee:ff", "name", {"source": "esphome_proxy_1"}), |
| 701 |
"test", |
| 702 |
) |
| 703 |
except BleakError as e: |
| 704 |
exc = e |
| 705 |
|
| 706 |
assert isinstance(exc, BleakOutOfConnectionSlotsError) |
| 707 |
assert str(exc) == ( |
| 708 |
"test - aa:bb:cc:dd:ee:ff: Failed to connect after 9 attempt(s): " |
| 709 |
"out of connection slots: The proxy/adapter is " |
| 710 |
"out of connection slots or the device is no " |
| 711 |
"longer reachable; Add additional proxies " |
| 712 |
"(https://esphome.io/projects/?type=bluetooth) near this device" |
| 713 |
) |
| 714 |
|
| 715 |
|
| 716 |
@pytest.mark.asyncio |
| 717 |
async def test_establish_connection_esp_gatt_conn_conn_cancel_aborted(): |
| 718 |
"""Test ESP_GATT_CONN_CONN_CANCEL is not reported as out of slots.""" |
| 719 |
|
| 720 |
class FakeBleakClient(BleakClient): |
| 721 |
def __init__(self, *args, **kwargs): |
| 722 |
pass |
| 723 |
|
| 724 |
async def connect(self, *args, **kwargs): |
| 725 |
raise BleakError("ESP_GATT_CONN_CONN_CANCEL") |
| 726 |
|
| 727 |
async def disconnect(self, *args, **kwargs): |
| 728 |
pass |
| 729 |
|
| 730 |
with patch("bleak_retry_connector.calculate_backoff_time", return_value=0): |
| 731 |
try: |
| 732 |
await establish_connection( |
| 733 |
FakeBleakClient, |
| 734 |
BLEDevice("aa:bb:cc:dd:ee:ff", "name", {"source": "esphome_proxy_1"}), |
| 735 |
"test", |
| 736 |
) |
| 737 |
except BleakError as e: |
| 738 |
exc = e |
| 739 |
|
| 740 |
assert isinstance(exc, BleakAbortedError) |
| 741 |
assert str(exc) == ( |
| 742 |
"test - aa:bb:cc:dd:ee:ff: Failed to connect after 9 attempt(s): " |
| 743 |
"ESP_GATT_CONN_CONN_CANCEL: The proxy/adapter controller rejected " |
| 744 |
"the connection immediately; This usually points to a " |
| 745 |
"controller or firmware problem, not a lack of connection slots; " |
| 746 |
"Check the proxy logs and update its firmware" |
| 747 |
) |
| 748 |
|
| 749 |
|
| 750 |
@pytest.mark.asyncio |
| 751 |
async def test_establish_connection_esp_gatt_conn_conn_cancel_after_timeout(): |
| 752 |
"""Test a slow ESP_GATT_CONN_CONN_CANCEL is reported as the device not responding.""" |
| 753 |
|
| 754 |
class FakeBleakClient(BleakClient): |
| 755 |
def __init__(self, *args, **kwargs): |
| 756 |
pass |
| 757 |
|
| 758 |
async def connect(self, *args, **kwargs): |
| 759 |
raise BleakError("ESP_GATT_CONN_CONN_CANCEL") |
| 760 |
|
| 761 |
async def disconnect(self, *args, **kwargs): |
| 762 |
pass |
| 763 |
|
| 764 |
with ( |
| 765 |
patch("bleak_retry_connector.calculate_backoff_time", return_value=0), |
| 766 |
patch( |
| 767 |
"bleak_retry_connector.monotonic", |
| 768 |
side_effect=itertools.count(step=20), |
| 769 |
), |
| 770 |
): |
| 771 |
try: |
| 772 |
await establish_connection( |
| 773 |
FakeBleakClient, |
| 774 |
BLEDevice("aa:bb:cc:dd:ee:ff", "name", {"source": "esphome_proxy_1"}), |
| 775 |
"test", |
| 776 |
) |
| 777 |
except BleakError as e: |
| 778 |
exc = e |
| 779 |
|
| 780 |
assert isinstance(exc, BleakAbortedError) |
| 781 |
assert str(exc) == ( |
| 782 |
"test - aa:bb:cc:dd:ee:ff: Failed to connect after 9 attempt(s): " |
| 783 |
"ESP_GATT_CONN_CONN_CANCEL: The proxy/adapter gave up waiting for " |
| 784 |
"the device to respond; The device may be out of range or not " |
| 785 |
"accepting connections; Move the device closer or add additional " |
| 786 |
"proxies (https://esphome.io/projects/?type=bluetooth) near this device" |
| 787 |
) |
| 788 |
|
| 789 |
|
| 790 |
@pytest.mark.asyncio |
| 791 |
async def test_establish_connection_no_free_slot_timeout_out_of_slots(): |
| 792 |
"""Test a TimeoutError waiting for a free slot is reported as out of slots.""" |
| 793 |
|
| 794 |
class FakeBleakClient(BleakClient): |
| 795 |
def __init__(self, *args, **kwargs): |
| 796 |
pass |
| 797 |
|
| 798 |
async def connect(self, *args, **kwargs): |
| 799 |
raise asyncio.TimeoutError( |
| 800 |
"test [aa:bb:cc:dd:ee:ff]: No free BLE connection slot " |
| 801 |
"became available (limit=3, in use=3)" |
| 802 |
) |
| 803 |
|
| 804 |
async def disconnect(self, *args, **kwargs): |
| 805 |
pass |
| 806 |
|
| 807 |
with patch("bleak_retry_connector.calculate_backoff_time", return_value=0): |
| 808 |
try: |
| 809 |
await establish_connection( |
| 810 |
FakeBleakClient, |
| 811 |
BLEDevice("aa:bb:cc:dd:ee:ff", "name", {"source": "esphome_proxy_1"}), |
| 812 |
"test", |
| 813 |
) |
| 814 |
except BleakError as e: |
| 815 |
exc = e |
| 816 |
|
| 817 |
assert isinstance(exc, BleakOutOfConnectionSlotsError) |
| 818 |
assert str(exc) == ( |
| 819 |
"test - aa:bb:cc:dd:ee:ff: Failed to connect after 4 attempt(s): " |
| 820 |
"test [aa:bb:cc:dd:ee:ff]: No free BLE connection slot " |
| 821 |
"became available (limit=3, in use=3): The proxy/adapter is " |
| 822 |
"out of connection slots or the device is no " |
| 823 |
"longer reachable; Add additional proxies " |
| 824 |
"(https://esphome.io/projects/?type=bluetooth) near this device" |
| 825 |
) |
| 826 |
|
| 827 |
|
| 828 |
@pytest.mark.asyncio |
| 829 |
async def test_device_disappeared_error(): |
| 830 |
class FakeBleakClient(BleakClient): |
| 831 |
def __init__(self, *args, **kwargs): |
| 832 |
pass |
| 833 |
|
| 834 |
async def connect(self, *args, **kwargs): |
| 835 |
raise BleakError( |
| 836 |
'[org.freedesktop.DBus.Error.UnknownObject] Method "Connect" with ' |
| 837 |
'signature "" on interface ' |
| 838 |
'"org.bluez.Device1" ' |
| 839 |
"doesn't exist" |
| 840 |
) |
| 841 |
|
| 842 |
async def disconnect(self, *args, **kwargs): |
| 843 |
pass |
| 844 |
|
| 845 |
with patch("bleak_retry_connector.calculate_backoff_time", return_value=0): |
| 846 |
try: |
| 847 |
await establish_connection( |
| 848 |
FakeBleakClient, |
| 849 |
BLEDevice( |
| 850 |
"aa:bb:cc:dd:ee:ff", |
| 851 |
"name", |
| 852 |
{"path": "/org/bluez/hci2/dev_FA_23_9D_AA_45_46"}, |
| 853 |
), |
| 854 |
"test", |
| 855 |
) |
| 856 |
except BleakError as e: |
| 857 |
exc = e |
| 858 |
|
| 859 |
assert isinstance(exc, BleakNotFoundError) |
| 860 |
assert str(exc) == ( |
| 861 |
"test - aa:bb:cc:dd:ee:ff: " |
| 862 |
"Failed to connect after 4 attempt(s): " |
| 863 |
"[org.freedesktop.DBus.Error.UnknownObject] " |
| 864 |
'Method "Connect" with signature "" on interface "org.bluez.Device1" ' |
| 865 |
"doesn't exist: The device disappeared; " |
| 866 |
"Try restarting the scanner or moving the device closer" |
| 867 |
) |
| 868 |
|
| 869 |
|
| 870 |
@pytest.mark.asyncio |
| 871 |
@patch.object(bleak_retry_connector.bluez, "IS_LINUX", True) |
| 872 |
async def test_device_disappeared_and_reappears(): |
| 873 |
class FakeBluezManager: |
| 874 |
def __init__(self): |
| 875 |
self._services_cache = {} |
| 876 |
self.watchers: set[DeviceWatcher] = set() |
| 877 |
self._properties = { |
| 878 |
"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": { |
| 879 |
"UUID": "service", |
| 880 |
"Primary": True, |
| 881 |
"Characteristics": [], |
| 882 |
defs.DEVICE_INTERFACE: { |
| 883 |
"Address": "FA:23:9D:AA:45:46", |
| 884 |
"Alias": "FA:23:9D:AA:45:46", |
| 885 |
"RSSI": -30, |
| 886 |
}, |
| 887 |
defs.GATT_SERVICE_INTERFACE: True, |
| 888 |
}, |
| 889 |
"/org/bluez/hci1/dev_FA_23_9D_AA_45_46": { |
| 890 |
"UUID": "service", |
| 891 |
"Primary": True, |
| 892 |
"Characteristics": [], |
| 893 |
defs.DEVICE_INTERFACE: { |
| 894 |
"Connected": True, |
| 895 |
"Address": "FA:23:9D:AA:45:46", |
| 896 |
"Alias": "FA:23:9D:AA:45:46", |
| 897 |
"RSSI": -79, |
| 898 |
}, |
| 899 |
defs.GATT_SERVICE_INTERFACE: True, |
| 900 |
}, |
| 901 |
} |
| 902 |
|
| 903 |
def add_device_watcher(self, path: str, **kwargs: Any) -> DeviceWatcher: |
| 904 |
"""Add a watcher for device changes.""" |
| 905 |
watcher = DeviceWatcher(path, **kwargs) |
| 906 |
self.watchers.add(watcher) |
| 907 |
return watcher |
| 908 |
|
| 909 |
async def _wait_condition(self, *args: Any, **kwargs: Any) -> None: |
| 910 |
"""Wait for a condition to be met.""" |
| 911 |
raise KeyError |
| 912 |
|
| 913 |
def remove_device_watcher(self, watcher: DeviceWatcher) -> None: |
| 914 |
"""Remove a watcher for device changes.""" |
| 915 |
self.watchers.remove(watcher) |
| 916 |
|
| 917 |
def is_connected(self, path: str) -> bool: |
| 918 |
"""Check if device is connected.""" |
| 919 |
return False |
| 920 |
|
| 921 |
bluez_manager = FakeBluezManager() |
| 922 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock( |
| 923 |
return_value=bluez_manager |
| 924 |
) |
| 925 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager_with_timeout = ( |
| 926 |
AsyncMock(return_value=bluez_manager) |
| 927 |
) |
| 928 |
bleak_retry_connector.bluez.defs = defs |
| 929 |
|
| 930 |
class FakeBleakClient(BleakClient): |
| 931 |
def __init__(self, *args, **kwargs): |
| 932 |
pass |
| 933 |
|
| 934 |
async def connect(self, *args, **kwargs): |
| 935 |
raise BleakDeviceNotFoundError( |
| 936 |
'[org.freedesktop.DBus.Error.UnknownObject] Method "Connect" with ' |
| 937 |
'signature "" on interface ' |
| 938 |
'"org.bluez.Device1" ' |
| 939 |
"doesn't exist" |
| 940 |
) |
| 941 |
|
| 942 |
async def disconnect(self, *args, **kwargs): |
| 943 |
pass |
| 944 |
|
| 945 |
with ( |
| 946 |
patch("bleak_retry_connector.calculate_backoff_time", return_value=0.01), |
| 947 |
patch.object(bleak_retry_connector.bluez, "REAPPEAR_WAIT_INTERVAL", 0.0025), |
| 948 |
): |
| 949 |
try: |
| 950 |
await establish_connection( |
| 951 |
FakeBleakClient, |
| 952 |
BLEDevice( |
| 953 |
"FA:23:9D:AA:45:46", |
| 954 |
"name", |
| 955 |
{"path": "/org/bluez/hci2/dev_FA_23_9D_AA_45_46"}, |
| 956 |
), |
| 957 |
"test", |
| 958 |
) |
| 959 |
except BleakError as e: |
| 960 |
exc = e |
| 961 |
|
| 962 |
assert isinstance(exc, BleakNotFoundError) |
| 963 |
assert str(exc) == ( |
| 964 |
"test - FA:23:9D:AA:45:46: " |
| 965 |
"Failed to connect after 9 attempt(s): " |
| 966 |
"BleakDeviceNotFoundError: " |
| 967 |
"The device disappeared; " |
| 968 |
"Try restarting the scanner or moving the device closer" |
| 969 |
) |
| 970 |
|
| 971 |
|
| 972 |
@pytest.mark.asyncio |
| 973 |
async def test_establish_connection_has_one_unknown_error(): |
| 974 |
attempts = 0 |
| 975 |
|
| 976 |
class FakeBleakClient(BleakClient): |
| 977 |
def __init__(self, *args, **kwargs): |
| 978 |
pass |
| 979 |
|
| 980 |
async def connect(self, *args, **kwargs): |
| 981 |
nonlocal attempts |
| 982 |
attempts += 1 |
| 983 |
if attempts == 1: |
| 984 |
raise BleakError("unknown") |
| 985 |
pass |
| 986 |
|
| 987 |
async def disconnect(self, *args, **kwargs): |
| 988 |
pass |
| 989 |
|
| 990 |
client = await establish_connection(FakeBleakClient, MagicMock(), "test") |
| 991 |
assert isinstance(client, FakeBleakClient) |
| 992 |
assert attempts == 2 |
| 993 |
|
| 994 |
|
| 995 |
@pytest.mark.asyncio |
| 996 |
async def test_establish_connection_has_one_many_error(): |
| 997 |
attempts = 0 |
| 998 |
|
| 999 |
class FakeBleakClient(BleakClient): |
| 1000 |
def __init__(self, *args, **kwargs): |
| 1001 |
pass |
| 1002 |
|
| 1003 |
async def connect(self, *args, **kwargs): |
| 1004 |
nonlocal attempts |
| 1005 |
attempts += 1 |
| 1006 |
if attempts < 10: |
| 1007 |
raise BleakError("unknown") |
| 1008 |
pass |
| 1009 |
|
| 1010 |
async def disconnect(self, *args, **kwargs): |
| 1011 |
pass |
| 1012 |
|
| 1013 |
with ( |
| 1014 |
patch("bleak_retry_connector.calculate_backoff_time", return_value=0), |
| 1015 |
pytest.raises(BleakConnectionError), |
| 1016 |
): |
| 1017 |
await establish_connection(FakeBleakClient, MagicMock(), "test") |
| 1018 |
|
| 1019 |
|
| 1020 |
@pytest.mark.asyncio |
| 1021 |
async def test_bleak_connect_overruns_timeout(): |
| 1022 |
class FakeBleakClient(BleakClient): |
| 1023 |
def __init__(self, *args, **kwargs): |
| 1024 |
pass |
| 1025 |
|
| 1026 |
async def connect(self, *args, **kwargs): |
| 1027 |
await asyncio.sleep(40) |
| 1028 |
|
| 1029 |
async def disconnect(self, *args, **kwargs): |
| 1030 |
pass |
| 1031 |
|
| 1032 |
with ( |
| 1033 |
patch("bleak_retry_connector.calculate_backoff_time", return_value=0), |
| 1034 |
patch.object(bleak_retry_connector, "BLEAK_SAFETY_TIMEOUT", 0), |
| 1035 |
pytest.raises(BleakNotFoundError), |
| 1036 |
): |
| 1037 |
await establish_connection(FakeBleakClient, MagicMock(), "test") |
| 1038 |
|
| 1039 |
|
| 1040 |
def test_ble_device_has_changed(): |
| 1041 |
"""Test that the BLEDevice has changed when the underlying device has changed.""" |
| 1042 |
assert not ble_device_has_changed( |
| 1043 |
BLEDevice("aa:bb:cc:dd:ee:ff", "name", {"path": "/dev/1"}), |
| 1044 |
BLEDevice("aa:bb:cc:dd:ee:ff", "name", {"path": "/dev/1"}), |
| 1045 |
) |
| 1046 |
assert ble_device_has_changed( |
| 1047 |
BLEDevice("aa:bb:cc:dd:ee:ff", "name", {"path": "/dev/1"}), |
| 1048 |
BLEDevice("ab:bb:cc:dd:ee:ff", "name", {"path": "/dev/1"}), |
| 1049 |
) |
| 1050 |
assert ble_device_has_changed( |
| 1051 |
BLEDevice("aa:bb:cc:dd:ee:ff", "name", {"path": "/dev/1"}), |
| 1052 |
BLEDevice("aa:bb:cc:dd:ee:ff", "name", {"path": "/dev/2"}), |
| 1053 |
) |
| 1054 |
|
| 1055 |
|
| 1056 |
@pytest.mark.asyncio |
| 1057 |
async def test_establish_connection_other_adapter_already_connected(mock_linux): |
| 1058 |
device: BLEDevice | None = None |
| 1059 |
|
| 1060 |
class FakeBleakClient(BleakClient): |
| 1061 |
def __init__(self, ble_device_or_address, *args, **kwargs): |
| 1062 |
ble_device_or_address.details["delegate"] = 0 |
| 1063 |
super().__init__(ble_device_or_address, *args, **kwargs) |
| 1064 |
nonlocal device |
| 1065 |
device = ble_device_or_address |
| 1066 |
self._device_path = "/org/bluez/hci2/dev_FA_23_9D_AA_45_46" |
| 1067 |
|
| 1068 |
async def connect(self, *args, **kwargs): |
| 1069 |
return True |
| 1070 |
|
| 1071 |
async def disconnect(self, *args, **kwargs): |
| 1072 |
pass |
| 1073 |
|
| 1074 |
async def get_services(self, *args, **kwargs): |
| 1075 |
return [] |
| 1076 |
|
| 1077 |
class FakeBleakClientWithServiceCache(BleakClientWithServiceCache, FakeBleakClient): |
| 1078 |
"""Fake BleakClientWithServiceCache.""" |
| 1079 |
|
| 1080 |
async def get_services(self, *args, **kwargs): |
| 1081 |
return [] |
| 1082 |
|
| 1083 |
collection = BleakGATTServiceCollection() |
| 1084 |
|
| 1085 |
class FakeBluezManager: |
| 1086 |
def __init__(self): |
| 1087 |
self._services_cache = {} |
| 1088 |
self._properties = { |
| 1089 |
"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": { |
| 1090 |
"UUID": "service", |
| 1091 |
"Primary": True, |
| 1092 |
"Characteristics": [], |
| 1093 |
defs.DEVICE_INTERFACE: { |
| 1094 |
"Address": "FA:23:9D:AA:45:46", |
| 1095 |
"Alias": "FA:23:9D_AA:45:46", |
| 1096 |
"RSSI": -30, |
| 1097 |
}, |
| 1098 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1099 |
}, |
| 1100 |
"/org/bluez/hci1/dev_FA_23_9D_AA_45_46": { |
| 1101 |
"UUID": "service", |
| 1102 |
"Primary": True, |
| 1103 |
"Characteristics": [], |
| 1104 |
defs.DEVICE_INTERFACE: { |
| 1105 |
"Address": "FA:23:9D:AA:45:46", |
| 1106 |
"Alias": "FA:23:9D:AA:45:46", |
| 1107 |
"Connected": True, |
| 1108 |
"RSSI": -79, |
| 1109 |
}, |
| 1110 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1111 |
}, |
| 1112 |
"/org/bluez/hci2/dev_FA_23_9D_AA_45_46": { |
| 1113 |
"UUID": "service", |
| 1114 |
"Primary": True, |
| 1115 |
"Characteristics": [], |
| 1116 |
defs.DEVICE_INTERFACE: { |
| 1117 |
"Address": "FA:23:9D:AA:45:46", |
| 1118 |
"Alias": "FA:23:9D:AA:45:46", |
| 1119 |
"Connected": False, |
| 1120 |
"RSSI": -80, |
| 1121 |
}, |
| 1122 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1123 |
}, |
| 1124 |
"/org/bluez/hci3/dev_FA_23_9D_AA_45_46": { |
| 1125 |
"UUID": "service", |
| 1126 |
"Primary": True, |
| 1127 |
"Characteristics": [], |
| 1128 |
defs.DEVICE_INTERFACE: { |
| 1129 |
"Address": "FA:23:9D:AA:45:46", |
| 1130 |
"Alias": "FA:23:9D:AA:45:46", |
| 1131 |
"RSSI": -31, |
| 1132 |
}, |
| 1133 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1134 |
}, |
| 1135 |
} |
| 1136 |
|
| 1137 |
bluez_manager = FakeBluezManager() |
| 1138 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock( |
| 1139 |
return_value=bluez_manager |
| 1140 |
) |
| 1141 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager_with_timeout = ( |
| 1142 |
AsyncMock(return_value=bluez_manager) |
| 1143 |
) |
| 1144 |
bleak_retry_connector.bluez.defs = defs |
| 1145 |
|
| 1146 |
client = await establish_connection( |
| 1147 |
FakeBleakClientWithServiceCache, |
| 1148 |
BLEDevice( |
| 1149 |
"aa:bb:cc:dd:ee:ff", |
| 1150 |
"name", |
| 1151 |
{"path": "/org/bluez/hci2/dev_FA_23_9D_AA_45_46"}, |
| 1152 |
), |
| 1153 |
"test", |
| 1154 |
disconnected_callback=MagicMock(), |
| 1155 |
cached_services=collection, |
| 1156 |
) |
| 1157 |
|
| 1158 |
assert isinstance(client, FakeBleakClientWithServiceCache) |
| 1159 |
await client.get_services() is collection |
| 1160 |
assert device is not None |
| 1161 |
assert device.details["path"] == "/org/bluez/hci1/dev_FA_23_9D_AA_45_46" |
| 1162 |
|
| 1163 |
|
| 1164 |
@pytest.mark.asyncio |
| 1165 |
async def test_establish_connection_device_disappeared(mock_linux): |
| 1166 |
class FakeBleakClient(BleakClient): |
| 1167 |
def __init__(self, ble_device_or_address, *args, **kwargs): |
| 1168 |
ble_device_or_address.details["delegate"] = 0 |
| 1169 |
super().__init__(ble_device_or_address, *args, **kwargs) |
| 1170 |
self._device_path = "/org/bluez/hci2/dev_FA_23_9D_AA_45_46" |
| 1171 |
|
| 1172 |
async def connect(self, *args, **kwargs): |
| 1173 |
return True |
| 1174 |
|
| 1175 |
async def disconnect(self, *args, **kwargs): |
| 1176 |
pass |
| 1177 |
|
| 1178 |
async def get_services(self, *args, **kwargs): |
| 1179 |
return [] |
| 1180 |
|
| 1181 |
class FakeBleakClientWithServiceCache(BleakClientWithServiceCache, FakeBleakClient): |
| 1182 |
"""Fake BleakClientWithServiceCache.""" |
| 1183 |
|
| 1184 |
async def get_services(self, *args, **kwargs): |
| 1185 |
return [] |
| 1186 |
|
| 1187 |
collection = BleakGATTServiceCollection() |
| 1188 |
|
| 1189 |
class FakeBluezManager: |
| 1190 |
def __init__(self): |
| 1191 |
self._services_cache = {} |
| 1192 |
self._properties = { |
| 1193 |
"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": { |
| 1194 |
"UUID": "service", |
| 1195 |
"Primary": True, |
| 1196 |
"Characteristics": [], |
| 1197 |
defs.DEVICE_INTERFACE: { |
| 1198 |
"Address": "FA:23:9D:AA:45:46", |
| 1199 |
"Alias": "bob", |
| 1200 |
"RSSI": -30, |
| 1201 |
}, |
| 1202 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1203 |
}, |
| 1204 |
} |
| 1205 |
|
| 1206 |
bluez_manager = FakeBluezManager() |
| 1207 |
|
| 1208 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock( |
| 1209 |
return_value=bluez_manager |
| 1210 |
) |
| 1211 |
|
| 1212 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager_with_timeout = ( |
| 1213 |
AsyncMock(return_value=bluez_manager) |
| 1214 |
) |
| 1215 |
bleak_retry_connector.bluez.defs = defs |
| 1216 |
|
| 1217 |
with patch("bleak_retry_connector.calculate_backoff_time", return_value=0): |
| 1218 |
client = await establish_connection( |
| 1219 |
FakeBleakClientWithServiceCache, |
| 1220 |
BLEDevice( |
| 1221 |
"aa:bb:cc:dd:ee:ff", |
| 1222 |
"name", |
| 1223 |
{"path": "/org/bluez/hci2/dev_FA_23_9D_AA_45_46"}, |
| 1224 |
), |
| 1225 |
"test", |
| 1226 |
disconnected_callback=MagicMock(), |
| 1227 |
cached_services=collection, |
| 1228 |
) |
| 1229 |
|
| 1230 |
assert isinstance(client, FakeBleakClientWithServiceCache) |
| 1231 |
await client.get_services() is collection |
| 1232 |
|
| 1233 |
|
| 1234 |
@pytest.mark.asyncio |
| 1235 |
async def test_get_device(mock_linux): |
| 1236 |
class FakeBluezManager: |
| 1237 |
def __init__(self): |
| 1238 |
self._services_cache = {} |
| 1239 |
self._properties = { |
| 1240 |
"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": { |
| 1241 |
"UUID": "service", |
| 1242 |
"Primary": True, |
| 1243 |
"Characteristics": [], |
| 1244 |
defs.DEVICE_INTERFACE: { |
| 1245 |
"Address": "FA:23:9D:AA:45:46", |
| 1246 |
"Alias": "FA:23:9D:AA:45:46", |
| 1247 |
"RSSI": -30, |
| 1248 |
}, |
| 1249 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1250 |
}, |
| 1251 |
"/org/bluez/hci1/dev_FA_23_9D_AA_45_46": { |
| 1252 |
"UUID": "service", |
| 1253 |
"Primary": True, |
| 1254 |
"Characteristics": [], |
| 1255 |
defs.DEVICE_INTERFACE: { |
| 1256 |
"Address": "FA:23:9D:AA:45:46", |
| 1257 |
"Alias": "FA:23:9D:AA:45:46", |
| 1258 |
"RSSI": -79, |
| 1259 |
}, |
| 1260 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1261 |
}, |
| 1262 |
"/org/bluez/hci2/dev_FA_23_9D_AA_45_46": { |
| 1263 |
"UUID": "service", |
| 1264 |
"Primary": True, |
| 1265 |
"Characteristics": [], |
| 1266 |
defs.DEVICE_INTERFACE: { |
| 1267 |
"Address": "FA:23:9D:AA:45:46", |
| 1268 |
"Alias": "FA:23:9D:AA:45:46", |
| 1269 |
"RSSI": -80, |
| 1270 |
}, |
| 1271 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1272 |
}, |
| 1273 |
"/org/bluez/hci3/dev_FA_23_9D_AA_45_46": { |
| 1274 |
"UUID": "service", |
| 1275 |
"Primary": True, |
| 1276 |
"Characteristics": [], |
| 1277 |
defs.DEVICE_INTERFACE: { |
| 1278 |
"Address": "FA:23:9D:AA:45:46", |
| 1279 |
"Alias": "FA:23:9D:AA:45:46", |
| 1280 |
"RSSI": -31, |
| 1281 |
}, |
| 1282 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1283 |
}, |
| 1284 |
} |
| 1285 |
|
| 1286 |
bluez_manager = FakeBluezManager() |
| 1287 |
|
| 1288 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock( |
| 1289 |
return_value=bluez_manager |
| 1290 |
) |
| 1291 |
|
| 1292 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager_with_timeout = ( |
| 1293 |
AsyncMock(return_value=bluez_manager) |
| 1294 |
) |
| 1295 |
bleak_retry_connector.bluez.defs = defs |
| 1296 |
|
| 1297 |
device = await get_device("FA:23:9D:AA:45:46") |
| 1298 |
|
| 1299 |
assert device is not None |
| 1300 |
assert device.details["path"] == "/org/bluez/hci0/dev_FA_23_9D_AA_45_46" |
| 1301 |
|
| 1302 |
|
| 1303 |
@pytest.mark.asyncio |
| 1304 |
async def test_clear_cache(mock_linux): |
| 1305 |
class FakeBluezManager: |
| 1306 |
def __init__(self): |
| 1307 |
self._services_cache = { |
| 1308 |
"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": "test", |
| 1309 |
"/org/bluez/hci1/dev_FA_23_9D_AA_45_46": "test", |
| 1310 |
} |
| 1311 |
self._properties = { |
| 1312 |
"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": { |
| 1313 |
"UUID": "service", |
| 1314 |
"Primary": True, |
| 1315 |
"Characteristics": [], |
| 1316 |
defs.DEVICE_INTERFACE: { |
| 1317 |
"Address": "FA:23:9D:AA:45:46", |
| 1318 |
"Alias": "FA:23:9D:AA:45:46", |
| 1319 |
"RSSI": -30, |
| 1320 |
}, |
| 1321 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1322 |
}, |
| 1323 |
"/org/bluez/hci1/dev_FA_23_9D_AA_45_46": { |
| 1324 |
"UUID": "service", |
| 1325 |
"Primary": True, |
| 1326 |
"Characteristics": [], |
| 1327 |
defs.DEVICE_INTERFACE: { |
| 1328 |
"Address": "FA:23:9D:AA:45:46", |
| 1329 |
"Alias": "FA:23:9D:AA:45:46", |
| 1330 |
"RSSI": -79, |
| 1331 |
}, |
| 1332 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1333 |
}, |
| 1334 |
"/org/bluez/hci2/dev_FA_23_9D_AA_45_46": { |
| 1335 |
"UUID": "service", |
| 1336 |
"Primary": True, |
| 1337 |
"Characteristics": [], |
| 1338 |
defs.DEVICE_INTERFACE: { |
| 1339 |
"Address": "FA:23:9D:AA:45:46", |
| 1340 |
"Alias": "FA:23:9D:AA:45:46", |
| 1341 |
"RSSI": -80, |
| 1342 |
}, |
| 1343 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1344 |
}, |
| 1345 |
"/org/bluez/hci3/dev_FA_23_9D_AA_45_46": { |
| 1346 |
"UUID": "service", |
| 1347 |
"Primary": True, |
| 1348 |
"Characteristics": [], |
| 1349 |
defs.DEVICE_INTERFACE: { |
| 1350 |
"Address": "FA:23:9D:AA:45:46", |
| 1351 |
"Alias": "FA:23:9D:AA:45:46", |
| 1352 |
"RSSI": -31, |
| 1353 |
}, |
| 1354 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1355 |
}, |
| 1356 |
} |
| 1357 |
|
| 1358 |
bluez_manager = FakeBluezManager() |
| 1359 |
|
| 1360 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock( |
| 1361 |
return_value=bluez_manager |
| 1362 |
) |
| 1363 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager_with_timeout = ( |
| 1364 |
AsyncMock(return_value=bluez_manager) |
| 1365 |
) |
| 1366 |
bleak_retry_connector.bluez.defs = defs |
| 1367 |
|
| 1368 |
device = await get_device("FA:23:9D:AA:45:46") |
| 1369 |
|
| 1370 |
assert device is not None |
| 1371 |
assert device.details["path"] == "/org/bluez/hci0/dev_FA_23_9D_AA_45_46" |
| 1372 |
|
| 1373 |
assert await clear_cache("FA:23:9D:AA:45:46") |
| 1374 |
assert bluez_manager._services_cache == {} |
| 1375 |
|
| 1376 |
|
| 1377 |
@pytest.mark.asyncio |
| 1378 |
async def test_get_device_mac_os(mock_macos): |
| 1379 |
class FakeBluezManager: |
| 1380 |
def __init__(self): |
| 1381 |
self._services_cache = {} |
| 1382 |
self._properties = { |
| 1383 |
"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": { |
| 1384 |
"UUID": "service", |
| 1385 |
"Primary": True, |
| 1386 |
"Characteristics": [], |
| 1387 |
defs.DEVICE_INTERFACE: { |
| 1388 |
"Address": "FA:23:9D:AA:45:46", |
| 1389 |
"Alias": "FA:23:9D:AA:45:46", |
| 1390 |
"RSSI": -30, |
| 1391 |
}, |
| 1392 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1393 |
}, |
| 1394 |
"/org/bluez/hci1/dev_FA_23_9D_AA_45_46": { |
| 1395 |
"UUID": "service", |
| 1396 |
"Primary": True, |
| 1397 |
"Characteristics": [], |
| 1398 |
defs.DEVICE_INTERFACE: { |
| 1399 |
"Address": "FA:23:9D:AA:45:46", |
| 1400 |
"Alias": "FA:23:9D:AA:45:46", |
| 1401 |
"RSSI": -79, |
| 1402 |
}, |
| 1403 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1404 |
}, |
| 1405 |
"/org/bluez/hci2/dev_FA_23_9D_AA_45_46": { |
| 1406 |
"UUID": "service", |
| 1407 |
"Primary": True, |
| 1408 |
"Characteristics": [], |
| 1409 |
defs.DEVICE_INTERFACE: { |
| 1410 |
"Address": "FA:23:9D:AA:45:46", |
| 1411 |
"Alias": "FA:23:9D:AA:45:46", |
| 1412 |
"RSSI": -80, |
| 1413 |
}, |
| 1414 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1415 |
}, |
| 1416 |
"/org/bluez/hci3/dev_FA_23_9D_AA_45_46": { |
| 1417 |
"UUID": "service", |
| 1418 |
"Primary": True, |
| 1419 |
"Characteristics": [], |
| 1420 |
defs.DEVICE_INTERFACE: { |
| 1421 |
"Address": "FA:23:9D:AA:45:46", |
| 1422 |
"Alias": "FA:23:9D:AA:45:46", |
| 1423 |
"RSSI": -31, |
| 1424 |
}, |
| 1425 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1426 |
}, |
| 1427 |
} |
| 1428 |
|
| 1429 |
bluez_manager = FakeBluezManager() |
| 1430 |
|
| 1431 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock( |
| 1432 |
return_value=bluez_manager |
| 1433 |
) |
| 1434 |
|
| 1435 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager_with_timeout = ( |
| 1436 |
AsyncMock(return_value=bluez_manager) |
| 1437 |
) |
| 1438 |
bleak_retry_connector.bluez.defs = defs |
| 1439 |
|
| 1440 |
device = await get_device("FA:23:9D:AA:45:46") |
| 1441 |
|
| 1442 |
assert device is None |
| 1443 |
|
| 1444 |
|
| 1445 |
@pytest.mark.asyncio |
| 1446 |
async def test_get_device_already_connected(mock_linux): |
| 1447 |
class FakeBluezManager: |
| 1448 |
def __init__(self): |
| 1449 |
self._services_cache = {} |
| 1450 |
self._properties = { |
| 1451 |
"/org/bluez/hci1/dev_BD_24_6F_85_AA_61": { |
| 1452 |
"org.freedesktop.DBus.Introspectable": {}, |
| 1453 |
"org.bluez.Device1": { |
| 1454 |
"Address": "BD:24:6F:85:AA:61", |
| 1455 |
"AddressType": "public", |
| 1456 |
"Name": "Dream~BD246F85AA61", |
| 1457 |
"Alias": "Dream~BD246F85AA61", |
| 1458 |
"Appearance": 962, |
| 1459 |
"Icon": "input-mouse", |
| 1460 |
"Paired": False, |
| 1461 |
"Trusted": False, |
| 1462 |
"Blocked": False, |
| 1463 |
"LegacyPairing": False, |
| 1464 |
"Connected": True, |
| 1465 |
"UUIDs": [ |
| 1466 |
"00001800-0000-1000-8000-00805f9b34fb", |
| 1467 |
"00001801-0000-1000-8000-00805f9b34fb", |
| 1468 |
"0000180a-0000-1000-8000-00805f9b34fb", |
| 1469 |
"0000ffd0-0000-1000-8000-00805f9b34fb", |
| 1470 |
"0000ffd5-0000-1000-8000-00805f9b34fb", |
| 1471 |
], |
| 1472 |
"Modalias": "usb:v045Ep0040d0300", |
| 1473 |
"Adapter": "/org/bluez/hci1", |
| 1474 |
"ManufacturerData": {20808: bytearray(b"364656")}, |
| 1475 |
"ServicesResolved": True, |
| 1476 |
}, |
| 1477 |
"org.freedesktop.DBus.Properties": {}, |
| 1478 |
} |
| 1479 |
} |
| 1480 |
|
| 1481 |
bluez_manager = FakeBluezManager() |
| 1482 |
|
| 1483 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock( |
| 1484 |
return_value=bluez_manager |
| 1485 |
) |
| 1486 |
|
| 1487 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager_with_timeout = ( |
| 1488 |
AsyncMock(return_value=bluez_manager) |
| 1489 |
) |
| 1490 |
bleak_retry_connector.bluez.defs = defs |
| 1491 |
|
| 1492 |
device = await get_device("BD:24:6F:85:AA:61") |
| 1493 |
|
| 1494 |
assert device is not None |
| 1495 |
assert device.details["path"] == "/org/bluez/hci1/dev_BD_24_6F_85_AA_61" |
| 1496 |
connected = await get_connected_devices(device) |
| 1497 |
assert len(connected) == 1 |
| 1498 |
assert isinstance(connected[0], BLEDevice) |
| 1499 |
assert connected[0].details["path"] == "/org/bluez/hci1/dev_BD_24_6F_85_AA_61" |
| 1500 |
|
| 1501 |
|
| 1502 |
@pytest.mark.asyncio |
| 1503 |
async def test_get_device_not_there(): |
| 1504 |
class FakeBluezManager: |
| 1505 |
def __init__(self): |
| 1506 |
self._services_cache = {} |
| 1507 |
self._properties = { |
| 1508 |
"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": { |
| 1509 |
"UUID": "service", |
| 1510 |
"Primary": True, |
| 1511 |
"Characteristics": [], |
| 1512 |
defs.DEVICE_INTERFACE: { |
| 1513 |
"Address": "FA:23:9D:AA:45:46", |
| 1514 |
"Alias": "FA:23:9D:AA:45:46", |
| 1515 |
"RSSI": -30, |
| 1516 |
}, |
| 1517 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1518 |
}, |
| 1519 |
"/org/bluez/hci1/dev_FA_23_9D_AA_45_46": { |
| 1520 |
"UUID": "service", |
| 1521 |
"Primary": True, |
| 1522 |
"Characteristics": [], |
| 1523 |
defs.DEVICE_INTERFACE: { |
| 1524 |
"Address": "FA:23:9D:AA:45:46", |
| 1525 |
"Alias": "FA:23:9D:AA:45:46", |
| 1526 |
"RSSI": -79, |
| 1527 |
}, |
| 1528 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1529 |
}, |
| 1530 |
"/org/bluez/hci2/dev_FA_23_9D_AA_45_46": { |
| 1531 |
"UUID": "service", |
| 1532 |
"Primary": True, |
| 1533 |
"Characteristics": [], |
| 1534 |
defs.DEVICE_INTERFACE: { |
| 1535 |
"Address": "FA:23:9D:AA:45:46", |
| 1536 |
"Alias": "FA:23:9D:AA:45:46", |
| 1537 |
"RSSI": -80, |
| 1538 |
}, |
| 1539 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1540 |
}, |
| 1541 |
"/org/bluez/hci3/dev_FA_23_9D_AA_45_46": { |
| 1542 |
"UUID": "service", |
| 1543 |
"Primary": True, |
| 1544 |
"Characteristics": [], |
| 1545 |
defs.DEVICE_INTERFACE: { |
| 1546 |
"Address": "FA:23:9D:AA:45:46", |
| 1547 |
"Alias": "FA:23:9D:AA:45:46", |
| 1548 |
"RSSI": -31, |
| 1549 |
}, |
| 1550 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1551 |
}, |
| 1552 |
} |
| 1553 |
|
| 1554 |
bluez_manager = FakeBluezManager() |
| 1555 |
|
| 1556 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock( |
| 1557 |
return_value=bluez_manager |
| 1558 |
) |
| 1559 |
|
| 1560 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager_with_timeout = ( |
| 1561 |
AsyncMock(return_value=bluez_manager) |
| 1562 |
) |
| 1563 |
bleak_retry_connector.bluez.defs = defs |
| 1564 |
|
| 1565 |
with patch.object(bleak_retry_connector.const, "IS_LINUX", True): |
| 1566 |
device = await get_device("00:00:00:00:00:00") |
| 1567 |
|
| 1568 |
assert device is None |
| 1569 |
|
| 1570 |
|
| 1571 |
@pytest.mark.asyncio |
| 1572 |
async def test_establish_connection_better_rssi_available_already_connected_supported_different_adapter( |
| 1573 |
mock_linux, |
| 1574 |
): |
| 1575 |
device: BLEDevice | None = None |
| 1576 |
|
| 1577 |
class FakeBleakClient(BleakClient): |
| 1578 |
def __init__(self, ble_device_or_address, *args, **kwargs): |
| 1579 |
ble_device_or_address.details["delegate"] = 0 |
| 1580 |
super().__init__(ble_device_or_address, *args, **kwargs) |
| 1581 |
nonlocal device |
| 1582 |
device = ble_device_or_address |
| 1583 |
self._device_path = "/org/bluez/hci2/dev_FA_23_9D_AA_45_46" |
| 1584 |
|
| 1585 |
async def connect(self, *args, **kwargs): |
| 1586 |
return True |
| 1587 |
|
| 1588 |
async def disconnect(self, *args, **kwargs): |
| 1589 |
pass |
| 1590 |
|
| 1591 |
async def get_services(self, *args, **kwargs): |
| 1592 |
return [] |
| 1593 |
|
| 1594 |
class FakeBleakClientWithServiceCache(BleakClientWithServiceCache, FakeBleakClient): |
| 1595 |
"""Fake BleakClientWithServiceCache.""" |
| 1596 |
|
| 1597 |
async def get_services(self, *args, **kwargs): |
| 1598 |
return [] |
| 1599 |
|
| 1600 |
collection = BleakGATTServiceCollection() |
| 1601 |
|
| 1602 |
class FakeBluezManager: |
| 1603 |
def __init__(self): |
| 1604 |
self._services_cache = {} |
| 1605 |
self._properties = { |
| 1606 |
"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": { |
| 1607 |
"UUID": "service", |
| 1608 |
"Primary": True, |
| 1609 |
"Characteristics": [], |
| 1610 |
defs.DEVICE_INTERFACE: { |
| 1611 |
"Address": "FA:23:9D:AA:45:46", |
| 1612 |
"Alias": "FA:23:9D:AA:45:46", |
| 1613 |
"RSSI": -30, |
| 1614 |
}, |
| 1615 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1616 |
}, |
| 1617 |
"/org/bluez/hci1/dev_FA_23_9D_AA_45_46": { |
| 1618 |
"UUID": "service", |
| 1619 |
"Primary": True, |
| 1620 |
"Characteristics": [], |
| 1621 |
defs.DEVICE_INTERFACE: { |
| 1622 |
"Connected": True, |
| 1623 |
"Address": "FA:23:9D:AA:45:46", |
| 1624 |
"Alias": "FA:23:9D:AA:45:46", |
| 1625 |
"RSSI": -79, |
| 1626 |
}, |
| 1627 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1628 |
}, |
| 1629 |
"/org/bluez/hci2/dev_FA_23_9D_AA_45_46": { |
| 1630 |
"UUID": "service", |
| 1631 |
"Primary": True, |
| 1632 |
"Characteristics": [], |
| 1633 |
defs.DEVICE_INTERFACE: { |
| 1634 |
"Connected": True, |
| 1635 |
"Address": "FA:23:9D:AA:45:46", |
| 1636 |
"Alias": "FA:23:9D:AA:45:46", |
| 1637 |
"RSSI": -80, |
| 1638 |
}, |
| 1639 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1640 |
}, |
| 1641 |
"/org/bluez/hci3/dev_FA_23_9D_AA_45_46": { |
| 1642 |
"UUID": "service", |
| 1643 |
"Primary": True, |
| 1644 |
"Characteristics": [], |
| 1645 |
defs.DEVICE_INTERFACE: { |
| 1646 |
"Address": "FA:23:9D:AA:45:46", |
| 1647 |
"Alias": "FA:23:9D:AA:45:46", |
| 1648 |
"RSSI": -31, |
| 1649 |
}, |
| 1650 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1651 |
}, |
| 1652 |
} |
| 1653 |
|
| 1654 |
bluez_manager = FakeBluezManager() |
| 1655 |
|
| 1656 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock( |
| 1657 |
return_value=bluez_manager |
| 1658 |
) |
| 1659 |
|
| 1660 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager_with_timeout = ( |
| 1661 |
AsyncMock(return_value=bluez_manager) |
| 1662 |
) |
| 1663 |
bleak_retry_connector.bluez.defs = defs |
| 1664 |
|
| 1665 |
mock_device = BLEDevice( |
| 1666 |
"aa:bb:cc:dd:ee:ff", |
| 1667 |
"name", |
| 1668 |
{"path": "/org/bluez/hci2/dev_FA_23_9D_AA_45_46"}, |
| 1669 |
) |
| 1670 |
|
| 1671 |
connected = await get_connected_devices(mock_device) |
| 1672 |
assert len(connected) == 2 |
| 1673 |
assert isinstance(connected[0], BLEDevice) |
| 1674 |
assert connected[0].details["path"] == "/org/bluez/hci1/dev_FA_23_9D_AA_45_46" |
| 1675 |
assert connected[1].details["path"] == "/org/bluez/hci2/dev_FA_23_9D_AA_45_46" |
| 1676 |
|
| 1677 |
with patch("bleak_retry_connector.disconnect_devices") as mock_disconnect_device: |
| 1678 |
client = await establish_connection( |
| 1679 |
FakeBleakClientWithServiceCache, |
| 1680 |
BLEDevice( |
| 1681 |
"FA:23:9D:AA:45:46", |
| 1682 |
"name", |
| 1683 |
{"path": "/org/bluez/hci2/dev_FA_23_9D_AA_45_46"}, |
| 1684 |
), |
| 1685 |
"test", |
| 1686 |
disconnected_callback=MagicMock(), |
| 1687 |
cached_services=collection, |
| 1688 |
) |
| 1689 |
|
| 1690 |
assert isinstance(client, FakeBleakClientWithServiceCache) |
| 1691 |
await client.get_services() is collection |
| 1692 |
assert device is not None |
| 1693 |
assert device.details["path"] == "/org/bluez/hci1/dev_FA_23_9D_AA_45_46" |
| 1694 |
assert not mock_disconnect_device.mock_calls |
| 1695 |
|
| 1696 |
|
| 1697 |
@pytest.mark.asyncio |
| 1698 |
async def test_establish_connection_better_rssi_available_already_connected_supported_same_adapter( |
| 1699 |
mock_linux, |
| 1700 |
): |
| 1701 |
device: BLEDevice | None = None |
| 1702 |
|
| 1703 |
class FakeBleakClient(BleakClient): |
| 1704 |
def __init__(self, ble_device_or_address, *args, **kwargs): |
| 1705 |
ble_device_or_address.details["delegate"] = 0 |
| 1706 |
super().__init__(ble_device_or_address, *args, **kwargs) |
| 1707 |
nonlocal device |
| 1708 |
device = ble_device_or_address |
| 1709 |
self._device_path = "/org/bluez/hci2/dev_FA_23_9D_AA_45_46" |
| 1710 |
|
| 1711 |
async def connect(self, *args, **kwargs): |
| 1712 |
return True |
| 1713 |
|
| 1714 |
async def disconnect(self, *args, **kwargs): |
| 1715 |
pass |
| 1716 |
|
| 1717 |
async def get_services(self, *args, **kwargs): |
| 1718 |
return [] |
| 1719 |
|
| 1720 |
class FakeBleakClientWithServiceCache(BleakClientWithServiceCache, FakeBleakClient): |
| 1721 |
"""Fake BleakClientWithServiceCache.""" |
| 1722 |
|
| 1723 |
async def get_services(self, *args, **kwargs): |
| 1724 |
return [] |
| 1725 |
|
| 1726 |
collection = BleakGATTServiceCollection() |
| 1727 |
|
| 1728 |
class FakeBluezManager: |
| 1729 |
def __init__(self): |
| 1730 |
self._services_cache = {} |
| 1731 |
self._properties = { |
| 1732 |
"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": { |
| 1733 |
"UUID": "service", |
| 1734 |
"Primary": True, |
| 1735 |
"Characteristics": [], |
| 1736 |
defs.DEVICE_INTERFACE: { |
| 1737 |
"Address": "FA:23:9D:AA:45:46", |
| 1738 |
"Alias": "FA:23:9D:AA:45:46", |
| 1739 |
"RSSI": -30, |
| 1740 |
}, |
| 1741 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1742 |
}, |
| 1743 |
"/org/bluez/hci1/dev_FA_23_9D_AA_45_46": { |
| 1744 |
"UUID": "service", |
| 1745 |
"Primary": True, |
| 1746 |
"Characteristics": [], |
| 1747 |
defs.DEVICE_INTERFACE: { |
| 1748 |
"Connected": True, |
| 1749 |
"Address": "FA:23:9D:AA:45:46", |
| 1750 |
"Alias": "FA:23:9D:AA:45:46", |
| 1751 |
"RSSI": -79, |
| 1752 |
}, |
| 1753 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1754 |
}, |
| 1755 |
"/org/bluez/hci2/dev_FA_23_9D_AA_45_46": { |
| 1756 |
"UUID": "service", |
| 1757 |
"Primary": True, |
| 1758 |
"Characteristics": [], |
| 1759 |
defs.DEVICE_INTERFACE: { |
| 1760 |
"Connected": True, |
| 1761 |
"Address": "FA:23:9D:AA:45:46", |
| 1762 |
"Alias": "FA:23:9D:AA:45:46", |
| 1763 |
"RSSI": -80, |
| 1764 |
}, |
| 1765 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1766 |
}, |
| 1767 |
"/org/bluez/hci3/dev_FA_23_9D_AA_45_46": { |
| 1768 |
"UUID": "service", |
| 1769 |
"Primary": True, |
| 1770 |
"Characteristics": [], |
| 1771 |
defs.DEVICE_INTERFACE: { |
| 1772 |
"Address": "FA:23:9D:AA:45:46", |
| 1773 |
"Alias": "FA:23:9D:AA:45:46", |
| 1774 |
"RSSI": -31, |
| 1775 |
}, |
| 1776 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1777 |
}, |
| 1778 |
} |
| 1779 |
|
| 1780 |
bluez_manager = FakeBluezManager() |
| 1781 |
|
| 1782 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock( |
| 1783 |
return_value=bluez_manager |
| 1784 |
) |
| 1785 |
|
| 1786 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager_with_timeout = ( |
| 1787 |
AsyncMock(return_value=bluez_manager) |
| 1788 |
) |
| 1789 |
bleak_retry_connector.bluez.defs = defs |
| 1790 |
|
| 1791 |
mock_device = BLEDevice( |
| 1792 |
"aa:bb:cc:dd:ee:ff", |
| 1793 |
"name", |
| 1794 |
{"path": "/org/bluez/hci2/dev_FA_23_9D_AA_45_46"}, |
| 1795 |
) |
| 1796 |
|
| 1797 |
connected = await get_connected_devices(mock_device) |
| 1798 |
assert len(connected) == 2 |
| 1799 |
assert isinstance(connected[0], BLEDevice) |
| 1800 |
assert connected[0].details["path"] == "/org/bluez/hci1/dev_FA_23_9D_AA_45_46" |
| 1801 |
assert connected[1].details["path"] == "/org/bluez/hci2/dev_FA_23_9D_AA_45_46" |
| 1802 |
|
| 1803 |
backend_info = bleak.get_platform_client_backend_type() |
| 1804 |
with ( |
| 1805 |
patch("bleak_retry_connector.disconnect_devices") as mock_disconnect_device, |
| 1806 |
patch("bleak.get_platform_client_backend_type", return_value=backend_info), |
| 1807 |
): |
| 1808 |
client = await establish_connection( |
| 1809 |
FakeBleakClientWithServiceCache, |
| 1810 |
BLEDevice( |
| 1811 |
"FA:23:9D:AA:45:46", |
| 1812 |
"name", |
| 1813 |
{"path": "/org/bluez/hci1/dev_FA_23_9D_AA_45_46"}, |
| 1814 |
), |
| 1815 |
"test", |
| 1816 |
disconnected_callback=MagicMock(), |
| 1817 |
cached_services=collection, |
| 1818 |
) |
| 1819 |
|
| 1820 |
assert isinstance(client, FakeBleakClientWithServiceCache) |
| 1821 |
await client.get_services() is collection |
| 1822 |
assert device is not None |
| 1823 |
assert device.details["path"] == "/org/bluez/hci1/dev_FA_23_9D_AA_45_46" |
| 1824 |
assert not mock_disconnect_device.mock_calls |
| 1825 |
|
| 1826 |
|
| 1827 |
@pytest.mark.asyncio |
| 1828 |
async def test_get_device_by_adapter(mock_linux): |
| 1829 |
class FakeBluezManager: |
| 1830 |
def __init__(self): |
| 1831 |
self._services_cache = {} |
| 1832 |
self._properties = { |
| 1833 |
"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": { |
| 1834 |
"UUID": "service", |
| 1835 |
"Primary": True, |
| 1836 |
"Characteristics": [], |
| 1837 |
defs.DEVICE_INTERFACE: { |
| 1838 |
"Address": "FA:23:9D:AA:45:46", |
| 1839 |
"Alias": "FA:23:9D:AA:45:46", |
| 1840 |
"RSSI": -30, |
| 1841 |
}, |
| 1842 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1843 |
}, |
| 1844 |
"/org/bluez/hci1/dev_FA_23_9D_AA_45_46": { |
| 1845 |
"UUID": "service", |
| 1846 |
"Primary": True, |
| 1847 |
"Characteristics": [], |
| 1848 |
defs.DEVICE_INTERFACE: { |
| 1849 |
"Address": "FA:23:9D:AA:45:46", |
| 1850 |
"Alias": "FA:23:9D:AA:45:46", |
| 1851 |
"RSSI": -79, |
| 1852 |
}, |
| 1853 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1854 |
}, |
| 1855 |
"/org/bluez/hci2/dev_FA_23_9D_AA_45_46": { |
| 1856 |
"UUID": "service", |
| 1857 |
"Primary": True, |
| 1858 |
"Characteristics": [], |
| 1859 |
defs.DEVICE_INTERFACE: { |
| 1860 |
"Address": "FA:23:9D:AA:45:46", |
| 1861 |
"Alias": "FA:23:9D:AA:45:46", |
| 1862 |
"RSSI": -80, |
| 1863 |
}, |
| 1864 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1865 |
}, |
| 1866 |
"/org/bluez/hci3/dev_FA_23_9D_AA_45_46": { |
| 1867 |
"UUID": "service", |
| 1868 |
"Primary": True, |
| 1869 |
"Characteristics": [], |
| 1870 |
defs.DEVICE_INTERFACE: { |
| 1871 |
"Address": "FA:23:9D:AA:45:46", |
| 1872 |
"Alias": "FA:23:9D:AA:45:46", |
| 1873 |
"RSSI": -31, |
| 1874 |
}, |
| 1875 |
defs.GATT_SERVICE_INTERFACE: True, |
| 1876 |
}, |
| 1877 |
} |
| 1878 |
|
| 1879 |
bluez_manager = FakeBluezManager() |
| 1880 |
|
| 1881 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock( |
| 1882 |
return_value=bluez_manager |
| 1883 |
) |
| 1884 |
|
| 1885 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager_with_timeout = ( |
| 1886 |
AsyncMock(return_value=bluez_manager) |
| 1887 |
) |
| 1888 |
bleak_retry_connector.bluez.defs = defs |
| 1889 |
|
| 1890 |
device_hci0 = await get_device_by_adapter("FA:23:9D:AA:45:46", "hci0") |
| 1891 |
device_hci1 = await get_device_by_adapter("FA:23:9D:AA:45:46", "hci1") |
| 1892 |
|
| 1893 |
assert device_hci0 is not None |
| 1894 |
assert device_hci0.details["path"] == "/org/bluez/hci0/dev_FA_23_9D_AA_45_46" |
| 1895 |
assert device_hci1 is not None |
| 1896 |
assert device_hci1.details["path"] == "/org/bluez/hci1/dev_FA_23_9D_AA_45_46" |
| 1897 |
|
| 1898 |
|
| 1899 |
def test_calculate_backoff_time(): |
| 1900 |
"""Test that the backoff time is calculated correctly.""" |
| 1901 |
assert calculate_backoff_time(Exception()) == BLEAK_BACKOFF_TIME |
| 1902 |
assert ( |
| 1903 |
calculate_backoff_time(BleakDBusError(MagicMock(), MagicMock())) |
| 1904 |
== BLEAK_DBUS_BACKOFF_TIME |
| 1905 |
) |
| 1906 |
assert ( |
| 1907 |
calculate_backoff_time( |
| 1908 |
BleakError( |
| 1909 |
"No backend with an available connection slot that can reach address EB:4A:D4:93:68:EF was found" |
| 1910 |
) |
| 1911 |
) |
| 1912 |
== BLEAK_OUT_OF_SLOTS_BACKOFF_TIME |
| 1913 |
) |
| 1914 |
assert ( |
| 1915 |
calculate_backoff_time(BleakError("ESP_GATT_CONN_TERMINATE_PEER_USER")) |
| 1916 |
== BLEAK_TRANSIENT_BACKOFF_TIME |
| 1917 |
) |
| 1918 |
assert ( |
| 1919 |
calculate_backoff_time(BleakError("ESP_GATT_CONN_FAIL_ESTABLISH")) |
| 1920 |
== BLEAK_TRANSIENT_MEDIUM_BACKOFF_TIME |
| 1921 |
) |
| 1922 |
assert ( |
| 1923 |
calculate_backoff_time(BleakError("ESP_GATT_ERROR")) |
| 1924 |
== BLEAK_TRANSIENT_LONG_BACKOFF_TIME |
| 1925 |
) |
| 1926 |
assert ( |
| 1927 |
calculate_backoff_time(BleakDeviceNotFoundError("Out of slots")) |
| 1928 |
== BLEAK_OUT_OF_SLOTS_BACKOFF_TIME |
| 1929 |
) |
| 1930 |
assert ( |
| 1931 |
calculate_backoff_time(BleakError("ESP_GATT_CONN_CONN_CANCEL")) |
| 1932 |
== BLEAK_OUT_OF_SLOTS_BACKOFF_TIME |
| 1933 |
) |
| 1934 |
assert ( |
| 1935 |
calculate_backoff_time( |
| 1936 |
asyncio.TimeoutError( |
| 1937 |
"test [aa:bb:cc:dd:ee:ff]: No free BLE connection slot " |
| 1938 |
"became available (limit=3, in use=3)" |
| 1939 |
) |
| 1940 |
) |
| 1941 |
== BLEAK_OUT_OF_SLOTS_BACKOFF_TIME |
| 1942 |
) |
| 1943 |
assert calculate_backoff_time(EOFError()) == BLEAK_DBUS_BACKOFF_TIME |
| 1944 |
assert calculate_backoff_time(BrokenPipeError()) == BLEAK_DBUS_BACKOFF_TIME |
| 1945 |
assert calculate_backoff_time(asyncio.TimeoutError()) == BLEAK_DBUS_BACKOFF_TIME |
| 1946 |
assert ( |
| 1947 |
calculate_backoff_time(BleakNotFoundError("not found")) |
| 1948 |
== BLEAK_OUT_OF_SLOTS_BACKOFF_TIME |
| 1949 |
) |
| 1950 |
assert ( |
| 1951 |
calculate_backoff_time(BleakError("Disconnected")) |
| 1952 |
== BLEAK_DISCONNECTED_BACKOFF_TIME |
| 1953 |
) |
| 1954 |
|
| 1955 |
|
| 1956 |
@pytest.mark.asyncio |
| 1957 |
async def test_retry_bluetooth_connection_error(): |
| 1958 |
"""Test that the retry_bluetooth_connection_error decorator works correctly.""" |
| 1959 |
|
| 1960 |
@retry_bluetooth_connection_error() |
| 1961 |
async def test_function(): |
| 1962 |
raise BleakDBusError(MagicMock(), MagicMock()) |
| 1963 |
|
| 1964 |
with patch( |
| 1965 |
"bleak_retry_connector.calculate_backoff_time" |
| 1966 |
) as mock_calculate_backoff_time: |
| 1967 |
mock_calculate_backoff_time.return_value = 0 |
| 1968 |
with pytest.raises(BleakDBusError): |
| 1969 |
await test_function() |
| 1970 |
|
| 1971 |
assert mock_calculate_backoff_time.call_count == 2 |
| 1972 |
|
| 1973 |
|
| 1974 |
@pytest.mark.asyncio |
| 1975 |
async def test_retry_bluetooth_connection_error_non_default_max_attempts(): |
| 1976 |
"""Test that the retry_bluetooth_connection_error decorator works correctly with a different number of retries.""" |
| 1977 |
|
| 1978 |
@retry_bluetooth_connection_error(4) |
| 1979 |
async def test_function(): |
| 1980 |
raise BleakDBusError(MagicMock(), MagicMock()) |
| 1981 |
|
| 1982 |
with patch( |
| 1983 |
"bleak_retry_connector.calculate_backoff_time" |
| 1984 |
) as mock_calculate_backoff_time: |
| 1985 |
mock_calculate_backoff_time.return_value = 0 |
| 1986 |
with pytest.raises(BleakDBusError): |
| 1987 |
await test_function() |
| 1988 |
|
| 1989 |
assert mock_calculate_backoff_time.call_count == 4 |
| 1990 |
|
| 1991 |
|
| 1992 |
@pytest.mark.asyncio |
| 1993 |
@pytest.mark.parametrize("exception", [EOFError, BrokenPipeError]) |
| 1994 |
async def test_retry_bluetooth_connection_error_retries_dead_socket_errors( |
| 1995 |
exception: type[Exception], |
| 1996 |
) -> None: |
| 1997 |
"""Test that errors from a dead D-Bus socket are retried.""" |
| 1998 |
|
| 1999 |
@retry_bluetooth_connection_error() |
| 2000 |
async def test_function() -> None: |
| 2001 |
raise exception("socket died") |
| 2002 |
|
| 2003 |
with patch( |
| 2004 |
"bleak_retry_connector.calculate_backoff_time" |
| 2005 |
) as mock_calculate_backoff_time: |
| 2006 |
mock_calculate_backoff_time.return_value = 0 |
| 2007 |
with pytest.raises(exception): |
| 2008 |
await test_function() |
| 2009 |
|
| 2010 |
assert mock_calculate_backoff_time.call_count == 2 |
| 2011 |
|
| 2012 |
|
| 2013 |
@pytest.mark.asyncio |
| 2014 |
async def test_retry_bluetooth_connection_error_recovers_after_eof_error() -> None: |
| 2015 |
"""Test that a transient EOFError is retried and the call succeeds.""" |
| 2016 |
attempts: list[int] = [] |
| 2017 |
|
| 2018 |
@retry_bluetooth_connection_error() |
| 2019 |
async def test_function() -> str: |
| 2020 |
attempts.append(1) |
| 2021 |
if len(attempts) == 1: |
| 2022 |
raise EOFError("socket died") |
| 2023 |
return "success" |
| 2024 |
|
| 2025 |
with patch( |
| 2026 |
"bleak_retry_connector.calculate_backoff_time" |
| 2027 |
) as mock_calculate_backoff_time: |
| 2028 |
mock_calculate_backoff_time.return_value = 0 |
| 2029 |
assert await test_function() == "success" |
| 2030 |
|
| 2031 |
assert len(attempts) == 2 |
| 2032 |
|
| 2033 |
|
| 2034 |
@pytest.mark.asyncio |
| 2035 |
async def test_retry_bluetooth_connection_error_does_not_retry_timeout() -> None: |
| 2036 |
"""Test that asyncio.TimeoutError is not retried.""" |
| 2037 |
|
| 2038 |
@retry_bluetooth_connection_error() |
| 2039 |
async def test_function() -> None: |
| 2040 |
raise asyncio.TimeoutError |
| 2041 |
|
| 2042 |
with patch( |
| 2043 |
"bleak_retry_connector.calculate_backoff_time" |
| 2044 |
) as mock_calculate_backoff_time: |
| 2045 |
with pytest.raises(asyncio.TimeoutError): |
| 2046 |
await test_function() |
| 2047 |
|
| 2048 |
assert mock_calculate_backoff_time.call_count == 0 |
| 2049 |
|
| 2050 |
|
| 2051 |
@pytest.mark.asyncio |
| 2052 |
async def test_dbus_is_missing(mock_linux): |
| 2053 |
"""Test getting a device when dbus is missing.""" |
| 2054 |
|
| 2055 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock( |
| 2056 |
side_effect=FileNotFoundError("dbus not here") |
| 2057 |
) |
| 2058 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager_with_timeout = ( |
| 2059 |
AsyncMock(side_effect=FileNotFoundError("dbus not here")) |
| 2060 |
) |
| 2061 |
bleak_retry_connector.bluez.defs = defs |
| 2062 |
|
| 2063 |
with patch.object(bleak_retry_connector.const, "IS_LINUX", True): |
| 2064 |
device = await get_device("FA:23:9D:AA:45:46") |
| 2065 |
|
| 2066 |
assert device is None |
| 2067 |
|
| 2068 |
class FakeBluezManager: |
| 2069 |
def __init__(self): |
| 2070 |
self._services_cache = {} |
| 2071 |
self._properties = { |
| 2072 |
"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": { |
| 2073 |
"UUID": "service", |
| 2074 |
"Primary": True, |
| 2075 |
"Characteristics": [], |
| 2076 |
defs.DEVICE_INTERFACE: { |
| 2077 |
"Address": "FA:23:9D:AA:45:46", |
| 2078 |
"Alias": "FA:23:9D:AA:45:46", |
| 2079 |
"RSSI": -30, |
| 2080 |
}, |
| 2081 |
defs.GATT_SERVICE_INTERFACE: True, |
| 2082 |
}, |
| 2083 |
"/org/bluez/hci1/dev_FA_23_9D_AA_45_46": { |
| 2084 |
"UUID": "service", |
| 2085 |
"Primary": True, |
| 2086 |
"Characteristics": [], |
| 2087 |
defs.DEVICE_INTERFACE: { |
| 2088 |
"Address": "FA:23:9D:AA:45:46", |
| 2089 |
"Alias": "FA:23:9D:AA:45:46", |
| 2090 |
"RSSI": -79, |
| 2091 |
}, |
| 2092 |
defs.GATT_SERVICE_INTERFACE: True, |
| 2093 |
}, |
| 2094 |
"/org/bluez/hci2/dev_FA_23_9D_AA_45_46": { |
| 2095 |
"UUID": "service", |
| 2096 |
"Primary": True, |
| 2097 |
"Characteristics": [], |
| 2098 |
defs.DEVICE_INTERFACE: { |
| 2099 |
"Address": "FA:23:9D:AA:45:46", |
| 2100 |
"Alias": "FA:23:9D:AA:45:46", |
| 2101 |
"RSSI": -80, |
| 2102 |
}, |
| 2103 |
defs.GATT_SERVICE_INTERFACE: True, |
| 2104 |
}, |
| 2105 |
"/org/bluez/hci3/dev_FA_23_9D_AA_45_46": { |
| 2106 |
"UUID": "service", |
| 2107 |
"Primary": True, |
| 2108 |
"Characteristics": [], |
| 2109 |
defs.DEVICE_INTERFACE: { |
| 2110 |
"Address": "FA:23:9D:AA:45:46", |
| 2111 |
"Alias": "FA:23:9D:AA:45:46", |
| 2112 |
"RSSI": -31, |
| 2113 |
}, |
| 2114 |
defs.GATT_SERVICE_INTERFACE: True, |
| 2115 |
}, |
| 2116 |
} |
| 2117 |
|
| 2118 |
bluez_manager = FakeBluezManager() |
| 2119 |
|
| 2120 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock( |
| 2121 |
return_value=bluez_manager |
| 2122 |
) |
| 2123 |
|
| 2124 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager_with_timeout = ( |
| 2125 |
AsyncMock(return_value=bluez_manager) |
| 2126 |
) |
| 2127 |
|
| 2128 |
device = await get_device("FA:23:9D:AA:45:46") |
| 2129 |
|
| 2130 |
assert device is not None |
| 2131 |
|
| 2132 |
_reset_dbus_socket_cache() |
| 2133 |
|
| 2134 |
device = await get_device("FA:23:9D:AA:45:46") |
| 2135 |
|
| 2136 |
assert device is not None |
| 2137 |
|
| 2138 |
|
| 2139 |
@pytest.mark.asyncio |
| 2140 |
async def test_ble_device_description(): |
| 2141 |
device = BLEDevice( |
| 2142 |
"aa:bb:cc:dd:ee:ff", |
| 2143 |
"name", |
| 2144 |
{"path": "/org/bluez/hci2/dev_FA_23_9D_AA_45_46"}, |
| 2145 |
) |
| 2146 |
assert ( |
| 2147 |
ble_device_description(device) == "aa:bb:cc:dd:ee:ff - name -> /org/bluez/hci2" |
| 2148 |
) |
| 2149 |
device2 = BLEDevice( |
| 2150 |
"aa:bb:cc:dd:ee:ff", |
| 2151 |
"name", |
| 2152 |
{"path": "/org/bluez/hci2/dev_FA_23_9D_AA_45_46"}, |
| 2153 |
) |
| 2154 |
assert ( |
| 2155 |
ble_device_description(device2) == "aa:bb:cc:dd:ee:ff - name -> /org/bluez/hci2" |
| 2156 |
) |
| 2157 |
device3 = BLEDevice("aa:bb:cc:dd:ee:ff", "name", {"source": "esphome_proxy_1"}) |
| 2158 |
assert ( |
| 2159 |
ble_device_description(device3) == "aa:bb:cc:dd:ee:ff - name -> esphome_proxy_1" |
| 2160 |
) |
| 2161 |
|
| 2162 |
|
| 2163 |
@pytest.mark.asyncio |
| 2164 |
@pytest.mark.skipif("not bleak_retry_connector.const.IS_LINUX") |
| 2165 |
async def test_restore_discoveries(mock_linux): |
| 2166 |
class FakeBluezManager: |
| 2167 |
def __init__(self): |
| 2168 |
self._services_cache = {} |
| 2169 |
self._properties = { |
| 2170 |
"/org/bluez/hci1/dev_BD_24_6F_85_AA_61": { |
| 2171 |
"org.freedesktop.DBus.Introspectable": {}, |
| 2172 |
"org.bluez.Device1": { |
| 2173 |
"Address": "BD:24:6F:85:AA:61", |
| 2174 |
"AddressType": "public", |
| 2175 |
"Name": "Dream~BD246F85AA61", |
| 2176 |
"Alias": "Dream~BD246F85AA61", |
| 2177 |
"Appearance": 962, |
| 2178 |
"Icon": "input-mouse", |
| 2179 |
"Paired": False, |
| 2180 |
"Trusted": False, |
| 2181 |
"Blocked": False, |
| 2182 |
"LegacyPairing": False, |
| 2183 |
"Connected": True, |
| 2184 |
"UUIDs": [ |
| 2185 |
"00001800-0000-1000-8000-00805f9b34fb", |
| 2186 |
"00001801-0000-1000-8000-00805f9b34fb", |
| 2187 |
"0000180a-0000-1000-8000-00805f9b34fb", |
| 2188 |
"0000ffd0-0000-1000-8000-00805f9b34fb", |
| 2189 |
"0000ffd5-0000-1000-8000-00805f9b34fb", |
| 2190 |
], |
| 2191 |
"Modalias": "usb:v045Ep0040d0300", |
| 2192 |
"Adapter": "/org/bluez/hci1", |
| 2193 |
"ManufacturerData": {20808: bytearray(b"364656")}, |
| 2194 |
"ServicesResolved": True, |
| 2195 |
}, |
| 2196 |
"org.freedesktop.DBus.Properties": {}, |
| 2197 |
}, |
| 2198 |
"/org/bluez/hci5/dev_BE_24_6F_85_AA_61": { |
| 2199 |
"org.freedesktop.DBus.Introspectable": {}, |
| 2200 |
"org.bluez.Device1": { |
| 2201 |
"Address": "BE:24:6F:85:AA:61", |
| 2202 |
"AddressType": "public", |
| 2203 |
"Name": "Dream~BD246F85AA61", |
| 2204 |
"Alias": "Dream~BD246F85AA61", |
| 2205 |
"Appearance": 962, |
| 2206 |
"Icon": "input-mouse", |
| 2207 |
"Paired": False, |
| 2208 |
"Trusted": False, |
| 2209 |
"Blocked": False, |
| 2210 |
"LegacyPairing": False, |
| 2211 |
"Connected": True, |
| 2212 |
"UUIDs": [ |
| 2213 |
"00001800-0000-1000-8000-00805f9b34fb", |
| 2214 |
"00001801-0000-1000-8000-00805f9b34fb", |
| 2215 |
"0000180a-0000-1000-8000-00805f9b34fb", |
| 2216 |
"0000ffd0-0000-1000-8000-00805f9b34fb", |
| 2217 |
"0000ffd5-0000-1000-8000-00805f9b34fb", |
| 2218 |
], |
| 2219 |
"Modalias": "usb:v045Ep0040d0300", |
| 2220 |
"Adapter": "/org/bluez/hci1", |
| 2221 |
"ManufacturerData": {20808: bytearray(b"364656")}, |
| 2222 |
"ServicesResolved": True, |
| 2223 |
}, |
| 2224 |
"org.freedesktop.DBus.Properties": {}, |
| 2225 |
}, |
| 2226 |
} |
| 2227 |
|
| 2228 |
bluez_manager = FakeBluezManager() |
| 2229 |
|
| 2230 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock( |
| 2231 |
return_value=bluez_manager |
| 2232 |
) |
| 2233 |
|
| 2234 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager_with_timeout = ( |
| 2235 |
AsyncMock(return_value=bluez_manager) |
| 2236 |
) |
| 2237 |
from bluetooth_adapters.history import load_history_from_managed_objects |
| 2238 |
|
| 2239 |
bleak_retry_connector.load_history_from_managed_objects = ( |
| 2240 |
load_history_from_managed_objects |
| 2241 |
) |
| 2242 |
bleak_retry_connector.bluez.defs = defs |
| 2243 |
seen_devices: dict[str, tuple[BLEDevice, AdvertisementData]] = {} |
| 2244 |
|
| 2245 |
mock_backend = Mock(seen_devices=seen_devices) |
| 2246 |
mock_scanner = Mock(_backend=mock_backend) |
| 2247 |
|
| 2248 |
await restore_discoveries(mock_scanner, "hci1") |
| 2249 |
|
| 2250 |
assert len(seen_devices) == 1 |
| 2251 |
|
| 2252 |
|
| 2253 |
@pytest.mark.asyncio |
| 2254 |
async def test_close_stale_connections_by_address(mock_linux): |
| 2255 |
class FakeBluezManager: |
| 2256 |
def __init__(self): |
| 2257 |
self._services_cache = { |
| 2258 |
"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": "test", |
| 2259 |
"/org/bluez/hci1/dev_FA_23_9D_AA_45_46": "test", |
| 2260 |
} |
| 2261 |
self._properties = { |
| 2262 |
"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": { |
| 2263 |
"UUID": "service", |
| 2264 |
"Primary": True, |
| 2265 |
"Characteristics": [], |
| 2266 |
defs.DEVICE_INTERFACE: { |
| 2267 |
"Address": "FA:23:9D:AA:45:46", |
| 2268 |
"Alias": "FA:23:9D:AA:45:46", |
| 2269 |
"RSSI": -30, |
| 2270 |
}, |
| 2271 |
defs.GATT_SERVICE_INTERFACE: True, |
| 2272 |
}, |
| 2273 |
"/org/bluez/hci1/dev_FA_23_9D_AA_45_46": { |
| 2274 |
"UUID": "service", |
| 2275 |
"Primary": True, |
| 2276 |
"Characteristics": [], |
| 2277 |
defs.DEVICE_INTERFACE: { |
| 2278 |
"Address": "FA:23:9D:AA:45:46", |
| 2279 |
"Alias": "FA:23:9D:AA:45:46", |
| 2280 |
"RSSI": -79, |
| 2281 |
"Connected": True, |
| 2282 |
}, |
| 2283 |
defs.GATT_SERVICE_INTERFACE: True, |
| 2284 |
}, |
| 2285 |
"/org/bluez/hci2/dev_FA_23_9D_AA_45_46": { |
| 2286 |
"UUID": "service", |
| 2287 |
"Primary": True, |
| 2288 |
"Characteristics": [], |
| 2289 |
defs.DEVICE_INTERFACE: { |
| 2290 |
"Address": "FA:23:9D:AA:45:46", |
| 2291 |
"Alias": "FA:23:9D:AA:45:46", |
| 2292 |
"RSSI": -80, |
| 2293 |
}, |
| 2294 |
defs.GATT_SERVICE_INTERFACE: True, |
| 2295 |
}, |
| 2296 |
"/org/bluez/hci3/dev_FA_23_9D_AA_45_46": { |
| 2297 |
"UUID": "service", |
| 2298 |
"Primary": True, |
| 2299 |
"Characteristics": [], |
| 2300 |
defs.DEVICE_INTERFACE: { |
| 2301 |
"Address": "FA:23:9D:AA:45:46", |
| 2302 |
"Alias": "FA:23:9D:AA:45:46", |
| 2303 |
"RSSI": -31, |
| 2304 |
}, |
| 2305 |
defs.GATT_SERVICE_INTERFACE: True, |
| 2306 |
}, |
| 2307 |
} |
| 2308 |
|
| 2309 |
bluez_manager = FakeBluezManager() |
| 2310 |
|
| 2311 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager = AsyncMock( |
| 2312 |
return_value=bluez_manager |
| 2313 |
) |
| 2314 |
bleak_retry_connector.bleak_manager.get_global_bluez_manager_with_timeout = ( |
| 2315 |
AsyncMock(return_value=bluez_manager) |
| 2316 |
) |
| 2317 |
bleak_retry_connector.bluez.defs = defs |
| 2318 |
|
| 2319 |
with patch.object( |
| 2320 |
bleak_retry_connector, "disconnect_devices", AsyncMock() |
| 2321 |
) as mock_disconnect_devices: |
| 2322 |
await close_stale_connections_by_address("FA:23:9D:AA:45:46") |
| 2323 |
assert len(mock_disconnect_devices.mock_calls) == 1 |
| 2324 |
|
| 2325 |
|
| 2326 |
@pytest.mark.asyncio |
| 2327 |
async def test_has_valid_services_in_cache_success(mock_linux): |
| 2328 |
"""Test successful validation when all cached services are present in properties.""" |
| 2329 |
|
| 2330 |
class FakeBleakClient(BleakClient): |
| 2331 |
"""Fake BleakClient.""" |
| 2332 |
|
| 2333 |
async def connect(self, **kwargs): |
| 2334 |
"""Connect.""" |
| 2335 |
|
| 2336 |
async def disconnect(self): |
| 2337 |
"""Disconnect.""" |
| 2338 |
|
| 2339 |
async def get_services(self): |
| 2340 |
"""Get services.""" |
| 2341 |
return [] |
| 2342 |
|
| 2343 |
# Create a proper BleakGATTServiceCollection with services |
| 2344 |
collection = BleakGATTServiceCollection() |
| 2345 |
|
| 2346 |
# Add a service that will be present in properties |
| 2347 |
service_path = "/org/bluez/hci0/dev_FA_23_9D_AA_45_46/service0001" |
| 2348 |
service_props = { |
| 2349 |
"UUID": "0000180a-0000-1000-8000-00805f9b34fb", |
| 2350 |
"Primary": True, |
| 2351 |
"Characteristics": [], |
| 2352 |
} |
| 2353 |
service = BleakGATTService( |
| 2354 |
obj=(service_path, service_props), |
| 2355 |
handle=1, |
| 2356 |
uuid="0000180a-0000-1000-8000-00805f9b34fb", |
| 2357 |
) |
| 2358 |
collection.add_service(service) |
| 2359 |
|
| 2360 |
# Add another service |
| 2361 |
service_path2 = "/org/bluez/hci0/dev_FA_23_9D_AA_45_46/service0002" |
| 2362 |
service_props2 = { |
| 2363 |
"UUID": "0000180f-0000-1000-8000-00805f9b34fb", |
| 2364 |
"Primary": True, |
| 2365 |
"Characteristics": [], |
| 2366 |
} |
| 2367 |
service2 = BleakGATTService( |
| 2368 |
obj=(service_path2, service_props2), |
| 2369 |
handle=2, |
| 2370 |
uuid="0000180f-0000-1000-8000-00805f9b34fb", |
| 2371 |
) |
| 2372 |
collection.add_service(service2) |
| 2373 |
|
| 2374 |
class FakeBluezManager: |
| 2375 |
def __init__(self): |
| 2376 |
# Services cache contains our collection for the device |
| 2377 |
self._services_cache = {"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": collection} |
| 2378 |
# Properties contain both service paths |
| 2379 |
self._properties = { |
| 2380 |
"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": { |
| 2381 |
"org.bluez.Device1": { |
| 2382 |
"Address": "FA:23:9D:AA:45:46", |
| 2383 |
"Connected": False, |
| 2384 |
} |
| 2385 |
}, |
| 2386 |
# Both services are present in properties |
| 2387 |
service_path: service_props, |
| 2388 |
service_path2: service_props2, |
| 2389 |
} |
| 2390 |
|
| 2391 |
bluez_manager = FakeBluezManager() |
| 2392 |
|
| 2393 |
bleak_retry_connector.bluez.get_global_bluez_manager_with_timeout = AsyncMock( |
| 2394 |
return_value=bluez_manager |
| 2395 |
) |
| 2396 |
bleak_retry_connector.bluez.defs = defs |
| 2397 |
|
| 2398 |
device = BLEDevice( |
| 2399 |
address="FA:23:9D:AA:45:46", |
| 2400 |
name="Test Device", |
| 2401 |
details={"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"}, |
| 2402 |
) |
| 2403 |
|
| 2404 |
# Capture the log to verify the success message |
| 2405 |
with patch.object( |
| 2406 |
bleak_retry_connector, |
| 2407 |
"_has_valid_services_in_cache", |
| 2408 |
wraps=bleak_retry_connector._has_valid_services_in_cache, |
| 2409 |
) as mock_validate: |
| 2410 |
client = await bleak_retry_connector.establish_connection( |
| 2411 |
FakeBleakClient, |
| 2412 |
device, |
| 2413 |
"Test Device", |
| 2414 |
use_services_cache=True, |
| 2415 |
) |
| 2416 |
|
| 2417 |
# Verify the validation was called |
| 2418 |
mock_validate.assert_called_once() |
| 2419 |
|
| 2420 |
# Call the wrapped function directly to verify it returns True |
| 2421 |
result = await bleak_retry_connector._has_valid_services_in_cache(device) |
| 2422 |
assert result is True |
| 2423 |
|
| 2424 |
assert client is not None |
| 2425 |
|
| 2426 |
|
| 2427 |
@pytest.mark.asyncio |
| 2428 |
async def test_has_valid_services_in_cache_service_missing(mock_linux): |
| 2429 |
"""Test validation fails when a cached service is not in properties.""" |
| 2430 |
|
| 2431 |
class FakeBleakClient(BleakClient): |
| 2432 |
"""Fake BleakClient.""" |
| 2433 |
|
| 2434 |
async def connect(self, **kwargs): |
| 2435 |
"""Connect.""" |
| 2436 |
|
| 2437 |
async def disconnect(self): |
| 2438 |
"""Disconnect.""" |
| 2439 |
|
| 2440 |
async def get_services(self): |
| 2441 |
"""Get services.""" |
| 2442 |
return [] |
| 2443 |
|
| 2444 |
# Create a proper BleakGATTServiceCollection with services |
| 2445 |
collection = BleakGATTServiceCollection() |
| 2446 |
|
| 2447 |
# Add a service that will NOT be present in properties |
| 2448 |
service_path = "/org/bluez/hci0/dev_FA_23_9D_AA_45_46/service0001" |
| 2449 |
service_props = { |
| 2450 |
"UUID": "0000180a-0000-1000-8000-00805f9b34fb", |
| 2451 |
"Primary": True, |
| 2452 |
"Characteristics": [], |
| 2453 |
} |
| 2454 |
service = BleakGATTService( |
| 2455 |
obj=(service_path, service_props), |
| 2456 |
handle=1, |
| 2457 |
uuid="0000180a-0000-1000-8000-00805f9b34fb", |
| 2458 |
) |
| 2459 |
collection.add_service(service) |
| 2460 |
|
| 2461 |
class FakeBluezManager: |
| 2462 |
def __init__(self): |
| 2463 |
# Services cache contains our collection for the device |
| 2464 |
self._services_cache = {"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": collection} |
| 2465 |
# Properties do NOT contain the service path - service is missing |
| 2466 |
self._properties = { |
| 2467 |
"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": { |
| 2468 |
"org.bluez.Device1": { |
| 2469 |
"Address": "FA:23:9D:AA:45:46", |
| 2470 |
"Connected": False, |
| 2471 |
} |
| 2472 |
}, |
| 2473 |
# service_path is NOT in properties |
| 2474 |
} |
| 2475 |
|
| 2476 |
bluez_manager = FakeBluezManager() |
| 2477 |
|
| 2478 |
bleak_retry_connector.bluez.get_global_bluez_manager_with_timeout = AsyncMock( |
| 2479 |
return_value=bluez_manager |
| 2480 |
) |
| 2481 |
bleak_retry_connector.bluez.defs = defs |
| 2482 |
|
| 2483 |
device = BLEDevice( |
| 2484 |
address="FA:23:9D:AA:45:46", |
| 2485 |
name="Test Device", |
| 2486 |
details={"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"}, |
| 2487 |
) |
| 2488 |
|
| 2489 |
# Call the function directly to verify it returns False |
| 2490 |
result = await bleak_retry_connector._has_valid_services_in_cache(device) |
| 2491 |
assert result is False |
| 2492 |
|
| 2493 |
# Verify that the cache is not used when validation fails |
| 2494 |
client = await bleak_retry_connector.establish_connection( |
| 2495 |
FakeBleakClient, |
| 2496 |
device, |
| 2497 |
"Test Device", |
| 2498 |
use_services_cache=True, |
| 2499 |
) |
| 2500 |
assert client is not None |
| 2501 |
|
| 2502 |
|
| 2503 |
@pytest.mark.asyncio |
| 2504 |
async def test_has_valid_services_in_cache_no_services(mock_linux): |
| 2505 |
"""Test validation returns False when there are no services in the collection.""" |
| 2506 |
|
| 2507 |
class FakeBleakClient(BleakClient): |
| 2508 |
"""Fake BleakClient.""" |
| 2509 |
|
| 2510 |
async def connect(self, **kwargs): |
| 2511 |
"""Connect.""" |
| 2512 |
|
| 2513 |
async def disconnect(self): |
| 2514 |
"""Disconnect.""" |
| 2515 |
|
| 2516 |
async def get_services(self): |
| 2517 |
"""Get services.""" |
| 2518 |
return [] |
| 2519 |
|
| 2520 |
# Create an empty BleakGATTServiceCollection (no services) |
| 2521 |
collection = BleakGATTServiceCollection() |
| 2522 |
|
| 2523 |
class FakeBluezManager: |
| 2524 |
def __init__(self): |
| 2525 |
# Services cache contains an empty collection for the device |
| 2526 |
self._services_cache = {"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": collection} |
| 2527 |
# Properties exist but collection has no services |
| 2528 |
self._properties = { |
| 2529 |
"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": { |
| 2530 |
"org.bluez.Device1": { |
| 2531 |
"Address": "FA:23:9D:AA:45:46", |
| 2532 |
"Connected": False, |
| 2533 |
} |
| 2534 |
}, |
| 2535 |
} |
| 2536 |
|
| 2537 |
bluez_manager = FakeBluezManager() |
| 2538 |
|
| 2539 |
bleak_retry_connector.bluez.get_global_bluez_manager_with_timeout = AsyncMock( |
| 2540 |
return_value=bluez_manager |
| 2541 |
) |
| 2542 |
bleak_retry_connector.bluez.defs = defs |
| 2543 |
|
| 2544 |
device = BLEDevice( |
| 2545 |
address="FA:23:9D:AA:45:46", |
| 2546 |
name="Test Device", |
| 2547 |
details={"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"}, |
| 2548 |
) |
| 2549 |
|
| 2550 |
# Call the function directly to verify it returns False |
| 2551 |
result = await bleak_retry_connector._has_valid_services_in_cache(device) |
| 2552 |
assert result is False |
| 2553 |
|
| 2554 |
# Verify that the cache is not used when there are no services |
| 2555 |
client = await bleak_retry_connector.establish_connection( |
| 2556 |
FakeBleakClient, |
| 2557 |
device, |
| 2558 |
"Test Device", |
| 2559 |
use_services_cache=True, |
| 2560 |
) |
| 2561 |
assert client is not None |
| 2562 |
|
| 2563 |
|
| 2564 |
@pytest.mark.asyncio |
| 2565 |
async def test_has_valid_services_in_cache_non_linux(mock_macos): |
| 2566 |
"""Test that cache is always valid on non-Linux platforms.""" |
| 2567 |
|
| 2568 |
device = BLEDevice( |
| 2569 |
address="FA:23:9D:AA:45:46", |
| 2570 |
name="Test Device", |
| 2571 |
details={"path": "/some/macos/path"}, |
| 2572 |
) |
| 2573 |
|
| 2574 |
# Should return True on non-Linux platforms |
| 2575 |
result = await bleak_retry_connector._has_valid_services_in_cache(device) |
| 2576 |
assert result is True |
| 2577 |
|
| 2578 |
|
| 2579 |
@pytest.mark.asyncio |
| 2580 |
async def test_has_valid_services_in_cache_esphome_proxy(mock_linux): |
| 2581 |
"""Test that cache is always valid for ESPHome proxy devices.""" |
| 2582 |
|
| 2583 |
# Device without a BlueZ path (ESPHome proxy device) |
| 2584 |
device = BLEDevice( |
| 2585 |
address="FA:23:9D:AA:45:46", |
| 2586 |
name="Test Device", |
| 2587 |
details={"source": "192.168.1.100"}, # ESPHome proxy source |
| 2588 |
) |
| 2589 |
|
| 2590 |
# Should return True for non-BlueZ devices (ESPHome proxy) |
| 2591 |
result = await bleak_retry_connector._has_valid_services_in_cache(device) |
| 2592 |
assert result is True |
| 2593 |
|
| 2594 |
|
| 2595 |
@pytest.mark.asyncio |
| 2596 |
async def test_set_connection_params_delegates_to_super(): |
| 2597 |
"""Test that set_connection_params delegates to super when available.""" |
| 2598 |
set_connection_params_mock = AsyncMock() |
| 2599 |
|
| 2600 |
class FakeBleakClientWithSetConnectionParams(BleakClient): |
| 2601 |
def __init__(self, *args, **kwargs): |
| 2602 |
pass |
| 2603 |
|
| 2604 |
async def connect(self, *args, **kwargs): |
| 2605 |
pass |
| 2606 |
|
| 2607 |
async def disconnect(self, *args, **kwargs): |
| 2608 |
pass |
| 2609 |
|
| 2610 |
async def set_connection_params( |
| 2611 |
self, min_interval, max_interval, latency, timeout |
| 2612 |
): |
| 2613 |
await set_connection_params_mock( |
| 2614 |
min_interval, max_interval, latency, timeout |
| 2615 |
) |
| 2616 |
|
| 2617 |
class FakeClientWithCache( |
| 2618 |
BleakClientWithServiceCache, FakeBleakClientWithSetConnectionParams |
| 2619 |
): |
| 2620 |
"""Fake BleakClientWithServiceCache with set_connection_params on parent.""" |
| 2621 |
|
| 2622 |
client = FakeClientWithCache(MagicMock()) |
| 2623 |
await client.set_connection_params(10, 20, 3, 400) |
| 2624 |
set_connection_params_mock.assert_called_once_with(10, 20, 3, 400) |
| 2625 |
|
| 2626 |
|
| 2627 |
@pytest.mark.asyncio |
| 2628 |
async def test_set_connection_params_warns_when_not_available(caplog): |
| 2629 |
"""Test that set_connection_params logs a warning when not available on parent.""" |
| 2630 |
import logging |
| 2631 |
|
| 2632 |
class FakeBleakClientNoSetConnectionParams(BleakClient): |
| 2633 |
def __init__(self, *args, **kwargs): |
| 2634 |
pass |
| 2635 |
|
| 2636 |
async def connect(self, *args, **kwargs): |
| 2637 |
pass |
| 2638 |
|
| 2639 |
async def disconnect(self, *args, **kwargs): |
| 2640 |
pass |
| 2641 |
|
| 2642 |
class FakeClientWithCache( |
| 2643 |
BleakClientWithServiceCache, FakeBleakClientNoSetConnectionParams |
| 2644 |
): |
| 2645 |
"""Fake BleakClientWithServiceCache without set_connection_params on parent.""" |
| 2646 |
|
| 2647 |
client = FakeClientWithCache(MagicMock()) |
| 2648 |
with caplog.at_level(logging.WARNING): |
| 2649 |
await client.set_connection_params(10, 20, 3, 400) |
| 2650 |
assert "set_connection_params not implemented in bleak version" in caplog.text |
| 2651 |
|
| 2652 |
|
| 2653 |
@pytest.mark.asyncio |
| 2654 |
async def test_clear_cache_delegates_to_super(): |
| 2655 |
"""clear_cache should call super().clear_cache when present and return its result.""" |
| 2656 |
clear_cache_mock = AsyncMock(return_value=True) |
| 2657 |
|
| 2658 |
class FakeBleakClientWithClearCache(BleakClient): |
| 2659 |
def __init__(self, *args, **kwargs): |
| 2660 |
pass |
| 2661 |
|
| 2662 |
async def connect(self, *args, **kwargs): |
| 2663 |
pass |
| 2664 |
|
| 2665 |
async def disconnect(self, *args, **kwargs): |
| 2666 |
pass |
| 2667 |
|
| 2668 |
async def clear_cache(self) -> bool: |
| 2669 |
return await clear_cache_mock() |
| 2670 |
|
| 2671 |
class FakeClientWithCache( |
| 2672 |
BleakClientWithServiceCache, FakeBleakClientWithClearCache |
| 2673 |
): |
| 2674 |
"""Fake BleakClientWithServiceCache with clear_cache on parent.""" |
| 2675 |
|
| 2676 |
client = FakeClientWithCache(MagicMock()) |
| 2677 |
assert await client.clear_cache() is True |
| 2678 |
clear_cache_mock.assert_called_once() |
| 2679 |
|
| 2680 |
|
| 2681 |
@pytest.mark.asyncio |
| 2682 |
async def test_clear_cache_warns_when_not_available(caplog): |
| 2683 |
"""clear_cache should warn and return False when parent has no clear_cache.""" |
| 2684 |
import logging |
| 2685 |
|
| 2686 |
class FakeBleakClientNoClearCache(BleakClient): |
| 2687 |
def __init__(self, *args, **kwargs): |
| 2688 |
pass |
| 2689 |
|
| 2690 |
async def connect(self, *args, **kwargs): |
| 2691 |
pass |
| 2692 |
|
| 2693 |
async def disconnect(self, *args, **kwargs): |
| 2694 |
pass |
| 2695 |
|
| 2696 |
class FakeClientWithCache(BleakClientWithServiceCache, FakeBleakClientNoClearCache): |
| 2697 |
"""Fake BleakClientWithServiceCache without clear_cache on parent.""" |
| 2698 |
|
| 2699 |
# Sanity: this bleak version has no parent clear_cache so the else branch runs. |
| 2700 |
parent_for_super = FakeBleakClientNoClearCache |
| 2701 |
assert not hasattr(parent_for_super, "clear_cache") |
| 2702 |
|
| 2703 |
client = FakeClientWithCache(MagicMock()) |
| 2704 |
with caplog.at_level(logging.WARNING): |
| 2705 |
result = await client.clear_cache() |
| 2706 |
assert result is False |
| 2707 |
assert "clear_cache not implemented in bleak version" in caplog.text |
| 2708 |
|
| 2709 |
|
| 2710 |
@pytest.mark.asyncio |
| 2711 |
async def test_ble_device_description_address_only(): |
| 2712 |
"""Name equal to address and no path/source should return address only.""" |
| 2713 |
device = BLEDevice("AA:BB:CC:DD:EE:FF", "AA:BB:CC:DD:EE:FF", {}) |
| 2714 |
assert ble_device_description(device) == "AA:BB:CC:DD:EE:FF" |
| 2715 |
|
| 2716 |
|
| 2717 |
@pytest.mark.asyncio |
| 2718 |
async def test_ble_device_description_non_dict_details(): |
| 2719 |
"""Non-dict details should skip the path/source branches.""" |
| 2720 |
device = BLEDevice("AA:BB:CC:DD:EE:FF", "name", "not-a-dict") |
| 2721 |
assert ble_device_description(device) == "AA:BB:CC:DD:EE:FF - name" |
| 2722 |
|
| 2723 |
|
| 2724 |
@pytest.mark.asyncio |
| 2725 |
async def test_has_valid_services_in_cache_no_cached_services_for_path(mock_linux): |
| 2726 |
"""Services cache exists but has no entry for the device path.""" |
| 2727 |
|
| 2728 |
class FakeBluezManager: |
| 2729 |
def __init__(self): |
| 2730 |
self._services_cache = {"/org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF": "other"} |
| 2731 |
self._properties = {} |
| 2732 |
|
| 2733 |
bluez_manager = FakeBluezManager() |
| 2734 |
bleak_retry_connector.bluez.get_global_bluez_manager_with_timeout = AsyncMock( |
| 2735 |
return_value=bluez_manager |
| 2736 |
) |
| 2737 |
bleak_retry_connector.bluez.defs = defs |
| 2738 |
|
| 2739 |
device = BLEDevice( |
| 2740 |
address="FA:23:9D:AA:45:46", |
| 2741 |
name="Test Device", |
| 2742 |
details={"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"}, |
| 2743 |
) |
| 2744 |
|
| 2745 |
result = await bleak_retry_connector._has_valid_services_in_cache(device) |
| 2746 |
assert result is False |
| 2747 |
|
| 2748 |
|
| 2749 |
@pytest.mark.asyncio |
| 2750 |
async def test_has_valid_services_in_cache_no_properties(mock_linux): |
| 2751 |
"""Services cache has the device but properties are unavailable.""" |
| 2752 |
|
| 2753 |
collection = BleakGATTServiceCollection() |
| 2754 |
service_path = "/org/bluez/hci0/dev_FA_23_9D_AA_45_46/service0001" |
| 2755 |
service_props = { |
| 2756 |
"UUID": "0000180a-0000-1000-8000-00805f9b34fb", |
| 2757 |
"Primary": True, |
| 2758 |
"Characteristics": [], |
| 2759 |
} |
| 2760 |
collection.add_service( |
| 2761 |
BleakGATTService( |
| 2762 |
obj=(service_path, service_props), |
| 2763 |
handle=1, |
| 2764 |
uuid="0000180a-0000-1000-8000-00805f9b34fb", |
| 2765 |
) |
| 2766 |
) |
| 2767 |
|
| 2768 |
class FakeBluezManager: |
| 2769 |
def __init__(self): |
| 2770 |
self._services_cache = {"/org/bluez/hci0/dev_FA_23_9D_AA_45_46": collection} |
| 2771 |
# Empty properties → _get_properties returns falsy |
| 2772 |
self._properties = {} |
| 2773 |
|
| 2774 |
bluez_manager = FakeBluezManager() |
| 2775 |
bleak_retry_connector.bluez.get_global_bluez_manager_with_timeout = AsyncMock( |
| 2776 |
return_value=bluez_manager |
| 2777 |
) |
| 2778 |
bleak_retry_connector.bluez.defs = defs |
| 2779 |
|
| 2780 |
device = BLEDevice( |
| 2781 |
address="FA:23:9D:AA:45:46", |
| 2782 |
name="Test Device", |
| 2783 |
details={"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"}, |
| 2784 |
) |
| 2785 |
|
| 2786 |
result = await bleak_retry_connector._has_valid_services_in_cache(device) |
| 2787 |
assert result is False |
| 2788 |
|
| 2789 |
|
| 2790 |
@pytest.mark.asyncio |
| 2791 |
async def test_close_stale_connections_by_address_non_linux(mock_macos): |
| 2792 |
"""On non-Linux, close_stale_connections_by_address returns without doing anything.""" |
| 2793 |
with patch.object( |
| 2794 |
bleak_retry_connector, "disconnect_devices", AsyncMock() |
| 2795 |
) as mock_disconnect_devices: |
| 2796 |
await close_stale_connections_by_address("FA:23:9D:AA:45:46") |
| 2797 |
assert mock_disconnect_devices.mock_calls == [] |
| 2798 |
|
| 2799 |
|
| 2800 |
@pytest.mark.asyncio |
| 2801 |
async def test_close_stale_connections_by_address_device_not_found(mock_linux): |
| 2802 |
"""If get_device returns None, no disconnect should happen.""" |
| 2803 |
with ( |
| 2804 |
patch.object(bleak_retry_connector, "get_device", AsyncMock(return_value=None)), |
| 2805 |
patch.object( |
| 2806 |
bleak_retry_connector, "disconnect_devices", AsyncMock() |
| 2807 |
) as mock_disconnect_devices, |
| 2808 |
): |
| 2809 |
await close_stale_connections_by_address("FA:23:9D:AA:45:46") |
| 2810 |
assert mock_disconnect_devices.mock_calls == [] |
| 2811 |
|
| 2812 |
|
| 2813 |
@pytest.mark.asyncio |
| 2814 |
async def test_close_stale_connections_non_linux(mock_macos): |
| 2815 |
"""On non-Linux, close_stale_connections returns immediately.""" |
| 2816 |
device = BLEDevice( |
| 2817 |
address="FA:23:9D:AA:45:46", |
| 2818 |
name="Test Device", |
| 2819 |
details={"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"}, |
| 2820 |
) |
| 2821 |
with patch.object( |
| 2822 |
bleak_retry_connector, "disconnect_devices", AsyncMock() |
| 2823 |
) as mock_disconnect_devices: |
| 2824 |
await close_stale_connections(device) |
| 2825 |
assert mock_disconnect_devices.mock_calls == [] |
| 2826 |
|
| 2827 |
|
| 2828 |
@pytest.mark.asyncio |
| 2829 |
async def test_close_stale_connections_no_connected_devices(mock_linux): |
| 2830 |
"""If get_connected_devices returns nothing, no disconnect should happen.""" |
| 2831 |
device = BLEDevice( |
| 2832 |
address="FA:23:9D:AA:45:46", |
| 2833 |
name="Test Device", |
| 2834 |
details={"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"}, |
| 2835 |
) |
| 2836 |
with ( |
| 2837 |
patch.object( |
| 2838 |
bleak_retry_connector, |
| 2839 |
"get_connected_devices", |
| 2840 |
AsyncMock(return_value=[]), |
| 2841 |
), |
| 2842 |
patch.object( |
| 2843 |
bleak_retry_connector, "disconnect_devices", AsyncMock() |
| 2844 |
) as mock_disconnect_devices, |
| 2845 |
): |
| 2846 |
await close_stale_connections(device) |
| 2847 |
assert mock_disconnect_devices.mock_calls == [] |
| 2848 |
|
| 2849 |
|
| 2850 |
@pytest.mark.asyncio |
| 2851 |
async def test_close_stale_connections_only_other_adapters_skips_same(mock_linux): |
| 2852 |
"""With only_other_adapters=True, devices on the same adapter are skipped.""" |
| 2853 |
device = BLEDevice( |
| 2854 |
address="FA:23:9D:AA:45:46", |
| 2855 |
name="Test Device", |
| 2856 |
details={"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"}, |
| 2857 |
) |
| 2858 |
# Connected device has the same path → ble_device_has_changed returns False |
| 2859 |
same_adapter_device = BLEDevice( |
| 2860 |
address="FA:23:9D:AA:45:46", |
| 2861 |
name="Test Device", |
| 2862 |
details={"path": "/org/bluez/hci0/dev_FA_23_9D_AA_45_46"}, |
| 2863 |
) |
| 2864 |
with ( |
| 2865 |
patch.object( |
| 2866 |
bleak_retry_connector, |
| 2867 |
"get_connected_devices", |
| 2868 |
AsyncMock(return_value=[same_adapter_device]), |
| 2869 |
), |
| 2870 |
patch.object( |
| 2871 |
bleak_retry_connector, "disconnect_devices", AsyncMock() |
| 2872 |
) as mock_disconnect_devices, |
| 2873 |
): |
| 2874 |
await close_stale_connections(device, only_other_adapters=True) |
| 2875 |
assert mock_disconnect_devices.mock_calls == [] |
| 2876 |
|
| 2877 |
|
| 2878 |
@pytest.mark.asyncio |
| 2879 |
async def test_restore_discoveries_non_linux(mock_macos: None) -> None: |
| 2880 |
"""restore_discoveries is a no-op on non-Linux platforms.""" |
| 2881 |
mock_backend = Mock(seen_devices={}) |
| 2882 |
mock_scanner = Mock(_backend=mock_backend) |
| 2883 |
|
| 2884 |
get_props = AsyncMock() |
| 2885 |
with patch.object(bleak_retry_connector, "_get_properties", get_props): |
| 2886 |
await restore_discoveries(mock_scanner, "hci0") |
| 2887 |
|
| 2888 |
get_props.assert_not_called() |
| 2889 |
assert mock_backend.seen_devices == {} |
| 2890 |
|
| 2891 |
|
| 2892 |
@pytest.mark.asyncio |
| 2893 |
@pytest.mark.skipif("not bleak_retry_connector.const.IS_LINUX") |
| 2894 |
async def test_restore_discoveries_sync(mock_linux: None) -> None: |
| 2895 |
"""restore_discoveries_sync reads the manager of the running loop.""" |
| 2896 |
|
| 2897 |
class FakeBluezManager: |
| 2898 |
_properties = { |
| 2899 |
"/org/bluez/hci1/dev_BD_24_6F_85_AA_61": { |
| 2900 |
"org.bluez.Device1": { |
| 2901 |
"Address": "BD:24:6F:85:AA:61", |
| 2902 |
"AddressType": "public", |
| 2903 |
"Name": "Dream~BD246F85AA61", |
| 2904 |
"Alias": "Dream~BD246F85AA61", |
| 2905 |
"Paired": False, |
| 2906 |
"Trusted": False, |
| 2907 |
"Blocked": False, |
| 2908 |
"LegacyPairing": False, |
| 2909 |
"Connected": False, |
| 2910 |
"UUIDs": [], |
| 2911 |
"Adapter": "/org/bluez/hci1", |
| 2912 |
"ServicesResolved": False, |
| 2913 |
"RSSI": -60, |
| 2914 |
}, |
| 2915 |
}, |
| 2916 |
} |
| 2917 |
|
| 2918 |
from bluetooth_adapters.history import load_history_from_managed_objects |
| 2919 |
|
| 2920 |
seen_devices: dict[str, tuple[BLEDevice, AdvertisementData]] = {} |
| 2921 |
mock_scanner = Mock(_backend=Mock(seen_devices=seen_devices)) |
| 2922 |
with ( |
| 2923 |
patch.object( |
| 2924 |
bleak_retry_connector.bleak_manager, |
| 2925 |
"_global_instances", |
| 2926 |
{asyncio.get_running_loop(): FakeBluezManager()}, |
| 2927 |
), |
| 2928 |
patch.object( |
| 2929 |
bleak_retry_connector, |
| 2930 |
"load_history_from_managed_objects", |
| 2931 |
load_history_from_managed_objects, |
| 2932 |
), |
| 2933 |
): |
| 2934 |
restore_discoveries_sync(mock_scanner, "hci1") |
| 2935 |
|
| 2936 |
assert len(seen_devices) == 1 |
| 2937 |
|
| 2938 |
|
| 2939 |
@pytest.mark.asyncio |
| 2940 |
async def test_restore_discoveries_sync_no_manager(mock_linux: None) -> None: |
| 2941 |
"""restore_discoveries_sync is a no-op when no manager is running.""" |
| 2942 |
mock_backend = Mock(seen_devices={}) |
| 2943 |
with patch.object(bleak_retry_connector.bleak_manager, "_global_instances", {}): |
| 2944 |
restore_discoveries_sync(Mock(_backend=mock_backend), "hci0") |
| 2945 |
assert mock_backend.seen_devices == {} |
| 2946 |
|
| 2947 |
|
| 2948 |
@pytest.mark.asyncio |
| 2949 |
async def test_restore_discoveries_sync_other_loop(mock_linux: None) -> None: |
| 2950 |
"""A manager registered for another loop is not used.""" |
| 2951 |
mock_backend = Mock(seen_devices={}) |
| 2952 |
with patch.object( |
| 2953 |
bleak_retry_connector.bleak_manager, |
| 2954 |
"_global_instances", |
| 2955 |
{Mock(): Mock(_properties={"/x": {}})}, |
| 2956 |
): |
| 2957 |
restore_discoveries_sync(Mock(_backend=mock_backend), "hci0") |
| 2958 |
assert mock_backend.seen_devices == {} |
| 2959 |
|
| 2960 |
|
| 2961 |
# Intentionally sync: no running loop, so this is the only test of the |
| 2962 |
# RuntimeError branch in get_global_bluez_manager_sync. |
| 2963 |
def test_restore_discoveries_sync_no_running_loop(mock_linux: None) -> None: |
| 2964 |
"""Off the loop restore_discoveries_sync is a no-op, not an error.""" |
| 2965 |
mock_backend = Mock(seen_devices={}) |
| 2966 |
with patch.object( |
| 2967 |
bleak_retry_connector.bleak_manager, |
| 2968 |
"_global_instances", |
| 2969 |
{Mock(): Mock(_properties={"/x": {}})}, |
| 2970 |
): |
| 2971 |
restore_discoveries_sync(Mock(_backend=mock_backend), "hci0") |
| 2972 |
assert mock_backend.seen_devices == {} |
| 2973 |
|
| 2974 |
|
| 2975 |
@pytest.mark.skipif("not bleak_retry_connector.const.IS_LINUX") |
| 2976 |
def test_bleak_global_instances_imported() -> None: |
| 2977 |
"""The bleak private the sync lookup relies on still imports.""" |
| 2978 |
assert bleak_retry_connector.bleak_manager._global_instances is not None |
| 2979 |
|
| 2980 |
|
| 2981 |
@pytest.mark.asyncio |
| 2982 |
async def test_restore_discoveries_sync_non_linux(mock_macos: None) -> None: |
| 2983 |
"""restore_discoveries_sync is a no-op off Linux.""" |
| 2984 |
mock_backend = Mock(seen_devices={}) |
| 2985 |
restore_discoveries_sync(Mock(_backend=mock_backend), "hci0") |
| 2986 |
assert mock_backend.seen_devices == {} |
| 2987 |
|
| 2988 |
|
| 2989 |
@pytest.mark.asyncio |
| 2990 |
async def test_restore_discoveries_no_properties(mock_linux: None) -> None: |
| 2991 |
"""restore_discoveries returns early when properties are unavailable.""" |
| 2992 |
mock_backend = Mock(seen_devices={}) |
| 2993 |
mock_scanner = Mock(_backend=mock_backend) |
| 2994 |
|
| 2995 |
with patch.object( |
| 2996 |
bleak_retry_connector, |
| 2997 |
"_get_properties", |
| 2998 |
AsyncMock(return_value=None), |
| 2999 |
): |
| 3000 |
await restore_discoveries(mock_scanner, "hci0") |
| 3001 |
|
| 3002 |
assert mock_backend.seen_devices == {} |
| 3003 |
|
| 3004 |
|
| 3005 |
@pytest.mark.asyncio |
| 3006 |
async def test_establish_connection_debug_disabled_cycles_all_exception_paths() -> None: |
| 3007 |
"""Cycle through every retryable exception class with debug logging off. |
| 3008 |
|
| 3009 |
Exercises the falsy ``if debug_enabled:`` branches inside each ``except`` |
| 3010 |
handler in ``establish_connection``, the ``should_use_cache=False`` skip |
| 3011 |
around the services-cache restore, and the non-cache-client fork of the |
| 3012 |
``KeyError`` handler that skips ``wait_for_disconnect``. |
| 3013 |
""" |
| 3014 |
wait_calls: list[float] = [] |
| 3015 |
|
| 3016 |
scripted, attempts = make_scripted_client( |
| 3017 |
[ |
| 3018 |
asyncio.TimeoutError(), |
| 3019 |
KeyError("org.bluez.GattService1"), |
| 3020 |
BrokenPipeError(32, "Broken pipe"), |
| 3021 |
EOFError(), |
| 3022 |
BleakError("le-connection-abort-by-local"), |
| 3023 |
None, |
| 3024 |
] |
| 3025 |
) |
| 3026 |
|
| 3027 |
async def fake_wait_for_disconnect(device: Any, backoff_time: float) -> None: |
| 3028 |
wait_calls.append(backoff_time) |
| 3029 |
|
| 3030 |
with ( |
| 3031 |
patch.object(bleak_retry_connector._LOGGER, "isEnabledFor", return_value=False), |
| 3032 |
patch( |
| 3033 |
"bleak_retry_connector.wait_for_disconnect", |
| 3034 |
side_effect=fake_wait_for_disconnect, |
| 3035 |
), |
| 3036 |
patch("bleak_retry_connector.calculate_backoff_time", return_value=0), |
| 3037 |
): |
| 3038 |
client = await establish_connection( |
| 3039 |
scripted, |
| 3040 |
MagicMock(), |
| 3041 |
"test", |
| 3042 |
use_services_cache=False, |
| 3043 |
) |
| 3044 |
|
| 3045 |
assert isinstance(client, scripted) |
| 3046 |
assert attempts["n"] == 6 |
| 3047 |
# TimeoutError, EOFError, BLEAK_EXCEPTIONS all call wait_for_disconnect. |
| 3048 |
# KeyError on a non-cache client skips the wait. BrokenPipeError skips too. |
| 3049 |
assert wait_calls == [0, 0, 0] |
| 3050 |
|
| 3051 |
|
| 3052 |
@pytest.mark.asyncio |
| 3053 |
async def test_retry_bluetooth_connection_error_zero_attempts_returns_none() -> None: |
| 3054 |
"""A decorator with ``attempts=0`` never enters the retry loop. |
| 3055 |
|
| 3056 |
Exercises the loop-exit branch of ``for attempt in range(attempts):`` |
| 3057 |
inside ``retry_bluetooth_connection_error`` when the caller asks for zero |
| 3058 |
attempts — the wrapped coroutine must not run. |
| 3059 |
""" |
| 3060 |
call_count = 0 |
| 3061 |
|
| 3062 |
@retry_bluetooth_connection_error(attempts=0) |
| 3063 |
async def never_called() -> None: |
| 3064 |
nonlocal call_count |
| 3065 |
call_count += 1 |
| 3066 |
|
| 3067 |
await never_called() |
| 3068 |
assert call_count == 0 |