File: test_wrappers.py

package info (click to toggle)
habluetooth 5.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,052 kB
  • sloc: python: 10,979; makefile: 18
file content (2046 lines) | stat: -rw-r--r-- 72,006 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
"""Tests for bluetooth wrappers."""

from __future__ import annotations

import asyncio
import logging
from collections.abc import Callable, Generator
from contextlib import contextmanager, suppress
from typing import Any
from unittest.mock import Mock, patch

import bleak
import pytest
from bleak.backends.device import BLEDevice
from bleak.backends.scanner import AdvertisementData
from bleak.exc import BleakError
from bleak_retry_connector import Allocations
from bluetooth_data_tools import monotonic_time_coarse as MONOTONIC_TIME

from habluetooth import BaseHaRemoteScanner, HaBluetoothConnector
from habluetooth import get_manager as _get_manager
from habluetooth.manager import BluetoothManager
from habluetooth.usage import (
    install_multiple_bleak_catcher,
    uninstall_multiple_bleak_catcher,
)
from habluetooth.wrappers import HaBleakScannerWrapper

from . import (
    HCI0_SOURCE_ADDRESS,
    generate_advertisement_data,
    generate_ble_device,
    inject_advertisement,
    patch_discovered_devices,
)


@contextmanager
def mock_shutdown(manager: BluetoothManager) -> Generator[None, None, None]:
    """Mock shutdown of the HomeAssistantBluetoothManager."""
    manager.shutdown = True
    yield
    manager.shutdown = False


class FakeScanner(BaseHaRemoteScanner):
    """Fake scanner."""

    def __init__(
        self,
        scanner_id: str,
        name: str,
        connector: Any,
        connectable: bool,
    ) -> None:
        """Initialize the scanner."""
        super().__init__(scanner_id, name, connector, connectable)
        self._details: dict[str, str | HaBluetoothConnector] = {}

    def __repr__(self) -> str:
        """Return the representation."""
        return f"FakeScanner({self.name})"

    def inject_advertisement(
        self, device: BLEDevice, advertisement_data: AdvertisementData
    ) -> None:
        """Inject an advertisement."""
        self._async_on_advertisement(
            device.address,
            advertisement_data.rssi,
            device.name,
            advertisement_data.service_uuids,
            advertisement_data.service_data,
            advertisement_data.manufacturer_data,
            advertisement_data.tx_power,
            device.details | {"scanner_specific_data": "test"},
            MONOTONIC_TIME(),
        )


class BaseFakeBleakClient:
    """Base class for fake bleak clients."""

    def __init__(self, address_or_ble_device: BLEDevice | str, **kwargs: Any) -> None:
        """Initialize the fake bleak client."""
        self._device_path = "/dev/test"
        self._device = address_or_ble_device
        assert isinstance(address_or_ble_device, BLEDevice)
        self._address = address_or_ble_device.address

    async def disconnect(self, *args, **kwargs):
        """Disconnect."""

    async def get_services(self, *args, **kwargs):
        """Get services."""
        return []


class FakeBleakClient(BaseFakeBleakClient):
    """Fake bleak client."""

    async def connect(self, *args, **kwargs):
        """Connect."""
        return True

    @property
    def is_connected(self):
        return False


class FakeBleakClientFailsToConnect(BaseFakeBleakClient):
    """Fake bleak client that fails to connect."""

    async def connect(self, *args, **kwargs):
        """Connect."""
        return

    @property
    def is_connected(self):
        return False


class FakeBleakClientRaisesOnConnect(BaseFakeBleakClient):
    """Fake bleak client that raises on connect."""

    async def connect(self, *args, **kwargs):
        """Connect."""
        raise ConnectionError("Test exception")


def _generate_ble_device_and_adv_data(
    interface: str, mac: str, rssi: int
) -> tuple[BLEDevice, AdvertisementData]:
    """Generate a BLE device with adv data."""
    return (
        generate_ble_device(
            mac,
            "any",
            delegate="",
            details={"path": f"/org/bluez/{interface}/dev_{mac}"},
        ),
        generate_advertisement_data(rssi=rssi),
    )


@pytest.fixture(name="install_bleak_catcher")
def install_bleak_catcher_fixture():
    """Fixture that installs the bleak catcher."""
    install_multiple_bleak_catcher()
    yield
    uninstall_multiple_bleak_catcher()


@pytest.fixture(name="mock_platform_client")
def mock_platform_client_fixture():
    """Fixture that mocks the platform client."""
    with patch(
        "habluetooth.wrappers.get_platform_client_backend_type",
        return_value=FakeBleakClient,
    ):
        yield


@pytest.fixture(name="mock_platform_client_that_fails_to_connect")
def mock_platform_client_that_fails_to_connect_fixture():
    """Fixture that mocks the platform client that fails to connect."""
    with patch(
        "habluetooth.wrappers.get_platform_client_backend_type",
        return_value=FakeBleakClientFailsToConnect,
    ):
        yield


@pytest.fixture(name="mock_platform_client_that_raises_on_connect")
def mock_platform_client_that_raises_on_connect_fixture():
    """Fixture that mocks the platform client that fails to connect."""
    with patch(
        "habluetooth.wrappers.get_platform_client_backend_type",
        return_value=FakeBleakClientRaisesOnConnect,
    ):
        yield


def _generate_scanners_with_fake_devices():
    """Generate scanners with fake devices."""
    manager = _get_manager()
    hci0_device_advs = {}
    for i in range(10):
        device, adv_data = _generate_ble_device_and_adv_data(
            "hci0", f"00:00:00:00:00:{i:02x}", rssi=-60
        )
        hci0_device_advs[device.address] = (device, adv_data)
    hci1_device_advs = {}
    for i in range(10):
        device, adv_data = _generate_ble_device_and_adv_data(
            "hci1", f"00:00:00:00:00:{i:02x}", rssi=-80
        )
        hci1_device_advs[device.address] = (device, adv_data)

    scanner_hci0 = FakeScanner("00:00:00:00:00:01", "hci0", None, True)
    scanner_hci1 = FakeScanner("00:00:00:00:00:02", "hci1", None, True)

    for device, adv_data in hci0_device_advs.values():
        scanner_hci0.inject_advertisement(device, adv_data)

    for device, adv_data in hci1_device_advs.values():
        scanner_hci1.inject_advertisement(device, adv_data)

    cancel_hci0 = manager.async_register_scanner(scanner_hci0, connection_slots=2)
    cancel_hci1 = manager.async_register_scanner(scanner_hci1, connection_slots=1)

    return hci0_device_advs, cancel_hci0, cancel_hci1


@pytest.mark.asyncio
async def test_test_switch_adapters_when_out_of_slots(
    two_adapters: None,
    enable_bluetooth: None,
    install_bleak_catcher: None,
    mock_platform_client: None,
) -> None:
    """Ensure we try another scanner when one runs out of slots."""
    manager = _get_manager()
    # hci0 has an rssi of -60, hci1 has an rssi of -80
    hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices()
    # hci0 has 2 slots, hci1 has 1 slot
    with (
        patch.object(manager.slot_manager, "release_slot") as release_slot_mock,
        patch.object(
            manager.slot_manager, "allocate_slot", return_value=True
        ) as allocate_slot_mock,
    ):
        ble_device = hci0_device_advs["00:00:00:00:00:01"][0]
        with patch.object(FakeBleakClient, "is_connected", return_value=True):
            client = bleak.BleakClient(ble_device)
            await client.connect()
        assert allocate_slot_mock.call_count == 1
        assert release_slot_mock.call_count == 0

    # All adapters are out of slots
    with (
        patch.object(manager.slot_manager, "release_slot") as release_slot_mock,
        patch.object(
            manager.slot_manager, "allocate_slot", return_value=False
        ) as allocate_slot_mock,
    ):
        ble_device = hci0_device_advs["00:00:00:00:00:02"][0]
        client = bleak.BleakClient(ble_device)
        with pytest.raises(bleak.exc.BleakError):
            await client.connect()
        assert allocate_slot_mock.call_count == 2
        assert release_slot_mock.call_count == 0

    # When hci0 runs out of slots, we should try hci1
    def _allocate_slot_mock(ble_device: BLEDevice) -> bool:
        return "hci1" in ble_device.details["path"]

    with (
        patch.object(manager.slot_manager, "release_slot") as release_slot_mock,
        patch.object(  # type: ignore
            manager.slot_manager, "allocate_slot", _allocate_slot_mock
        ) as allocate_slot_mock,
    ):
        ble_device = hci0_device_advs["00:00:00:00:00:03"][0]
        with patch.object(FakeBleakClient, "is_connected", return_value=True):
            client = bleak.BleakClient(ble_device)
            await client.connect()
        assert release_slot_mock.call_count == 0

    cancel_hci0()
    cancel_hci1()


@pytest.mark.asyncio
async def test_release_slot_on_connect_failure(
    two_adapters: None,
    enable_bluetooth: None,
    install_bleak_catcher: None,
    mock_platform_client_that_raises_on_connect: None,
) -> None:
    """Ensure the slot gets released on connection failure."""
    manager = _get_manager()
    hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices()
    # hci0 has 2 slots, hci1 has 1 slot
    with (
        patch.object(manager.slot_manager, "release_slot") as release_slot_mock,
        patch.object(
            manager.slot_manager, "allocate_slot", return_value=True
        ) as allocate_slot_mock,
    ):
        ble_device = hci0_device_advs["00:00:00:00:00:01"][0]
        client = bleak.BleakClient(ble_device)
        with pytest.raises(ConnectionError):
            await client.connect()
        assert allocate_slot_mock.call_count == 1
        assert release_slot_mock.call_count == 1

    cancel_hci0()
    cancel_hci1()


@pytest.mark.asyncio
async def test_release_slot_on_connect_exception(
    two_adapters: None,
    enable_bluetooth: None,
    install_bleak_catcher: None,
    mock_platform_client_that_raises_on_connect: None,
) -> None:
    """Ensure the slot gets released on connection exception."""
    manager = _get_manager()
    hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices()
    # hci0 has 2 slots, hci1 has 1 slot
    with (
        patch.object(manager.slot_manager, "release_slot") as release_slot_mock,
        patch.object(
            manager.slot_manager, "allocate_slot", return_value=True
        ) as allocate_slot_mock,
    ):
        ble_device = hci0_device_advs["00:00:00:00:00:01"][0]
        client = bleak.BleakClient(ble_device)
        with pytest.raises(ConnectionError) as exc_info:
            await client.connect()
        assert str(exc_info.value) == "Test exception"
        assert allocate_slot_mock.call_count == 1
        assert release_slot_mock.call_count == 1

    cancel_hci0()
    cancel_hci1()


@pytest.mark.asyncio
async def test_switch_adapters_on_failure(
    two_adapters: None,
    enable_bluetooth: None,
    install_bleak_catcher: None,
) -> None:
    """Ensure we try the next best adapter after a failure."""
    hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices()
    ble_device = hci0_device_advs["00:00:00:00:00:01"][0]
    client = bleak.BleakClient(ble_device)

    class FakeBleakClientFailsHCI0Only(BaseFakeBleakClient):
        """Fake bleak client that fails to connect on hci0."""

        async def connect(self, *args: Any, **kwargs: Any) -> None:
            """Connect."""
            assert isinstance(self._device, BLEDevice)
            if "/hci0/" in self._device.details["path"]:
                raise BleakError("Failed to connect on hci0")

        @property
        def is_connected(self) -> bool:
            return True

    class FakeBleakClientFailsHCI1Only(BaseFakeBleakClient):
        """Fake bleak client that fails to connect on hci1."""

        async def connect(self, *args: Any, **kwargs: Any) -> None:
            """Connect."""
            assert isinstance(self._device, BLEDevice)
            if "/hci1/" in self._device.details["path"]:
                raise BleakError("Failed to connect on hci1")

        @property
        def is_connected(self) -> bool:
            return True

    with patch(
        "habluetooth.wrappers.get_platform_client_backend_type",
        return_value=FakeBleakClientFailsHCI0Only,
    ):
        # Should try to connect to hci0 first
        with pytest.raises(BleakError):
            await client.connect()
        assert not client.is_connected
        # Should try to connect with hci0 again
        with pytest.raises(BleakError):
            await client.connect()
        assert not client.is_connected

        # After two tries we should switch to hci1
        await client.connect()
        assert client.is_connected

        # ..and we remember that hci1 works as long as the client doesn't change
        await client.connect()
        assert client.is_connected

        # If we replace the client, we should remember hci0 is failing
        client = bleak.BleakClient(ble_device)

        await client.connect()
        assert client.is_connected

    with patch(
        "habluetooth.wrappers.get_platform_client_backend_type",
        return_value=FakeBleakClientFailsHCI1Only,
    ):
        # Should try to connect to hci1 first
        await client.connect()
        assert client.is_connected
        # Should work with hci0 on next attempt
        await client.connect()
        assert client.is_connected
        # Next attempt should also use hci0
        await client.connect()
        assert client.is_connected

    cancel_hci0()
    cancel_hci1()


@pytest.mark.asyncio
async def test_switch_adapters_on_connecting(
    two_adapters: None,
    enable_bluetooth: None,
    install_bleak_catcher: None,
) -> None:
    """Ensure we try the next best adapter after a failure."""
    # hci0 has an rssi of -60, hci1 has an rssi of -80
    hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices()
    ble_device = hci0_device_advs["00:00:00:00:00:01"][0]
    client = bleak.BleakClient(ble_device)

    class FakeBleakClientSlowHCI0Connnect(BaseFakeBleakClient):
        """Fake bleak client that connects instantly on hci1 and slow on hci0."""

        valid = False

        async def connect(self, *args: Any, **kwargs: Any) -> None:
            """Connect."""
            assert isinstance(self._device, BLEDevice)
            if "/hci0/" in self._device.details["path"]:
                await asyncio.sleep(0.4)
                self.valid = True
            else:
                self.valid = True

        @property
        def is_connected(self) -> bool:
            return self.valid

    with patch(
        "habluetooth.wrappers.get_platform_client_backend_type",
        return_value=FakeBleakClientSlowHCI0Connnect,
    ):
        task = asyncio.create_task(client.connect())
        await asyncio.sleep(0.1)
        assert not task.done()

        task2 = asyncio.create_task(client.connect())
        await asyncio.sleep(0.1)
        assert task2.done()
        await task2
        assert client.is_connected

        task3 = asyncio.create_task(client.connect())
        await asyncio.sleep(0.1)
        assert task3.done()
        await task3
        assert client.is_connected

        await task
        assert client.is_connected

    cancel_hci0()
    cancel_hci1()


@pytest.mark.asyncio
@pytest.mark.usefixtures("enable_bluetooth", "install_bleak_catcher")
async def test_single_adapter_connection_history(
    caplog: pytest.LogCaptureFixture,
) -> None:
    """Test connection history failure count."""
    manager = _get_manager()
    scanner_hci0 = FakeScanner(HCI0_SOURCE_ADDRESS, "hci0", None, True)
    unsub_hci0 = manager.async_register_scanner(scanner_hci0, connection_slots=2)
    ble_device, adv_data = _generate_ble_device_and_adv_data(
        "hci0", "00:00:00:00:00:11", rssi=-60
    )
    scanner_hci0.inject_advertisement(ble_device, adv_data)
    service_info = manager.async_last_service_info(
        ble_device.address, connectable=False
    )
    assert service_info is not None
    assert service_info.source == HCI0_SOURCE_ADDRESS

    client = bleak.BleakClient(ble_device)

    class FakeBleakClientFastConnect(BaseFakeBleakClient):
        """Fake bleak client that connects instantly on hci1 and slow on hci0."""

        valid = False

        async def connect(self, *args: Any, **kwargs: Any) -> None:
            """Connect."""
            assert isinstance(self._device, BLEDevice)
            self.valid = "/hci0/" in self._device.details["path"]

        @property
        def is_connected(self) -> bool:
            return self.valid

    with patch(
        "habluetooth.wrappers.get_platform_client_backend_type",
        return_value=FakeBleakClientFastConnect,
    ):
        await client.connect()
    unsub_hci0()


@pytest.mark.asyncio
async def test_passing_subclassed_str_as_address(
    two_adapters: None,
    enable_bluetooth: None,
    install_bleak_catcher: None,
) -> None:
    """Ensure the client wrapper can handle a subclassed str as the address."""
    _, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices()

    class SubclassedStr(str):
        __slots__ = ()

    address = SubclassedStr("00:00:00:00:00:01")
    client = bleak.BleakClient(address)

    class FakeBleakClient(BaseFakeBleakClient):
        """Fake bleak client."""

        async def connect(self, *args, **kwargs):
            """Connect."""
            return

        @property
        def is_connected(self) -> bool:
            return True

    with patch(
        "habluetooth.wrappers.get_platform_client_backend_type",
        return_value=FakeBleakClient,
    ):
        await client.connect()

    cancel_hci0()
    cancel_hci1()


@pytest.mark.asyncio
async def test_find_device_by_address(
    two_adapters: None,
    enable_bluetooth: None,
    install_bleak_catcher: None,
) -> None:
    """Ensure the client wrapper can handle a subclassed str as the address."""
    _, _cancel_hci0, _cancel_hci1 = _generate_scanners_with_fake_devices()
    device = await bleak.BleakScanner.find_device_by_address("00:00:00:00:00:01")
    assert device.address == "00:00:00:00:00:01"
    device = await bleak.BleakScanner().find_device_by_address("00:00:00:00:00:01")
    assert device.address == "00:00:00:00:00:01"


@pytest.mark.asyncio
async def test_discover(
    two_adapters: None,
    enable_bluetooth: None,
    install_bleak_catcher: None,
) -> None:
    """Ensure the discover is implemented."""
    _, _cancel_hci0, _cancel_hci1 = _generate_scanners_with_fake_devices()
    devices = await bleak.BleakScanner.discover()
    assert any(device.address == "00:00:00:00:00:01" for device in devices)
    devices_adv = await bleak.BleakScanner.discover(return_adv=True)
    assert "00:00:00:00:00:01" in devices_adv


@pytest.mark.asyncio
async def test_raise_after_shutdown(
    two_adapters: None,
    enable_bluetooth: None,
    install_bleak_catcher: None,
    mock_platform_client_that_raises_on_connect: None,
) -> None:
    """Ensure the slot gets released on connection exception."""
    manager = _get_manager()
    hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices()
    # hci0 has 2 slots, hci1 has 1 slot
    with mock_shutdown(manager):
        ble_device = hci0_device_advs["00:00:00:00:00:01"][0]
        client = bleak.BleakClient(ble_device)
        with pytest.raises(BleakError, match="shutdown"):
            await client.connect()
    cancel_hci0()
    cancel_hci1()


@pytest.mark.usefixtures("enable_bluetooth")
@pytest.mark.asyncio
async def test_wrapped_instance_with_filter(
    register_hci0_scanner: None,
) -> None:
    """Test wrapped instance with a filter as if it was normal BleakScanner."""
    detected = []

    def _device_detected(
        device: BLEDevice, advertisement_data: AdvertisementData
    ) -> None:
        """Handle a detected device."""
        detected.append((device, advertisement_data))

    switchbot_device = generate_ble_device("44:44:33:11:23:45", "wohand")
    switchbot_adv = generate_advertisement_data(
        local_name="wohand",
        service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"],
        manufacturer_data={89: b"\xd8.\xad\xcd\r\x85"},
        service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"},
    )
    switchbot_adv_2 = generate_advertisement_data(
        local_name="wohand",
        service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"],
        manufacturer_data={89: b"\xd8.\xad\xcd\r\x84"},
        service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"},
    )
    empty_device = generate_ble_device("11:22:33:44:55:66", "empty")
    empty_adv = generate_advertisement_data(local_name="empty")

    assert _get_manager() is not None
    scanner = HaBleakScannerWrapper(
        filters={"UUIDs": ["cba20d00-224d-11e6-9fb8-0002a5d5c51b"]}
    )
    scanner.register_detection_callback(_device_detected)

    inject_advertisement(switchbot_device, switchbot_adv_2)
    await asyncio.sleep(0)

    discovered = await scanner.discover(timeout=0)
    assert len(discovered) == 1
    assert discovered == [switchbot_device]
    assert len(detected) == 1

    scanner.register_detection_callback(_device_detected)
    # We should get a reply from the history when we register again
    assert len(detected) == 2
    scanner.register_detection_callback(_device_detected)
    # We should get a reply from the history when we register again
    assert len(detected) == 3

    with patch_discovered_devices([]):
        discovered = await scanner.discover(timeout=0)
        assert len(discovered) == 0
        assert discovered == []

    inject_advertisement(switchbot_device, switchbot_adv)
    assert len(detected) == 4

    # The filter we created in the wrapped scanner with should be respected
    # and we should not get another callback
    inject_advertisement(empty_device, empty_adv)
    assert len(detected) == 4


@pytest.mark.usefixtures("enable_bluetooth")
@pytest.mark.asyncio
async def test_wrapped_instance_with_service_uuids(
    register_hci0_scanner: None,
) -> None:
    """Test wrapped instance with a service_uuids list as normal BleakScanner."""
    detected = []

    def _device_detected(
        device: BLEDevice, advertisement_data: AdvertisementData
    ) -> None:
        """Handle a detected device."""
        detected.append((device, advertisement_data))

    switchbot_device = generate_ble_device("44:44:33:11:23:45", "wohand")
    switchbot_adv = generate_advertisement_data(
        local_name="wohand",
        service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"],
        manufacturer_data={89: b"\xd8.\xad\xcd\r\x85"},
        service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"},
    )
    switchbot_adv_2 = generate_advertisement_data(
        local_name="wohand",
        service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"],
        manufacturer_data={89: b"\xd8.\xad\xcd\r\x84"},
        service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"},
    )
    empty_device = generate_ble_device("11:22:33:44:55:66", "empty")
    empty_adv = generate_advertisement_data(local_name="empty")

    assert _get_manager() is not None
    scanner = HaBleakScannerWrapper(
        service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"]
    )
    scanner.register_detection_callback(_device_detected)

    inject_advertisement(switchbot_device, switchbot_adv)
    inject_advertisement(switchbot_device, switchbot_adv_2)

    await asyncio.sleep(0)

    assert len(detected) == 2

    # The UUIDs list we created in the wrapped scanner with should be respected
    # and we should not get another callback
    inject_advertisement(empty_device, empty_adv)
    assert len(detected) == 2


@pytest.mark.usefixtures("enable_bluetooth")
@pytest.mark.asyncio
async def test_wrapped_instance_with_service_uuids_with_coro_callback(
    register_hci0_scanner: None,
) -> None:
    """
    Test wrapped instance with a service_uuids list as normal BleakScanner.

    Verify that coro callbacks are supported.
    """
    detected = []

    async def _device_detected(
        device: BLEDevice, advertisement_data: AdvertisementData
    ) -> None:
        """Handle a detected device."""
        detected.append((device, advertisement_data))

    switchbot_device = generate_ble_device("44:44:33:11:23:45", "wohand")
    switchbot_adv = generate_advertisement_data(
        local_name="wohand",
        service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"],
        manufacturer_data={89: b"\xd8.\xad\xcd\r\x85"},
        service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"},
    )
    switchbot_adv_2 = generate_advertisement_data(
        local_name="wohand",
        service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"],
        manufacturer_data={89: b"\xd8.\xad\xcd\r\x84"},
        service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"},
    )
    empty_device = generate_ble_device("11:22:33:44:55:66", "empty")
    empty_adv = generate_advertisement_data(local_name="empty")

    assert _get_manager() is not None
    scanner = HaBleakScannerWrapper(
        service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"]
    )
    scanner.register_detection_callback(_device_detected)

    inject_advertisement(switchbot_device, switchbot_adv)
    inject_advertisement(switchbot_device, switchbot_adv_2)

    await asyncio.sleep(0)

    assert len(detected) == 2

    # The UUIDs list we created in the wrapped scanner with should be respected
    # and we should not get another callback
    inject_advertisement(empty_device, empty_adv)
    assert len(detected) == 2


@pytest.mark.usefixtures("enable_bluetooth")
@pytest.mark.asyncio
async def test_wrapped_instance_with_broken_callbacks(
    register_hci0_scanner: None,
) -> None:
    """Test broken callbacks do not cause the scanner to fail."""
    detected: list[tuple[BLEDevice, AdvertisementData]] = []

    def _device_detected(
        device: BLEDevice, advertisement_data: AdvertisementData
    ) -> None:
        """Handle a detected device."""
        if detected:
            raise ValueError
        detected.append((device, advertisement_data))

    switchbot_device = generate_ble_device("44:44:33:11:23:45", "wohand")
    switchbot_adv = generate_advertisement_data(
        local_name="wohand",
        service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"],
        manufacturer_data={89: b"\xd8.\xad\xcd\r\x85"},
        service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"},
    )

    assert _get_manager() is not None
    scanner = HaBleakScannerWrapper(
        service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"]
    )
    scanner.register_detection_callback(_device_detected)

    inject_advertisement(switchbot_device, switchbot_adv)
    await asyncio.sleep(0)
    inject_advertisement(switchbot_device, switchbot_adv)
    await asyncio.sleep(0)
    assert len(detected) == 1


@pytest.mark.usefixtures("enable_bluetooth")
@pytest.mark.asyncio
async def test_wrapped_instance_changes_uuids(
    register_hci0_scanner: None,
) -> None:
    """Test consumers can use the wrapped instance can change the uuids later."""
    detected = []

    def _device_detected(
        device: BLEDevice, advertisement_data: AdvertisementData
    ) -> None:
        """Handle a detected device."""
        detected.append((device, advertisement_data))

    switchbot_device = generate_ble_device("44:44:33:11:23:45", "wohand")
    switchbot_adv = generate_advertisement_data(
        local_name="wohand",
        service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"],
        manufacturer_data={89: b"\xd8.\xad\xcd\r\x85"},
        service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"},
    )
    switchbot_adv_2 = generate_advertisement_data(
        local_name="wohand",
        service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"],
        manufacturer_data={89: b"\xd8.\xad\xcd\r\x84"},
        service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"},
    )
    empty_device = generate_ble_device("11:22:33:44:55:66", "empty")
    empty_adv = generate_advertisement_data(local_name="empty")

    assert _get_manager() is not None
    scanner = HaBleakScannerWrapper()
    scanner.set_scanning_filter(service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"])
    scanner.register_detection_callback(_device_detected)

    inject_advertisement(switchbot_device, switchbot_adv)
    inject_advertisement(switchbot_device, switchbot_adv_2)
    await asyncio.sleep(0)

    assert len(detected) == 2

    # The UUIDs list we created in the wrapped scanner with should be respected
    # and we should not get another callback
    inject_advertisement(empty_device, empty_adv)
    assert len(detected) == 2


@pytest.mark.usefixtures("enable_bluetooth")
@pytest.mark.asyncio
async def test_wrapped_instance_changes_filters(
    register_hci0_scanner: None,
) -> None:
    """Test consumers can use the wrapped instance can change the filter later."""
    detected = []

    def _device_detected(
        device: BLEDevice, advertisement_data: AdvertisementData
    ) -> None:
        """Handle a detected device."""
        detected.append((device, advertisement_data))

    switchbot_device = generate_ble_device("44:44:33:11:23:42", "wohand")
    switchbot_adv = generate_advertisement_data(
        local_name="wohand",
        service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"],
        manufacturer_data={89: b"\xd8.\xad\xcd\r\x85"},
        service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"},
    )
    switchbot_adv_2 = generate_advertisement_data(
        local_name="wohand",
        service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"],
        manufacturer_data={89: b"\xd8.\xad\xcd\r\x84"},
        service_data={"00000d00-0000-1000-8000-00805f9b34fb": b"H\x10c"},
    )
    empty_device = generate_ble_device("11:22:33:44:55:62", "empty")
    empty_adv = generate_advertisement_data(local_name="empty")

    assert _get_manager() is not None
    scanner = HaBleakScannerWrapper()
    scanner.set_scanning_filter(
        filters={"UUIDs": ["cba20d00-224d-11e6-9fb8-0002a5d5c51b"]}
    )
    scanner.register_detection_callback(_device_detected)

    inject_advertisement(switchbot_device, switchbot_adv)
    inject_advertisement(switchbot_device, switchbot_adv_2)

    await asyncio.sleep(0)

    assert len(detected) == 2

    # The UUIDs list we created in the wrapped scanner with should be respected
    # and we should not get another callback
    inject_advertisement(empty_device, empty_adv)
    assert len(detected) == 2


@pytest.mark.usefixtures("enable_bluetooth")
@pytest.mark.asyncio
async def test_wrapped_instance_unsupported_filter(
    register_hci0_scanner: None,
    caplog: pytest.LogCaptureFixture,
) -> None:
    """Test we want when their filter is ineffective."""
    assert _get_manager() is not None
    scanner = HaBleakScannerWrapper()
    scanner.set_scanning_filter(
        filters={
            "unsupported": ["cba20d00-224d-11e6-9fb8-0002a5d5c51b"],
            "DuplicateData": True,
        }
    )
    assert "Only UUIDs filters are supported" in caplog.text


@pytest.mark.asyncio
async def test_client_with_services_parameter(
    two_adapters: None,
    enable_bluetooth: None,
    install_bleak_catcher: None,
    mock_platform_client: None,
) -> None:
    """Test that services parameter is passed correctly to the backend."""
    hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices()
    ble_device = hci0_device_advs["00:00:00:00:00:01"][0]

    test_services = [
        "00001800-0000-1000-8000-00805f9b34fb",
        "00001801-0000-1000-8000-00805f9b34fb",
    ]

    # Track what services were passed to the backend
    services_passed_to_backend = None

    class FakeBleakClientTracksServices(BaseFakeBleakClient):
        """Fake bleak client that tracks services parameter."""

        def __init__(
            self, address_or_ble_device: BLEDevice | str, **kwargs: Any
        ) -> None:
            """Initialize and capture services."""
            super().__init__(address_or_ble_device, **kwargs)
            nonlocal services_passed_to_backend
            services_passed_to_backend = kwargs.get("services")

        async def connect(self, *args, **kwargs):
            """Connect."""
            return True

        @property
        def is_connected(self):
            return True

    with patch(
        "habluetooth.wrappers.get_platform_client_backend_type",
        return_value=FakeBleakClientTracksServices,
    ):
        client = bleak.BleakClient(ble_device, services=test_services)
        await client.connect()

        # Verify services were normalized and passed as a set
        assert services_passed_to_backend is not None
        assert isinstance(services_passed_to_backend, set)
        assert services_passed_to_backend == {
            "00001800-0000-1000-8000-00805f9b34fb",
            "00001801-0000-1000-8000-00805f9b34fb",
        }

    cancel_hci0()
    cancel_hci1()


@pytest.mark.asyncio
async def test_client_with_pair_parameter(
    two_adapters: None,
    enable_bluetooth: None,
    install_bleak_catcher: None,
    mock_platform_client: None,
) -> None:
    """Test that pair parameter is set correctly on the wrapper."""
    hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices()
    ble_device = hci0_device_advs["00:00:00:00:00:01"][0]

    # Test default pair=False
    client = bleak.BleakClient(ble_device)
    assert client._pair_before_connect is False

    # Test pair=True
    client = bleak.BleakClient(ble_device, pair=True)
    assert client._pair_before_connect is True

    cancel_hci0()
    cancel_hci1()


@pytest.mark.asyncio
async def test_client_services_normalization(
    two_adapters: None,
    enable_bluetooth: None,
    install_bleak_catcher: None,
    mock_platform_client: None,
) -> None:
    """Test that service UUIDs are normalized correctly."""
    hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices()
    ble_device = hci0_device_advs["00:00:00:00:00:01"][0]

    # Test with short UUIDs that need normalization
    test_services = ["1800", "1801", "CBA20D00-224D-11E6-9FB8-0002A5D5C51B"]

    services_passed_to_backend = None

    class FakeBleakClientTracksServices(BaseFakeBleakClient):
        """Fake bleak client that tracks services parameter."""

        def __init__(
            self, address_or_ble_device: BLEDevice | str, **kwargs: Any
        ) -> None:
            """Initialize and capture services."""
            super().__init__(address_or_ble_device, **kwargs)
            nonlocal services_passed_to_backend
            services_passed_to_backend = kwargs.get("services")

        async def connect(self, *args, **kwargs):
            """Connect."""
            return True

        @property
        def is_connected(self):
            return True

    with patch(
        "habluetooth.wrappers.get_platform_client_backend_type",
        return_value=FakeBleakClientTracksServices,
    ):
        client = bleak.BleakClient(ble_device, services=test_services)
        await client.connect()

        # Verify services were normalized
        assert services_passed_to_backend is not None
        assert isinstance(services_passed_to_backend, set)
        assert services_passed_to_backend == {
            "00001800-0000-1000-8000-00805f9b34fb",
            "00001801-0000-1000-8000-00805f9b34fb",
            "cba20d00-224d-11e6-9fb8-0002a5d5c51b",  # Should be lowercased
        }

    cancel_hci0()
    cancel_hci1()


@pytest.mark.asyncio
async def test_client_with_none_services(
    two_adapters: None,
    enable_bluetooth: None,
    install_bleak_catcher: None,
    mock_platform_client: None,
) -> None:
    """Test that None services parameter is handled correctly."""
    hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices()
    ble_device = hci0_device_advs["00:00:00:00:00:01"][0]

    services_passed_to_backend = "not_set"

    class FakeBleakClientTracksServices(BaseFakeBleakClient):
        """Fake bleak client that tracks services parameter."""

        def __init__(
            self, address_or_ble_device: BLEDevice | str, **kwargs: Any
        ) -> None:
            """Initialize and capture services."""
            super().__init__(address_or_ble_device, **kwargs)
            nonlocal services_passed_to_backend
            services_passed_to_backend = kwargs.get("services", "not_set")

        async def connect(self, *args, **kwargs):
            """Connect."""
            return True

        @property
        def is_connected(self):
            return True

    with patch(
        "habluetooth.wrappers.get_platform_client_backend_type",
        return_value=FakeBleakClientTracksServices,
    ):
        # Test with no services parameter (default None)
        client = bleak.BleakClient(ble_device)
        await client.connect()
        assert services_passed_to_backend is None

    # Reset the captured value
    services_passed_to_backend = "not_set"  # type: ignore[unreachable]

    with patch(
        "habluetooth.wrappers.get_platform_client_backend_type",
        return_value=FakeBleakClientTracksServices,
    ):
        # Test with explicit None
        client = bleak.BleakClient(ble_device, services=None)
        await client.connect()
        assert services_passed_to_backend is None

    cancel_hci0()
    cancel_hci1()


@pytest.mark.usefixtures("enable_bluetooth")
@pytest.mark.asyncio
async def test_passive_only_scanner_error_message() -> None:
    """Test error message when all scanners are passive-only (like Shelly)."""
    manager = _get_manager()
    # Register a passive-only scanner (connectable=False)
    scanner = FakeScanner(
        "passive_scanner_1", "shelly_plus1pm_e86bea01020c", None, False
    )
    cancel = manager.async_register_scanner(scanner)

    # Inject an advertisement from this passive scanner
    device = generate_ble_device(
        "00:00:00:00:00:01", "Test Device", {"source": "passive_scanner_1"}
    )
    adv_data = generate_advertisement_data(
        local_name="Test Device",
        service_uuids=[],
        rssi=-50,
    )
    scanner.inject_advertisement(device, adv_data)
    await asyncio.sleep(0)  # Let the advertisement be processed

    # Try to connect - should fail with our custom error message
    client = bleak.BleakClient("00:00:00:00:00:01")
    with pytest.raises(
        BleakError,
        match=r"00:00:00:00:00:01: No connectable Bluetooth adapters\. "
        r"Shelly devices are passive-only and cannot connect\. "
        r"Need local Bluetooth adapter or ESPHome proxy\. "
        r"Available: shelly_plus1pm_e86bea01020c \(passive_scanner_1\)",
    ):
        await client.connect()

    cancel()


@pytest.mark.usefixtures("enable_bluetooth")
@pytest.mark.asyncio
async def test_passive_scanner_with_active_scanner() -> None:
    """Test normal error when there's a mix of passive and active scanners."""
    manager = _get_manager()
    # Register a passive-only scanner
    passive_scanner = FakeScanner("passive_scanner", "shelly_device", None, False)
    cancel_passive = manager.async_register_scanner(passive_scanner)

    # Register an active scanner with no available slots
    active_scanner = FakeScanner("active_scanner", "esphome_device", None, True)
    cancel_active = manager.async_register_scanner(active_scanner)

    # Inject advertisements from both scanners
    device1 = generate_ble_device(
        "00:00:00:00:00:02", "Test Device", {"source": "passive_scanner"}
    )
    device2 = generate_ble_device(
        "00:00:00:00:00:02", "Test Device", {"source": "active_scanner"}
    )
    adv_data = generate_advertisement_data(
        local_name="Test Device",
        service_uuids=[],
        rssi=-50,
    )
    passive_scanner.inject_advertisement(device1, adv_data)
    active_scanner.inject_advertisement(device2, adv_data)
    await asyncio.sleep(0)  # Let the advertisements be processed

    # Mock the slot allocation to fail (simulating no available slots)
    with patch.object(manager.slot_manager, "allocate_slot", return_value=False):
        # Should get the normal "no available slot" error, not the passive-only error
        client = bleak.BleakClient("00:00:00:00:00:02")
        with pytest.raises(
            BleakError,
            match=(
                "No backend with an available connection slot that can reach "
                "address 00:00:00:00:00:02 was found"
            ),
        ):
            await client.connect()

    cancel_passive()
    cancel_active()


@pytest.mark.asyncio
async def test_connection_params_loading_with_bluez_mgmt(
    two_adapters: None,
    enable_bluetooth: None,
    install_bleak_catcher: None,
    caplog: pytest.LogCaptureFixture,
) -> None:
    """Test that connection parameters are loaded when mgmt API is available."""
    manager = _get_manager()
    hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices()

    # Mock the bluez mgmt controller
    mock_mgmt_ctl = Mock()
    mock_mgmt_ctl.load_conn_params.return_value = True

    class FakeBleakClientTracksConnect(BaseFakeBleakClient):
        """Fake bleak client that tracks connect."""

        connected = False

        async def connect(self, *args, **kwargs):
            """Connect."""
            self.connected = True
            # Simulate service discovery
            await asyncio.sleep(0)

        @property
        def is_connected(self) -> bool:
            return self.connected

    # Test with debug logging enabled
    with (
        caplog.at_level(logging.DEBUG),
        patch.object(manager, "get_bluez_mgmt_ctl", return_value=mock_mgmt_ctl),
        patch(
            "habluetooth.wrappers.get_platform_client_backend_type",
            return_value=FakeBleakClientTracksConnect,
        ),
    ):
        ble_device = hci0_device_advs["00:00:00:00:00:01"][0]
        client = bleak.BleakClient(ble_device)
        await client.connect()

        # Verify load_conn_params was called twice (fast before connect, medium after)
        assert mock_mgmt_ctl.load_conn_params.call_count == 2

        # First call should be for FAST params
        first_call = mock_mgmt_ctl.load_conn_params.call_args_list[0]
        assert first_call[0][0] == 0  # adapter_idx
        assert first_call[0][1] == "00:00:00:00:00:01"  # address
        assert first_call[0][2] == 1  # BDADDR_LE_PUBLIC (default)
        assert first_call[0][3].value == "fast"  # ConnectParams.FAST

        # Second call should be for MEDIUM params
        second_call = mock_mgmt_ctl.load_conn_params.call_args_list[1]
        assert second_call[0][0] == 0  # adapter_idx
        assert second_call[0][1] == "00:00:00:00:00:01"  # address
        assert second_call[0][2] == 1  # BDADDR_LE_PUBLIC
        assert second_call[0][3].value == "medium"  # ConnectParams.MEDIUM

        # Verify debug logging
        assert "Loaded ConnectParams.FAST connection parameters" in caplog.text
        assert "Loaded ConnectParams.MEDIUM connection parameters" in caplog.text

    cancel_hci0()
    cancel_hci1()


@pytest.mark.asyncio
async def test_connection_params_not_loaded_without_mgmt(
    two_adapters: None,
    enable_bluetooth: None,
    install_bleak_catcher: None,
    caplog: pytest.LogCaptureFixture,
) -> None:
    """Test that connection parameters are not loaded when mgmt API is unavailable."""
    manager = _get_manager()
    hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices()

    class FakeBleakClientTracksConnect(BaseFakeBleakClient):
        """Fake bleak client that tracks connect."""

        connected = False

        async def connect(self, *args, **kwargs):
            """Connect."""
            self.connected = True
            await asyncio.sleep(0)

        @property
        def is_connected(self) -> bool:
            return self.connected

    with (
        caplog.at_level(logging.DEBUG),
        patch.object(manager, "get_bluez_mgmt_ctl", return_value=None),
        patch(
            "habluetooth.wrappers.get_platform_client_backend_type",
            return_value=FakeBleakClientTracksConnect,
        ),
    ):
        ble_device = hci0_device_advs["00:00:00:00:00:01"][0]
        client = bleak.BleakClient(ble_device)
        await client.connect()

        # Verify no connection parameters were loaded
        assert "connection parameters" not in caplog.text

    cancel_hci0()
    cancel_hci1()


@pytest.mark.asyncio
async def test_get_device_address_type_random(
    two_adapters: None,
    enable_bluetooth: None,
    install_bleak_catcher: None,
) -> None:
    """Test _get_device_address_type returns BDADDR_LE_RANDOM for random address."""
    _hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices()

    # Create a device with random address type
    device = generate_ble_device(
        "00:00:00:00:00:02",
        "Test Device",
        {
            "path": "/org/bluez/hci0/dev_00_00_00_00_00_02",
            "props": {"AddressType": "random"},
        },
    )

    from habluetooth.const import BDADDR_LE_RANDOM
    from habluetooth.wrappers import _get_device_address_type

    assert _get_device_address_type(device) == BDADDR_LE_RANDOM

    cancel_hci0()
    cancel_hci1()


@pytest.mark.asyncio
async def test_get_device_address_type_public(
    two_adapters: None,
    enable_bluetooth: None,
    install_bleak_catcher: None,
) -> None:
    """Test _get_device_address_type returns BDADDR_LE_PUBLIC for public address."""
    hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices()

    # Create a device with public address type (default)
    device = hci0_device_advs["00:00:00:00:00:01"][0]

    from habluetooth.const import BDADDR_LE_PUBLIC
    from habluetooth.wrappers import _get_device_address_type

    assert _get_device_address_type(device) == BDADDR_LE_PUBLIC

    cancel_hci0()
    cancel_hci1()


@pytest.mark.asyncio
async def test_connection_params_loading_fails_silently(
    two_adapters: None,
    enable_bluetooth: None,
    install_bleak_catcher: None,
    caplog: pytest.LogCaptureFixture,
) -> None:
    """Test that connection still succeeds even if loading params fails."""
    manager = _get_manager()
    hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices()

    # Mock the bluez mgmt controller to fail loading params
    mock_mgmt_ctl = Mock()
    mock_mgmt_ctl.load_conn_params.return_value = False

    class FakeBleakClientTracksConnect(BaseFakeBleakClient):
        """Fake bleak client that tracks connect."""

        connected = False

        async def connect(self, *args, **kwargs):
            """Connect."""
            self.connected = True
            await asyncio.sleep(0)

        @property
        def is_connected(self) -> bool:
            return self.connected

    with (
        caplog.at_level(logging.DEBUG),
        patch.object(manager, "get_bluez_mgmt_ctl", return_value=mock_mgmt_ctl),
        patch(
            "habluetooth.wrappers.get_platform_client_backend_type",
            return_value=FakeBleakClientTracksConnect,
        ),
    ):
        ble_device = hci0_device_advs["00:00:00:00:00:01"][0]
        client = bleak.BleakClient(ble_device)
        # Connection should succeed even though param loading failed
        await client.connect()

        # Verify load_conn_params was called
        assert mock_mgmt_ctl.load_conn_params.call_count == 2

        # But no success message should be logged
        assert "Loaded" not in caplog.text

    cancel_hci0()
    cancel_hci1()


@pytest.mark.asyncio
async def test_connection_params_no_adapter_idx(
    two_adapters: None,
    enable_bluetooth: None,
    install_bleak_catcher: None,
    caplog: pytest.LogCaptureFixture,
) -> None:
    """Test that connection params are not loaded if scanner has no adapter_idx."""
    manager = _get_manager()

    # Mock the bluez mgmt controller
    mock_mgmt_ctl = Mock()
    mock_mgmt_ctl.load_conn_params.return_value = True

    class FakeBleakClientTracksConnect(BaseFakeBleakClient):
        """Fake bleak client that tracks connect."""

        connected = False

        async def connect(self, *args, **kwargs):
            """Connect."""
            self.connected = True
            await asyncio.sleep(0)

        @property
        def is_connected(self) -> bool:
            return self.connected

    # Create a fake connector for the remote scanner
    fake_connector = HaBluetoothConnector(
        client=FakeBleakClientTracksConnect, source="any", can_connect=lambda: True
    )

    # Create a scanner without adapter_idx (e.g., remote scanner)
    remote_scanner = FakeScanner(
        "remote_scanner", "ESPHome Device", fake_connector, True
    )
    cancel_remote = manager.async_register_scanner(remote_scanner)

    # Inject advertisement
    device = generate_ble_device(
        "00:00:00:00:00:03", "Test Device", {"source": "remote_scanner"}
    )
    adv_data = generate_advertisement_data(
        local_name="Test Device",
        service_uuids=[],
        rssi=-50,
    )
    remote_scanner.inject_advertisement(device, adv_data)
    await asyncio.sleep(0)

    # Remote scanner should already have adapter_idx returning None
    with (
        caplog.at_level(logging.DEBUG),
        patch.object(manager, "get_bluez_mgmt_ctl", return_value=mock_mgmt_ctl),
    ):
        client = bleak.BleakClient("00:00:00:00:00:03")
        await client.connect()

        # Verify load_conn_params was NOT called since adapter_idx is None
        assert mock_mgmt_ctl.load_conn_params.call_count == 0

    cancel_remote()


@pytest.mark.asyncio
async def test_connection_path_scoring_with_slots_and_logging(
    caplog: pytest.LogCaptureFixture,
) -> None:
    """Test connection path scoring and logging reflects slot availability."""
    from bleak_retry_connector import Allocations

    manager = _get_manager()

    class FakeBleakClientNoConnect(BaseFakeBleakClient):
        """Fake bleak client that doesn't connect."""

        async def connect(self, *args, **kwargs):
            """Don't actually connect."""
            raise BleakError("Test - connection not needed")

    # Create fake connectors
    fake_connector_1 = HaBluetoothConnector(
        client=FakeBleakClientNoConnect, source="scanner1", can_connect=lambda: True
    )
    fake_connector_2 = HaBluetoothConnector(
        client=FakeBleakClientNoConnect, source="scanner2", can_connect=lambda: True
    )
    fake_connector_3 = HaBluetoothConnector(
        client=FakeBleakClientNoConnect, source="scanner3", can_connect=lambda: True
    )

    # Create scanners with different sources
    scanner1 = FakeScanner("scanner1", "Scanner 1", fake_connector_1, True)
    scanner2 = FakeScanner("scanner2", "Scanner 2", fake_connector_2, True)
    scanner3 = FakeScanner("scanner3", "Scanner 3", fake_connector_3, True)

    # Mock get_allocations for each scanner using patch.object
    with (
        patch.object(
            scanner1,
            "get_allocations",
            return_value=Allocations(
                adapter="scanner1",
                slots=3,
                free=1,  # Only 1 slot free - should get penalty
                allocated=["AA:BB:CC:DD:EE:01", "AA:BB:CC:DD:EE:02"],
            ),
        ),
        patch.object(
            scanner2,
            "get_allocations",
            return_value=Allocations(
                adapter="scanner2",
                slots=3,
                free=2,  # 2 slots free - no penalty
                allocated=["AA:BB:CC:DD:EE:03"],
            ),
        ),
        patch.object(
            scanner3,
            "get_allocations",
            return_value=Allocations(
                adapter="scanner3",
                slots=3,
                free=3,  # All slots free - no penalty
                allocated=[],
            ),
        ),
    ):
        cancel1 = manager.async_register_scanner(scanner1)
        cancel2 = manager.async_register_scanner(scanner2)
        cancel3 = manager.async_register_scanner(scanner3)

        # Inject advertisements with different RSSI values
        device1 = generate_ble_device(
            "00:00:00:00:00:01", "Test Device", {"source": "scanner1"}
        )
        adv_data1 = generate_advertisement_data(local_name="Test Device", rssi=-60)
        scanner1.inject_advertisement(device1, adv_data1)

        device2 = generate_ble_device(
            "00:00:00:00:00:01", "Test Device", {"source": "scanner2"}
        )
        adv_data2 = generate_advertisement_data(local_name="Test Device", rssi=-65)
        scanner2.inject_advertisement(device2, adv_data2)

        device3 = generate_ble_device(
            "00:00:00:00:00:01", "Test Device", {"source": "scanner3"}
        )
        adv_data3 = generate_advertisement_data(local_name="Test Device", rssi=-70)
        scanner3.inject_advertisement(device3, adv_data3)

        await asyncio.sleep(0)

        # Try to connect with logging enabled
        with caplog.at_level(logging.INFO):
            client = bleak.BleakClient("00:00:00:00:00:01")
            with suppress(BleakError):
                await client.connect()

        # Check that the log contains the connection paths with correct scoring
        log_text = caplog.text
        assert "Found 3 connection path(s)" in log_text

        # Extract the log line with connection paths
        for line in caplog.text.splitlines():
            if "Found 3 connection path(s)" in line:
                # rssi_diff = best_rssi - second_best_rssi = -60 - (-65) = 5
                # Scanner 1 has best RSSI (-60) but only 1 slot free, so with penalty:
                # score = -60 - (5 * 0.76) = -63.8
                assert "Scanner 1" in line
                assert "(slots=1/3 free)" in line
                assert "(score=-63.8)" in line

                # Scanner 2 has RSSI -65 with 2 slots free, no penalty:
                # score = -65
                assert "Scanner 2" in line
                assert "(slots=2/3 free)" in line
                # Check for both -65 and -65.0
                assert ("(score=-65)" in line) or ("(score=-65.0)" in line)

                # Scanner 3 has RSSI -70 with all slots free, no penalty:
                # score = -70
                assert "Scanner 3" in line
                assert "(slots=3/3 free)" in line
                # Check for both -70 and -70.0
                assert ("(score=-70)" in line) or ("(score=-70.0)" in line)

                # Verify order: Scanner 1 should be first (best score -63.8),
                # then Scanner 2 (-65), then Scanner 3 (-70)
                scanner1_pos = line.find("Scanner 1")
                scanner2_pos = line.find("Scanner 2")
                scanner3_pos = line.find("Scanner 3")

                assert scanner1_pos < scanner2_pos < scanner3_pos, (
                    f"Expected Scanner 1 before Scanner 2 before Scanner 3, "
                    f"but got positions {scanner1_pos}, {scanner2_pos}, {scanner3_pos}"
                )
                break
        else:
            pytest.fail("Could not find connection path log line")

        cancel1()
        cancel2()
        cancel3()


@pytest.mark.asyncio
async def test_connection_path_scoring_no_slots_available(
    caplog: pytest.LogCaptureFixture,
) -> None:
    """Test that scanners with no free slots are excluded."""
    manager = _get_manager()

    class FakeBleakClientNoConnect(BaseFakeBleakClient):
        """Fake bleak client that doesn't connect."""

        async def connect(self, *args, **kwargs):
            """Don't actually connect."""
            raise BleakError("Test - connection not needed")

    # Create fake connectors
    fake_connector_1 = HaBluetoothConnector(
        client=FakeBleakClientNoConnect, source="scanner1", can_connect=lambda: True
    )
    fake_connector_2 = HaBluetoothConnector(
        client=FakeBleakClientNoConnect, source="scanner2", can_connect=lambda: True
    )

    # Create scanners
    scanner1 = FakeScanner("scanner1", "Scanner 1", fake_connector_1, True)
    scanner2 = FakeScanner("scanner2", "Scanner 2", fake_connector_2, True)

    # Mock get_allocations - scanner1 has no free slots
    with (
        patch.object(
            scanner1,
            "get_allocations",
            return_value=Allocations(
                adapter="scanner1",
                slots=3,
                free=0,  # No slots available - should be excluded
                allocated=[
                    "AA:BB:CC:DD:EE:01",
                    "AA:BB:CC:DD:EE:02",
                    "AA:BB:CC:DD:EE:03",
                ],
            ),
        ),
        patch.object(
            scanner2,
            "get_allocations",
            return_value=Allocations(
                adapter="scanner2", slots=3, free=3, allocated=[]  # All slots free
            ),
        ),
    ):
        cancel1 = manager.async_register_scanner(scanner1)
        cancel2 = manager.async_register_scanner(scanner2)

        # Inject advertisements
        device1 = generate_ble_device(
            "00:00:00:00:00:02", "Test Device", {"source": "scanner1"}
        )
        adv_data1 = generate_advertisement_data(
            local_name="Test Device", rssi=-50
        )  # Better RSSI
        scanner1.inject_advertisement(device1, adv_data1)

        device2 = generate_ble_device(
            "00:00:00:00:00:02", "Test Device", {"source": "scanner2"}
        )
        adv_data2 = generate_advertisement_data(
            local_name="Test Device", rssi=-70
        )  # Worse RSSI
        scanner2.inject_advertisement(device2, adv_data2)

        await asyncio.sleep(0)

        # Try to connect with logging enabled
        with caplog.at_level(logging.INFO):
            client = bleak.BleakClient("00:00:00:00:00:02")
            with suppress(BleakError):
                await client.connect()

        # Check that only scanner2 is in the connection paths
        log_text = caplog.text
        assert (
            "Found 1 connection path(s)" in log_text
            or "Found 2 connection path(s)" in log_text
        )

        # If both are shown, scanner1 should have bad score (NO_RSSI_VALUE = -127)
        for line in caplog.text.splitlines():
            if "connection path(s)" in line:
                if "Scanner 1" in line:
                    # Scanner 1 should show 0 free slots and bad score
                    assert "(slots=0/3 free)" in line
                    assert "(score=-127)" in line  # NO_RSSI_VALUE

                # Scanner 2 should be present with normal score
                assert "Scanner 2" in line
                assert "(slots=3/3 free)" in line
                # Check for both -70 and -70.0
                assert ("(score=-70)" in line) or ("(score=-70.0)" in line)
                break

        cancel1()
        cancel2()


@pytest.mark.asyncio
async def test_thundering_herd_connection_slots() -> None:
    """
    Test thundering herd scenario with limited connection slots.

    Simulates 7 devices trying to connect simultaneously to 3 proxies:
    - Proxy 1 & 2: Good signal (-60 RSSI), 3 slots each
    - Proxy 3: Bad signal (-95 RSSI), 3 slots each

    Expected behavior:
    - First 6 devices should connect to proxy1 and proxy2 (3 each)
    - 7th device should connect to proxy3 (bad signal) when others are full
    """
    from bleak_retry_connector import Allocations

    manager = _get_manager()

    # Track which backend each device connected to
    connection_tracker = {}

    class FakeBleakClientThunderingHerd(BaseFakeBleakClient):
        """Fake bleak client for thundering herd test."""

        def __init__(self, address_or_ble_device, *args, **kwargs):
            """Initialize with tracking."""
            super().__init__(address_or_ble_device, *args, **kwargs)
            self._connected = False
            # Track the device and source
            if isinstance(address_or_ble_device, BLEDevice):
                self._address = address_or_ble_device.address
                self._source = address_or_ble_device.details.get("source")
            else:
                self._address = str(address_or_ble_device)
                self._source = None

        async def connect(self, *args, **kwargs):
            """Simulate connection and record which backend was used."""
            # Small delay to simulate connection time
            await asyncio.sleep(0.01)
            self._connected = True
            # Record which backend this device connected to
            if self._address and self._source:
                connection_tracker[self._address] = self._source
            return True

        @property
        def is_connected(self) -> bool:
            """Return connection state."""
            return self._connected

    # Create fake connectors for 3 proxies
    fake_connector_1 = HaBluetoothConnector(
        client=FakeBleakClientThunderingHerd,
        source="proxy1",
        can_connect=lambda: True,
    )
    fake_connector_2 = HaBluetoothConnector(
        client=FakeBleakClientThunderingHerd,
        source="proxy2",
        can_connect=lambda: True,
    )
    fake_connector_3 = HaBluetoothConnector(
        client=FakeBleakClientThunderingHerd,
        source="proxy3",
        can_connect=lambda: True,
    )

    # Create 3 scanners (proxies) with 3 connection slots each
    proxy1 = FakeScanner("proxy1", "Proxy 1 (Good)", fake_connector_1, True)
    proxy2 = FakeScanner("proxy2", "Proxy 2 (Good)", fake_connector_2, True)
    proxy3 = FakeScanner("proxy3", "Proxy 3 (Bad)", fake_connector_3, True)

    # Track actual slot allocations dynamically
    proxy_allocations: dict[str, set[str]] = {
        "proxy1": set(),
        "proxy2": set(),
        "proxy3": set(),
    }

    def get_proxy_allocations(proxy_name: str) -> Allocations:
        """Get allocations for a specific proxy."""
        allocated = proxy_allocations[proxy_name]
        return Allocations(
            adapter=proxy_name,
            slots=3,
            free=3 - len(allocated),
            allocated=list(allocated),
        )

    # Mock methods to track allocations
    def make_add_connecting(proxy_name: str) -> Callable[[str], None]:
        def _add_connecting(addr: str) -> None:
            proxy_allocations[proxy_name].add(addr)

        return _add_connecting

    def make_finished_connecting(proxy_name: str) -> Callable[[str, bool], None]:
        def _finished_connecting(addr: str, success: bool) -> None:
            if not success:
                proxy_allocations[proxy_name].discard(addr)

        return _finished_connecting

    # Mock get_allocations and connection tracking
    with (
        patch.object(
            proxy1, "get_allocations", lambda: get_proxy_allocations("proxy1")
        ),
        patch.object(
            proxy2, "get_allocations", lambda: get_proxy_allocations("proxy2")
        ),
        patch.object(
            proxy3, "get_allocations", lambda: get_proxy_allocations("proxy3")
        ),
        patch.object(proxy1, "_add_connecting", make_add_connecting("proxy1")),
        patch.object(proxy2, "_add_connecting", make_add_connecting("proxy2")),
        patch.object(proxy3, "_add_connecting", make_add_connecting("proxy3")),
        patch.object(
            proxy1, "_finished_connecting", make_finished_connecting("proxy1")
        ),
        patch.object(
            proxy2, "_finished_connecting", make_finished_connecting("proxy2")
        ),
        patch.object(
            proxy3, "_finished_connecting", make_finished_connecting("proxy3")
        ),
    ):
        cancel1 = manager.async_register_scanner(proxy1)
        cancel2 = manager.async_register_scanner(proxy2)
        cancel3 = manager.async_register_scanner(proxy3)

        # Create 7 devices to connect
        device_addresses = [f"AA:BB:CC:DD:EE:0{i}" for i in range(1, 8)]

        # Inject advertisements for all devices on all proxies
        for i, address in enumerate(device_addresses, 1):
            # Good signal on proxy1
            device1 = generate_ble_device(address, f"Device {i}", {"source": "proxy1"})
            adv_data1 = generate_advertisement_data(local_name=f"Device {i}", rssi=-60)
            proxy1.inject_advertisement(device1, adv_data1)

            # Good signal on proxy2 (exactly same as proxy1)
            device2 = generate_ble_device(address, f"Device {i}", {"source": "proxy2"})
            adv_data2 = generate_advertisement_data(local_name=f"Device {i}", rssi=-60)
            proxy2.inject_advertisement(device2, adv_data2)

            # Bad signal on proxy3
            device3 = generate_ble_device(address, f"Device {i}", {"source": "proxy3"})
            adv_data3 = generate_advertisement_data(local_name=f"Device {i}", rssi=-95)
            proxy3.inject_advertisement(device3, adv_data3)

        await asyncio.sleep(0)

        # Clear the connection tracker before starting
        connection_tracker.clear()

        async def connect_device(address: str) -> tuple[str, str | None]:
            """Try to connect to a device."""
            client = bleak.BleakClient(address)
            try:
                await client.connect()
                # The connection tracker should have recorded which backend was used
                return address, connection_tracker.get(address, "unknown")
            except BleakError:
                # Connection failed (no available backend)
                return address, None

        # Simulate thundering herd - all devices try to connect at once
        tasks = [connect_device(addr) for addr in device_addresses]
        results = await asyncio.gather(*tasks, return_exceptions=True)

        # Process results
        connection_results = {}
        for result in results:
            if isinstance(result, tuple):
                address, proxy = result
                connection_results[address] = proxy

        # Count connections per proxy
        proxy1_connections = [
            addr for addr, p in connection_results.items() if p == "proxy1"
        ]
        proxy2_connections = [
            addr for addr, p in connection_results.items() if p == "proxy2"
        ]
        proxy3_connections = [
            addr for addr, p in connection_results.items() if p == "proxy3"
        ]
        failed_connections = [
            addr for addr, p in connection_results.items() if p is None
        ]

        # Verify constraints
        # 1. No proxy should exceed its slot limit
        assert (
            len(proxy1_connections) <= 3
        ), f"Proxy1 exceeded slot limit: {len(proxy1_connections)} > 3"
        assert (
            len(proxy2_connections) <= 3
        ), f"Proxy2 exceeded slot limit: {len(proxy2_connections)} > 3"
        assert (
            len(proxy3_connections) <= 3
        ), f"Proxy3 exceeded slot limit: {len(proxy3_connections)} > 3"

        # 2. Good signal proxies should be preferred and fill up first
        good_proxy_total = len(proxy1_connections) + len(proxy2_connections)
        assert (
            good_proxy_total == 6
        ), f"Expected exactly 6 connections on good proxies, got {good_proxy_total}"

        # 3. All 7 devices should connect (6 to good proxies, 1 to bad proxy)
        total_connected = (
            len(proxy1_connections) + len(proxy2_connections) + len(proxy3_connections)
        )
        assert (
            total_connected == 7
        ), f"Expected all 7 devices to connect, but only {total_connected} did"

        # 4. The 7th device should go to proxy3 since good ones are full
        assert (
            len(proxy3_connections) == 1
        ), f"Expected exactly 1 connection on proxy3, got {len(proxy3_connections)}"

        # 5. Verify good distribution across proxy1 and proxy2
        # Both should have roughly equal load (3 connections each)
        assert (
            len(proxy1_connections) == 3
        ), f"Expected proxy1 to have 3 connections, got {len(proxy1_connections)}"
        assert (
            len(proxy2_connections) == 3
        ), f"Expected proxy2 to have 3 connections, got {len(proxy2_connections)}"

        # 6. No connections should fail
        assert (
            len(failed_connections) == 0
        ), f"Expected no failed connections, but {len(failed_connections)} failed"

        # Clean up
        cancel1()
        cancel2()
        cancel3()


@pytest.mark.asyncio
async def test_backend_name_from_tuple(
    enable_bluetooth: None,
    install_bleak_catcher: None,
    mock_platform_client: None,
) -> None:
    """Test that backend name is extracted from tuple (bleak 2.0.0+)."""
    manager = _get_manager()
    hci0_device_advs, cancel_hci0, _ = _generate_scanners_with_fake_devices()

    with patch(
        "habluetooth.wrappers.get_platform_client_backend_type",
        return_value=(FakeBleakClient, "TestBackend"),
    ):
        ble_device = hci0_device_advs["00:00:00:00:00:01"][0]
        client = bleak.BleakClient(ble_device)

        # Access the wrapped backend through the client
        # The backend name should be extracted from the tuple
        wrapped_backend = client._async_get_best_available_backend_and_device(manager)
        assert wrapped_backend.backend_name == "TestBackend"
        assert wrapped_backend.client == FakeBleakClient

    cancel_hci0()


@pytest.mark.asyncio
async def test_backend_name_from_class(
    enable_bluetooth: None,
    install_bleak_catcher: None,
    mock_platform_client: None,
) -> None:
    """Test that backend name is derived from class name (pre-bleak 2.0.0)."""
    manager = _get_manager()
    hci0_device_advs, cancel_hci0, _ = _generate_scanners_with_fake_devices()

    with patch(
        "habluetooth.wrappers.get_platform_client_backend_type",
        return_value=FakeBleakClient,
    ):
        ble_device = hci0_device_advs["00:00:00:00:00:01"][0]
        client = bleak.BleakClient(ble_device)

        # Access the wrapped backend through the client
        # The backend name should be derived from the class name
        wrapped_backend = client._async_get_best_available_backend_and_device(manager)
        assert wrapped_backend.backend_name == "type"
        assert wrapped_backend.client == FakeBleakClient

    cancel_hci0()


@pytest.mark.asyncio
async def test_backend_name_in_logs(
    enable_bluetooth: None,
    install_bleak_catcher: None,
    mock_platform_client: None,
    caplog: pytest.LogCaptureFixture,
) -> None:
    """Test that backend name appears in debug logs."""
    caplog.set_level(logging.DEBUG)

    hci0_device_advs, cancel_hci0, _ = _generate_scanners_with_fake_devices()

    with patch(
        "habluetooth.wrappers.get_platform_client_backend_type",
        return_value=(FakeBleakClient, "TestBackend"),
    ):
        ble_device = hci0_device_advs["00:00:00:00:00:01"][0]
        with patch.object(FakeBleakClient, "is_connected", return_value=True):
            client = bleak.BleakClient(ble_device)
            await client.connect()

        # Check that the backend name appears in the logs
        assert any(
            "[TestBackend]" in record.message
            for record in caplog.records
            if "Connecting via" in record.message
        ), f"Backend name not found in logs: {[r.message for r in caplog.records]}"
        assert any(
            "[TestBackend]" in record.message
            for record in caplog.records
            if "Connected via" in record.message
        ), f"Backend name not found in logs: {[r.message for r in caplog.records]}"

        await client.disconnect()

    cancel_hci0()