init home-assistant
This commit is contained in:
326
home-assistant/tests/components/bluetooth/__init__.py
Normal file
326
home-assistant/tests/components/bluetooth/__init__.py
Normal file
@@ -0,0 +1,326 @@
|
||||
"""Tests for the Bluetooth integration."""
|
||||
|
||||
from collections.abc import Iterable
|
||||
from contextlib import contextmanager
|
||||
import itertools
|
||||
import time
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from bleak import BleakClient
|
||||
from bleak.backends.scanner import AdvertisementData, BLEDevice
|
||||
from bluetooth_adapters import DEFAULT_ADDRESS
|
||||
from habluetooth import BaseHaScanner, BluetoothManager, get_manager
|
||||
|
||||
from homeassistant.components.bluetooth import (
|
||||
DOMAIN,
|
||||
SOURCE_LOCAL,
|
||||
BluetoothServiceInfo,
|
||||
BluetoothServiceInfoBleak,
|
||||
async_get_advertisement_callback,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
__all__ = (
|
||||
"inject_advertisement",
|
||||
"inject_advertisement_with_source",
|
||||
"inject_advertisement_with_time_and_source",
|
||||
"inject_advertisement_with_time_and_source_connectable",
|
||||
"inject_bluetooth_service_info",
|
||||
"patch_all_discovered_devices",
|
||||
"patch_discovered_devices",
|
||||
"generate_advertisement_data",
|
||||
"generate_ble_device",
|
||||
"MockBleakClient",
|
||||
"patch_bluetooth_time",
|
||||
)
|
||||
|
||||
ADVERTISEMENT_DATA_DEFAULTS = {
|
||||
"local_name": "",
|
||||
"manufacturer_data": {},
|
||||
"service_data": {},
|
||||
"service_uuids": [],
|
||||
"rssi": -127,
|
||||
"platform_data": ((),),
|
||||
"tx_power": -127,
|
||||
}
|
||||
|
||||
BLE_DEVICE_DEFAULTS = {
|
||||
"name": None,
|
||||
"rssi": -127,
|
||||
"details": None,
|
||||
}
|
||||
|
||||
|
||||
@contextmanager
|
||||
def patch_bluetooth_time(mock_time: float) -> None:
|
||||
"""Patch the bluetooth time."""
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.bluetooth.MONOTONIC_TIME", return_value=mock_time
|
||||
),
|
||||
patch("habluetooth.base_scanner.monotonic_time_coarse", return_value=mock_time),
|
||||
patch("habluetooth.manager.monotonic_time_coarse", return_value=mock_time),
|
||||
patch("habluetooth.scanner.monotonic_time_coarse", return_value=mock_time),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
def generate_advertisement_data(**kwargs: Any) -> AdvertisementData:
|
||||
"""Generate advertisement data with defaults."""
|
||||
new = kwargs.copy()
|
||||
for key, value in ADVERTISEMENT_DATA_DEFAULTS.items():
|
||||
new.setdefault(key, value)
|
||||
return AdvertisementData(**new)
|
||||
|
||||
|
||||
def generate_ble_device(
|
||||
address: str | None = None,
|
||||
name: str | None = None,
|
||||
details: Any | None = None,
|
||||
rssi: int | None = None,
|
||||
**kwargs: Any,
|
||||
) -> BLEDevice:
|
||||
"""Generate a BLEDevice with defaults."""
|
||||
new = kwargs.copy()
|
||||
if address is not None:
|
||||
new["address"] = address
|
||||
if name is not None:
|
||||
new["name"] = name
|
||||
if details is not None:
|
||||
new["details"] = details
|
||||
if rssi is not None:
|
||||
new["rssi"] = rssi
|
||||
for key, value in BLE_DEVICE_DEFAULTS.items():
|
||||
new.setdefault(key, value)
|
||||
return BLEDevice(**new)
|
||||
|
||||
|
||||
def _get_manager() -> BluetoothManager:
|
||||
"""Return the bluetooth manager."""
|
||||
return get_manager()
|
||||
|
||||
|
||||
def inject_advertisement(
|
||||
hass: HomeAssistant, device: BLEDevice, adv: AdvertisementData
|
||||
) -> None:
|
||||
"""Inject an advertisement into the manager."""
|
||||
return inject_advertisement_with_source(hass, device, adv, SOURCE_LOCAL)
|
||||
|
||||
|
||||
def inject_advertisement_with_source(
|
||||
hass: HomeAssistant, device: BLEDevice, adv: AdvertisementData, source: str
|
||||
) -> None:
|
||||
"""Inject an advertisement into the manager from a specific source."""
|
||||
inject_advertisement_with_time_and_source(
|
||||
hass, device, adv, time.monotonic(), source
|
||||
)
|
||||
|
||||
|
||||
def inject_advertisement_with_time_and_source(
|
||||
hass: HomeAssistant,
|
||||
device: BLEDevice,
|
||||
adv: AdvertisementData,
|
||||
time: float,
|
||||
source: str,
|
||||
) -> None:
|
||||
"""Inject an advertisement into the manager from a specific source at a time."""
|
||||
inject_advertisement_with_time_and_source_connectable(
|
||||
hass, device, adv, time, source, True
|
||||
)
|
||||
|
||||
|
||||
def inject_advertisement_with_time_and_source_connectable(
|
||||
hass: HomeAssistant,
|
||||
device: BLEDevice,
|
||||
adv: AdvertisementData,
|
||||
time: float,
|
||||
source: str,
|
||||
connectable: bool,
|
||||
) -> None:
|
||||
"""Inject an advertisement into the manager from a specific source at a time and connectable status."""
|
||||
async_get_advertisement_callback(hass)(
|
||||
BluetoothServiceInfoBleak(
|
||||
name=adv.local_name or device.name or device.address,
|
||||
address=device.address,
|
||||
rssi=adv.rssi,
|
||||
manufacturer_data=adv.manufacturer_data,
|
||||
service_data=adv.service_data,
|
||||
service_uuids=adv.service_uuids,
|
||||
source=source,
|
||||
device=device,
|
||||
advertisement=adv,
|
||||
connectable=connectable,
|
||||
time=time,
|
||||
tx_power=adv.tx_power,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def inject_bluetooth_service_info_bleak(
|
||||
hass: HomeAssistant, info: BluetoothServiceInfoBleak
|
||||
) -> None:
|
||||
"""Inject an advertisement into the manager with connectable status."""
|
||||
advertisement_data = generate_advertisement_data(
|
||||
local_name=None if info.name == "" else info.name,
|
||||
manufacturer_data=info.manufacturer_data,
|
||||
service_data=info.service_data,
|
||||
service_uuids=info.service_uuids,
|
||||
rssi=info.rssi,
|
||||
)
|
||||
device = generate_ble_device( # type: ignore[no-untyped-call]
|
||||
address=info.address,
|
||||
name=info.name,
|
||||
details={},
|
||||
)
|
||||
inject_advertisement_with_time_and_source_connectable(
|
||||
hass,
|
||||
device,
|
||||
advertisement_data,
|
||||
info.time,
|
||||
SOURCE_LOCAL,
|
||||
connectable=info.connectable,
|
||||
)
|
||||
|
||||
|
||||
def inject_bluetooth_service_info(
|
||||
hass: HomeAssistant, info: BluetoothServiceInfo
|
||||
) -> None:
|
||||
"""Inject a BluetoothServiceInfo into the manager."""
|
||||
advertisement_data = generate_advertisement_data( # type: ignore[no-untyped-call]
|
||||
local_name=None if info.name == "" else info.name,
|
||||
manufacturer_data=info.manufacturer_data,
|
||||
service_data=info.service_data,
|
||||
service_uuids=info.service_uuids,
|
||||
rssi=info.rssi,
|
||||
)
|
||||
device = generate_ble_device( # type: ignore[no-untyped-call]
|
||||
address=info.address,
|
||||
name=info.name,
|
||||
details={},
|
||||
)
|
||||
inject_advertisement(hass, device, advertisement_data)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def patch_all_discovered_devices(mock_discovered: list[BLEDevice]) -> None:
|
||||
"""Mock all the discovered devices from all the scanners."""
|
||||
manager = _get_manager()
|
||||
original_history = {}
|
||||
scanners = list(
|
||||
itertools.chain(
|
||||
manager._connectable_scanners, manager._non_connectable_scanners
|
||||
)
|
||||
)
|
||||
for scanner in scanners:
|
||||
data = scanner.discovered_devices_and_advertisement_data
|
||||
original_history[scanner] = data.copy()
|
||||
data.clear()
|
||||
if scanners:
|
||||
data = scanners[0].discovered_devices_and_advertisement_data
|
||||
data.clear()
|
||||
data.update(
|
||||
{device.address: (device, MagicMock()) for device in mock_discovered}
|
||||
)
|
||||
yield
|
||||
for scanner in scanners:
|
||||
data = scanner.discovered_devices_and_advertisement_data
|
||||
data.clear()
|
||||
data.update(original_history[scanner])
|
||||
|
||||
|
||||
@contextmanager
|
||||
def patch_discovered_devices(mock_discovered: list[BLEDevice]) -> None:
|
||||
"""Mock the combined best path to discovered devices from all the scanners."""
|
||||
manager = _get_manager()
|
||||
original_all_history = manager._all_history
|
||||
original_connectable_history = manager._connectable_history
|
||||
manager._connectable_history = {}
|
||||
manager._all_history = {
|
||||
device.address: MagicMock(device=device) for device in mock_discovered
|
||||
}
|
||||
yield
|
||||
manager._all_history = original_all_history
|
||||
manager._connectable_history = original_connectable_history
|
||||
|
||||
|
||||
async def async_setup_with_default_adapter(hass: HomeAssistant) -> MockConfigEntry:
|
||||
"""Set up the Bluetooth integration with a default adapter."""
|
||||
return await _async_setup_with_adapter(hass, DEFAULT_ADDRESS)
|
||||
|
||||
|
||||
async def async_setup_with_one_adapter(hass: HomeAssistant) -> MockConfigEntry:
|
||||
"""Set up the Bluetooth integration with one adapter."""
|
||||
return await _async_setup_with_adapter(hass, "00:00:00:00:00:01")
|
||||
|
||||
|
||||
async def _async_setup_with_adapter(
|
||||
hass: HomeAssistant, address: str
|
||||
) -> MockConfigEntry:
|
||||
"""Set up the Bluetooth integration with any adapter."""
|
||||
entry = MockConfigEntry(domain="bluetooth", unique_id=address)
|
||||
entry.add_to_hass(hass)
|
||||
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
await hass.async_block_till_done()
|
||||
return entry
|
||||
|
||||
|
||||
class MockBleakClient(BleakClient):
|
||||
"""Mock bleak client."""
|
||||
|
||||
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
||||
"""Mock init."""
|
||||
super().__init__(*args, **kwargs)
|
||||
self._device_path = "/dev/test"
|
||||
|
||||
@property
|
||||
def is_connected(self) -> bool:
|
||||
"""Mock connected."""
|
||||
return True
|
||||
|
||||
async def connect(self, *args, **kwargs):
|
||||
"""Mock connect."""
|
||||
return True
|
||||
|
||||
async def disconnect(self, *args, **kwargs):
|
||||
"""Mock disconnect."""
|
||||
|
||||
async def get_services(self, *args, **kwargs):
|
||||
"""Mock get_services."""
|
||||
return []
|
||||
|
||||
async def clear_cache(self, *args, **kwargs):
|
||||
"""Mock clear_cache."""
|
||||
return True
|
||||
|
||||
|
||||
class FakeScannerMixin:
|
||||
def get_discovered_device_advertisement_data(
|
||||
self, address: str
|
||||
) -> tuple[BLEDevice, AdvertisementData] | None:
|
||||
"""Return the advertisement data for a discovered device."""
|
||||
return self.discovered_devices_and_advertisement_data.get(address)
|
||||
|
||||
@property
|
||||
def discovered_addresses(self) -> Iterable[str]:
|
||||
"""Return an iterable of discovered devices."""
|
||||
return self.discovered_devices_and_advertisement_data
|
||||
|
||||
|
||||
class FakeScanner(FakeScannerMixin, BaseHaScanner):
|
||||
"""Fake scanner."""
|
||||
|
||||
@property
|
||||
def discovered_devices(self) -> list[BLEDevice]:
|
||||
"""Return a list of discovered devices."""
|
||||
return []
|
||||
|
||||
@property
|
||||
def discovered_devices_and_advertisement_data(
|
||||
self,
|
||||
) -> dict[str, tuple[BLEDevice, AdvertisementData]]:
|
||||
"""Return a list of discovered devices and their advertisement data."""
|
||||
return {}
|
||||
306
home-assistant/tests/components/bluetooth/conftest.py
Normal file
306
home-assistant/tests/components/bluetooth/conftest.py
Normal file
@@ -0,0 +1,306 @@
|
||||
"""Tests for the bluetooth component."""
|
||||
|
||||
from collections.abc import Generator
|
||||
from unittest.mock import patch
|
||||
|
||||
from bleak_retry_connector import bleak_manager
|
||||
from dbus_fast.aio import message_bus
|
||||
import habluetooth.util as habluetooth_utils
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(name="disable_bluez_manager_socket", autouse=True, scope="package")
|
||||
def disable_bluez_manager_socket():
|
||||
"""Mock the bluez manager socket."""
|
||||
with patch.object(bleak_manager, "get_global_bluez_manager_with_timeout"):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(name="disable_dbus_socket", autouse=True, scope="package")
|
||||
def disable_dbus_socket():
|
||||
"""Mock the dbus message bus to avoid creating a socket."""
|
||||
with patch.object(message_bus, "MessageBus"):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(name="disable_bluetooth_auto_recovery", autouse=True, scope="package")
|
||||
def disable_bluetooth_auto_recovery():
|
||||
"""Mock out auto recovery."""
|
||||
with patch.object(habluetooth_utils, "recover_adapter"):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(name="operating_system_85")
|
||||
def mock_operating_system_85():
|
||||
"""Mock running Home Assistant Operating system 8.5."""
|
||||
with (
|
||||
patch("homeassistant.components.hassio.is_hassio", return_value=True),
|
||||
patch(
|
||||
"homeassistant.components.hassio.get_os_info",
|
||||
return_value={
|
||||
"version": "8.5",
|
||||
"version_latest": "10.0.dev20220912",
|
||||
"update_available": False,
|
||||
"board": "odroid-n2",
|
||||
"boot": "B",
|
||||
"data_disk": "/dev/mmcblk1p4",
|
||||
},
|
||||
),
|
||||
patch("homeassistant.components.hassio.get_info", return_value={}),
|
||||
patch("homeassistant.components.hassio.get_host_info", return_value={}),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(name="operating_system_90")
|
||||
def mock_operating_system_90():
|
||||
"""Mock running Home Assistant Operating system 9.0."""
|
||||
with (
|
||||
patch("homeassistant.components.hassio.is_hassio", return_value=True),
|
||||
patch(
|
||||
"homeassistant.components.hassio.get_os_info",
|
||||
return_value={
|
||||
"version": "9.0.dev20220912",
|
||||
"version_latest": "10.0.dev20220912",
|
||||
"update_available": False,
|
||||
"board": "odroid-n2",
|
||||
"boot": "B",
|
||||
"data_disk": "/dev/mmcblk1p4",
|
||||
},
|
||||
),
|
||||
patch("homeassistant.components.hassio.get_info", return_value={}),
|
||||
patch("homeassistant.components.hassio.get_host_info", return_value={}),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(name="macos_adapter")
|
||||
def macos_adapter() -> Generator[None]:
|
||||
"""Fixture that mocks the macos adapter."""
|
||||
with (
|
||||
patch("bleak.get_platform_scanner_backend_type"),
|
||||
patch(
|
||||
"homeassistant.components.bluetooth.platform.system",
|
||||
return_value="Darwin",
|
||||
),
|
||||
patch(
|
||||
"habluetooth.scanner.platform.system",
|
||||
return_value="Darwin",
|
||||
),
|
||||
patch(
|
||||
"bluetooth_adapters.systems.platform.system",
|
||||
return_value="Darwin",
|
||||
),
|
||||
patch("habluetooth.scanner.SYSTEM", "Darwin"),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(name="windows_adapter")
|
||||
def windows_adapter():
|
||||
"""Fixture that mocks the windows adapter."""
|
||||
with (
|
||||
patch(
|
||||
"bluetooth_adapters.systems.platform.system",
|
||||
return_value="Windows",
|
||||
),
|
||||
patch("habluetooth.scanner.SYSTEM", "Windows"),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(name="no_adapters")
|
||||
def no_adapter_fixture() -> Generator[None]:
|
||||
"""Fixture that mocks no adapters on Linux."""
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.bluetooth.platform.system",
|
||||
return_value="Linux",
|
||||
),
|
||||
patch(
|
||||
"habluetooth.scanner.platform.system",
|
||||
return_value="Linux",
|
||||
),
|
||||
patch(
|
||||
"bluetooth_adapters.systems.platform.system",
|
||||
return_value="Linux",
|
||||
),
|
||||
patch("habluetooth.scanner.SYSTEM", "Linux"),
|
||||
patch(
|
||||
"bluetooth_adapters.systems.linux.LinuxAdapters.refresh",
|
||||
),
|
||||
patch(
|
||||
"bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
|
||||
{},
|
||||
),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(name="one_adapter")
|
||||
def one_adapter_fixture() -> Generator[None]:
|
||||
"""Fixture that mocks one adapter on Linux."""
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.bluetooth.platform.system",
|
||||
return_value="Linux",
|
||||
),
|
||||
patch(
|
||||
"habluetooth.scanner.platform.system",
|
||||
return_value="Linux",
|
||||
),
|
||||
patch(
|
||||
"bluetooth_adapters.systems.platform.system",
|
||||
return_value="Linux",
|
||||
),
|
||||
patch("habluetooth.scanner.SYSTEM", "Linux"),
|
||||
patch(
|
||||
"bluetooth_adapters.systems.linux.LinuxAdapters.refresh",
|
||||
),
|
||||
patch(
|
||||
"bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
|
||||
{
|
||||
"hci0": {
|
||||
"address": "00:00:00:00:00:01",
|
||||
"hw_version": "usb:v1D6Bp0246d053F",
|
||||
"passive_scan": True,
|
||||
"sw_version": "homeassistant",
|
||||
"manufacturer": "ACME",
|
||||
"product": "Bluetooth Adapter 5.0",
|
||||
"product_id": "aa01",
|
||||
"vendor_id": "cc01",
|
||||
},
|
||||
},
|
||||
),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(name="two_adapters")
|
||||
def two_adapters_fixture() -> Generator[None]:
|
||||
"""Fixture that mocks two adapters on Linux."""
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.bluetooth.platform.system", return_value="Linux"
|
||||
),
|
||||
patch(
|
||||
"habluetooth.scanner.platform.system",
|
||||
return_value="Linux",
|
||||
),
|
||||
patch("bluetooth_adapters.systems.platform.system", return_value="Linux"),
|
||||
patch("bluetooth_adapters.systems.linux.LinuxAdapters.refresh"),
|
||||
patch(
|
||||
"bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
|
||||
{
|
||||
"hci0": {
|
||||
"address": "00:00:00:00:00:01",
|
||||
"hw_version": "usb:v1D6Bp0246d053F",
|
||||
"passive_scan": False,
|
||||
"sw_version": "homeassistant",
|
||||
"manufacturer": "ACME",
|
||||
"product": "Bluetooth Adapter 5.0",
|
||||
"product_id": "aa01",
|
||||
"vendor_id": "cc01",
|
||||
"connection_slots": 1,
|
||||
},
|
||||
"hci1": {
|
||||
"address": "00:00:00:00:00:02",
|
||||
"hw_version": "usb:v1D6Bp0246d053F",
|
||||
"passive_scan": True,
|
||||
"sw_version": "homeassistant",
|
||||
"manufacturer": "ACME",
|
||||
"product": "Bluetooth Adapter 5.0",
|
||||
"product_id": "aa01",
|
||||
"vendor_id": "cc01",
|
||||
"connection_slots": 2,
|
||||
},
|
||||
},
|
||||
),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(name="crashed_adapter")
|
||||
def crashed_adapter_fixture():
|
||||
"""Fixture that mocks one crashed adapter on Linux."""
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.bluetooth.platform.system",
|
||||
return_value="Linux",
|
||||
),
|
||||
patch(
|
||||
"habluetooth.scanner.platform.system",
|
||||
return_value="Linux",
|
||||
),
|
||||
patch(
|
||||
"bluetooth_adapters.systems.platform.system",
|
||||
return_value="Linux",
|
||||
),
|
||||
patch("habluetooth.scanner.SYSTEM", "Linux"),
|
||||
patch(
|
||||
"bluetooth_adapters.systems.linux.LinuxAdapters.refresh",
|
||||
),
|
||||
patch(
|
||||
"bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
|
||||
{
|
||||
"hci0": {
|
||||
"address": "00:00:00:00:00:00",
|
||||
"hw_version": "usb:v1D6Bp0246d053F",
|
||||
"passive_scan": True,
|
||||
"sw_version": "homeassistant",
|
||||
"manufacturer": None,
|
||||
"product": None,
|
||||
"product_id": None,
|
||||
"vendor_id": None,
|
||||
},
|
||||
},
|
||||
),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(name="one_adapter_old_bluez")
|
||||
def one_adapter_old_bluez():
|
||||
"""Fixture that mocks two adapters on Linux."""
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.bluetooth.platform.system", return_value="Linux"
|
||||
),
|
||||
patch(
|
||||
"habluetooth.scanner.platform.system",
|
||||
return_value="Linux",
|
||||
),
|
||||
patch("bluetooth_adapters.systems.platform.system", return_value="Linux"),
|
||||
patch("bluetooth_adapters.systems.linux.LinuxAdapters.refresh"),
|
||||
patch(
|
||||
"bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
|
||||
{
|
||||
"hci0": {
|
||||
"address": "00:00:00:00:00:01",
|
||||
"hw_version": "usb:v1D6Bp0246d053F",
|
||||
"passive_scan": False,
|
||||
"sw_version": "homeassistant",
|
||||
"manufacturer": "ACME",
|
||||
"product": "Bluetooth Adapter 5.0",
|
||||
"product_id": "aa01",
|
||||
"vendor_id": "cc01",
|
||||
},
|
||||
},
|
||||
),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(name="disable_new_discovery_flows")
|
||||
def disable_new_discovery_flows_fixture():
|
||||
"""Fixture that disables new discovery flows.
|
||||
|
||||
We want to disable new discovery flows as we are testing the
|
||||
BluetoothManager and not the discovery flows. This fixture
|
||||
will patch the discovery_flow.async_create_flow method to
|
||||
ensure we do not load other integrations.
|
||||
"""
|
||||
with patch(
|
||||
"homeassistant.components.bluetooth.manager.discovery_flow.async_create_flow"
|
||||
) as mock_create_flow:
|
||||
yield mock_create_flow
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,434 @@
|
||||
"""Tests for the Bluetooth integration ActiveBluetoothDataUpdateCoordinator."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Callable, Coroutine
|
||||
import logging
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from bleak.exc import BleakError
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.bluetooth import (
|
||||
DOMAIN,
|
||||
BluetoothChange,
|
||||
BluetoothScanningMode,
|
||||
BluetoothServiceInfoBleak,
|
||||
)
|
||||
from homeassistant.components.bluetooth.active_update_coordinator import (
|
||||
ActiveBluetoothDataUpdateCoordinator,
|
||||
)
|
||||
from homeassistant.core import CoreState, HomeAssistant
|
||||
from homeassistant.helpers.debounce import Debouncer
|
||||
from homeassistant.helpers.service_info.bluetooth import BluetoothServiceInfo
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from . import inject_bluetooth_service_info
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
GENERIC_BLUETOOTH_SERVICE_INFO = BluetoothServiceInfo(
|
||||
name="Generic",
|
||||
address="aa:bb:cc:dd:ee:ff",
|
||||
rssi=-95,
|
||||
manufacturer_data={
|
||||
1: b"\x01\x01\x01\x01\x01\x01\x01\x01",
|
||||
},
|
||||
service_data={},
|
||||
service_uuids=[],
|
||||
source="local",
|
||||
)
|
||||
|
||||
GENERIC_BLUETOOTH_SERVICE_INFO_2 = BluetoothServiceInfo(
|
||||
name="Generic",
|
||||
address="aa:bb:cc:dd:ee:ff",
|
||||
rssi=-95,
|
||||
manufacturer_data={
|
||||
2: b"\x01\x01\x01\x01\x01\x01\x01\x01",
|
||||
},
|
||||
service_data={},
|
||||
service_uuids=[],
|
||||
source="local",
|
||||
)
|
||||
|
||||
|
||||
class MyCoordinator(ActiveBluetoothDataUpdateCoordinator[dict[str, Any]]):
|
||||
"""An example coordinator that subclasses ActiveBluetoothDataUpdateCoordinator."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hass: HomeAssistant,
|
||||
logger: logging.Logger,
|
||||
*,
|
||||
address: str,
|
||||
mode: BluetoothScanningMode,
|
||||
needs_poll_method: Callable[[BluetoothServiceInfoBleak, float | None], bool],
|
||||
poll_method: Callable[
|
||||
[BluetoothServiceInfoBleak],
|
||||
Coroutine[Any, Any, dict[str, Any]],
|
||||
]
|
||||
| None = None,
|
||||
poll_debouncer: Debouncer[Coroutine[Any, Any, None]] | None = None,
|
||||
connectable: bool = True,
|
||||
) -> None:
|
||||
"""Initialize the coordinator."""
|
||||
self.passive_data: dict[str, Any] = {}
|
||||
super().__init__(
|
||||
hass=hass,
|
||||
logger=logger,
|
||||
address=address,
|
||||
mode=mode,
|
||||
needs_poll_method=needs_poll_method,
|
||||
poll_method=poll_method,
|
||||
poll_debouncer=poll_debouncer,
|
||||
connectable=connectable,
|
||||
)
|
||||
|
||||
def _async_handle_bluetooth_event(
|
||||
self,
|
||||
service_info: BluetoothServiceInfo,
|
||||
change: BluetoothChange,
|
||||
) -> None:
|
||||
"""Handle a Bluetooth event."""
|
||||
self.passive_data = {"rssi": service_info.rssi}
|
||||
super()._async_handle_bluetooth_event(service_info, change)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_bleak_scanner_start", "mock_bluetooth_adapters")
|
||||
async def test_basic_usage(hass: HomeAssistant) -> None:
|
||||
"""Test basic usage of the ActiveBluetoothDataUpdateCoordinator."""
|
||||
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
|
||||
def _needs_poll(
|
||||
service_info: BluetoothServiceInfoBleak, seconds_since_last_poll: float | None
|
||||
) -> bool:
|
||||
return True
|
||||
|
||||
async def _poll_method(service_info: BluetoothServiceInfoBleak) -> dict[str, Any]:
|
||||
return {"fake": "data"}
|
||||
|
||||
coordinator = MyCoordinator(
|
||||
hass=hass,
|
||||
logger=_LOGGER,
|
||||
address="aa:bb:cc:dd:ee:ff",
|
||||
mode=BluetoothScanningMode.ACTIVE,
|
||||
needs_poll_method=_needs_poll,
|
||||
poll_method=_poll_method,
|
||||
)
|
||||
assert coordinator.available is False # no data yet
|
||||
|
||||
mock_listener = MagicMock()
|
||||
unregister_listener = coordinator.async_add_listener(mock_listener)
|
||||
|
||||
cancel = coordinator.async_start()
|
||||
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert coordinator.passive_data == {"rssi": GENERIC_BLUETOOTH_SERVICE_INFO.rssi}
|
||||
assert coordinator.data == {"fake": "data"}
|
||||
|
||||
cancel()
|
||||
unregister_listener()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_bleak_scanner_start", "mock_bluetooth_adapters")
|
||||
async def test_bleak_error_during_polling(hass: HomeAssistant) -> None:
|
||||
"""Test bleak error during polling ActiveBluetoothDataUpdateCoordinator."""
|
||||
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
poll_count = 0
|
||||
|
||||
def _needs_poll(
|
||||
service_info: BluetoothServiceInfoBleak, seconds_since_last_poll: float | None
|
||||
) -> bool:
|
||||
return True
|
||||
|
||||
async def _poll_method(service_info: BluetoothServiceInfoBleak) -> dict[str, Any]:
|
||||
nonlocal poll_count
|
||||
poll_count += 1
|
||||
if poll_count == 1:
|
||||
raise BleakError("fake bleak error")
|
||||
return {"fake": "data"}
|
||||
|
||||
coordinator = MyCoordinator(
|
||||
hass=hass,
|
||||
logger=_LOGGER,
|
||||
address="aa:bb:cc:dd:ee:ff",
|
||||
mode=BluetoothScanningMode.ACTIVE,
|
||||
needs_poll_method=_needs_poll,
|
||||
poll_method=_poll_method,
|
||||
poll_debouncer=Debouncer(hass, _LOGGER, cooldown=0, immediate=True),
|
||||
)
|
||||
assert coordinator.available is False # no data yet
|
||||
|
||||
mock_listener = MagicMock()
|
||||
unregister_listener = coordinator.async_add_listener(mock_listener)
|
||||
|
||||
cancel = coordinator.async_start()
|
||||
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert coordinator.passive_data == {"rssi": GENERIC_BLUETOOTH_SERVICE_INFO.rssi}
|
||||
assert coordinator.data is None
|
||||
assert coordinator.last_poll_successful is False
|
||||
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO_2)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert coordinator.passive_data == {"rssi": GENERIC_BLUETOOTH_SERVICE_INFO_2.rssi}
|
||||
assert coordinator.data == {"fake": "data"}
|
||||
assert coordinator.last_poll_successful is True
|
||||
|
||||
cancel()
|
||||
unregister_listener()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_bleak_scanner_start", "mock_bluetooth_adapters")
|
||||
async def test_generic_exception_during_polling(hass: HomeAssistant) -> None:
|
||||
"""Test generic exception during polling ActiveBluetoothDataUpdateCoordinator."""
|
||||
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
poll_count = 0
|
||||
|
||||
def _needs_poll(
|
||||
service_info: BluetoothServiceInfoBleak, seconds_since_last_poll: float | None
|
||||
) -> bool:
|
||||
return True
|
||||
|
||||
async def _poll_method(service_info: BluetoothServiceInfoBleak) -> dict[str, Any]:
|
||||
nonlocal poll_count
|
||||
poll_count += 1
|
||||
if poll_count == 1:
|
||||
raise ValueError("fake error")
|
||||
return {"fake": "data"}
|
||||
|
||||
coordinator = MyCoordinator(
|
||||
hass=hass,
|
||||
logger=_LOGGER,
|
||||
address="aa:bb:cc:dd:ee:ff",
|
||||
mode=BluetoothScanningMode.ACTIVE,
|
||||
needs_poll_method=_needs_poll,
|
||||
poll_method=_poll_method,
|
||||
poll_debouncer=Debouncer(hass, _LOGGER, cooldown=0, immediate=True),
|
||||
)
|
||||
assert coordinator.available is False # no data yet
|
||||
|
||||
mock_listener = MagicMock()
|
||||
unregister_listener = coordinator.async_add_listener(mock_listener)
|
||||
|
||||
cancel = coordinator.async_start()
|
||||
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert coordinator.passive_data == {"rssi": GENERIC_BLUETOOTH_SERVICE_INFO.rssi}
|
||||
assert coordinator.data is None
|
||||
assert coordinator.last_poll_successful is False
|
||||
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO_2)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert coordinator.passive_data == {"rssi": GENERIC_BLUETOOTH_SERVICE_INFO_2.rssi}
|
||||
assert coordinator.data == {"fake": "data"}
|
||||
assert coordinator.last_poll_successful is True
|
||||
|
||||
cancel()
|
||||
unregister_listener()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_bleak_scanner_start", "mock_bluetooth_adapters")
|
||||
async def test_polling_debounce(hass: HomeAssistant) -> None:
|
||||
"""Test basic usage of the ActiveBluetoothDataUpdateCoordinator."""
|
||||
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
poll_count = 0
|
||||
|
||||
def _needs_poll(
|
||||
service_info: BluetoothServiceInfoBleak, seconds_since_last_poll: float | None
|
||||
) -> bool:
|
||||
return True
|
||||
|
||||
async def _poll_method(service_info: BluetoothServiceInfoBleak) -> dict[str, Any]:
|
||||
nonlocal poll_count
|
||||
poll_count += 1
|
||||
await asyncio.sleep(0.0001)
|
||||
return {"poll_count": poll_count}
|
||||
|
||||
coordinator = MyCoordinator(
|
||||
hass=hass,
|
||||
logger=_LOGGER,
|
||||
address="aa:bb:cc:dd:ee:ff",
|
||||
mode=BluetoothScanningMode.ACTIVE,
|
||||
needs_poll_method=_needs_poll,
|
||||
poll_method=_poll_method,
|
||||
)
|
||||
assert coordinator.available is False # no data yet
|
||||
|
||||
mock_listener = MagicMock()
|
||||
unregister_listener = coordinator.async_add_listener(mock_listener)
|
||||
|
||||
cancel = coordinator.async_start()
|
||||
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO_2)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert coordinator.passive_data == {"rssi": GENERIC_BLUETOOTH_SERVICE_INFO.rssi}
|
||||
# We should only get one poll because of the debounce
|
||||
assert coordinator.data == {"poll_count": 1}
|
||||
|
||||
cancel()
|
||||
unregister_listener()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_bleak_scanner_start", "mock_bluetooth_adapters")
|
||||
async def test_polling_debounce_with_custom_debouncer(hass: HomeAssistant) -> None:
|
||||
"""Test basic usage of the ActiveBluetoothDataUpdateCoordinator."""
|
||||
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
poll_count = 0
|
||||
|
||||
def _needs_poll(
|
||||
service_info: BluetoothServiceInfoBleak, seconds_since_last_poll: float | None
|
||||
) -> bool:
|
||||
return True
|
||||
|
||||
async def _poll_method(service_info: BluetoothServiceInfoBleak) -> dict[str, Any]:
|
||||
nonlocal poll_count
|
||||
poll_count += 1
|
||||
await asyncio.sleep(0.0001)
|
||||
return {"poll_count": poll_count}
|
||||
|
||||
coordinator = MyCoordinator(
|
||||
hass=hass,
|
||||
logger=_LOGGER,
|
||||
address="aa:bb:cc:dd:ee:ff",
|
||||
mode=BluetoothScanningMode.ACTIVE,
|
||||
needs_poll_method=_needs_poll,
|
||||
poll_method=_poll_method,
|
||||
poll_debouncer=Debouncer(
|
||||
hass, _LOGGER, cooldown=0.1, immediate=True, background=True
|
||||
),
|
||||
)
|
||||
assert coordinator.available is False # no data yet
|
||||
|
||||
mock_listener = MagicMock()
|
||||
unregister_listener = coordinator.async_add_listener(mock_listener)
|
||||
|
||||
cancel = coordinator.async_start()
|
||||
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO_2)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert coordinator.passive_data == {"rssi": GENERIC_BLUETOOTH_SERVICE_INFO.rssi}
|
||||
# We should only get one poll because of the debounce
|
||||
assert coordinator.data == {"poll_count": 1}
|
||||
|
||||
cancel()
|
||||
unregister_listener()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_bleak_scanner_start", "mock_bluetooth_adapters")
|
||||
async def test_polling_rejecting_the_first_time(hass: HomeAssistant) -> None:
|
||||
"""Test need_poll rejects the first time ActiveBluetoothDataUpdateCoordinator."""
|
||||
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
attempt = 0
|
||||
|
||||
def _needs_poll(
|
||||
service_info: BluetoothServiceInfoBleak, seconds_since_last_poll: float | None
|
||||
) -> bool:
|
||||
nonlocal attempt
|
||||
attempt += 1
|
||||
return attempt != 1
|
||||
|
||||
async def _poll_method(service_info: BluetoothServiceInfoBleak) -> dict[str, Any]:
|
||||
return {"fake": "data"}
|
||||
|
||||
coordinator = MyCoordinator(
|
||||
hass=hass,
|
||||
logger=_LOGGER,
|
||||
address="aa:bb:cc:dd:ee:ff",
|
||||
mode=BluetoothScanningMode.ACTIVE,
|
||||
needs_poll_method=_needs_poll,
|
||||
poll_method=_poll_method,
|
||||
)
|
||||
assert coordinator.available is False # no data yet
|
||||
|
||||
mock_listener = MagicMock()
|
||||
unregister_listener = coordinator.async_add_listener(mock_listener)
|
||||
|
||||
cancel = coordinator.async_start()
|
||||
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert coordinator.passive_data == {"rssi": GENERIC_BLUETOOTH_SERVICE_INFO.rssi}
|
||||
# First poll is rejected, so no data yet
|
||||
assert coordinator.data is None
|
||||
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert coordinator.passive_data == {"rssi": GENERIC_BLUETOOTH_SERVICE_INFO.rssi}
|
||||
# Data is the same so no poll check
|
||||
assert coordinator.data is None
|
||||
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO_2)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert coordinator.passive_data == {"rssi": GENERIC_BLUETOOTH_SERVICE_INFO_2.rssi}
|
||||
# Data is different so poll is done
|
||||
assert coordinator.data == {"fake": "data"}
|
||||
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert coordinator.passive_data == {"rssi": GENERIC_BLUETOOTH_SERVICE_INFO.rssi}
|
||||
# Data is different again so poll is done
|
||||
assert coordinator.data == {"fake": "data"}
|
||||
|
||||
cancel()
|
||||
unregister_listener()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_bleak_scanner_start", "mock_bluetooth_adapters")
|
||||
async def test_no_polling_after_stop_event(hass: HomeAssistant) -> None:
|
||||
"""Test we do not poll after the stop event."""
|
||||
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
needs_poll_calls = 0
|
||||
|
||||
def _needs_poll(
|
||||
service_info: BluetoothServiceInfoBleak, seconds_since_last_poll: float | None
|
||||
) -> bool:
|
||||
nonlocal needs_poll_calls
|
||||
needs_poll_calls += 1
|
||||
return True
|
||||
|
||||
async def _poll_method(service_info: BluetoothServiceInfoBleak) -> dict[str, Any]:
|
||||
return {"fake": "data"}
|
||||
|
||||
coordinator = MyCoordinator(
|
||||
hass=hass,
|
||||
logger=_LOGGER,
|
||||
address="aa:bb:cc:dd:ee:ff",
|
||||
mode=BluetoothScanningMode.ACTIVE,
|
||||
needs_poll_method=_needs_poll,
|
||||
poll_method=_poll_method,
|
||||
)
|
||||
assert coordinator.available is False # no data yet
|
||||
|
||||
mock_listener = MagicMock()
|
||||
unregister_listener = coordinator.async_add_listener(mock_listener)
|
||||
|
||||
cancel = coordinator.async_start()
|
||||
assert needs_poll_calls == 0
|
||||
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert coordinator.passive_data == {"rssi": GENERIC_BLUETOOTH_SERVICE_INFO.rssi}
|
||||
assert coordinator.data == {"fake": "data"}
|
||||
|
||||
assert needs_poll_calls == 1
|
||||
|
||||
hass.set_state(CoreState.stopping)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert needs_poll_calls == 1
|
||||
|
||||
# Should not generate a poll now
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO_2)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert needs_poll_calls == 1
|
||||
|
||||
cancel()
|
||||
unregister_listener()
|
||||
@@ -0,0 +1,426 @@
|
||||
"""Tests for the Bluetooth integration PassiveBluetoothDataUpdateCoordinator."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from unittest.mock import MagicMock, call
|
||||
|
||||
from bleak import BleakError
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.bluetooth import (
|
||||
DOMAIN,
|
||||
BluetoothScanningMode,
|
||||
BluetoothServiceInfoBleak,
|
||||
)
|
||||
from homeassistant.components.bluetooth.active_update_processor import (
|
||||
ActiveBluetoothProcessorCoordinator,
|
||||
)
|
||||
from homeassistant.core import CoreState, HomeAssistant
|
||||
from homeassistant.helpers.debounce import Debouncer
|
||||
from homeassistant.helpers.service_info.bluetooth import BluetoothServiceInfo
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from . import inject_bluetooth_service_info
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
GENERIC_BLUETOOTH_SERVICE_INFO = BluetoothServiceInfo(
|
||||
name="Generic",
|
||||
address="aa:bb:cc:dd:ee:ff",
|
||||
rssi=-95,
|
||||
manufacturer_data={
|
||||
1: b"\x01\x01\x01\x01\x01\x01\x01\x01",
|
||||
},
|
||||
service_data={},
|
||||
service_uuids=[],
|
||||
source="local",
|
||||
)
|
||||
GENERIC_BLUETOOTH_SERVICE_INFO_2 = BluetoothServiceInfo(
|
||||
name="Generic",
|
||||
address="aa:bb:cc:dd:ee:ff",
|
||||
rssi=-95,
|
||||
manufacturer_data={1: b"\x01\x01\x01\x01\x01\x01\x01\x01", 2: b"\x02"},
|
||||
service_data={},
|
||||
service_uuids=[],
|
||||
source="local",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_bleak_scanner_start", "mock_bluetooth_adapters")
|
||||
async def test_basic_usage(hass: HomeAssistant) -> None:
|
||||
"""Test basic usage of the ActiveBluetoothProcessorCoordinator."""
|
||||
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
|
||||
def _update_method(service_info: BluetoothServiceInfoBleak):
|
||||
return {"testdata": 0}
|
||||
|
||||
def _poll_needed(*args, **kwargs):
|
||||
return True
|
||||
|
||||
async def _poll(*args, **kwargs):
|
||||
return {"testdata": 1}
|
||||
|
||||
coordinator = ActiveBluetoothProcessorCoordinator(
|
||||
hass,
|
||||
_LOGGER,
|
||||
address="aa:bb:cc:dd:ee:ff",
|
||||
mode=BluetoothScanningMode.ACTIVE,
|
||||
update_method=_update_method,
|
||||
needs_poll_method=_poll_needed,
|
||||
poll_method=_poll,
|
||||
)
|
||||
assert coordinator.available is False # no data yet
|
||||
|
||||
processor = MagicMock()
|
||||
coordinator.async_register_processor(processor)
|
||||
async_handle_update = processor.async_handle_update
|
||||
|
||||
cancel = coordinator.async_start()
|
||||
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
assert coordinator.available is True
|
||||
|
||||
# async_handle_update should have been called twice
|
||||
# The first time, it was passed the data from parsing the advertisement
|
||||
# The second time, it was passed the data from polling
|
||||
assert len(async_handle_update.mock_calls) == 2
|
||||
assert async_handle_update.mock_calls[0] == call({"testdata": 0}, False)
|
||||
assert async_handle_update.mock_calls[1] == call({"testdata": 1})
|
||||
|
||||
cancel()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_bleak_scanner_start", "mock_bluetooth_adapters")
|
||||
async def test_poll_can_be_skipped(hass: HomeAssistant) -> None:
|
||||
"""Test need_poll callback works and can skip a poll if its not needed."""
|
||||
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
|
||||
flag = True
|
||||
|
||||
def _update_method(service_info: BluetoothServiceInfoBleak):
|
||||
return {"testdata": None}
|
||||
|
||||
def _poll_needed(*args, **kwargs):
|
||||
nonlocal flag
|
||||
return flag
|
||||
|
||||
async def _poll(*args, **kwargs):
|
||||
return {"testdata": flag}
|
||||
|
||||
coordinator = ActiveBluetoothProcessorCoordinator(
|
||||
hass,
|
||||
_LOGGER,
|
||||
address="aa:bb:cc:dd:ee:ff",
|
||||
mode=BluetoothScanningMode.ACTIVE,
|
||||
update_method=_update_method,
|
||||
needs_poll_method=_poll_needed,
|
||||
poll_method=_poll,
|
||||
poll_debouncer=Debouncer(
|
||||
hass, _LOGGER, cooldown=0, immediate=True, background=True
|
||||
),
|
||||
)
|
||||
assert coordinator.available is False # no data yet
|
||||
|
||||
processor = MagicMock()
|
||||
coordinator.async_register_processor(processor)
|
||||
async_handle_update = processor.async_handle_update
|
||||
|
||||
cancel = coordinator.async_start()
|
||||
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert async_handle_update.mock_calls[-1] == call({"testdata": True})
|
||||
|
||||
flag = False
|
||||
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO_2)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert async_handle_update.mock_calls[-1] == call({"testdata": None}, True)
|
||||
|
||||
flag = True
|
||||
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert async_handle_update.mock_calls[-1] == call({"testdata": True})
|
||||
|
||||
cancel()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_bleak_scanner_start", "mock_bluetooth_adapters")
|
||||
async def test_bleak_error_and_recover(
|
||||
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""Test bleak error handling and recovery."""
|
||||
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
|
||||
flag = True
|
||||
|
||||
def _update_method(service_info: BluetoothServiceInfoBleak):
|
||||
return {"testdata": None}
|
||||
|
||||
def _poll_needed(*args, **kwargs):
|
||||
return True
|
||||
|
||||
async def _poll(*args, **kwargs):
|
||||
nonlocal flag
|
||||
if flag:
|
||||
raise BleakError("Connection was aborted")
|
||||
return {"testdata": flag}
|
||||
|
||||
coordinator = ActiveBluetoothProcessorCoordinator(
|
||||
hass,
|
||||
_LOGGER,
|
||||
address="aa:bb:cc:dd:ee:ff",
|
||||
mode=BluetoothScanningMode.ACTIVE,
|
||||
update_method=_update_method,
|
||||
needs_poll_method=_poll_needed,
|
||||
poll_method=_poll,
|
||||
poll_debouncer=Debouncer(
|
||||
hass,
|
||||
_LOGGER,
|
||||
cooldown=0,
|
||||
immediate=True,
|
||||
),
|
||||
)
|
||||
assert coordinator.available is False # no data yet
|
||||
|
||||
processor = MagicMock()
|
||||
coordinator.async_register_processor(processor)
|
||||
async_handle_update = processor.async_handle_update
|
||||
|
||||
cancel = coordinator.async_start()
|
||||
|
||||
# First poll fails
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert async_handle_update.mock_calls[-1] == call({"testdata": None}, False)
|
||||
|
||||
assert (
|
||||
"aa:bb:cc:dd:ee:ff: Bluetooth error whilst polling: Connection was aborted"
|
||||
in caplog.text
|
||||
)
|
||||
|
||||
# Second poll works
|
||||
flag = False
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO_2)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert async_handle_update.mock_calls[-1] == call({"testdata": False})
|
||||
|
||||
cancel()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_bleak_scanner_start", "mock_bluetooth_adapters")
|
||||
async def test_poll_failure_and_recover(hass: HomeAssistant) -> None:
|
||||
"""Test error handling and recovery."""
|
||||
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
|
||||
flag = True
|
||||
|
||||
def _update_method(service_info: BluetoothServiceInfoBleak):
|
||||
return {"testdata": None}
|
||||
|
||||
def _poll_needed(*args, **kwargs):
|
||||
return True
|
||||
|
||||
async def _poll(*args, **kwargs):
|
||||
nonlocal flag
|
||||
if flag:
|
||||
raise RuntimeError("Poll failure")
|
||||
return {"testdata": flag}
|
||||
|
||||
coordinator = ActiveBluetoothProcessorCoordinator(
|
||||
hass,
|
||||
_LOGGER,
|
||||
address="aa:bb:cc:dd:ee:ff",
|
||||
mode=BluetoothScanningMode.ACTIVE,
|
||||
update_method=_update_method,
|
||||
needs_poll_method=_poll_needed,
|
||||
poll_method=_poll,
|
||||
poll_debouncer=Debouncer(
|
||||
hass,
|
||||
_LOGGER,
|
||||
cooldown=0,
|
||||
immediate=True,
|
||||
),
|
||||
)
|
||||
assert coordinator.available is False # no data yet
|
||||
|
||||
processor = MagicMock()
|
||||
coordinator.async_register_processor(processor)
|
||||
async_handle_update = processor.async_handle_update
|
||||
|
||||
cancel = coordinator.async_start()
|
||||
|
||||
# First poll fails
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert async_handle_update.mock_calls[-1] == call({"testdata": None}, False)
|
||||
|
||||
# Second poll works
|
||||
flag = False
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO_2)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert async_handle_update.mock_calls[-1] == call({"testdata": False})
|
||||
|
||||
cancel()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_bleak_scanner_start", "mock_bluetooth_adapters")
|
||||
async def test_second_poll_needed(hass: HomeAssistant) -> None:
|
||||
"""If a poll is queued, by the time it starts it may no longer be needed."""
|
||||
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
|
||||
count = 0
|
||||
|
||||
def _update_method(service_info: BluetoothServiceInfoBleak):
|
||||
return {"testdata": None}
|
||||
|
||||
# Only poll once
|
||||
def _poll_needed(*args, **kwargs):
|
||||
nonlocal count
|
||||
return count == 0
|
||||
|
||||
async def _poll(*args, **kwargs):
|
||||
nonlocal count
|
||||
count += 1
|
||||
return {"testdata": count}
|
||||
|
||||
coordinator = ActiveBluetoothProcessorCoordinator(
|
||||
hass,
|
||||
_LOGGER,
|
||||
address="aa:bb:cc:dd:ee:ff",
|
||||
mode=BluetoothScanningMode.ACTIVE,
|
||||
update_method=_update_method,
|
||||
needs_poll_method=_poll_needed,
|
||||
poll_method=_poll,
|
||||
)
|
||||
assert coordinator.available is False # no data yet
|
||||
|
||||
processor = MagicMock()
|
||||
coordinator.async_register_processor(processor)
|
||||
async_handle_update = processor.async_handle_update
|
||||
|
||||
cancel = coordinator.async_start()
|
||||
|
||||
# First poll gets queued
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
# Second poll gets stuck behind first poll
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO_2)
|
||||
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert async_handle_update.mock_calls[1] == call({"testdata": 1})
|
||||
|
||||
cancel()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_bleak_scanner_start", "mock_bluetooth_adapters")
|
||||
async def test_rate_limit(hass: HomeAssistant) -> None:
|
||||
"""Test error handling and recovery."""
|
||||
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
|
||||
count = 0
|
||||
|
||||
def _update_method(service_info: BluetoothServiceInfoBleak):
|
||||
return {"testdata": None}
|
||||
|
||||
def _poll_needed(*args, **kwargs):
|
||||
return True
|
||||
|
||||
async def _poll(*args, **kwargs):
|
||||
nonlocal count
|
||||
count += 1
|
||||
await asyncio.sleep(0)
|
||||
return {"testdata": count}
|
||||
|
||||
coordinator = ActiveBluetoothProcessorCoordinator(
|
||||
hass,
|
||||
_LOGGER,
|
||||
address="aa:bb:cc:dd:ee:ff",
|
||||
mode=BluetoothScanningMode.ACTIVE,
|
||||
update_method=_update_method,
|
||||
needs_poll_method=_poll_needed,
|
||||
poll_method=_poll,
|
||||
)
|
||||
assert coordinator.available is False # no data yet
|
||||
|
||||
processor = MagicMock()
|
||||
coordinator.async_register_processor(processor)
|
||||
async_handle_update = processor.async_handle_update
|
||||
|
||||
cancel = coordinator.async_start()
|
||||
|
||||
# First poll gets queued
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
# Second poll gets stuck behind first poll
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO_2)
|
||||
# Third poll gets stuck behind first poll doesn't get queued
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert async_handle_update.mock_calls[-1] == call({"testdata": 1})
|
||||
|
||||
cancel()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_bleak_scanner_start", "mock_bluetooth_adapters")
|
||||
async def test_no_polling_after_stop_event(hass: HomeAssistant) -> None:
|
||||
"""Test we do not poll after the stop event."""
|
||||
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
needs_poll_calls = 0
|
||||
|
||||
def _update_method(service_info: BluetoothServiceInfoBleak):
|
||||
return {"testdata": 0}
|
||||
|
||||
def _poll_needed(*args, **kwargs):
|
||||
nonlocal needs_poll_calls
|
||||
needs_poll_calls += 1
|
||||
return True
|
||||
|
||||
async def _poll(*args, **kwargs):
|
||||
return {"testdata": 1}
|
||||
|
||||
coordinator = ActiveBluetoothProcessorCoordinator(
|
||||
hass,
|
||||
_LOGGER,
|
||||
address="aa:bb:cc:dd:ee:ff",
|
||||
mode=BluetoothScanningMode.ACTIVE,
|
||||
update_method=_update_method,
|
||||
needs_poll_method=_poll_needed,
|
||||
poll_method=_poll,
|
||||
)
|
||||
assert coordinator.available is False # no data yet
|
||||
|
||||
processor = MagicMock()
|
||||
coordinator.async_register_processor(processor)
|
||||
async_handle_update = processor.async_handle_update
|
||||
|
||||
cancel = coordinator.async_start()
|
||||
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert needs_poll_calls == 1
|
||||
|
||||
assert coordinator.available is True
|
||||
|
||||
# async_handle_update should have been called twice
|
||||
# The first time, it was passed the data from parsing the advertisement
|
||||
# The second time, it was passed the data from polling
|
||||
assert len(async_handle_update.mock_calls) == 2
|
||||
assert async_handle_update.mock_calls[0] == call({"testdata": 0}, False)
|
||||
assert async_handle_update.mock_calls[1] == call({"testdata": 1})
|
||||
|
||||
hass.set_state(CoreState.stopping)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert needs_poll_calls == 1
|
||||
|
||||
# Should not generate a poll now that CoreState is stopping
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO_2)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert needs_poll_calls == 1
|
||||
|
||||
cancel()
|
||||
@@ -0,0 +1,476 @@
|
||||
"""Tests for the Bluetooth integration advertisement tracking."""
|
||||
|
||||
from datetime import timedelta
|
||||
import time
|
||||
|
||||
# pylint: disable-next=no-name-in-module
|
||||
from habluetooth.advertisement_tracker import ADVERTISING_TIMES_NEEDED
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.bluetooth import (
|
||||
async_get_learned_advertising_interval,
|
||||
async_register_scanner,
|
||||
async_track_unavailable,
|
||||
)
|
||||
from homeassistant.components.bluetooth.const import (
|
||||
FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS,
|
||||
SOURCE_LOCAL,
|
||||
UNAVAILABLE_TRACK_SECONDS,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from . import (
|
||||
FakeScanner,
|
||||
generate_advertisement_data,
|
||||
generate_ble_device,
|
||||
inject_advertisement_with_time_and_source,
|
||||
inject_advertisement_with_time_and_source_connectable,
|
||||
patch_bluetooth_time,
|
||||
)
|
||||
|
||||
from tests.common import async_fire_time_changed
|
||||
|
||||
ONE_HOUR_SECONDS = 3600
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "macos_adapter")
|
||||
async def test_advertisment_interval_shorter_than_adapter_stack_timeout(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test we can determine the advertisement interval."""
|
||||
start_monotonic_time = time.monotonic()
|
||||
switchbot_device = generate_ble_device("44:44:33:11:23:12", "wohand")
|
||||
switchbot_adv = generate_advertisement_data(
|
||||
local_name="wohand", service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"]
|
||||
)
|
||||
switchbot_device_went_unavailable = False
|
||||
|
||||
@callback
|
||||
def _switchbot_device_unavailable_callback(_address: str) -> None:
|
||||
"""Switchbot device unavailable callback."""
|
||||
nonlocal switchbot_device_went_unavailable
|
||||
switchbot_device_went_unavailable = True
|
||||
|
||||
for i in range(ADVERTISING_TIMES_NEEDED):
|
||||
inject_advertisement_with_time_and_source(
|
||||
hass,
|
||||
switchbot_device,
|
||||
switchbot_adv,
|
||||
start_monotonic_time + (i * 2),
|
||||
SOURCE_LOCAL,
|
||||
)
|
||||
|
||||
assert async_get_learned_advertising_interval(
|
||||
hass, "44:44:33:11:23:12"
|
||||
) == pytest.approx(2.0)
|
||||
|
||||
switchbot_device_unavailable_cancel = async_track_unavailable(
|
||||
hass, _switchbot_device_unavailable_callback, switchbot_device.address
|
||||
)
|
||||
|
||||
monotonic_now = start_monotonic_time + ((ADVERTISING_TIMES_NEEDED - 1) * 2)
|
||||
with patch_bluetooth_time(
|
||||
monotonic_now + UNAVAILABLE_TRACK_SECONDS,
|
||||
):
|
||||
async_fire_time_changed(
|
||||
hass, dt_util.utcnow() + timedelta(seconds=UNAVAILABLE_TRACK_SECONDS)
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert switchbot_device_went_unavailable is True
|
||||
switchbot_device_unavailable_cancel()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "macos_adapter")
|
||||
async def test_advertisment_interval_longer_than_adapter_stack_timeout_connectable(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test device with a long advertisement interval."""
|
||||
start_monotonic_time = time.monotonic()
|
||||
switchbot_device = generate_ble_device("44:44:33:11:23:18", "wohand")
|
||||
switchbot_adv = generate_advertisement_data(
|
||||
local_name="wohand", service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"]
|
||||
)
|
||||
switchbot_device_went_unavailable = False
|
||||
|
||||
@callback
|
||||
def _switchbot_device_unavailable_callback(_address: str) -> None:
|
||||
"""Switchbot device unavailable callback."""
|
||||
nonlocal switchbot_device_went_unavailable
|
||||
switchbot_device_went_unavailable = True
|
||||
|
||||
for i in range(ADVERTISING_TIMES_NEEDED):
|
||||
inject_advertisement_with_time_and_source(
|
||||
hass,
|
||||
switchbot_device,
|
||||
switchbot_adv,
|
||||
start_monotonic_time + (i * ONE_HOUR_SECONDS),
|
||||
SOURCE_LOCAL,
|
||||
)
|
||||
|
||||
assert async_get_learned_advertising_interval(
|
||||
hass, "44:44:33:11:23:18"
|
||||
) == pytest.approx(ONE_HOUR_SECONDS)
|
||||
|
||||
switchbot_device_unavailable_cancel = async_track_unavailable(
|
||||
hass, _switchbot_device_unavailable_callback, switchbot_device.address
|
||||
)
|
||||
|
||||
monotonic_now = start_monotonic_time + (
|
||||
(ADVERTISING_TIMES_NEEDED - 1) * ONE_HOUR_SECONDS
|
||||
)
|
||||
with patch_bluetooth_time(
|
||||
monotonic_now + UNAVAILABLE_TRACK_SECONDS,
|
||||
):
|
||||
async_fire_time_changed(
|
||||
hass, dt_util.utcnow() + timedelta(seconds=UNAVAILABLE_TRACK_SECONDS)
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert switchbot_device_went_unavailable is True
|
||||
switchbot_device_unavailable_cancel()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "macos_adapter")
|
||||
async def test_advertisment_interval_longer_than_adapter_stack_timeout_adapter_change_connectable(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test device with a long advertisement interval with an adapter change."""
|
||||
start_monotonic_time = time.monotonic()
|
||||
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"]
|
||||
)
|
||||
switchbot_device_went_unavailable = False
|
||||
|
||||
@callback
|
||||
def _switchbot_device_unavailable_callback(_address: str) -> None:
|
||||
"""Switchbot device unavailable callback."""
|
||||
nonlocal switchbot_device_went_unavailable
|
||||
switchbot_device_went_unavailable = True
|
||||
|
||||
for i in range(ADVERTISING_TIMES_NEEDED):
|
||||
inject_advertisement_with_time_and_source(
|
||||
hass,
|
||||
switchbot_device,
|
||||
switchbot_adv,
|
||||
start_monotonic_time + (i * 2),
|
||||
"original",
|
||||
)
|
||||
|
||||
assert async_get_learned_advertising_interval(
|
||||
hass, "44:44:33:11:23:45"
|
||||
) == pytest.approx(2.0)
|
||||
|
||||
for i in range(ADVERTISING_TIMES_NEEDED):
|
||||
inject_advertisement_with_time_and_source(
|
||||
hass,
|
||||
switchbot_device,
|
||||
switchbot_adv,
|
||||
start_monotonic_time + (i * ONE_HOUR_SECONDS),
|
||||
"new",
|
||||
)
|
||||
|
||||
assert async_get_learned_advertising_interval(
|
||||
hass, "44:44:33:11:23:45"
|
||||
) == pytest.approx(ONE_HOUR_SECONDS)
|
||||
|
||||
switchbot_device_unavailable_cancel = async_track_unavailable(
|
||||
hass, _switchbot_device_unavailable_callback, switchbot_device.address
|
||||
)
|
||||
|
||||
monotonic_now = start_monotonic_time + (
|
||||
(ADVERTISING_TIMES_NEEDED - 1) * ONE_HOUR_SECONDS
|
||||
)
|
||||
with patch_bluetooth_time(
|
||||
monotonic_now + UNAVAILABLE_TRACK_SECONDS,
|
||||
):
|
||||
async_fire_time_changed(
|
||||
hass, dt_util.utcnow() + timedelta(seconds=UNAVAILABLE_TRACK_SECONDS)
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert switchbot_device_went_unavailable is True
|
||||
switchbot_device_unavailable_cancel()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "macos_adapter")
|
||||
async def test_advertisment_interval_longer_than_adapter_stack_timeout_not_connectable(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test device with a long advertisement interval that is not connectable not reaching the advertising interval."""
|
||||
start_monotonic_time = time.monotonic()
|
||||
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"]
|
||||
)
|
||||
switchbot_device_went_unavailable = False
|
||||
|
||||
@callback
|
||||
def _switchbot_device_unavailable_callback(_address: str) -> None:
|
||||
"""Switchbot device unavailable callback."""
|
||||
nonlocal switchbot_device_went_unavailable
|
||||
switchbot_device_went_unavailable = True
|
||||
|
||||
for i in range(ADVERTISING_TIMES_NEEDED):
|
||||
inject_advertisement_with_time_and_source(
|
||||
hass,
|
||||
switchbot_device,
|
||||
switchbot_adv,
|
||||
start_monotonic_time + (i * ONE_HOUR_SECONDS),
|
||||
SOURCE_LOCAL,
|
||||
)
|
||||
|
||||
assert async_get_learned_advertising_interval(
|
||||
hass, "44:44:33:11:23:45"
|
||||
) == pytest.approx(ONE_HOUR_SECONDS)
|
||||
|
||||
switchbot_device_unavailable_cancel = async_track_unavailable(
|
||||
hass,
|
||||
_switchbot_device_unavailable_callback,
|
||||
switchbot_device.address,
|
||||
connectable=False,
|
||||
)
|
||||
|
||||
monotonic_now = start_monotonic_time + (
|
||||
(ADVERTISING_TIMES_NEEDED - 1) * ONE_HOUR_SECONDS
|
||||
)
|
||||
with patch_bluetooth_time(
|
||||
monotonic_now + UNAVAILABLE_TRACK_SECONDS,
|
||||
):
|
||||
async_fire_time_changed(
|
||||
hass, dt_util.utcnow() + timedelta(seconds=UNAVAILABLE_TRACK_SECONDS)
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert switchbot_device_went_unavailable is False
|
||||
switchbot_device_unavailable_cancel()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "macos_adapter")
|
||||
async def test_advertisment_interval_shorter_than_adapter_stack_timeout_adapter_change_not_connectable(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test device with a short advertisement interval with an adapter change that is not connectable."""
|
||||
start_monotonic_time = time.monotonic()
|
||||
switchbot_device = generate_ble_device("44:44:33:11:23:5C", "wohand")
|
||||
switchbot_adv = generate_advertisement_data(
|
||||
local_name="wohand",
|
||||
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"],
|
||||
rssi=-100,
|
||||
)
|
||||
switchbot_device_went_unavailable = False
|
||||
|
||||
@callback
|
||||
def _switchbot_device_unavailable_callback(_address: str) -> None:
|
||||
"""Switchbot device unavailable callback."""
|
||||
nonlocal switchbot_device_went_unavailable
|
||||
switchbot_device_went_unavailable = True
|
||||
|
||||
for i in range(ADVERTISING_TIMES_NEEDED):
|
||||
inject_advertisement_with_time_and_source(
|
||||
hass,
|
||||
switchbot_device,
|
||||
switchbot_adv,
|
||||
start_monotonic_time + (i * ONE_HOUR_SECONDS),
|
||||
"original",
|
||||
)
|
||||
|
||||
assert async_get_learned_advertising_interval(
|
||||
hass, "44:44:33:11:23:5C"
|
||||
) == pytest.approx(ONE_HOUR_SECONDS)
|
||||
|
||||
switchbot_adv_better_rssi = generate_advertisement_data(
|
||||
local_name="wohand",
|
||||
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"],
|
||||
rssi=-30,
|
||||
)
|
||||
for i in range(ADVERTISING_TIMES_NEEDED):
|
||||
inject_advertisement_with_time_and_source(
|
||||
hass,
|
||||
switchbot_device,
|
||||
switchbot_adv_better_rssi,
|
||||
start_monotonic_time + (i * 2),
|
||||
"new",
|
||||
)
|
||||
|
||||
assert async_get_learned_advertising_interval(
|
||||
hass, "44:44:33:11:23:5C"
|
||||
) == pytest.approx(2.0)
|
||||
|
||||
switchbot_device_unavailable_cancel = async_track_unavailable(
|
||||
hass,
|
||||
_switchbot_device_unavailable_callback,
|
||||
switchbot_device.address,
|
||||
connectable=False,
|
||||
)
|
||||
|
||||
monotonic_now = start_monotonic_time + (
|
||||
(ADVERTISING_TIMES_NEEDED - 1) * ONE_HOUR_SECONDS
|
||||
)
|
||||
with patch_bluetooth_time(
|
||||
monotonic_now + UNAVAILABLE_TRACK_SECONDS,
|
||||
):
|
||||
async_fire_time_changed(
|
||||
hass, dt_util.utcnow() + timedelta(seconds=UNAVAILABLE_TRACK_SECONDS)
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert switchbot_device_went_unavailable is True
|
||||
switchbot_device_unavailable_cancel()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "macos_adapter")
|
||||
async def test_advertisment_interval_longer_than_adapter_stack_timeout_adapter_change_not_connectable(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test device with a long advertisement interval with an adapter change that is not connectable."""
|
||||
start_monotonic_time = time.monotonic()
|
||||
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"],
|
||||
rssi=-100,
|
||||
)
|
||||
switchbot_device_went_unavailable = False
|
||||
|
||||
scanner = FakeScanner("new", "fake_adapter")
|
||||
cancel_scanner = async_register_scanner(hass, scanner)
|
||||
|
||||
@callback
|
||||
def _switchbot_device_unavailable_callback(_address: str) -> None:
|
||||
"""Switchbot device unavailable callback."""
|
||||
nonlocal switchbot_device_went_unavailable
|
||||
switchbot_device_went_unavailable = True
|
||||
|
||||
for i in range(ADVERTISING_TIMES_NEEDED):
|
||||
inject_advertisement_with_time_and_source_connectable(
|
||||
hass,
|
||||
switchbot_device,
|
||||
switchbot_adv,
|
||||
start_monotonic_time + (i * 2),
|
||||
"original",
|
||||
connectable=False,
|
||||
)
|
||||
|
||||
assert async_get_learned_advertising_interval(
|
||||
hass, "44:44:33:11:23:45"
|
||||
) == pytest.approx(2.0)
|
||||
|
||||
switchbot_better_rssi_adv = generate_advertisement_data(
|
||||
local_name="wohand",
|
||||
service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"],
|
||||
rssi=-30,
|
||||
)
|
||||
for i in range(ADVERTISING_TIMES_NEEDED):
|
||||
inject_advertisement_with_time_and_source_connectable(
|
||||
hass,
|
||||
switchbot_device,
|
||||
switchbot_better_rssi_adv,
|
||||
start_monotonic_time + (i * ONE_HOUR_SECONDS),
|
||||
"new",
|
||||
connectable=False,
|
||||
)
|
||||
|
||||
assert async_get_learned_advertising_interval(
|
||||
hass, "44:44:33:11:23:45"
|
||||
) == pytest.approx(ONE_HOUR_SECONDS)
|
||||
|
||||
switchbot_device_unavailable_cancel = async_track_unavailable(
|
||||
hass,
|
||||
_switchbot_device_unavailable_callback,
|
||||
switchbot_device.address,
|
||||
connectable=False,
|
||||
)
|
||||
|
||||
monotonic_now = start_monotonic_time + (
|
||||
(ADVERTISING_TIMES_NEEDED - 1) * ONE_HOUR_SECONDS
|
||||
)
|
||||
with patch_bluetooth_time(
|
||||
monotonic_now + UNAVAILABLE_TRACK_SECONDS,
|
||||
):
|
||||
async_fire_time_changed(
|
||||
hass, dt_util.utcnow() + timedelta(seconds=UNAVAILABLE_TRACK_SECONDS)
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert switchbot_device_went_unavailable is False
|
||||
cancel_scanner()
|
||||
|
||||
# Now that the scanner is gone we should go back to the stack default timeout
|
||||
with patch_bluetooth_time(
|
||||
monotonic_now + UNAVAILABLE_TRACK_SECONDS,
|
||||
):
|
||||
async_fire_time_changed(
|
||||
hass, dt_util.utcnow() + timedelta(seconds=UNAVAILABLE_TRACK_SECONDS)
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert switchbot_device_went_unavailable is False
|
||||
|
||||
# Now that the scanner is gone we should go back to the stack default timeout
|
||||
with patch_bluetooth_time(
|
||||
monotonic_now + UNAVAILABLE_TRACK_SECONDS,
|
||||
):
|
||||
async_fire_time_changed(
|
||||
hass,
|
||||
dt_util.utcnow()
|
||||
+ timedelta(seconds=FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS),
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert switchbot_device_went_unavailable is False
|
||||
|
||||
switchbot_device_unavailable_cancel()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "macos_adapter")
|
||||
async def test_advertisment_interval_longer_increasing_than_adapter_stack_timeout_adapter_change_not_connectable(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test device with a increasing advertisement interval with an adapter change that is not connectable."""
|
||||
start_monotonic_time = time.monotonic()
|
||||
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"]
|
||||
)
|
||||
switchbot_device_went_unavailable = False
|
||||
|
||||
@callback
|
||||
def _switchbot_device_unavailable_callback(_address: str) -> None:
|
||||
"""Switchbot device unavailable callback."""
|
||||
nonlocal switchbot_device_went_unavailable
|
||||
switchbot_device_went_unavailable = True
|
||||
|
||||
for i in range(ADVERTISING_TIMES_NEEDED, 2 * ADVERTISING_TIMES_NEEDED):
|
||||
inject_advertisement_with_time_and_source(
|
||||
hass,
|
||||
switchbot_device,
|
||||
switchbot_adv,
|
||||
start_monotonic_time + (i**2),
|
||||
"new",
|
||||
)
|
||||
|
||||
assert async_get_learned_advertising_interval(
|
||||
hass, "44:44:33:11:23:45"
|
||||
) == pytest.approx(61.0)
|
||||
|
||||
switchbot_device_unavailable_cancel = async_track_unavailable(
|
||||
hass,
|
||||
_switchbot_device_unavailable_callback,
|
||||
switchbot_device.address,
|
||||
connectable=False,
|
||||
)
|
||||
|
||||
monotonic_now = start_monotonic_time + UNAVAILABLE_TRACK_SECONDS + 1
|
||||
with patch_bluetooth_time(
|
||||
monotonic_now + UNAVAILABLE_TRACK_SECONDS,
|
||||
):
|
||||
async_fire_time_changed(
|
||||
hass, dt_util.utcnow() + timedelta(seconds=UNAVAILABLE_TRACK_SECONDS)
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert switchbot_device_went_unavailable is False
|
||||
switchbot_device_unavailable_cancel()
|
||||
165
home-assistant/tests/components/bluetooth/test_api.py
Normal file
165
home-assistant/tests/components/bluetooth/test_api.py
Normal file
@@ -0,0 +1,165 @@
|
||||
"""Tests for the Bluetooth integration API."""
|
||||
|
||||
import time
|
||||
|
||||
from bleak.backends.scanner import AdvertisementData, BLEDevice
|
||||
import pytest
|
||||
|
||||
from homeassistant.components import bluetooth
|
||||
from homeassistant.components.bluetooth import (
|
||||
MONOTONIC_TIME,
|
||||
BaseHaRemoteScanner,
|
||||
HaBluetoothConnector,
|
||||
async_scanner_by_source,
|
||||
async_scanner_devices_by_address,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from . import (
|
||||
FakeScanner,
|
||||
MockBleakClient,
|
||||
_get_manager,
|
||||
generate_advertisement_data,
|
||||
generate_ble_device,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth")
|
||||
async def test_scanner_by_source(hass: HomeAssistant) -> None:
|
||||
"""Test we can get a scanner by source."""
|
||||
|
||||
hci2_scanner = FakeScanner("hci2", "hci2")
|
||||
cancel_hci2 = bluetooth.async_register_scanner(hass, hci2_scanner)
|
||||
|
||||
assert async_scanner_by_source(hass, "hci2") is hci2_scanner
|
||||
cancel_hci2()
|
||||
assert async_scanner_by_source(hass, "hci2") is None
|
||||
|
||||
|
||||
async def test_monotonic_time() -> None:
|
||||
"""Test monotonic time."""
|
||||
assert MONOTONIC_TIME() == pytest.approx(time.monotonic(), abs=0.1)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth")
|
||||
async def test_async_get_advertisement_callback(hass: HomeAssistant) -> None:
|
||||
"""Test getting advertisement callback."""
|
||||
callback = bluetooth.async_get_advertisement_callback(hass)
|
||||
assert callback is not None
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth")
|
||||
async def test_async_scanner_devices_by_address_connectable(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test getting scanner devices by address with connectable devices."""
|
||||
manager = _get_manager()
|
||||
|
||||
class FakeInjectableScanner(BaseHaRemoteScanner):
|
||||
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,
|
||||
{"scanner_specific_data": "test"},
|
||||
MONOTONIC_TIME(),
|
||||
)
|
||||
|
||||
connector = (
|
||||
HaBluetoothConnector(MockBleakClient, "mock_bleak_client", lambda: False),
|
||||
)
|
||||
scanner = FakeInjectableScanner("esp32", "esp32", connector, True)
|
||||
unsetup = scanner.async_setup()
|
||||
cancel = manager.async_register_scanner(scanner)
|
||||
switchbot_device = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"wohand",
|
||||
{},
|
||||
rssi=-100,
|
||||
)
|
||||
switchbot_device_adv = generate_advertisement_data(
|
||||
local_name="wohand",
|
||||
service_uuids=["050a021a-0000-1000-8000-00805f9b34fb"],
|
||||
service_data={"050a021a-0000-1000-8000-00805f9b34fb": b"\n\xff"},
|
||||
manufacturer_data={1: b"\x01"},
|
||||
rssi=-100,
|
||||
)
|
||||
scanner.inject_advertisement(switchbot_device, switchbot_device_adv)
|
||||
assert async_scanner_devices_by_address(
|
||||
hass, switchbot_device.address, connectable=True
|
||||
) == async_scanner_devices_by_address(hass, "44:44:33:11:23:45", connectable=False)
|
||||
devices = async_scanner_devices_by_address(
|
||||
hass, switchbot_device.address, connectable=False
|
||||
)
|
||||
assert len(devices) == 1
|
||||
assert devices[0].scanner == scanner
|
||||
assert devices[0].ble_device.name == switchbot_device.name
|
||||
assert devices[0].advertisement.local_name == switchbot_device_adv.local_name
|
||||
unsetup()
|
||||
cancel()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth")
|
||||
async def test_async_scanner_devices_by_address_non_connectable(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test getting scanner devices by address with non-connectable devices."""
|
||||
manager = _get_manager()
|
||||
switchbot_device = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"wohand",
|
||||
{},
|
||||
rssi=-100,
|
||||
)
|
||||
switchbot_device_adv = generate_advertisement_data(
|
||||
local_name="wohand",
|
||||
service_uuids=["050a021a-0000-1000-8000-00805f9b34fb"],
|
||||
service_data={"050a021a-0000-1000-8000-00805f9b34fb": b"\n\xff"},
|
||||
manufacturer_data={1: b"\x01"},
|
||||
rssi=-100,
|
||||
)
|
||||
|
||||
class FakeStaticScanner(FakeScanner):
|
||||
@property
|
||||
def discovered_devices(self) -> list[BLEDevice]:
|
||||
"""Return a list of discovered devices."""
|
||||
return [switchbot_device]
|
||||
|
||||
@property
|
||||
def discovered_devices_and_advertisement_data(
|
||||
self,
|
||||
) -> dict[str, tuple[BLEDevice, AdvertisementData]]:
|
||||
"""Return a list of discovered devices and their advertisement data."""
|
||||
return {switchbot_device.address: (switchbot_device, switchbot_device_adv)}
|
||||
|
||||
connector = (
|
||||
HaBluetoothConnector(MockBleakClient, "mock_bleak_client", lambda: False),
|
||||
)
|
||||
scanner = FakeStaticScanner("esp32", "esp32", connector)
|
||||
cancel = manager.async_register_scanner(scanner)
|
||||
|
||||
assert scanner.discovered_devices_and_advertisement_data == {
|
||||
switchbot_device.address: (switchbot_device, switchbot_device_adv)
|
||||
}
|
||||
|
||||
assert (
|
||||
async_scanner_devices_by_address(
|
||||
hass, switchbot_device.address, connectable=True
|
||||
)
|
||||
== []
|
||||
)
|
||||
devices = async_scanner_devices_by_address(
|
||||
hass, switchbot_device.address, connectable=False
|
||||
)
|
||||
assert len(devices) == 1
|
||||
assert devices[0].scanner == scanner
|
||||
assert devices[0].ble_device.name == switchbot_device.name
|
||||
assert devices[0].advertisement.local_name == switchbot_device_adv.local_name
|
||||
cancel()
|
||||
547
home-assistant/tests/components/bluetooth/test_base_scanner.py
Normal file
547
home-assistant/tests/components/bluetooth/test_base_scanner.py
Normal file
@@ -0,0 +1,547 @@
|
||||
"""Tests for the Bluetooth base scanner models."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
import time
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
from bleak.backends.device import BLEDevice
|
||||
from bleak.backends.scanner import AdvertisementData
|
||||
|
||||
# pylint: disable-next=no-name-in-module
|
||||
from habluetooth.advertisement_tracker import TRACKER_BUFFERING_WOBBLE_SECONDS
|
||||
import pytest
|
||||
|
||||
from homeassistant.components import bluetooth
|
||||
from homeassistant.components.bluetooth import (
|
||||
MONOTONIC_TIME,
|
||||
BaseHaRemoteScanner,
|
||||
HaBluetoothConnector,
|
||||
storage,
|
||||
)
|
||||
from homeassistant.components.bluetooth.const import (
|
||||
CONNECTABLE_FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS,
|
||||
FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS,
|
||||
SCANNER_WATCHDOG_INTERVAL,
|
||||
SCANNER_WATCHDOG_TIMEOUT,
|
||||
UNAVAILABLE_TRACK_SECONDS,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.setup import async_setup_component
|
||||
import homeassistant.util.dt as dt_util
|
||||
from homeassistant.util.json import json_loads
|
||||
|
||||
from . import (
|
||||
MockBleakClient,
|
||||
_get_manager,
|
||||
generate_advertisement_data,
|
||||
generate_ble_device,
|
||||
patch_bluetooth_time,
|
||||
)
|
||||
|
||||
from tests.common import async_fire_time_changed, load_fixture
|
||||
|
||||
|
||||
class FakeScanner(BaseHaRemoteScanner):
|
||||
"""Fake scanner."""
|
||||
|
||||
def inject_advertisement(
|
||||
self,
|
||||
device: BLEDevice,
|
||||
advertisement_data: AdvertisementData,
|
||||
now: float | None = None,
|
||||
) -> 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,
|
||||
{"scanner_specific_data": "test"},
|
||||
now or MONOTONIC_TIME(),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name_2", [None, "w"])
|
||||
@pytest.mark.usefixtures("enable_bluetooth")
|
||||
async def test_remote_scanner(hass: HomeAssistant, name_2: str | None) -> None:
|
||||
"""Test the remote scanner base class merges advertisement_data."""
|
||||
manager = _get_manager()
|
||||
|
||||
switchbot_device = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"wohand",
|
||||
{},
|
||||
rssi=-100,
|
||||
)
|
||||
switchbot_device_adv = generate_advertisement_data(
|
||||
local_name="wohand",
|
||||
service_uuids=["050a021a-0000-1000-8000-00805f9b34fb"],
|
||||
service_data={"050a021a-0000-1000-8000-00805f9b34fb": b"\n\xff"},
|
||||
manufacturer_data={1: b"\x01"},
|
||||
rssi=-100,
|
||||
)
|
||||
switchbot_device_2 = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
name_2,
|
||||
{},
|
||||
rssi=-100,
|
||||
)
|
||||
switchbot_device_adv_2 = generate_advertisement_data(
|
||||
local_name=name_2,
|
||||
service_uuids=["00000001-0000-1000-8000-00805f9b34fb"],
|
||||
service_data={"00000001-0000-1000-8000-00805f9b34fb": b"\n\xff"},
|
||||
manufacturer_data={1: b"\x01", 2: b"\x02"},
|
||||
rssi=-100,
|
||||
)
|
||||
switchbot_device_3 = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"wohandlonger",
|
||||
{},
|
||||
rssi=-100,
|
||||
)
|
||||
switchbot_device_adv_3 = generate_advertisement_data(
|
||||
local_name="wohandlonger",
|
||||
service_uuids=["00000001-0000-1000-8000-00805f9b34fb"],
|
||||
service_data={"00000001-0000-1000-8000-00805f9b34fb": b"\n\xff"},
|
||||
manufacturer_data={1: b"\x01", 2: b"\x02"},
|
||||
rssi=-100,
|
||||
)
|
||||
|
||||
connector = (
|
||||
HaBluetoothConnector(MockBleakClient, "mock_bleak_client", lambda: False),
|
||||
)
|
||||
scanner = FakeScanner("esp32", "esp32", connector, True)
|
||||
unsetup = scanner.async_setup()
|
||||
cancel = manager.async_register_scanner(scanner)
|
||||
|
||||
scanner.inject_advertisement(switchbot_device, switchbot_device_adv)
|
||||
|
||||
data = scanner.discovered_devices_and_advertisement_data
|
||||
discovered_device, discovered_adv_data = data[switchbot_device.address]
|
||||
assert discovered_device.address == switchbot_device.address
|
||||
assert discovered_device.name == switchbot_device.name
|
||||
assert (
|
||||
discovered_adv_data.manufacturer_data == switchbot_device_adv.manufacturer_data
|
||||
)
|
||||
assert discovered_adv_data.service_data == switchbot_device_adv.service_data
|
||||
assert discovered_adv_data.service_uuids == switchbot_device_adv.service_uuids
|
||||
scanner.inject_advertisement(switchbot_device_2, switchbot_device_adv_2)
|
||||
|
||||
data = scanner.discovered_devices_and_advertisement_data
|
||||
discovered_device, discovered_adv_data = data[switchbot_device.address]
|
||||
assert discovered_device.address == switchbot_device.address
|
||||
assert discovered_device.name == switchbot_device.name
|
||||
assert discovered_adv_data.manufacturer_data == {1: b"\x01", 2: b"\x02"}
|
||||
assert discovered_adv_data.service_data == {
|
||||
"050a021a-0000-1000-8000-00805f9b34fb": b"\n\xff",
|
||||
"00000001-0000-1000-8000-00805f9b34fb": b"\n\xff",
|
||||
}
|
||||
assert set(discovered_adv_data.service_uuids) == {
|
||||
"050a021a-0000-1000-8000-00805f9b34fb",
|
||||
"00000001-0000-1000-8000-00805f9b34fb",
|
||||
}
|
||||
|
||||
# The longer name should be used
|
||||
scanner.inject_advertisement(switchbot_device_3, switchbot_device_adv_3)
|
||||
assert discovered_device.name == switchbot_device_3.name
|
||||
|
||||
# Inject the shorter name / None again to make
|
||||
# sure we always keep the longer name
|
||||
scanner.inject_advertisement(switchbot_device_2, switchbot_device_adv_2)
|
||||
assert discovered_device.name == switchbot_device_3.name
|
||||
|
||||
cancel()
|
||||
unsetup()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth")
|
||||
async def test_remote_scanner_expires_connectable(hass: HomeAssistant) -> None:
|
||||
"""Test the remote scanner expires stale connectable data."""
|
||||
manager = _get_manager()
|
||||
|
||||
switchbot_device = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"wohand",
|
||||
{},
|
||||
rssi=-100,
|
||||
)
|
||||
switchbot_device_adv = generate_advertisement_data(
|
||||
local_name="wohand",
|
||||
service_uuids=[],
|
||||
manufacturer_data={1: b"\x01"},
|
||||
rssi=-100,
|
||||
)
|
||||
|
||||
connector = (
|
||||
HaBluetoothConnector(MockBleakClient, "mock_bleak_client", lambda: False),
|
||||
)
|
||||
scanner = FakeScanner("esp32", "esp32", connector, True)
|
||||
unsetup = scanner.async_setup()
|
||||
cancel = manager.async_register_scanner(scanner)
|
||||
|
||||
start_time_monotonic = time.monotonic()
|
||||
scanner.inject_advertisement(switchbot_device, switchbot_device_adv)
|
||||
|
||||
devices = scanner.discovered_devices
|
||||
assert len(scanner.discovered_devices) == 1
|
||||
assert len(scanner.discovered_devices_and_advertisement_data) == 1
|
||||
assert devices[0].name == "wohand"
|
||||
|
||||
expire_monotonic = (
|
||||
start_time_monotonic
|
||||
+ CONNECTABLE_FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS
|
||||
+ 1
|
||||
)
|
||||
expire_utc = dt_util.utcnow() + timedelta(
|
||||
seconds=CONNECTABLE_FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
|
||||
)
|
||||
with patch_bluetooth_time(expire_monotonic):
|
||||
async_fire_time_changed(hass, expire_utc)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
devices = scanner.discovered_devices
|
||||
assert len(scanner.discovered_devices) == 0
|
||||
assert len(scanner.discovered_devices_and_advertisement_data) == 0
|
||||
|
||||
cancel()
|
||||
unsetup()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth")
|
||||
async def test_remote_scanner_expires_non_connectable(hass: HomeAssistant) -> None:
|
||||
"""Test the remote scanner expires stale non connectable data."""
|
||||
manager = _get_manager()
|
||||
|
||||
switchbot_device = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"wohand",
|
||||
{},
|
||||
rssi=-100,
|
||||
)
|
||||
switchbot_device_adv = generate_advertisement_data(
|
||||
local_name="wohand",
|
||||
service_uuids=[],
|
||||
manufacturer_data={1: b"\x01"},
|
||||
rssi=-100,
|
||||
)
|
||||
|
||||
connector = (
|
||||
HaBluetoothConnector(MockBleakClient, "mock_bleak_client", lambda: False),
|
||||
)
|
||||
scanner = FakeScanner("esp32", "esp32", connector, True)
|
||||
unsetup = scanner.async_setup()
|
||||
cancel = manager.async_register_scanner(scanner)
|
||||
|
||||
start_time_monotonic = time.monotonic()
|
||||
scanner.inject_advertisement(switchbot_device, switchbot_device_adv)
|
||||
|
||||
devices = scanner.discovered_devices
|
||||
assert len(scanner.discovered_devices) == 1
|
||||
assert len(scanner.discovered_devices_and_advertisement_data) == 1
|
||||
assert devices[0].name == "wohand"
|
||||
|
||||
assert (
|
||||
FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS
|
||||
> CONNECTABLE_FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS
|
||||
)
|
||||
|
||||
# The connectable timeout is used for all devices
|
||||
# as the manager takes care of availability and the scanner
|
||||
# if only concerned about making a connection
|
||||
expire_monotonic = (
|
||||
start_time_monotonic
|
||||
+ CONNECTABLE_FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS
|
||||
+ 1
|
||||
)
|
||||
expire_utc = dt_util.utcnow() + timedelta(
|
||||
seconds=CONNECTABLE_FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
|
||||
)
|
||||
with patch_bluetooth_time(expire_monotonic):
|
||||
async_fire_time_changed(hass, expire_utc)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(scanner.discovered_devices) == 0
|
||||
assert len(scanner.discovered_devices_and_advertisement_data) == 0
|
||||
|
||||
expire_monotonic = (
|
||||
start_time_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
|
||||
)
|
||||
expire_utc = dt_util.utcnow() + timedelta(
|
||||
seconds=FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
|
||||
)
|
||||
with patch_bluetooth_time(expire_monotonic):
|
||||
async_fire_time_changed(hass, expire_utc)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(scanner.discovered_devices) == 0
|
||||
assert len(scanner.discovered_devices_and_advertisement_data) == 0
|
||||
|
||||
cancel()
|
||||
unsetup()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth")
|
||||
async def test_base_scanner_connecting_behavior(hass: HomeAssistant) -> None:
|
||||
"""Test that the default behavior is to mark the scanner as not scanning when connecting."""
|
||||
manager = _get_manager()
|
||||
|
||||
switchbot_device = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"wohand",
|
||||
{},
|
||||
rssi=-100,
|
||||
)
|
||||
switchbot_device_adv = generate_advertisement_data(
|
||||
local_name="wohand",
|
||||
service_uuids=[],
|
||||
manufacturer_data={1: b"\x01"},
|
||||
rssi=-100,
|
||||
)
|
||||
|
||||
connector = (
|
||||
HaBluetoothConnector(MockBleakClient, "mock_bleak_client", lambda: False),
|
||||
)
|
||||
scanner = FakeScanner("esp32", "esp32", connector, True)
|
||||
unsetup = scanner.async_setup()
|
||||
cancel = manager.async_register_scanner(scanner)
|
||||
|
||||
with scanner.connecting():
|
||||
assert scanner.scanning is False
|
||||
|
||||
# We should still accept new advertisements while connecting
|
||||
# since advertisements are delivered asynchronously and
|
||||
# we don't want to miss any even when we are willing to
|
||||
# accept advertisements from another scanner in the brief window
|
||||
# between when we start connecting and when we stop scanning
|
||||
scanner.inject_advertisement(switchbot_device, switchbot_device_adv)
|
||||
|
||||
devices = scanner.discovered_devices
|
||||
assert len(scanner.discovered_devices) == 1
|
||||
assert len(scanner.discovered_devices_and_advertisement_data) == 1
|
||||
assert devices[0].name == "wohand"
|
||||
|
||||
cancel()
|
||||
unsetup()
|
||||
|
||||
|
||||
async def test_restore_history_remote_adapter(
|
||||
hass: HomeAssistant, hass_storage: dict[str, Any], disable_new_discovery_flows
|
||||
) -> None:
|
||||
"""Test we can restore history for a remote adapter."""
|
||||
|
||||
data = hass_storage[storage.REMOTE_SCANNER_STORAGE_KEY] = json_loads(
|
||||
load_fixture("bluetooth.remote_scanners", bluetooth.DOMAIN)
|
||||
)
|
||||
now = time.time()
|
||||
timestamps = data["data"]["atom-bluetooth-proxy-ceaac4"][
|
||||
"discovered_device_timestamps"
|
||||
]
|
||||
for address in timestamps:
|
||||
if address != "E3:A5:63:3E:5E:23":
|
||||
timestamps[address] = now
|
||||
|
||||
with (
|
||||
patch(
|
||||
"bluetooth_adapters.systems.linux.LinuxAdapters.history",
|
||||
{},
|
||||
),
|
||||
patch(
|
||||
"bluetooth_adapters.systems.linux.LinuxAdapters.refresh",
|
||||
),
|
||||
):
|
||||
assert await async_setup_component(hass, bluetooth.DOMAIN, {})
|
||||
await hass.async_block_till_done()
|
||||
|
||||
connector = (
|
||||
HaBluetoothConnector(MockBleakClient, "mock_bleak_client", lambda: False),
|
||||
)
|
||||
scanner = BaseHaRemoteScanner(
|
||||
"atom-bluetooth-proxy-ceaac4",
|
||||
"atom-bluetooth-proxy-ceaac4",
|
||||
connector,
|
||||
True,
|
||||
)
|
||||
unsetup = scanner.async_setup()
|
||||
cancel = _get_manager().async_register_scanner(scanner)
|
||||
|
||||
assert "EB:0B:36:35:6F:A4" in scanner.discovered_devices_and_advertisement_data
|
||||
assert "E3:A5:63:3E:5E:23" not in scanner.discovered_devices_and_advertisement_data
|
||||
cancel()
|
||||
unsetup()
|
||||
|
||||
scanner = BaseHaRemoteScanner(
|
||||
"atom-bluetooth-proxy-ceaac4",
|
||||
"atom-bluetooth-proxy-ceaac4",
|
||||
connector,
|
||||
True,
|
||||
)
|
||||
unsetup = scanner.async_setup()
|
||||
cancel = _get_manager().async_register_scanner(scanner)
|
||||
assert "EB:0B:36:35:6F:A4" in scanner.discovered_devices_and_advertisement_data
|
||||
assert "E3:A5:63:3E:5E:23" not in scanner.discovered_devices_and_advertisement_data
|
||||
|
||||
cancel()
|
||||
unsetup()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth")
|
||||
async def test_device_with_ten_minute_advertising_interval(hass: HomeAssistant) -> None:
|
||||
"""Test a device with a 10 minute advertising interval."""
|
||||
manager = _get_manager()
|
||||
|
||||
bparasite_device = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"bparasite",
|
||||
{},
|
||||
rssi=-100,
|
||||
)
|
||||
bparasite_device_adv = generate_advertisement_data(
|
||||
local_name="bparasite",
|
||||
service_uuids=[],
|
||||
manufacturer_data={1: b"\x01"},
|
||||
rssi=-100,
|
||||
)
|
||||
|
||||
connector = (
|
||||
HaBluetoothConnector(MockBleakClient, "mock_bleak_client", lambda: False),
|
||||
)
|
||||
scanner = FakeScanner("esp32", "esp32", connector, True)
|
||||
unsetup = scanner.async_setup()
|
||||
cancel = manager.async_register_scanner(scanner)
|
||||
|
||||
monotonic_now = time.monotonic()
|
||||
new_time = monotonic_now
|
||||
bparasite_device_went_unavailable = False
|
||||
|
||||
@callback
|
||||
def _bparasite_device_unavailable_callback(_address: str) -> None:
|
||||
"""Barasite device unavailable callback."""
|
||||
nonlocal bparasite_device_went_unavailable
|
||||
bparasite_device_went_unavailable = True
|
||||
|
||||
advertising_interval = 60 * 10
|
||||
|
||||
bparasite_device_unavailable_cancel = bluetooth.async_track_unavailable(
|
||||
hass,
|
||||
_bparasite_device_unavailable_callback,
|
||||
bparasite_device.address,
|
||||
connectable=False,
|
||||
)
|
||||
|
||||
with patch_bluetooth_time(new_time):
|
||||
scanner.inject_advertisement(bparasite_device, bparasite_device_adv, new_time)
|
||||
|
||||
original_device = scanner.discovered_devices_and_advertisement_data[
|
||||
bparasite_device.address
|
||||
][0]
|
||||
assert original_device is not bparasite_device
|
||||
|
||||
for _ in range(1, 20):
|
||||
new_time += advertising_interval
|
||||
with patch_bluetooth_time(new_time):
|
||||
scanner.inject_advertisement(
|
||||
bparasite_device, bparasite_device_adv, new_time
|
||||
)
|
||||
|
||||
# Make sure the BLEDevice object gets updated
|
||||
# and not replaced
|
||||
assert (
|
||||
scanner.discovered_devices_and_advertisement_data[bparasite_device.address][0]
|
||||
is original_device
|
||||
)
|
||||
|
||||
future_time = new_time
|
||||
assert (
|
||||
bluetooth.async_address_present(hass, bparasite_device.address, False) is True
|
||||
)
|
||||
assert bparasite_device_went_unavailable is False
|
||||
with patch_bluetooth_time(new_time):
|
||||
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=future_time))
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert bparasite_device_went_unavailable is False
|
||||
|
||||
missed_advertisement_future_time = (
|
||||
future_time + advertising_interval + TRACKER_BUFFERING_WOBBLE_SECONDS + 1
|
||||
)
|
||||
|
||||
with patch_bluetooth_time(missed_advertisement_future_time):
|
||||
# Fire once for the scanner to expire the device
|
||||
async_fire_time_changed(
|
||||
hass, dt_util.utcnow() + timedelta(seconds=UNAVAILABLE_TRACK_SECONDS)
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
# Fire again for the manager to expire the device
|
||||
async_fire_time_changed(
|
||||
hass, dt_util.utcnow() + timedelta(seconds=missed_advertisement_future_time)
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert (
|
||||
bluetooth.async_address_present(hass, bparasite_device.address, False) is False
|
||||
)
|
||||
assert bparasite_device_went_unavailable is True
|
||||
bparasite_device_unavailable_cancel()
|
||||
|
||||
cancel()
|
||||
unsetup()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth")
|
||||
async def test_scanner_stops_responding(hass: HomeAssistant) -> None:
|
||||
"""Test we mark a scanner are not scanning when it stops responding."""
|
||||
manager = _get_manager()
|
||||
|
||||
connector = (
|
||||
HaBluetoothConnector(MockBleakClient, "mock_bleak_client", lambda: False),
|
||||
)
|
||||
scanner = FakeScanner("esp32", "esp32", connector, True)
|
||||
unsetup = scanner.async_setup()
|
||||
cancel = manager.async_register_scanner(scanner)
|
||||
|
||||
start_time_monotonic = time.monotonic()
|
||||
|
||||
assert scanner.scanning is True
|
||||
failure_reached_time = (
|
||||
start_time_monotonic
|
||||
+ SCANNER_WATCHDOG_TIMEOUT
|
||||
+ SCANNER_WATCHDOG_INTERVAL.total_seconds()
|
||||
)
|
||||
# We hit the timer with no detections, so we reset the adapter and restart the scanner
|
||||
with patch_bluetooth_time(failure_reached_time):
|
||||
async_fire_time_changed(hass, dt_util.utcnow() + SCANNER_WATCHDOG_INTERVAL)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert scanner.scanning is False
|
||||
|
||||
bparasite_device = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"bparasite",
|
||||
{},
|
||||
rssi=-100,
|
||||
)
|
||||
bparasite_device_adv = generate_advertisement_data(
|
||||
local_name="bparasite",
|
||||
service_uuids=[],
|
||||
manufacturer_data={1: b"\x01"},
|
||||
rssi=-100,
|
||||
)
|
||||
|
||||
failure_reached_time += 1
|
||||
|
||||
with patch_bluetooth_time(failure_reached_time):
|
||||
scanner.inject_advertisement(
|
||||
bparasite_device, bparasite_device_adv, failure_reached_time
|
||||
)
|
||||
|
||||
# As soon as we get a detection, we know the scanner is working again
|
||||
assert scanner.scanning is True
|
||||
|
||||
cancel()
|
||||
unsetup()
|
||||
469
home-assistant/tests/components/bluetooth/test_config_flow.py
Normal file
469
home-assistant/tests/components/bluetooth/test_config_flow.py
Normal file
@@ -0,0 +1,469 @@
|
||||
"""Test the bluetooth config flow."""
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from bluetooth_adapters import DEFAULT_ADDRESS, AdapterDetails
|
||||
import pytest
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.components.bluetooth.const import (
|
||||
CONF_ADAPTER,
|
||||
CONF_DETAILS,
|
||||
CONF_PASSIVE,
|
||||
DOMAIN,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
from tests.typing import WebSocketGenerator
|
||||
|
||||
|
||||
@pytest.mark.usefixtures(
|
||||
"macos_adapter", "mock_bleak_scanner_start", "mock_bluetooth_adapters"
|
||||
)
|
||||
async def test_options_flow_disabled_not_setup(
|
||||
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
|
||||
) -> None:
|
||||
"""Test options are disabled if the integration has not been setup."""
|
||||
await async_setup_component(hass, "config", {})
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN, data={}, options={}, unique_id=DEFAULT_ADDRESS
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
ws_client = await hass_ws_client(hass)
|
||||
|
||||
await ws_client.send_json(
|
||||
{
|
||||
"id": 5,
|
||||
"type": "config_entries/get",
|
||||
"domain": "bluetooth",
|
||||
}
|
||||
)
|
||||
response = await ws_client.receive_json()
|
||||
assert response["result"][0]["supports_options"] is False
|
||||
await hass.config_entries.async_unload(entry.entry_id)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("macos_adapter")
|
||||
async def test_async_step_user_macos(hass: HomeAssistant) -> None:
|
||||
"""Test setting up manually with one adapter on MacOS."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": config_entries.SOURCE_USER},
|
||||
data={},
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "single_adapter"
|
||||
with (
|
||||
patch("homeassistant.components.bluetooth.async_setup", return_value=True),
|
||||
patch(
|
||||
"homeassistant.components.bluetooth.async_setup_entry", return_value=True
|
||||
) as mock_setup_entry,
|
||||
):
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={}
|
||||
)
|
||||
assert result2["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result2["title"] == "Apple Unknown MacOS Model (Core Bluetooth)"
|
||||
assert result2["data"] == {}
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("one_adapter")
|
||||
async def test_async_step_user_linux_one_adapter(hass: HomeAssistant) -> None:
|
||||
"""Test setting up manually with one adapter on Linux."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": config_entries.SOURCE_USER},
|
||||
data={},
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "single_adapter"
|
||||
assert result["description_placeholders"] == {
|
||||
"name": "hci0 (00:00:00:00:00:01)",
|
||||
"model": "Bluetooth Adapter 5.0 (cc01:aa01)",
|
||||
"manufacturer": "ACME",
|
||||
}
|
||||
with (
|
||||
patch("homeassistant.components.bluetooth.async_setup", return_value=True),
|
||||
patch(
|
||||
"homeassistant.components.bluetooth.async_setup_entry", return_value=True
|
||||
) as mock_setup_entry,
|
||||
):
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={}
|
||||
)
|
||||
assert result2["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result2["title"] == "ACME Bluetooth Adapter 5.0 (00:00:00:00:00:01)"
|
||||
assert result2["data"] == {}
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
|
||||
|
||||
async def test_async_step_user_linux_crashed_adapter(
|
||||
hass: HomeAssistant, crashed_adapter: None
|
||||
) -> None:
|
||||
"""Test setting up manually with one crashed adapter on Linux."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": config_entries.SOURCE_USER},
|
||||
data={},
|
||||
)
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "no_adapters"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("two_adapters")
|
||||
async def test_async_step_user_linux_two_adapters(hass: HomeAssistant) -> None:
|
||||
"""Test setting up manually with two adapters on Linux."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": config_entries.SOURCE_USER},
|
||||
data={},
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "multiple_adapters"
|
||||
assert result["data_schema"].schema["adapter"].container == {
|
||||
"hci0": "hci0 (00:00:00:00:00:01) ACME Bluetooth Adapter 5.0 (cc01:aa01)",
|
||||
"hci1": "hci1 (00:00:00:00:00:02) ACME Bluetooth Adapter 5.0 (cc01:aa01)",
|
||||
}
|
||||
with (
|
||||
patch("homeassistant.components.bluetooth.async_setup", return_value=True),
|
||||
patch(
|
||||
"homeassistant.components.bluetooth.async_setup_entry", return_value=True
|
||||
) as mock_setup_entry,
|
||||
):
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={CONF_ADAPTER: "hci1"}
|
||||
)
|
||||
assert result2["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result2["title"] == "ACME Bluetooth Adapter 5.0 (00:00:00:00:00:02)"
|
||||
assert result2["data"] == {}
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("macos_adapter")
|
||||
async def test_async_step_user_only_allows_one(hass: HomeAssistant) -> None:
|
||||
"""Test setting up manually with an existing entry."""
|
||||
entry = MockConfigEntry(domain=DOMAIN, unique_id=DEFAULT_ADDRESS)
|
||||
entry.add_to_hass(hass)
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": config_entries.SOURCE_USER},
|
||||
data={},
|
||||
)
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "no_adapters"
|
||||
|
||||
|
||||
async def test_async_step_integration_discovery(hass: HomeAssistant) -> None:
|
||||
"""Test setting up from integration discovery."""
|
||||
|
||||
details = AdapterDetails(
|
||||
address="00:00:00:00:00:01",
|
||||
sw_version="1.23.5",
|
||||
hw_version="1.2.3",
|
||||
manufacturer="ACME",
|
||||
)
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
|
||||
data={CONF_ADAPTER: "hci0", CONF_DETAILS: details},
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["description_placeholders"] == {
|
||||
"name": "hci0 (00:00:00:00:00:01)",
|
||||
"model": "Unknown",
|
||||
"manufacturer": "ACME",
|
||||
}
|
||||
assert result["step_id"] == "single_adapter"
|
||||
with (
|
||||
patch("homeassistant.components.bluetooth.async_setup", return_value=True),
|
||||
patch(
|
||||
"homeassistant.components.bluetooth.async_setup_entry", return_value=True
|
||||
) as mock_setup_entry,
|
||||
):
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={}
|
||||
)
|
||||
assert result2["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result2["title"] == "ACME Unknown (00:00:00:00:00:01)"
|
||||
assert result2["data"] == {}
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("one_adapter")
|
||||
async def test_async_step_integration_discovery_during_onboarding_one_adapter(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test setting up from integration discovery during onboarding."""
|
||||
details = AdapterDetails(
|
||||
address="00:00:00:00:00:01",
|
||||
sw_version="1.23.5",
|
||||
hw_version="1.2.3",
|
||||
manufacturer="ACME",
|
||||
)
|
||||
|
||||
with (
|
||||
patch("homeassistant.components.bluetooth.async_setup", return_value=True),
|
||||
patch(
|
||||
"homeassistant.components.bluetooth.async_setup_entry", return_value=True
|
||||
) as mock_setup_entry,
|
||||
patch(
|
||||
"homeassistant.components.onboarding.async_is_onboarded",
|
||||
return_value=False,
|
||||
) as mock_onboarding,
|
||||
):
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
|
||||
data={CONF_ADAPTER: "hci0", CONF_DETAILS: details},
|
||||
)
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["title"] == "ACME Unknown (00:00:00:00:00:01)"
|
||||
assert result["data"] == {}
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
assert len(mock_onboarding.mock_calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("two_adapters")
|
||||
async def test_async_step_integration_discovery_during_onboarding_two_adapters(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test setting up from integration discovery during onboarding."""
|
||||
details1 = AdapterDetails(
|
||||
address="00:00:00:00:00:01",
|
||||
sw_version="1.23.5",
|
||||
hw_version="1.2.3",
|
||||
manufacturer="ACME",
|
||||
)
|
||||
details2 = AdapterDetails(
|
||||
address="00:00:00:00:00:02",
|
||||
sw_version="1.23.5",
|
||||
hw_version="1.2.3",
|
||||
manufacturer="ACME",
|
||||
)
|
||||
|
||||
with (
|
||||
patch("homeassistant.components.bluetooth.async_setup", return_value=True),
|
||||
patch(
|
||||
"homeassistant.components.bluetooth.async_setup_entry", return_value=True
|
||||
) as mock_setup_entry,
|
||||
patch(
|
||||
"homeassistant.components.onboarding.async_is_onboarded",
|
||||
return_value=False,
|
||||
) as mock_onboarding,
|
||||
):
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
|
||||
data={CONF_ADAPTER: "hci0", CONF_DETAILS: details1},
|
||||
)
|
||||
result2 = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
|
||||
data={CONF_ADAPTER: "hci1", CONF_DETAILS: details2},
|
||||
)
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["title"] == "ACME Unknown (00:00:00:00:00:01)"
|
||||
assert result["data"] == {}
|
||||
|
||||
assert result2["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result2["title"] == "ACME Unknown (00:00:00:00:00:02)"
|
||||
assert result2["data"] == {}
|
||||
|
||||
assert len(mock_setup_entry.mock_calls) == 2
|
||||
assert len(mock_onboarding.mock_calls) == 2
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("macos_adapter")
|
||||
async def test_async_step_integration_discovery_during_onboarding(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test setting up from integration discovery during onboarding."""
|
||||
details = AdapterDetails(
|
||||
address=DEFAULT_ADDRESS,
|
||||
sw_version="1.23.5",
|
||||
hw_version="1.2.3",
|
||||
manufacturer="ACME",
|
||||
)
|
||||
|
||||
with (
|
||||
patch("homeassistant.components.bluetooth.async_setup", return_value=True),
|
||||
patch(
|
||||
"homeassistant.components.bluetooth.async_setup_entry", return_value=True
|
||||
) as mock_setup_entry,
|
||||
patch(
|
||||
"homeassistant.components.onboarding.async_is_onboarded",
|
||||
return_value=False,
|
||||
) as mock_onboarding,
|
||||
):
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
|
||||
data={CONF_ADAPTER: "Core Bluetooth", CONF_DETAILS: details},
|
||||
)
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["title"] == "ACME Unknown (Core Bluetooth)"
|
||||
assert result["data"] == {}
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
assert len(mock_onboarding.mock_calls) == 1
|
||||
|
||||
|
||||
async def test_async_step_integration_discovery_already_exists(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test setting up from integration discovery when an entry already exists."""
|
||||
details = AdapterDetails(
|
||||
address="00:00:00:00:00:01",
|
||||
sw_version="1.23.5",
|
||||
hw_version="1.2.3",
|
||||
manufacturer="ACME",
|
||||
)
|
||||
|
||||
entry = MockConfigEntry(domain=DOMAIN, unique_id="00:00:00:00:00:01")
|
||||
entry.add_to_hass(hass)
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
|
||||
data={CONF_ADAPTER: "hci0", CONF_DETAILS: details},
|
||||
)
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "already_configured"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures(
|
||||
"one_adapter", "mock_bleak_scanner_start", "mock_bluetooth_adapters"
|
||||
)
|
||||
async def test_options_flow_linux(hass: HomeAssistant) -> None:
|
||||
"""Test options on Linux."""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={},
|
||||
options={},
|
||||
unique_id="00:00:00:00:00:01",
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "init"
|
||||
assert result["errors"] is None
|
||||
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
CONF_PASSIVE: True,
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"][CONF_PASSIVE] is True
|
||||
|
||||
# Verify we can change it to False
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "init"
|
||||
assert result["errors"] is None
|
||||
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
CONF_PASSIVE: False,
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"][CONF_PASSIVE] is False
|
||||
await hass.config_entries.async_unload(entry.entry_id)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures(
|
||||
"macos_adapter", "mock_bleak_scanner_start", "mock_bluetooth_adapters"
|
||||
)
|
||||
async def test_options_flow_disabled_macos(
|
||||
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
|
||||
) -> None:
|
||||
"""Test options are disabled on MacOS."""
|
||||
await async_setup_component(hass, "config", {})
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN, data={}, options={}, unique_id=DEFAULT_ADDRESS
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
ws_client = await hass_ws_client(hass)
|
||||
|
||||
await ws_client.send_json(
|
||||
{
|
||||
"id": 5,
|
||||
"type": "config_entries/get",
|
||||
"domain": "bluetooth",
|
||||
}
|
||||
)
|
||||
response = await ws_client.receive_json()
|
||||
assert response["result"][0]["supports_options"] is False
|
||||
await hass.config_entries.async_unload(entry.entry_id)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures(
|
||||
"one_adapter", "mock_bleak_scanner_start", "mock_bluetooth_adapters"
|
||||
)
|
||||
async def test_options_flow_enabled_linux(
|
||||
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
|
||||
) -> None:
|
||||
"""Test options are enabled on Linux."""
|
||||
await async_setup_component(hass, "config", {})
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={},
|
||||
options={},
|
||||
unique_id="00:00:00:00:00:01",
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
ws_client = await hass_ws_client(hass)
|
||||
|
||||
await ws_client.send_json(
|
||||
{
|
||||
"id": 5,
|
||||
"type": "config_entries/get",
|
||||
"domain": "bluetooth",
|
||||
}
|
||||
)
|
||||
response = await ws_client.receive_json()
|
||||
assert response["result"][0]["supports_options"] is True
|
||||
await hass.config_entries.async_unload(entry.entry_id)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("one_adapter")
|
||||
async def test_async_step_user_linux_adapter_is_ignored(hass: HomeAssistant) -> None:
|
||||
"""Test we give a hint that the adapter is ignored."""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
unique_id="00:00:00:00:00:01",
|
||||
source=config_entries.SOURCE_IGNORE,
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": config_entries.SOURCE_USER},
|
||||
data={},
|
||||
)
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "no_adapters"
|
||||
assert result["description_placeholders"] == {"ignored_adapters": "1"}
|
||||
637
home-assistant/tests/components/bluetooth/test_diagnostics.py
Normal file
637
home-assistant/tests/components/bluetooth/test_diagnostics.py
Normal file
@@ -0,0 +1,637 @@
|
||||
"""Test bluetooth diagnostics."""
|
||||
|
||||
from unittest.mock import ANY, MagicMock, patch
|
||||
|
||||
from bleak.backends.scanner import AdvertisementData, BLEDevice
|
||||
from bluetooth_adapters import DEFAULT_ADDRESS
|
||||
import pytest
|
||||
|
||||
from homeassistant.components import bluetooth
|
||||
from homeassistant.components.bluetooth import (
|
||||
MONOTONIC_TIME,
|
||||
BaseHaRemoteScanner,
|
||||
HaBluetoothConnector,
|
||||
HaScanner,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from . import (
|
||||
FakeScannerMixin,
|
||||
MockBleakClient,
|
||||
_get_manager,
|
||||
generate_advertisement_data,
|
||||
generate_ble_device,
|
||||
inject_advertisement,
|
||||
)
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
from tests.components.diagnostics import get_diagnostics_for_config_entry
|
||||
from tests.typing import ClientSessionGenerator
|
||||
|
||||
|
||||
class FakeHaScanner(FakeScannerMixin, HaScanner):
|
||||
"""Fake HaScanner."""
|
||||
|
||||
@property
|
||||
def discovered_devices_and_advertisement_data(self):
|
||||
"""Return the discovered devices and advertisement data."""
|
||||
return {
|
||||
"44:44:33:11:23:45": (
|
||||
generate_ble_device(name="x", rssi=-127, address="44:44:33:11:23:45"),
|
||||
generate_advertisement_data(local_name="x"),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@patch("homeassistant.components.bluetooth.HaScanner", FakeHaScanner)
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "two_adapters")
|
||||
async def test_diagnostics(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
mock_bleak_scanner_start: MagicMock,
|
||||
) -> None:
|
||||
"""Test we can setup and unsetup bluetooth with multiple adapters."""
|
||||
# Normally we do not want to patch our classes, but since bleak will import
|
||||
# a different scanner based on the operating system, we need to patch here
|
||||
# because we cannot import the scanner class directly without it throwing an
|
||||
# error if the test is not running on linux since we won't have the correct
|
||||
# deps installed when testing on MacOS.
|
||||
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.bluetooth.diagnostics.platform.system",
|
||||
return_value="Linux",
|
||||
),
|
||||
patch(
|
||||
"homeassistant.components.bluetooth.diagnostics.get_dbus_managed_objects",
|
||||
return_value={
|
||||
"org.bluez": {
|
||||
"/org/bluez/hci0": {
|
||||
"org.bluez.Adapter1": {
|
||||
"Name": "BlueZ 5.63",
|
||||
"Alias": "BlueZ 5.63",
|
||||
"Modalias": "usb:v1D6Bp0246d0540",
|
||||
"Discovering": False,
|
||||
},
|
||||
"org.bluez.AdvertisementMonitorManager1": {
|
||||
"SupportedMonitorTypes": ["or_patterns"],
|
||||
"SupportedFeatures": [],
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
),
|
||||
):
|
||||
entry2 = MockConfigEntry(
|
||||
domain=bluetooth.DOMAIN, data={}, unique_id="00:00:00:00:00:02"
|
||||
)
|
||||
entry2.add_to_hass(hass)
|
||||
|
||||
assert await hass.config_entries.async_setup(entry2.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
diag = await get_diagnostics_for_config_entry(hass, hass_client, entry2)
|
||||
expected = {
|
||||
"adapters": {
|
||||
"hci0": {
|
||||
"address": "00:00:00:00:00:01",
|
||||
"connection_slots": 1,
|
||||
"hw_version": "usb:v1D6Bp0246d053F",
|
||||
"manufacturer": "ACME",
|
||||
"passive_scan": False,
|
||||
"product": "Bluetooth Adapter 5.0",
|
||||
"product_id": "aa01",
|
||||
"sw_version": ANY,
|
||||
"vendor_id": "cc01",
|
||||
},
|
||||
"hci1": {
|
||||
"address": "00:00:00:00:00:02",
|
||||
"connection_slots": 2,
|
||||
"hw_version": "usb:v1D6Bp0246d053F",
|
||||
"manufacturer": "ACME",
|
||||
"passive_scan": True,
|
||||
"product": "Bluetooth Adapter 5.0",
|
||||
"product_id": "aa01",
|
||||
"sw_version": ANY,
|
||||
"vendor_id": "cc01",
|
||||
},
|
||||
},
|
||||
"dbus": {
|
||||
"org.bluez": {
|
||||
"/org/bluez/hci0": {
|
||||
"org.bluez.Adapter1": {
|
||||
"Alias": "BlueZ 5.63",
|
||||
"Discovering": False,
|
||||
"Modalias": "usb:v1D6Bp0246d0540",
|
||||
"Name": "BlueZ 5.63",
|
||||
},
|
||||
"org.bluez.AdvertisementMonitorManager1": {
|
||||
"SupportedFeatures": [],
|
||||
"SupportedMonitorTypes": ["or_patterns"],
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
"manager": {
|
||||
"adapters": {
|
||||
"hci0": {
|
||||
"address": "00:00:00:00:00:01",
|
||||
"connection_slots": 1,
|
||||
"hw_version": "usb:v1D6Bp0246d053F",
|
||||
"manufacturer": "ACME",
|
||||
"passive_scan": False,
|
||||
"product": "Bluetooth Adapter 5.0",
|
||||
"product_id": "aa01",
|
||||
"sw_version": "homeassistant",
|
||||
"vendor_id": "cc01",
|
||||
},
|
||||
"hci1": {
|
||||
"address": "00:00:00:00:00:02",
|
||||
"connection_slots": 2,
|
||||
"hw_version": "usb:v1D6Bp0246d053F",
|
||||
"manufacturer": "ACME",
|
||||
"passive_scan": True,
|
||||
"product": "Bluetooth Adapter 5.0",
|
||||
"product_id": "aa01",
|
||||
"sw_version": "homeassistant",
|
||||
"vendor_id": "cc01",
|
||||
},
|
||||
},
|
||||
"advertisement_tracker": {
|
||||
"fallback_intervals": {},
|
||||
"intervals": {},
|
||||
"sources": {},
|
||||
"timings": {},
|
||||
},
|
||||
"all_history": [],
|
||||
"connectable_history": [],
|
||||
"scanners": [
|
||||
{
|
||||
"adapter": "hci0",
|
||||
"discovered_devices_and_advertisement_data": [],
|
||||
"last_detection": ANY,
|
||||
"monotonic_time": ANY,
|
||||
"name": "hci0 (00:00:00:00:00:01)",
|
||||
"scanning": True,
|
||||
"source": "00:00:00:00:00:01",
|
||||
"start_time": ANY,
|
||||
"type": "HaScanner",
|
||||
"current_mode": {
|
||||
"__type": "<enum 'BluetoothScanningMode'>",
|
||||
"repr": "<BluetoothScanningMode.ACTIVE: 'active'>",
|
||||
},
|
||||
"requested_mode": {
|
||||
"__type": "<enum 'BluetoothScanningMode'>",
|
||||
"repr": "<BluetoothScanningMode.ACTIVE: 'active'>",
|
||||
},
|
||||
},
|
||||
{
|
||||
"adapter": "hci1",
|
||||
"discovered_devices_and_advertisement_data": [
|
||||
{
|
||||
"address": "44:44:33:11:23:45",
|
||||
"advertisement_data": [
|
||||
"x",
|
||||
{},
|
||||
{},
|
||||
[],
|
||||
-127,
|
||||
-127,
|
||||
[[]],
|
||||
],
|
||||
"details": None,
|
||||
"name": "x",
|
||||
"rssi": -127,
|
||||
}
|
||||
],
|
||||
"last_detection": ANY,
|
||||
"monotonic_time": ANY,
|
||||
"name": "hci1 (00:00:00:00:00:02)",
|
||||
"scanning": True,
|
||||
"source": "00:00:00:00:00:02",
|
||||
"start_time": ANY,
|
||||
"type": "FakeHaScanner",
|
||||
"current_mode": {
|
||||
"__type": "<enum 'BluetoothScanningMode'>",
|
||||
"repr": "<BluetoothScanningMode.ACTIVE: 'active'>",
|
||||
},
|
||||
"requested_mode": {
|
||||
"__type": "<enum 'BluetoothScanningMode'>",
|
||||
"repr": "<BluetoothScanningMode.ACTIVE: 'active'>",
|
||||
},
|
||||
},
|
||||
],
|
||||
"slot_manager": {
|
||||
"adapter_slots": {"hci0": 5, "hci1": 2},
|
||||
"allocations_by_adapter": {"hci0": [], "hci1": []},
|
||||
"manager": False,
|
||||
},
|
||||
},
|
||||
}
|
||||
diag_scanners = diag["manager"].pop("scanners")
|
||||
expected_scanners = expected["manager"].pop("scanners")
|
||||
assert diag == expected
|
||||
assert sorted(diag_scanners, key=lambda x: x["name"]) == sorted(
|
||||
expected_scanners, key=lambda x: x["name"]
|
||||
)
|
||||
|
||||
|
||||
@patch("homeassistant.components.bluetooth.HaScanner", FakeHaScanner)
|
||||
@pytest.mark.usefixtures(
|
||||
"macos_adapter", "mock_bleak_scanner_start", "mock_bluetooth_adapters"
|
||||
)
|
||||
async def test_diagnostics_macos(
|
||||
hass: HomeAssistant, hass_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test diagnostics for macos."""
|
||||
# Normally we do not want to patch our classes, but since bleak will import
|
||||
# a different scanner based on the operating system, we need to patch here
|
||||
# because we cannot import the scanner class directly without it throwing an
|
||||
# error if the test is not running on linux since we won't have the correct
|
||||
# deps installed when testing on MacOS.
|
||||
switchbot_device = generate_ble_device("44:44:33:11:23:45", "wohand")
|
||||
switchbot_adv = generate_advertisement_data(
|
||||
local_name="wohand", service_uuids=[], manufacturer_data={1: b"\x01"}
|
||||
)
|
||||
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.bluetooth.diagnostics.platform.system",
|
||||
return_value="Darwin",
|
||||
),
|
||||
patch(
|
||||
"homeassistant.components.bluetooth.diagnostics.get_dbus_managed_objects",
|
||||
return_value={},
|
||||
),
|
||||
):
|
||||
entry1 = MockConfigEntry(
|
||||
domain=bluetooth.DOMAIN,
|
||||
data={},
|
||||
title="Core Bluetooth",
|
||||
unique_id=DEFAULT_ADDRESS,
|
||||
)
|
||||
entry1.add_to_hass(hass)
|
||||
|
||||
assert await hass.config_entries.async_setup(entry1.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
inject_advertisement(hass, switchbot_device, switchbot_adv)
|
||||
|
||||
diag = await get_diagnostics_for_config_entry(hass, hass_client, entry1)
|
||||
assert diag == {
|
||||
"adapters": {
|
||||
"Core Bluetooth": {
|
||||
"address": "00:00:00:00:00:00",
|
||||
"manufacturer": "Apple",
|
||||
"passive_scan": False,
|
||||
"product": "Unknown MacOS Model",
|
||||
"product_id": "Unknown",
|
||||
"sw_version": ANY,
|
||||
"vendor_id": "Unknown",
|
||||
}
|
||||
},
|
||||
"manager": {
|
||||
"adapters": {
|
||||
"Core Bluetooth": {
|
||||
"address": "00:00:00:00:00:00",
|
||||
"manufacturer": "Apple",
|
||||
"passive_scan": False,
|
||||
"product": "Unknown MacOS Model",
|
||||
"product_id": "Unknown",
|
||||
"sw_version": ANY,
|
||||
"vendor_id": "Unknown",
|
||||
}
|
||||
},
|
||||
"advertisement_tracker": {
|
||||
"fallback_intervals": {},
|
||||
"intervals": {},
|
||||
"sources": {"44:44:33:11:23:45": "local"},
|
||||
"timings": {"44:44:33:11:23:45": [ANY]},
|
||||
},
|
||||
"all_history": [
|
||||
{
|
||||
"address": "44:44:33:11:23:45",
|
||||
"advertisement": [
|
||||
"wohand",
|
||||
{"1": {"__type": "<class 'bytes'>", "repr": "b'\\x01'"}},
|
||||
{},
|
||||
[],
|
||||
-127,
|
||||
-127,
|
||||
[[]],
|
||||
],
|
||||
"connectable": True,
|
||||
"device": {
|
||||
"__type": "<class 'bleak.backends.device.BLEDevice'>",
|
||||
"repr": "BLEDevice(44:44:33:11:23:45, wohand)",
|
||||
},
|
||||
"manufacturer_data": {
|
||||
"1": {"__type": "<class 'bytes'>", "repr": "b'\\x01'"}
|
||||
},
|
||||
"name": "wohand",
|
||||
"rssi": -127,
|
||||
"service_data": {},
|
||||
"service_uuids": [],
|
||||
"source": "local",
|
||||
"time": ANY,
|
||||
"tx_power": -127,
|
||||
}
|
||||
],
|
||||
"connectable_history": [
|
||||
{
|
||||
"address": "44:44:33:11:23:45",
|
||||
"advertisement": [
|
||||
"wohand",
|
||||
{"1": {"__type": "<class 'bytes'>", "repr": "b'\\x01'"}},
|
||||
{},
|
||||
[],
|
||||
-127,
|
||||
-127,
|
||||
[[]],
|
||||
],
|
||||
"connectable": True,
|
||||
"device": {
|
||||
"__type": "<class 'bleak.backends.device.BLEDevice'>",
|
||||
"repr": "BLEDevice(44:44:33:11:23:45, wohand)",
|
||||
},
|
||||
"manufacturer_data": {
|
||||
"1": {"__type": "<class 'bytes'>", "repr": "b'\\x01'"}
|
||||
},
|
||||
"name": "wohand",
|
||||
"rssi": -127,
|
||||
"service_data": {},
|
||||
"service_uuids": [],
|
||||
"source": "local",
|
||||
"time": ANY,
|
||||
"tx_power": -127,
|
||||
}
|
||||
],
|
||||
"scanners": [
|
||||
{
|
||||
"adapter": "Core Bluetooth",
|
||||
"discovered_devices_and_advertisement_data": [
|
||||
{
|
||||
"address": "44:44:33:11:23:45",
|
||||
"advertisement_data": [
|
||||
"x",
|
||||
{},
|
||||
{},
|
||||
[],
|
||||
-127,
|
||||
-127,
|
||||
[[]],
|
||||
],
|
||||
"details": None,
|
||||
"name": "x",
|
||||
"rssi": -127,
|
||||
}
|
||||
],
|
||||
"last_detection": ANY,
|
||||
"monotonic_time": ANY,
|
||||
"name": "Core Bluetooth",
|
||||
"scanning": True,
|
||||
"source": "Core Bluetooth",
|
||||
"start_time": ANY,
|
||||
"type": "FakeHaScanner",
|
||||
"current_mode": {
|
||||
"__type": "<enum 'BluetoothScanningMode'>",
|
||||
"repr": "<BluetoothScanningMode.ACTIVE: 'active'>",
|
||||
},
|
||||
"requested_mode": {
|
||||
"__type": "<enum 'BluetoothScanningMode'>",
|
||||
"repr": "<BluetoothScanningMode.ACTIVE: 'active'>",
|
||||
},
|
||||
}
|
||||
],
|
||||
"slot_manager": {
|
||||
"adapter_slots": {"Core Bluetooth": 5},
|
||||
"allocations_by_adapter": {"Core Bluetooth": []},
|
||||
"manager": False,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@patch("homeassistant.components.bluetooth.HaScanner", FakeHaScanner)
|
||||
@pytest.mark.usefixtures(
|
||||
"enable_bluetooth",
|
||||
"one_adapter",
|
||||
"mock_bleak_scanner_start",
|
||||
"mock_bluetooth_adapters",
|
||||
)
|
||||
async def test_diagnostics_remote_adapter(
|
||||
hass: HomeAssistant, hass_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test diagnostics for remote adapter."""
|
||||
manager = _get_manager()
|
||||
switchbot_device = generate_ble_device("44:44:33:11:23:45", "wohand")
|
||||
switchbot_adv = generate_advertisement_data(
|
||||
local_name="wohand", service_uuids=[], manufacturer_data={1: b"\x01"}
|
||||
)
|
||||
|
||||
class FakeScanner(BaseHaRemoteScanner):
|
||||
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,
|
||||
{"scanner_specific_data": "test"},
|
||||
MONOTONIC_TIME(),
|
||||
)
|
||||
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.bluetooth.diagnostics.platform.system",
|
||||
return_value="Linux",
|
||||
),
|
||||
patch(
|
||||
"homeassistant.components.bluetooth.diagnostics.get_dbus_managed_objects",
|
||||
return_value={},
|
||||
),
|
||||
):
|
||||
entry1 = hass.config_entries.async_entries(bluetooth.DOMAIN)[0]
|
||||
connector = (
|
||||
HaBluetoothConnector(MockBleakClient, "mock_bleak_client", lambda: False),
|
||||
)
|
||||
scanner = FakeScanner("esp32", "esp32", connector, True)
|
||||
unsetup = scanner.async_setup()
|
||||
cancel = manager.async_register_scanner(scanner)
|
||||
|
||||
scanner.inject_advertisement(switchbot_device, switchbot_adv)
|
||||
inject_advertisement(hass, switchbot_device, switchbot_adv)
|
||||
|
||||
diag = await get_diagnostics_for_config_entry(hass, hass_client, entry1)
|
||||
|
||||
expected = {
|
||||
"adapters": {
|
||||
"hci0": {
|
||||
"address": "00:00:00:00:00:01",
|
||||
"hw_version": "usb:v1D6Bp0246d053F",
|
||||
"manufacturer": "ACME",
|
||||
"passive_scan": False,
|
||||
"product": "Bluetooth Adapter 5.0",
|
||||
"product_id": "aa01",
|
||||
"sw_version": ANY,
|
||||
"vendor_id": "cc01",
|
||||
}
|
||||
},
|
||||
"dbus": {},
|
||||
"manager": {
|
||||
"adapters": {
|
||||
"hci0": {
|
||||
"address": "00:00:00:00:00:01",
|
||||
"hw_version": "usb:v1D6Bp0246d053F",
|
||||
"manufacturer": "ACME",
|
||||
"passive_scan": False,
|
||||
"product": "Bluetooth Adapter 5.0",
|
||||
"product_id": "aa01",
|
||||
"sw_version": ANY,
|
||||
"vendor_id": "cc01",
|
||||
}
|
||||
},
|
||||
"advertisement_tracker": {
|
||||
"fallback_intervals": {},
|
||||
"intervals": {},
|
||||
"sources": {"44:44:33:11:23:45": "esp32"},
|
||||
"timings": {"44:44:33:11:23:45": [ANY]},
|
||||
},
|
||||
"all_history": [
|
||||
{
|
||||
"address": "44:44:33:11:23:45",
|
||||
"advertisement": [
|
||||
"wohand",
|
||||
{"1": {"__type": "<class 'bytes'>", "repr": "b'\\x01'"}},
|
||||
{},
|
||||
[],
|
||||
-127,
|
||||
-127,
|
||||
[],
|
||||
],
|
||||
"connectable": True,
|
||||
"device": {
|
||||
"__type": "<class 'bleak.backends.device.BLEDevice'>",
|
||||
"repr": "BLEDevice(44:44:33:11:23:45, wohand)",
|
||||
},
|
||||
"manufacturer_data": {
|
||||
"1": {"__type": "<class 'bytes'>", "repr": "b'\\x01'"}
|
||||
},
|
||||
"name": "wohand",
|
||||
"rssi": -127,
|
||||
"service_data": {},
|
||||
"service_uuids": [],
|
||||
"source": "esp32",
|
||||
"time": ANY,
|
||||
"tx_power": -127,
|
||||
}
|
||||
],
|
||||
"connectable_history": [
|
||||
{
|
||||
"address": "44:44:33:11:23:45",
|
||||
"advertisement": [
|
||||
"wohand",
|
||||
{"1": {"__type": "<class 'bytes'>", "repr": "b'\\x01'"}},
|
||||
{},
|
||||
[],
|
||||
-127,
|
||||
-127,
|
||||
[],
|
||||
],
|
||||
"connectable": True,
|
||||
"device": {
|
||||
"__type": "<class 'bleak.backends.device.BLEDevice'>",
|
||||
"repr": "BLEDevice(44:44:33:11:23:45, wohand)",
|
||||
},
|
||||
"manufacturer_data": {
|
||||
"1": {"__type": "<class 'bytes'>", "repr": "b'\\x01'"}
|
||||
},
|
||||
"name": "wohand",
|
||||
"rssi": -127,
|
||||
"service_data": {},
|
||||
"service_uuids": [],
|
||||
"source": "esp32",
|
||||
"time": ANY,
|
||||
"tx_power": -127,
|
||||
}
|
||||
],
|
||||
"scanners": [
|
||||
{
|
||||
"adapter": "hci0",
|
||||
"discovered_devices_and_advertisement_data": [],
|
||||
"last_detection": ANY,
|
||||
"monotonic_time": ANY,
|
||||
"name": "hci0 (00:00:00:00:00:01)",
|
||||
"scanning": True,
|
||||
"source": "00:00:00:00:00:01",
|
||||
"start_time": ANY,
|
||||
"type": "HaScanner",
|
||||
"current_mode": {
|
||||
"__type": "<enum 'BluetoothScanningMode'>",
|
||||
"repr": "<BluetoothScanningMode.ACTIVE: 'active'>",
|
||||
},
|
||||
"requested_mode": {
|
||||
"__type": "<enum 'BluetoothScanningMode'>",
|
||||
"repr": "<BluetoothScanningMode.ACTIVE: 'active'>",
|
||||
},
|
||||
},
|
||||
{
|
||||
"connectable": True,
|
||||
"discovered_device_timestamps": {"44:44:33:11:23:45": ANY},
|
||||
"discovered_devices_and_advertisement_data": [
|
||||
{
|
||||
"address": "44:44:33:11:23:45",
|
||||
"advertisement_data": [
|
||||
"wohand",
|
||||
{
|
||||
"1": {
|
||||
"__type": "<class 'bytes'>",
|
||||
"repr": "b'\\x01'",
|
||||
}
|
||||
},
|
||||
{},
|
||||
[],
|
||||
-127,
|
||||
-127,
|
||||
[],
|
||||
],
|
||||
"details": {
|
||||
"scanner_specific_data": "test",
|
||||
"source": "esp32",
|
||||
},
|
||||
"name": "wohand",
|
||||
"rssi": -127,
|
||||
}
|
||||
],
|
||||
"last_detection": ANY,
|
||||
"monotonic_time": ANY,
|
||||
"name": "esp32",
|
||||
"scanning": True,
|
||||
"source": "esp32",
|
||||
"start_time": ANY,
|
||||
"time_since_last_device_detection": {"44:44:33:11:23:45": ANY},
|
||||
"type": "FakeScanner",
|
||||
},
|
||||
],
|
||||
"slot_manager": {
|
||||
"adapter_slots": {"hci0": 5},
|
||||
"allocations_by_adapter": {"hci0": []},
|
||||
"manager": False,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
diag_scanners = diag["manager"].pop("scanners")
|
||||
expected_scanners = expected["manager"].pop("scanners")
|
||||
assert diag == expected
|
||||
assert sorted(diag_scanners, key=lambda x: x["name"]) == sorted(
|
||||
expected_scanners, key=lambda x: x["name"]
|
||||
)
|
||||
|
||||
cancel()
|
||||
unsetup()
|
||||
3247
home-assistant/tests/components/bluetooth/test_init.py
Normal file
3247
home-assistant/tests/components/bluetooth/test_init.py
Normal file
File diff suppressed because it is too large
Load Diff
1662
home-assistant/tests/components/bluetooth/test_manager.py
Normal file
1662
home-assistant/tests/components/bluetooth/test_manager.py
Normal file
File diff suppressed because it is too large
Load Diff
610
home-assistant/tests/components/bluetooth/test_models.py
Normal file
610
home-assistant/tests/components/bluetooth/test_models.py
Normal file
@@ -0,0 +1,610 @@
|
||||
"""Tests for the Bluetooth integration models."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import bleak
|
||||
from bleak import BleakError
|
||||
from bleak.backends.device import BLEDevice
|
||||
from bleak.backends.scanner import AdvertisementData
|
||||
from habluetooth.wrappers import HaBleakClientWrapper, HaBleakScannerWrapper
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.bluetooth import (
|
||||
BaseHaRemoteScanner,
|
||||
BaseHaScanner,
|
||||
HaBluetoothConnector,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from . import (
|
||||
FakeScannerMixin,
|
||||
MockBleakClient,
|
||||
_get_manager,
|
||||
generate_advertisement_data,
|
||||
generate_ble_device,
|
||||
inject_advertisement,
|
||||
inject_advertisement_with_source,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth")
|
||||
async def test_wrapped_bleak_scanner(hass: HomeAssistant) -> None:
|
||||
"""Test wrapped bleak scanner dispatches calls as expected."""
|
||||
scanner = HaBleakScannerWrapper()
|
||||
switchbot_device = generate_ble_device("44:44:33:11:23:45", "wohand")
|
||||
switchbot_adv = generate_advertisement_data(
|
||||
local_name="wohand", service_uuids=[], manufacturer_data={1: b"\x01"}
|
||||
)
|
||||
inject_advertisement(hass, switchbot_device, switchbot_adv)
|
||||
assert scanner.discovered_devices == [switchbot_device]
|
||||
assert await scanner.discover() == [switchbot_device]
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth")
|
||||
async def test_wrapped_bleak_client_raises_device_missing(hass: HomeAssistant) -> None:
|
||||
"""Test wrapped bleak client dispatches calls as expected."""
|
||||
switchbot_device = generate_ble_device("44:44:33:11:23:45", "wohand")
|
||||
client = HaBleakClientWrapper(switchbot_device)
|
||||
assert client.is_connected is False
|
||||
with pytest.raises(bleak.BleakError):
|
||||
await client.connect()
|
||||
assert client.is_connected is False
|
||||
await client.disconnect()
|
||||
assert await client.clear_cache() is False
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth")
|
||||
async def test_wrapped_bleak_client_set_disconnected_callback_before_connected(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test wrapped bleak client can set a disconnected callback before connected."""
|
||||
switchbot_device = generate_ble_device("44:44:33:11:23:45", "wohand")
|
||||
client = HaBleakClientWrapper(switchbot_device)
|
||||
client.set_disconnected_callback(lambda client: None)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "one_adapter")
|
||||
async def test_wrapped_bleak_client_local_adapter_only(hass: HomeAssistant) -> None:
|
||||
"""Test wrapped bleak client with only a local adapter."""
|
||||
manager = _get_manager()
|
||||
|
||||
switchbot_device = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"wohand",
|
||||
{"path": "/org/bluez/hci0/dev_44_44_33_11_23_45"},
|
||||
)
|
||||
switchbot_adv = generate_advertisement_data(
|
||||
local_name="wohand", service_uuids=[], manufacturer_data={1: b"\x01"}, rssi=-100
|
||||
)
|
||||
|
||||
class FakeScanner(FakeScannerMixin, BaseHaScanner):
|
||||
@property
|
||||
def discovered_devices(self) -> list[BLEDevice]:
|
||||
"""Return a list of discovered devices."""
|
||||
return []
|
||||
|
||||
@property
|
||||
def discovered_devices_and_advertisement_data(
|
||||
self,
|
||||
) -> dict[str, tuple[BLEDevice, AdvertisementData]]:
|
||||
"""Return a list of discovered devices."""
|
||||
return {
|
||||
switchbot_device.address: (
|
||||
switchbot_device,
|
||||
switchbot_adv,
|
||||
)
|
||||
}
|
||||
|
||||
async def async_get_device_by_address(self, address: str) -> BLEDevice | None:
|
||||
"""Return a list of discovered devices."""
|
||||
if address == switchbot_device.address:
|
||||
return switchbot_adv
|
||||
return None
|
||||
|
||||
scanner = FakeScanner(
|
||||
"00:00:00:00:00:01",
|
||||
"hci0",
|
||||
)
|
||||
# pylint: disable-next=attribute-defined-outside-init
|
||||
scanner.connectable = True
|
||||
cancel = manager.async_register_scanner(scanner)
|
||||
inject_advertisement_with_source(
|
||||
hass, switchbot_device, switchbot_adv, "00:00:00:00:00:01"
|
||||
)
|
||||
|
||||
client = HaBleakClientWrapper(switchbot_device)
|
||||
with (
|
||||
patch(
|
||||
"bleak.backends.bluezdbus.client.BleakClientBlueZDBus.connect",
|
||||
return_value=True,
|
||||
),
|
||||
patch(
|
||||
"bleak.backends.bluezdbus.client.BleakClientBlueZDBus.is_connected", True
|
||||
),
|
||||
):
|
||||
assert await client.connect() is True
|
||||
assert client.is_connected is True
|
||||
client.set_disconnected_callback(lambda client: None)
|
||||
await client.disconnect()
|
||||
cancel()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "one_adapter")
|
||||
async def test_wrapped_bleak_client_set_disconnected_callback_after_connected(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test wrapped bleak client can set a disconnected callback after connected."""
|
||||
manager = _get_manager()
|
||||
|
||||
switchbot_proxy_device_has_connection_slot = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"wohand",
|
||||
{
|
||||
"source": "esp32_has_connection_slot",
|
||||
"path": "/org/bluez/hci0/dev_44_44_33_11_23_45",
|
||||
},
|
||||
rssi=-40,
|
||||
)
|
||||
switchbot_proxy_device_adv_has_connection_slot = generate_advertisement_data(
|
||||
local_name="wohand",
|
||||
service_uuids=[],
|
||||
manufacturer_data={1: b"\x01"},
|
||||
rssi=-40,
|
||||
)
|
||||
switchbot_device = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"wohand",
|
||||
{"path": "/org/bluez/hci0/dev_44_44_33_11_23_45"},
|
||||
)
|
||||
switchbot_adv = generate_advertisement_data(
|
||||
local_name="wohand", service_uuids=[], manufacturer_data={1: b"\x01"}, rssi=-100
|
||||
)
|
||||
|
||||
class FakeScanner(FakeScannerMixin, BaseHaRemoteScanner):
|
||||
@property
|
||||
def discovered_devices(self) -> list[BLEDevice]:
|
||||
"""Return a list of discovered devices."""
|
||||
return []
|
||||
|
||||
@property
|
||||
def discovered_devices_and_advertisement_data(
|
||||
self,
|
||||
) -> dict[str, tuple[BLEDevice, AdvertisementData]]:
|
||||
"""Return a list of discovered devices."""
|
||||
return {
|
||||
switchbot_proxy_device_has_connection_slot.address: (
|
||||
switchbot_proxy_device_has_connection_slot,
|
||||
switchbot_proxy_device_adv_has_connection_slot,
|
||||
)
|
||||
}
|
||||
|
||||
async def async_get_device_by_address(self, address: str) -> BLEDevice | None:
|
||||
"""Return a list of discovered devices."""
|
||||
if address == switchbot_proxy_device_has_connection_slot.address:
|
||||
return switchbot_proxy_device_has_connection_slot
|
||||
return None
|
||||
|
||||
connector = HaBluetoothConnector(
|
||||
MockBleakClient, "esp32_has_connection_slot", lambda: True
|
||||
)
|
||||
scanner = FakeScanner(
|
||||
"esp32_has_connection_slot",
|
||||
"esp32_has_connection_slot",
|
||||
connector,
|
||||
True,
|
||||
)
|
||||
cancel = manager.async_register_scanner(scanner)
|
||||
inject_advertisement_with_source(
|
||||
hass, switchbot_device, switchbot_adv, "00:00:00:00:00:01"
|
||||
)
|
||||
inject_advertisement_with_source(
|
||||
hass,
|
||||
switchbot_proxy_device_has_connection_slot,
|
||||
switchbot_proxy_device_adv_has_connection_slot,
|
||||
"esp32_has_connection_slot",
|
||||
)
|
||||
client = HaBleakClientWrapper(switchbot_proxy_device_has_connection_slot)
|
||||
with (
|
||||
patch(
|
||||
"bleak.backends.bluezdbus.client.BleakClientBlueZDBus.connect",
|
||||
return_value=True,
|
||||
),
|
||||
patch(
|
||||
"bleak.backends.bluezdbus.client.BleakClientBlueZDBus.is_connected", True
|
||||
),
|
||||
):
|
||||
assert await client.connect() is True
|
||||
assert client.is_connected is True
|
||||
client.set_disconnected_callback(lambda client: None)
|
||||
await client.disconnect()
|
||||
cancel()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "one_adapter")
|
||||
async def test_ble_device_with_proxy_client_out_of_connections_no_scanners(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test we switch to the next available proxy when one runs out of connections with no scanners."""
|
||||
manager = _get_manager()
|
||||
|
||||
switchbot_proxy_device_no_connection_slot = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"wohand",
|
||||
{
|
||||
"source": "esp32",
|
||||
"path": "/org/bluez/hci0/dev_44_44_33_11_23_45",
|
||||
},
|
||||
rssi=-30,
|
||||
)
|
||||
switchbot_adv = generate_advertisement_data(
|
||||
local_name="wohand", service_uuids=[], manufacturer_data={1: b"\x01"}
|
||||
)
|
||||
|
||||
inject_advertisement_with_source(
|
||||
hass, switchbot_proxy_device_no_connection_slot, switchbot_adv, "esp32"
|
||||
)
|
||||
|
||||
assert manager.async_discovered_devices(True) == [
|
||||
switchbot_proxy_device_no_connection_slot
|
||||
]
|
||||
|
||||
client = HaBleakClientWrapper(switchbot_proxy_device_no_connection_slot)
|
||||
with (
|
||||
patch("bleak.backends.bluezdbus.client.BleakClientBlueZDBus.connect"),
|
||||
pytest.raises(BleakError),
|
||||
):
|
||||
await client.connect()
|
||||
assert client.is_connected is False
|
||||
client.set_disconnected_callback(lambda client: None)
|
||||
await client.disconnect()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "one_adapter")
|
||||
async def test_ble_device_with_proxy_client_out_of_connections(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test handling all scanners are out of connection slots."""
|
||||
manager = _get_manager()
|
||||
|
||||
switchbot_proxy_device_no_connection_slot = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"wohand",
|
||||
{
|
||||
"source": "esp32",
|
||||
"path": "/org/bluez/hci0/dev_44_44_33_11_23_45",
|
||||
},
|
||||
rssi=-30,
|
||||
)
|
||||
switchbot_adv = generate_advertisement_data(
|
||||
local_name="wohand", service_uuids=[], manufacturer_data={1: b"\x01"}
|
||||
)
|
||||
|
||||
class FakeScanner(FakeScannerMixin, BaseHaRemoteScanner):
|
||||
@property
|
||||
def discovered_devices(self) -> list[BLEDevice]:
|
||||
"""Return a list of discovered devices."""
|
||||
return []
|
||||
|
||||
@property
|
||||
def discovered_devices_and_advertisement_data(
|
||||
self,
|
||||
) -> dict[str, tuple[BLEDevice, AdvertisementData]]:
|
||||
"""Return a list of discovered devices."""
|
||||
return {
|
||||
switchbot_proxy_device_no_connection_slot.address: (
|
||||
switchbot_proxy_device_no_connection_slot,
|
||||
switchbot_adv,
|
||||
)
|
||||
}
|
||||
|
||||
async def async_get_device_by_address(self, address: str) -> BLEDevice | None:
|
||||
"""Return a list of discovered devices."""
|
||||
if address == switchbot_proxy_device_no_connection_slot.address:
|
||||
return switchbot_adv
|
||||
return None
|
||||
|
||||
connector = HaBluetoothConnector(MockBleakClient, "esp32", lambda: False)
|
||||
scanner = FakeScanner("esp32", "esp32", connector, True)
|
||||
cancel = manager.async_register_scanner(scanner)
|
||||
inject_advertisement_with_source(
|
||||
hass, switchbot_proxy_device_no_connection_slot, switchbot_adv, "esp32"
|
||||
)
|
||||
|
||||
assert manager.async_discovered_devices(True) == [
|
||||
switchbot_proxy_device_no_connection_slot
|
||||
]
|
||||
|
||||
client = HaBleakClientWrapper(switchbot_proxy_device_no_connection_slot)
|
||||
with (
|
||||
patch("bleak.backends.bluezdbus.client.BleakClientBlueZDBus.connect"),
|
||||
pytest.raises(BleakError),
|
||||
):
|
||||
await client.connect()
|
||||
assert client.is_connected is False
|
||||
client.set_disconnected_callback(lambda client: None)
|
||||
await client.disconnect()
|
||||
cancel()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "one_adapter")
|
||||
async def test_ble_device_with_proxy_clear_cache(hass: HomeAssistant) -> None:
|
||||
"""Test we can clear cache on the proxy."""
|
||||
manager = _get_manager()
|
||||
|
||||
switchbot_proxy_device_with_connection_slot = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"wohand",
|
||||
{
|
||||
"source": "esp32",
|
||||
"path": "/org/bluez/hci0/dev_44_44_33_11_23_45",
|
||||
},
|
||||
rssi=-30,
|
||||
)
|
||||
switchbot_adv = generate_advertisement_data(
|
||||
local_name="wohand", service_uuids=[], manufacturer_data={1: b"\x01"}
|
||||
)
|
||||
|
||||
class FakeScanner(FakeScannerMixin, BaseHaRemoteScanner):
|
||||
@property
|
||||
def discovered_devices(self) -> list[BLEDevice]:
|
||||
"""Return a list of discovered devices."""
|
||||
return []
|
||||
|
||||
@property
|
||||
def discovered_devices_and_advertisement_data(
|
||||
self,
|
||||
) -> dict[str, tuple[BLEDevice, AdvertisementData]]:
|
||||
"""Return a list of discovered devices."""
|
||||
return {
|
||||
switchbot_proxy_device_with_connection_slot.address: (
|
||||
switchbot_proxy_device_with_connection_slot,
|
||||
switchbot_adv,
|
||||
)
|
||||
}
|
||||
|
||||
async def async_get_device_by_address(self, address: str) -> BLEDevice | None:
|
||||
"""Return a list of discovered devices."""
|
||||
if address == switchbot_proxy_device_with_connection_slot.address:
|
||||
return switchbot_adv
|
||||
return None
|
||||
|
||||
connector = HaBluetoothConnector(MockBleakClient, "esp32", lambda: True)
|
||||
scanner = FakeScanner("esp32", "esp32", connector, True)
|
||||
cancel = manager.async_register_scanner(scanner)
|
||||
inject_advertisement_with_source(
|
||||
hass, switchbot_proxy_device_with_connection_slot, switchbot_adv, "esp32"
|
||||
)
|
||||
|
||||
assert manager.async_discovered_devices(True) == [
|
||||
switchbot_proxy_device_with_connection_slot
|
||||
]
|
||||
|
||||
client = HaBleakClientWrapper(switchbot_proxy_device_with_connection_slot)
|
||||
await client.connect()
|
||||
assert client.is_connected is True
|
||||
assert await client.clear_cache() is True
|
||||
await client.disconnect()
|
||||
cancel()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "one_adapter")
|
||||
async def test_ble_device_with_proxy_client_out_of_connections_uses_best_available(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test we switch to the next available proxy when one runs out of connections."""
|
||||
manager = _get_manager()
|
||||
|
||||
switchbot_proxy_device_no_connection_slot = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"wohand",
|
||||
{
|
||||
"source": "esp32_no_connection_slot",
|
||||
"path": "/org/bluez/hci0/dev_44_44_33_11_23_45",
|
||||
},
|
||||
)
|
||||
switchbot_proxy_device_adv_no_connection_slot = generate_advertisement_data(
|
||||
local_name="wohand",
|
||||
service_uuids=[],
|
||||
manufacturer_data={1: b"\x01"},
|
||||
rssi=-30,
|
||||
)
|
||||
switchbot_proxy_device_has_connection_slot = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"wohand",
|
||||
{
|
||||
"source": "esp32_has_connection_slot",
|
||||
"path": "/org/bluez/hci0/dev_44_44_33_11_23_45",
|
||||
},
|
||||
rssi=-40,
|
||||
)
|
||||
switchbot_proxy_device_adv_has_connection_slot = generate_advertisement_data(
|
||||
local_name="wohand",
|
||||
service_uuids=[],
|
||||
manufacturer_data={1: b"\x01"},
|
||||
rssi=-40,
|
||||
)
|
||||
switchbot_device = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"wohand",
|
||||
{"path": "/org/bluez/hci0/dev_44_44_33_11_23_45"},
|
||||
)
|
||||
switchbot_adv = generate_advertisement_data(
|
||||
local_name="wohand", service_uuids=[], manufacturer_data={1: b"\x01"}, rssi=-100
|
||||
)
|
||||
|
||||
inject_advertisement_with_source(
|
||||
hass, switchbot_device, switchbot_adv, "00:00:00:00:00:01"
|
||||
)
|
||||
inject_advertisement_with_source(
|
||||
hass,
|
||||
switchbot_proxy_device_has_connection_slot,
|
||||
switchbot_proxy_device_adv_has_connection_slot,
|
||||
"esp32_has_connection_slot",
|
||||
)
|
||||
inject_advertisement_with_source(
|
||||
hass,
|
||||
switchbot_proxy_device_no_connection_slot,
|
||||
switchbot_proxy_device_adv_no_connection_slot,
|
||||
"esp32_no_connection_slot",
|
||||
)
|
||||
|
||||
class FakeScanner(FakeScannerMixin, BaseHaRemoteScanner):
|
||||
@property
|
||||
def discovered_devices(self) -> list[BLEDevice]:
|
||||
"""Return a list of discovered devices."""
|
||||
return []
|
||||
|
||||
@property
|
||||
def discovered_devices_and_advertisement_data(
|
||||
self,
|
||||
) -> dict[str, tuple[BLEDevice, AdvertisementData]]:
|
||||
"""Return a list of discovered devices."""
|
||||
return {
|
||||
switchbot_proxy_device_has_connection_slot.address: (
|
||||
switchbot_proxy_device_has_connection_slot,
|
||||
switchbot_proxy_device_adv_has_connection_slot,
|
||||
)
|
||||
}
|
||||
|
||||
async def async_get_device_by_address(self, address: str) -> BLEDevice | None:
|
||||
"""Return a list of discovered devices."""
|
||||
if address == switchbot_proxy_device_has_connection_slot.address:
|
||||
return switchbot_proxy_device_has_connection_slot
|
||||
return None
|
||||
|
||||
connector = HaBluetoothConnector(
|
||||
MockBleakClient, "esp32_has_connection_slot", lambda: True
|
||||
)
|
||||
scanner = FakeScanner(
|
||||
"esp32_has_connection_slot",
|
||||
"esp32_has_connection_slot",
|
||||
connector,
|
||||
True,
|
||||
)
|
||||
cancel = manager.async_register_scanner(scanner)
|
||||
assert manager.async_discovered_devices(True) == [
|
||||
switchbot_proxy_device_no_connection_slot
|
||||
]
|
||||
|
||||
client = HaBleakClientWrapper(switchbot_proxy_device_no_connection_slot)
|
||||
with patch("bleak.backends.bluezdbus.client.BleakClientBlueZDBus.connect"):
|
||||
await client.connect()
|
||||
assert client.is_connected is True
|
||||
client.set_disconnected_callback(lambda client: None)
|
||||
await client.disconnect()
|
||||
cancel()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "macos_adapter")
|
||||
async def test_ble_device_with_proxy_client_out_of_connections_uses_best_available_macos(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test we switch to the next available proxy when one runs out of connections on MacOS."""
|
||||
manager = _get_manager()
|
||||
|
||||
switchbot_proxy_device_no_connection_slot = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"wohand_no_connection_slot",
|
||||
{
|
||||
"source": "esp32_no_connection_slot",
|
||||
"path": "/org/bluez/hci0/dev_44_44_33_11_23_45",
|
||||
},
|
||||
rssi=-30,
|
||||
)
|
||||
switchbot_proxy_device_no_connection_slot_adv = generate_advertisement_data(
|
||||
local_name="wohand",
|
||||
service_uuids=[],
|
||||
manufacturer_data={1: b"\x01"},
|
||||
rssi=-30,
|
||||
)
|
||||
switchbot_proxy_device_has_connection_slot = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"wohand_has_connection_slot",
|
||||
{
|
||||
"source": "esp32_has_connection_slot",
|
||||
"path": "/org/bluez/hci0/dev_44_44_33_11_23_45",
|
||||
},
|
||||
)
|
||||
switchbot_proxy_device_has_connection_slot_adv = generate_advertisement_data(
|
||||
local_name="wohand",
|
||||
service_uuids=[],
|
||||
manufacturer_data={1: b"\x01"},
|
||||
rssi=-40,
|
||||
)
|
||||
|
||||
switchbot_device = generate_ble_device(
|
||||
"44:44:33:11:23:45",
|
||||
"wohand",
|
||||
{},
|
||||
rssi=-100,
|
||||
)
|
||||
switchbot_device_adv = generate_advertisement_data(
|
||||
local_name="wohand",
|
||||
service_uuids=[],
|
||||
manufacturer_data={1: b"\x01"},
|
||||
rssi=-100,
|
||||
)
|
||||
|
||||
inject_advertisement_with_source(
|
||||
hass, switchbot_device, switchbot_device_adv, "00:00:00:00:00:01"
|
||||
)
|
||||
inject_advertisement_with_source(
|
||||
hass,
|
||||
switchbot_proxy_device_has_connection_slot,
|
||||
switchbot_proxy_device_has_connection_slot_adv,
|
||||
"esp32_has_connection_slot",
|
||||
)
|
||||
inject_advertisement_with_source(
|
||||
hass,
|
||||
switchbot_proxy_device_no_connection_slot,
|
||||
switchbot_proxy_device_no_connection_slot_adv,
|
||||
"esp32_no_connection_slot",
|
||||
)
|
||||
|
||||
class FakeScanner(FakeScannerMixin, BaseHaRemoteScanner):
|
||||
@property
|
||||
def discovered_devices(self) -> list[BLEDevice]:
|
||||
"""Return a list of discovered devices."""
|
||||
return []
|
||||
|
||||
@property
|
||||
def discovered_devices_and_advertisement_data(
|
||||
self,
|
||||
) -> dict[str, tuple[BLEDevice, AdvertisementData]]:
|
||||
"""Return a list of discovered devices."""
|
||||
return {
|
||||
switchbot_proxy_device_has_connection_slot.address: (
|
||||
switchbot_proxy_device_has_connection_slot,
|
||||
switchbot_proxy_device_has_connection_slot_adv,
|
||||
)
|
||||
}
|
||||
|
||||
async def async_get_device_by_address(self, address: str) -> BLEDevice | None:
|
||||
"""Return a list of discovered devices."""
|
||||
if address == switchbot_proxy_device_has_connection_slot.address:
|
||||
return switchbot_proxy_device_has_connection_slot
|
||||
return None
|
||||
|
||||
connector = HaBluetoothConnector(
|
||||
MockBleakClient, "esp32_has_connection_slot", lambda: True
|
||||
)
|
||||
scanner = FakeScanner(
|
||||
"esp32_has_connection_slot",
|
||||
"esp32_has_connection_slot",
|
||||
connector,
|
||||
True,
|
||||
)
|
||||
cancel = manager.async_register_scanner(scanner)
|
||||
assert manager.async_discovered_devices(True) == [
|
||||
switchbot_proxy_device_no_connection_slot
|
||||
]
|
||||
|
||||
client = HaBleakClientWrapper(switchbot_proxy_device_no_connection_slot)
|
||||
with patch("bleak.get_platform_client_backend_type"):
|
||||
await client.connect()
|
||||
assert client.is_connected is True
|
||||
client.set_disconnected_callback(lambda client: None)
|
||||
await client.disconnect()
|
||||
cancel()
|
||||
@@ -0,0 +1,219 @@
|
||||
"""Tests for the Bluetooth integration PassiveBluetoothDataUpdateCoordinator."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
import time
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.bluetooth import (
|
||||
DOMAIN,
|
||||
FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS,
|
||||
BluetoothChange,
|
||||
BluetoothScanningMode,
|
||||
)
|
||||
from homeassistant.components.bluetooth.passive_update_coordinator import (
|
||||
PassiveBluetoothCoordinatorEntity,
|
||||
PassiveBluetoothDataUpdateCoordinator,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.service_info.bluetooth import BluetoothServiceInfo
|
||||
from homeassistant.setup import async_setup_component
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from . import (
|
||||
inject_bluetooth_service_info,
|
||||
patch_all_discovered_devices,
|
||||
patch_bluetooth_time,
|
||||
)
|
||||
|
||||
from tests.common import async_fire_time_changed
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
GENERIC_BLUETOOTH_SERVICE_INFO = BluetoothServiceInfo(
|
||||
name="Generic",
|
||||
address="aa:bb:cc:dd:ee:ff",
|
||||
rssi=-95,
|
||||
manufacturer_data={
|
||||
1: b"\x01\x01\x01\x01\x01\x01\x01\x01",
|
||||
},
|
||||
service_data={},
|
||||
service_uuids=[],
|
||||
source="local",
|
||||
)
|
||||
|
||||
|
||||
class MyCoordinator(PassiveBluetoothDataUpdateCoordinator):
|
||||
"""An example coordinator that subclasses PassiveBluetoothDataUpdateCoordinator."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hass: HomeAssistant,
|
||||
logger: logging.Logger,
|
||||
device_id: str,
|
||||
mode: BluetoothScanningMode,
|
||||
) -> None:
|
||||
"""Initialize the coordinator."""
|
||||
super().__init__(hass, logger, device_id, mode)
|
||||
self.data: dict[str, Any] = {}
|
||||
|
||||
def _async_handle_bluetooth_event(
|
||||
self,
|
||||
service_info: BluetoothServiceInfo,
|
||||
change: BluetoothChange,
|
||||
) -> None:
|
||||
"""Handle a Bluetooth event."""
|
||||
self.data = {"rssi": service_info.rssi}
|
||||
super()._async_handle_bluetooth_event(service_info, change)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_bleak_scanner_start", "mock_bluetooth_adapters")
|
||||
async def test_basic_usage(hass: HomeAssistant) -> None:
|
||||
"""Test basic usage of the PassiveBluetoothDataUpdateCoordinator."""
|
||||
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
coordinator = MyCoordinator(
|
||||
hass, _LOGGER, "aa:bb:cc:dd:ee:ff", BluetoothScanningMode.ACTIVE
|
||||
)
|
||||
assert coordinator.available is False # no data yet
|
||||
|
||||
mock_listener = MagicMock()
|
||||
unregister_listener = coordinator.async_add_listener(mock_listener)
|
||||
|
||||
cancel = coordinator.async_start()
|
||||
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
|
||||
assert len(mock_listener.mock_calls) == 1
|
||||
assert coordinator.data == {"rssi": GENERIC_BLUETOOTH_SERVICE_INFO.rssi}
|
||||
assert coordinator.available is True
|
||||
|
||||
unregister_listener()
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
|
||||
assert len(mock_listener.mock_calls) == 1
|
||||
assert coordinator.data == {"rssi": GENERIC_BLUETOOTH_SERVICE_INFO.rssi}
|
||||
assert coordinator.available is True
|
||||
cancel()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_bleak_scanner_start", "mock_bluetooth_adapters")
|
||||
async def test_context_compatiblity_with_data_update_coordinator(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test contexts can be passed for compatibility with DataUpdateCoordinator."""
|
||||
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
coordinator = MyCoordinator(
|
||||
hass, _LOGGER, "aa:bb:cc:dd:ee:ff", BluetoothScanningMode.ACTIVE
|
||||
)
|
||||
assert coordinator.available is False # no data yet
|
||||
|
||||
mock_listener = MagicMock()
|
||||
coordinator.async_add_listener(mock_listener)
|
||||
|
||||
coordinator.async_start()
|
||||
|
||||
assert not set(coordinator.async_contexts())
|
||||
|
||||
def update_callback1():
|
||||
pass
|
||||
|
||||
def update_callback2():
|
||||
pass
|
||||
|
||||
unsub1 = coordinator.async_add_listener(update_callback1, 1)
|
||||
assert set(coordinator.async_contexts()) == {1}
|
||||
|
||||
unsub2 = coordinator.async_add_listener(update_callback2, 2)
|
||||
assert set(coordinator.async_contexts()) == {1, 2}
|
||||
|
||||
unsub1()
|
||||
assert set(coordinator.async_contexts()) == {2}
|
||||
|
||||
unsub2()
|
||||
assert not set(coordinator.async_contexts())
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_bleak_scanner_start", "mock_bluetooth_adapters")
|
||||
async def test_unavailable_callbacks_mark_the_coordinator_unavailable(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test that the coordinator goes unavailable when the bluetooth stack no longer sees the device."""
|
||||
start_monotonic = time.monotonic()
|
||||
with patch(
|
||||
"bleak.BleakScanner.discovered_devices_and_advertisement_data", # Must patch before we setup
|
||||
{"44:44:33:11:23:45": (MagicMock(address="44:44:33:11:23:45"), MagicMock())},
|
||||
):
|
||||
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
await hass.async_block_till_done()
|
||||
coordinator = MyCoordinator(
|
||||
hass, _LOGGER, "aa:bb:cc:dd:ee:ff", BluetoothScanningMode.PASSIVE
|
||||
)
|
||||
assert coordinator.available is False # no data yet
|
||||
|
||||
mock_listener = MagicMock()
|
||||
coordinator.async_add_listener(mock_listener)
|
||||
|
||||
coordinator.async_start()
|
||||
|
||||
assert coordinator.available is False
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
assert coordinator.available is True
|
||||
|
||||
monotonic_now = start_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
|
||||
|
||||
with (
|
||||
patch_bluetooth_time(monotonic_now),
|
||||
patch_all_discovered_devices([MagicMock(address="44:44:33:11:23:45")]),
|
||||
):
|
||||
async_fire_time_changed(
|
||||
hass,
|
||||
dt_util.utcnow()
|
||||
+ timedelta(seconds=FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1),
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
assert coordinator.available is False
|
||||
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
assert coordinator.available is True
|
||||
|
||||
monotonic_now = start_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 2
|
||||
|
||||
with (
|
||||
patch_bluetooth_time(
|
||||
monotonic_now,
|
||||
),
|
||||
patch_all_discovered_devices([MagicMock(address="44:44:33:11:23:45")]),
|
||||
):
|
||||
async_fire_time_changed(
|
||||
hass,
|
||||
dt_util.utcnow()
|
||||
+ timedelta(seconds=FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 2),
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
assert coordinator.available is False
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_bleak_scanner_start", "mock_bluetooth_adapters")
|
||||
async def test_passive_bluetooth_coordinator_entity(hass: HomeAssistant) -> None:
|
||||
"""Test integration of PassiveBluetoothDataUpdateCoordinator with PassiveBluetoothCoordinatorEntity."""
|
||||
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
coordinator = MyCoordinator(
|
||||
hass, _LOGGER, "aa:bb:cc:dd:ee:ff", BluetoothScanningMode.ACTIVE
|
||||
)
|
||||
entity = PassiveBluetoothCoordinatorEntity(coordinator)
|
||||
assert entity.available is False
|
||||
|
||||
coordinator.async_start()
|
||||
|
||||
assert coordinator.available is False
|
||||
inject_bluetooth_service_info(hass, GENERIC_BLUETOOTH_SERVICE_INFO)
|
||||
assert coordinator.available is True
|
||||
entity.hass = hass
|
||||
await entity.async_update()
|
||||
assert entity.available is True
|
||||
File diff suppressed because it is too large
Load Diff
666
home-assistant/tests/components/bluetooth/test_scanner.py
Normal file
666
home-assistant/tests/components/bluetooth/test_scanner.py
Normal file
@@ -0,0 +1,666 @@
|
||||
"""Tests for the Bluetooth integration scanners."""
|
||||
|
||||
import asyncio
|
||||
from datetime import timedelta
|
||||
import time
|
||||
from typing import Any
|
||||
from unittest.mock import ANY, MagicMock, patch
|
||||
|
||||
from bleak import BleakError
|
||||
from bleak.backends.scanner import AdvertisementDataCallback
|
||||
from dbus_fast import InvalidMessageError
|
||||
import pytest
|
||||
|
||||
from homeassistant.components import bluetooth
|
||||
from homeassistant.components.bluetooth.const import (
|
||||
SCANNER_WATCHDOG_INTERVAL,
|
||||
SCANNER_WATCHDOG_TIMEOUT,
|
||||
)
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.const import EVENT_HOMEASSISTANT_STARTED, EVENT_HOMEASSISTANT_STOP
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from . import (
|
||||
async_setup_with_one_adapter,
|
||||
generate_advertisement_data,
|
||||
generate_ble_device,
|
||||
patch_bluetooth_time,
|
||||
)
|
||||
|
||||
from tests.common import MockConfigEntry, async_fire_time_changed
|
||||
|
||||
# If the adapter is in a stuck state the following errors are raised:
|
||||
NEED_RESET_ERRORS = [
|
||||
"org.bluez.Error.Failed",
|
||||
"org.bluez.Error.InProgress",
|
||||
"org.bluez.Error.NotReady",
|
||||
"not found",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "macos_adapter")
|
||||
async def test_config_entry_can_be_reloaded_when_stop_raises(
|
||||
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""Test we can reload if stopping the scanner raises."""
|
||||
entry = hass.config_entries.async_entries(bluetooth.DOMAIN)[0]
|
||||
assert entry.state is ConfigEntryState.LOADED
|
||||
|
||||
with patch(
|
||||
"habluetooth.scanner.OriginalBleakScanner.stop",
|
||||
side_effect=BleakError,
|
||||
):
|
||||
await hass.config_entries.async_reload(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert entry.state is ConfigEntryState.LOADED
|
||||
assert "Error stopping scanner" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("one_adapter")
|
||||
async def test_dbus_socket_missing_in_container(
|
||||
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""Test we handle dbus being missing in the container."""
|
||||
|
||||
with (
|
||||
patch("habluetooth.scanner.is_docker_env", return_value=True),
|
||||
patch(
|
||||
"habluetooth.scanner.OriginalBleakScanner.start",
|
||||
side_effect=FileNotFoundError,
|
||||
),
|
||||
):
|
||||
await async_setup_with_one_adapter(hass)
|
||||
|
||||
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
|
||||
await hass.async_block_till_done()
|
||||
assert "/run/dbus" in caplog.text
|
||||
assert "docker" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("one_adapter")
|
||||
async def test_dbus_socket_missing(
|
||||
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""Test we handle dbus being missing."""
|
||||
|
||||
with (
|
||||
patch("habluetooth.scanner.is_docker_env", return_value=False),
|
||||
patch(
|
||||
"habluetooth.scanner.OriginalBleakScanner.start",
|
||||
side_effect=FileNotFoundError,
|
||||
),
|
||||
):
|
||||
await async_setup_with_one_adapter(hass)
|
||||
|
||||
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
|
||||
await hass.async_block_till_done()
|
||||
assert "DBus" in caplog.text
|
||||
assert "docker" not in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("one_adapter")
|
||||
async def test_dbus_broken_pipe_in_container(
|
||||
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""Test we handle dbus broken pipe in the container."""
|
||||
|
||||
with (
|
||||
patch("habluetooth.scanner.is_docker_env", return_value=True),
|
||||
patch(
|
||||
"habluetooth.scanner.OriginalBleakScanner.start",
|
||||
side_effect=BrokenPipeError,
|
||||
),
|
||||
):
|
||||
await async_setup_with_one_adapter(hass)
|
||||
|
||||
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
|
||||
await hass.async_block_till_done()
|
||||
assert "dbus" in caplog.text
|
||||
assert "restarting" in caplog.text
|
||||
assert "container" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("one_adapter")
|
||||
async def test_dbus_broken_pipe(
|
||||
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""Test we handle dbus broken pipe."""
|
||||
|
||||
with (
|
||||
patch("habluetooth.scanner.is_docker_env", return_value=False),
|
||||
patch(
|
||||
"habluetooth.scanner.OriginalBleakScanner.start",
|
||||
side_effect=BrokenPipeError,
|
||||
),
|
||||
):
|
||||
await async_setup_with_one_adapter(hass)
|
||||
|
||||
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
|
||||
await hass.async_block_till_done()
|
||||
assert "DBus" in caplog.text
|
||||
assert "restarting" in caplog.text
|
||||
assert "container" not in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("one_adapter")
|
||||
async def test_invalid_dbus_message(
|
||||
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""Test we handle invalid dbus message."""
|
||||
|
||||
with patch(
|
||||
"habluetooth.scanner.OriginalBleakScanner.start",
|
||||
side_effect=InvalidMessageError,
|
||||
):
|
||||
await async_setup_with_one_adapter(hass)
|
||||
|
||||
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
|
||||
await hass.async_block_till_done()
|
||||
assert "dbus" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("error", NEED_RESET_ERRORS)
|
||||
@pytest.mark.usefixtures("one_adapter")
|
||||
async def test_adapter_needs_reset_at_start(hass: HomeAssistant, error: str) -> None:
|
||||
"""Test we cycle the adapter when it needs a restart."""
|
||||
|
||||
with (
|
||||
patch(
|
||||
"habluetooth.scanner.OriginalBleakScanner.start",
|
||||
side_effect=[BleakError(error), BleakError(error), None],
|
||||
),
|
||||
patch(
|
||||
"habluetooth.util.recover_adapter", return_value=True
|
||||
) as mock_recover_adapter,
|
||||
):
|
||||
await async_setup_with_one_adapter(hass)
|
||||
|
||||
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(mock_recover_adapter.mock_calls) == 1
|
||||
|
||||
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("one_adapter")
|
||||
async def test_recovery_from_dbus_restart(hass: HomeAssistant) -> None:
|
||||
"""Test we can recover when DBus gets restarted out from under us."""
|
||||
|
||||
called_start = 0
|
||||
called_stop = 0
|
||||
_callback = None
|
||||
mock_discovered = []
|
||||
|
||||
class MockBleakScanner:
|
||||
def __init__(self, detection_callback, *args: Any, **kwargs: Any) -> None:
|
||||
nonlocal _callback
|
||||
_callback = detection_callback
|
||||
|
||||
async def start(self, *args, **kwargs):
|
||||
"""Mock Start."""
|
||||
nonlocal called_start
|
||||
called_start += 1
|
||||
|
||||
async def stop(self, *args, **kwargs):
|
||||
"""Mock Start."""
|
||||
nonlocal called_stop
|
||||
called_stop += 1
|
||||
|
||||
@property
|
||||
def discovered_devices(self):
|
||||
"""Mock discovered_devices."""
|
||||
nonlocal mock_discovered
|
||||
return mock_discovered
|
||||
|
||||
with patch(
|
||||
"habluetooth.scanner.OriginalBleakScanner",
|
||||
MockBleakScanner,
|
||||
):
|
||||
await async_setup_with_one_adapter(hass)
|
||||
|
||||
assert called_start == 1
|
||||
|
||||
start_time_monotonic = time.monotonic()
|
||||
mock_discovered = [MagicMock()]
|
||||
|
||||
# Ensure we don't restart the scanner if we don't need to
|
||||
with patch_bluetooth_time(
|
||||
start_time_monotonic + 10,
|
||||
):
|
||||
async_fire_time_changed(hass, dt_util.utcnow() + SCANNER_WATCHDOG_INTERVAL)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert called_start == 1
|
||||
|
||||
# Fire a callback to reset the timer
|
||||
with patch_bluetooth_time(
|
||||
start_time_monotonic,
|
||||
):
|
||||
_callback(
|
||||
generate_ble_device("44:44:33:11:23:42", "any_name"),
|
||||
generate_advertisement_data(local_name="any_name"),
|
||||
)
|
||||
|
||||
# Ensure we don't restart the scanner if we don't need to
|
||||
with patch_bluetooth_time(
|
||||
start_time_monotonic + 20,
|
||||
):
|
||||
async_fire_time_changed(hass, dt_util.utcnow() + SCANNER_WATCHDOG_INTERVAL)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert called_start == 1
|
||||
|
||||
# We hit the timer, so we restart the scanner
|
||||
with patch_bluetooth_time(
|
||||
start_time_monotonic + SCANNER_WATCHDOG_TIMEOUT + 20,
|
||||
):
|
||||
async_fire_time_changed(
|
||||
hass,
|
||||
dt_util.utcnow() + SCANNER_WATCHDOG_INTERVAL + timedelta(seconds=20),
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert called_start == 2
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("one_adapter")
|
||||
async def test_adapter_recovery(hass: HomeAssistant) -> None:
|
||||
"""Test we can recover when the adapter stops responding."""
|
||||
|
||||
called_start = 0
|
||||
called_stop = 0
|
||||
_callback = None
|
||||
mock_discovered = []
|
||||
|
||||
class MockBleakScanner:
|
||||
async def start(self, *args, **kwargs):
|
||||
"""Mock Start."""
|
||||
nonlocal called_start
|
||||
called_start += 1
|
||||
|
||||
async def stop(self, *args, **kwargs):
|
||||
"""Mock Start."""
|
||||
nonlocal called_stop
|
||||
called_stop += 1
|
||||
|
||||
@property
|
||||
def discovered_devices(self):
|
||||
"""Mock discovered_devices."""
|
||||
nonlocal mock_discovered
|
||||
return mock_discovered
|
||||
|
||||
def register_detection_callback(self, callback: AdvertisementDataCallback):
|
||||
"""Mock Register Detection Callback."""
|
||||
nonlocal _callback
|
||||
_callback = callback
|
||||
|
||||
scanner = MockBleakScanner()
|
||||
start_time_monotonic = time.monotonic()
|
||||
|
||||
with (
|
||||
patch_bluetooth_time(
|
||||
start_time_monotonic,
|
||||
),
|
||||
patch(
|
||||
"habluetooth.scanner.OriginalBleakScanner",
|
||||
return_value=scanner,
|
||||
),
|
||||
):
|
||||
await async_setup_with_one_adapter(hass)
|
||||
|
||||
assert called_start == 1
|
||||
|
||||
mock_discovered = [MagicMock()]
|
||||
|
||||
# Ensure we don't restart the scanner if we don't need to
|
||||
with patch_bluetooth_time(
|
||||
start_time_monotonic + 10,
|
||||
):
|
||||
async_fire_time_changed(hass, dt_util.utcnow() + SCANNER_WATCHDOG_INTERVAL)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert called_start == 1
|
||||
|
||||
# Ensure we don't restart the scanner if we don't need to
|
||||
with patch_bluetooth_time(
|
||||
start_time_monotonic + 20,
|
||||
):
|
||||
async_fire_time_changed(hass, dt_util.utcnow() + SCANNER_WATCHDOG_INTERVAL)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert called_start == 1
|
||||
|
||||
# We hit the timer with no detections, so we reset the adapter and restart the scanner
|
||||
with (
|
||||
patch_bluetooth_time(
|
||||
start_time_monotonic
|
||||
+ SCANNER_WATCHDOG_TIMEOUT
|
||||
+ SCANNER_WATCHDOG_INTERVAL.total_seconds(),
|
||||
),
|
||||
patch(
|
||||
"habluetooth.util.recover_adapter", return_value=True
|
||||
) as mock_recover_adapter,
|
||||
):
|
||||
async_fire_time_changed(hass, dt_util.utcnow() + SCANNER_WATCHDOG_INTERVAL)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(mock_recover_adapter.mock_calls) == 1
|
||||
assert called_start == 2
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("one_adapter")
|
||||
async def test_adapter_scanner_fails_to_start_first_time(hass: HomeAssistant) -> None:
|
||||
"""Test we can recover when the adapter stops responding and the first recovery fails."""
|
||||
|
||||
called_start = 0
|
||||
called_stop = 0
|
||||
_callback = None
|
||||
mock_discovered = []
|
||||
|
||||
class MockBleakScanner:
|
||||
async def start(self, *args, **kwargs):
|
||||
"""Mock Start."""
|
||||
nonlocal called_start
|
||||
called_start += 1
|
||||
if called_start == 1:
|
||||
return # Start ok the first time
|
||||
if called_start < 4:
|
||||
raise BleakError("Failed to start")
|
||||
|
||||
async def stop(self, *args, **kwargs):
|
||||
"""Mock Start."""
|
||||
nonlocal called_stop
|
||||
called_stop += 1
|
||||
|
||||
@property
|
||||
def discovered_devices(self):
|
||||
"""Mock discovered_devices."""
|
||||
nonlocal mock_discovered
|
||||
return mock_discovered
|
||||
|
||||
def register_detection_callback(self, callback: AdvertisementDataCallback):
|
||||
"""Mock Register Detection Callback."""
|
||||
nonlocal _callback
|
||||
_callback = callback
|
||||
|
||||
scanner = MockBleakScanner()
|
||||
start_time_monotonic = time.monotonic()
|
||||
|
||||
with (
|
||||
patch_bluetooth_time(
|
||||
start_time_monotonic,
|
||||
),
|
||||
patch(
|
||||
"habluetooth.scanner.OriginalBleakScanner",
|
||||
return_value=scanner,
|
||||
),
|
||||
):
|
||||
await async_setup_with_one_adapter(hass)
|
||||
|
||||
assert called_start == 1
|
||||
|
||||
mock_discovered = [MagicMock()]
|
||||
|
||||
# Ensure we don't restart the scanner if we don't need to
|
||||
with patch_bluetooth_time(
|
||||
start_time_monotonic + 10,
|
||||
):
|
||||
async_fire_time_changed(hass, dt_util.utcnow() + SCANNER_WATCHDOG_INTERVAL)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert called_start == 1
|
||||
|
||||
# Ensure we don't restart the scanner if we don't need to
|
||||
with patch_bluetooth_time(
|
||||
start_time_monotonic + 20,
|
||||
):
|
||||
async_fire_time_changed(hass, dt_util.utcnow() + SCANNER_WATCHDOG_INTERVAL)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert called_start == 1
|
||||
|
||||
# We hit the timer with no detections, so we reset the adapter and restart the scanner
|
||||
with (
|
||||
patch_bluetooth_time(
|
||||
start_time_monotonic
|
||||
+ SCANNER_WATCHDOG_TIMEOUT
|
||||
+ SCANNER_WATCHDOG_INTERVAL.total_seconds(),
|
||||
),
|
||||
patch(
|
||||
"habluetooth.util.recover_adapter", return_value=True
|
||||
) as mock_recover_adapter,
|
||||
):
|
||||
async_fire_time_changed(hass, dt_util.utcnow() + SCANNER_WATCHDOG_INTERVAL)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(mock_recover_adapter.mock_calls) == 1
|
||||
assert called_start == 4
|
||||
|
||||
now_monotonic = time.monotonic()
|
||||
# We hit the timer again the previous start call failed, make sure
|
||||
# we try again
|
||||
with (
|
||||
patch_bluetooth_time(
|
||||
now_monotonic
|
||||
+ SCANNER_WATCHDOG_TIMEOUT * 2
|
||||
+ SCANNER_WATCHDOG_INTERVAL.total_seconds(),
|
||||
),
|
||||
patch(
|
||||
"habluetooth.util.recover_adapter", return_value=True
|
||||
) as mock_recover_adapter,
|
||||
):
|
||||
async_fire_time_changed(hass, dt_util.utcnow() + SCANNER_WATCHDOG_INTERVAL)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(mock_recover_adapter.mock_calls) == 1
|
||||
assert called_start == 5
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("one_adapter")
|
||||
async def test_adapter_fails_to_start_and_takes_a_bit_to_init(
|
||||
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""Test we can recover the adapter at startup and we wait for Dbus to init."""
|
||||
assert await async_setup_component(hass, "logger", {})
|
||||
await hass.services.async_call(
|
||||
"logger",
|
||||
"set_level",
|
||||
{"homeassistant.components.bluetooth": "DEBUG"},
|
||||
blocking=True,
|
||||
)
|
||||
called_start = 0
|
||||
called_stop = 0
|
||||
_callback = None
|
||||
mock_discovered = []
|
||||
|
||||
class MockBleakScanner:
|
||||
async def start(self, *args, **kwargs):
|
||||
"""Mock Start."""
|
||||
nonlocal called_start
|
||||
called_start += 1
|
||||
if called_start == 1:
|
||||
raise BleakError("org.freedesktop.DBus.Error.UnknownObject")
|
||||
if called_start == 2:
|
||||
raise BleakError("org.bluez.Error.InProgress")
|
||||
if called_start == 3:
|
||||
raise BleakError("org.bluez.Error.InProgress")
|
||||
|
||||
async def stop(self, *args, **kwargs):
|
||||
"""Mock Start."""
|
||||
nonlocal called_stop
|
||||
called_stop += 1
|
||||
|
||||
@property
|
||||
def discovered_devices(self):
|
||||
"""Mock discovered_devices."""
|
||||
nonlocal mock_discovered
|
||||
return mock_discovered
|
||||
|
||||
def register_detection_callback(self, callback: AdvertisementDataCallback):
|
||||
"""Mock Register Detection Callback."""
|
||||
nonlocal _callback
|
||||
_callback = callback
|
||||
|
||||
scanner = MockBleakScanner()
|
||||
start_time_monotonic = time.monotonic()
|
||||
|
||||
with (
|
||||
patch(
|
||||
"habluetooth.scanner.ADAPTER_INIT_TIME",
|
||||
0,
|
||||
),
|
||||
patch_bluetooth_time(
|
||||
start_time_monotonic,
|
||||
),
|
||||
patch(
|
||||
"habluetooth.scanner.OriginalBleakScanner",
|
||||
return_value=scanner,
|
||||
),
|
||||
patch(
|
||||
"habluetooth.util.recover_adapter", return_value=True
|
||||
) as mock_recover_adapter,
|
||||
):
|
||||
await async_setup_with_one_adapter(hass)
|
||||
|
||||
assert called_start == 4
|
||||
|
||||
assert len(mock_recover_adapter.mock_calls) == 1
|
||||
assert "Waiting for adapter to initialize" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("one_adapter")
|
||||
async def test_restart_takes_longer_than_watchdog_time(
|
||||
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""Test we do not try to recover the adapter again if the restart is still in progress."""
|
||||
|
||||
release_start_event = asyncio.Event()
|
||||
called_start = 0
|
||||
|
||||
class MockBleakScanner:
|
||||
async def start(self, *args, **kwargs):
|
||||
"""Mock Start."""
|
||||
nonlocal called_start
|
||||
called_start += 1
|
||||
if called_start == 1:
|
||||
return
|
||||
await release_start_event.wait()
|
||||
|
||||
async def stop(self, *args, **kwargs):
|
||||
"""Mock Start."""
|
||||
|
||||
@property
|
||||
def discovered_devices(self):
|
||||
"""Mock discovered_devices."""
|
||||
return []
|
||||
|
||||
def register_detection_callback(self, callback: AdvertisementDataCallback):
|
||||
"""Mock Register Detection Callback."""
|
||||
|
||||
scanner = MockBleakScanner()
|
||||
start_time_monotonic = time.monotonic()
|
||||
|
||||
with (
|
||||
patch(
|
||||
"habluetooth.scanner.ADAPTER_INIT_TIME",
|
||||
0,
|
||||
),
|
||||
patch_bluetooth_time(
|
||||
start_time_monotonic,
|
||||
),
|
||||
patch(
|
||||
"habluetooth.scanner.OriginalBleakScanner",
|
||||
return_value=scanner,
|
||||
),
|
||||
patch("habluetooth.util.recover_adapter", return_value=True),
|
||||
):
|
||||
await async_setup_with_one_adapter(hass)
|
||||
|
||||
assert called_start == 1
|
||||
|
||||
# Now force a recover adapter 2x
|
||||
for _ in range(2):
|
||||
with patch_bluetooth_time(
|
||||
start_time_monotonic
|
||||
+ SCANNER_WATCHDOG_TIMEOUT
|
||||
+ SCANNER_WATCHDOG_INTERVAL.total_seconds(),
|
||||
):
|
||||
async_fire_time_changed(
|
||||
hass, dt_util.utcnow() + SCANNER_WATCHDOG_INTERVAL
|
||||
)
|
||||
await asyncio.sleep(0)
|
||||
|
||||
# Now release the start event
|
||||
release_start_event.set()
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert "already restarting" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.skipif("platform.system() != 'Darwin'")
|
||||
@pytest.mark.usefixtures("macos_adapter")
|
||||
async def test_setup_and_stop_macos(
|
||||
hass: HomeAssistant, mock_bleak_scanner_start: MagicMock
|
||||
) -> None:
|
||||
"""Test we enable use_bdaddr on MacOS."""
|
||||
entry = MockConfigEntry(
|
||||
domain=bluetooth.DOMAIN,
|
||||
data={},
|
||||
unique_id="00:00:00:00:00:00",
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
init_kwargs = None
|
||||
|
||||
class MockBleakScanner:
|
||||
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
||||
"""Init the scanner."""
|
||||
nonlocal init_kwargs
|
||||
init_kwargs = kwargs
|
||||
|
||||
async def start(self, *args, **kwargs):
|
||||
"""Start the scanner."""
|
||||
|
||||
async def stop(self, *args, **kwargs):
|
||||
"""Stop the scanner."""
|
||||
|
||||
def register_detection_callback(self, *args, **kwargs):
|
||||
"""Register a callback."""
|
||||
|
||||
with patch(
|
||||
"habluetooth.scanner.OriginalBleakScanner",
|
||||
MockBleakScanner,
|
||||
):
|
||||
assert await async_setup_component(
|
||||
hass, bluetooth.DOMAIN, {bluetooth.DOMAIN: {}}
|
||||
)
|
||||
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert init_kwargs == {
|
||||
"detection_callback": ANY,
|
||||
"scanning_mode": "active",
|
||||
"cb": {"use_bdaddr": True},
|
||||
}
|
||||
55
home-assistant/tests/components/bluetooth/test_usage.py
Normal file
55
home-assistant/tests/components/bluetooth/test_usage.py
Normal file
@@ -0,0 +1,55 @@
|
||||
"""Tests for the Bluetooth integration."""
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import bleak
|
||||
from habluetooth.usage import (
|
||||
install_multiple_bleak_catcher,
|
||||
uninstall_multiple_bleak_catcher,
|
||||
)
|
||||
from habluetooth.wrappers import HaBleakClientWrapper, HaBleakScannerWrapper
|
||||
import pytest
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from . import generate_ble_device
|
||||
|
||||
MOCK_BLE_DEVICE = generate_ble_device(
|
||||
"00:00:00:00:00:00",
|
||||
"any",
|
||||
delegate="",
|
||||
details={"path": "/dev/hci0/device"},
|
||||
rssi=-127,
|
||||
)
|
||||
|
||||
|
||||
async def test_multiple_bleak_scanner_instances(hass: HomeAssistant) -> None:
|
||||
"""Test creating multiple BleakScanners without an integration."""
|
||||
install_multiple_bleak_catcher()
|
||||
|
||||
instance = bleak.BleakScanner()
|
||||
|
||||
assert isinstance(instance, HaBleakScannerWrapper)
|
||||
|
||||
uninstall_multiple_bleak_catcher()
|
||||
|
||||
with patch("bleak.get_platform_scanner_backend_type"):
|
||||
instance = bleak.BleakScanner()
|
||||
|
||||
assert not isinstance(instance, HaBleakScannerWrapper)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth")
|
||||
async def test_wrapping_bleak_client(hass: HomeAssistant) -> None:
|
||||
"""Test we wrap BleakClient."""
|
||||
install_multiple_bleak_catcher()
|
||||
|
||||
instance = bleak.BleakClient(MOCK_BLE_DEVICE)
|
||||
|
||||
assert isinstance(instance, HaBleakClientWrapper)
|
||||
|
||||
uninstall_multiple_bleak_catcher()
|
||||
|
||||
instance = bleak.BleakClient(MOCK_BLE_DEVICE)
|
||||
|
||||
assert not isinstance(instance, HaBleakClientWrapper)
|
||||
427
home-assistant/tests/components/bluetooth/test_wrappers.py
Normal file
427
home-assistant/tests/components/bluetooth/test_wrappers.py
Normal file
@@ -0,0 +1,427 @@
|
||||
"""Tests for the Bluetooth integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from unittest.mock import patch
|
||||
|
||||
import bleak
|
||||
from bleak.backends.device import BLEDevice
|
||||
from bleak.backends.scanner import AdvertisementData
|
||||
from bleak.exc import BleakError
|
||||
from habluetooth.usage import (
|
||||
install_multiple_bleak_catcher,
|
||||
uninstall_multiple_bleak_catcher,
|
||||
)
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.bluetooth import (
|
||||
MONOTONIC_TIME,
|
||||
BaseHaRemoteScanner,
|
||||
HaBluetoothConnector,
|
||||
HomeAssistantBluetoothManager,
|
||||
)
|
||||
from homeassistant.core import CALLBACK_TYPE, HomeAssistant
|
||||
|
||||
from . import _get_manager, generate_advertisement_data, generate_ble_device
|
||||
|
||||
|
||||
@contextmanager
|
||||
def mock_shutdown(manager: HomeAssistantBluetoothManager) -> Iterator[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: None,
|
||||
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) -> None:
|
||||
"""Initialize the fake bleak client."""
|
||||
self._device_path = "/dev/test"
|
||||
self._device = address_or_ble_device
|
||||
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
|
||||
|
||||
|
||||
class FakeBleakClientFailsToConnect(BaseFakeBleakClient):
|
||||
"""Fake bleak client that fails to connect."""
|
||||
|
||||
async def connect(self, *args, **kwargs):
|
||||
"""Connect."""
|
||||
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(
|
||||
hass: HomeAssistant,
|
||||
) -> tuple[
|
||||
dict[str, tuple[BLEDevice, AdvertisementData]], CALLBACK_TYPE, CALLBACK_TYPE
|
||||
]:
|
||||
"""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.usefixtures("enable_bluetooth", "two_adapters")
|
||||
async def test_test_switch_adapters_when_out_of_slots(
|
||||
hass: HomeAssistant,
|
||||
install_bleak_catcher,
|
||||
mock_platform_client,
|
||||
) -> None:
|
||||
"""Ensure we try another scanner when one runs out of slots."""
|
||||
manager = _get_manager()
|
||||
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices(
|
||||
hass
|
||||
)
|
||||
# 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)
|
||||
assert await client.connect() is True
|
||||
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):
|
||||
if "hci1" in ble_device.details["path"]:
|
||||
return True
|
||||
return False
|
||||
|
||||
with (
|
||||
patch.object(manager.slot_manager, "release_slot") as release_slot_mock,
|
||||
patch.object(
|
||||
manager.slot_manager, "allocate_slot", _allocate_slot_mock
|
||||
) as allocate_slot_mock,
|
||||
):
|
||||
ble_device = hci0_device_advs["00:00:00:00:00:03"][0]
|
||||
client = bleak.BleakClient(ble_device)
|
||||
assert await client.connect() is True
|
||||
assert release_slot_mock.call_count == 0
|
||||
|
||||
cancel_hci0()
|
||||
cancel_hci1()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "two_adapters")
|
||||
async def test_release_slot_on_connect_failure(
|
||||
hass: HomeAssistant,
|
||||
install_bleak_catcher,
|
||||
mock_platform_client_that_fails_to_connect,
|
||||
) -> None:
|
||||
"""Ensure the slot gets released on connection failure."""
|
||||
manager = _get_manager()
|
||||
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices(
|
||||
hass
|
||||
)
|
||||
# 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)
|
||||
assert await client.connect() is False
|
||||
assert allocate_slot_mock.call_count == 1
|
||||
assert release_slot_mock.call_count == 1
|
||||
|
||||
cancel_hci0()
|
||||
cancel_hci1()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "two_adapters")
|
||||
async def test_release_slot_on_connect_exception(
|
||||
hass: HomeAssistant,
|
||||
install_bleak_catcher,
|
||||
mock_platform_client_that_raises_on_connect,
|
||||
) -> None:
|
||||
"""Ensure the slot gets released on connection exception."""
|
||||
manager = _get_manager()
|
||||
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices(
|
||||
hass
|
||||
)
|
||||
# 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.usefixtures("enable_bluetooth", "two_adapters")
|
||||
async def test_we_switch_adapters_on_failure(
|
||||
hass: HomeAssistant,
|
||||
install_bleak_catcher,
|
||||
) -> None:
|
||||
"""Ensure we try the next best adapter after a failure."""
|
||||
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices(
|
||||
hass
|
||||
)
|
||||
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."""
|
||||
|
||||
async def connect(self, *args, **kwargs):
|
||||
"""Connect."""
|
||||
if "/hci0/" in self._device.details["path"]:
|
||||
return False
|
||||
return True
|
||||
|
||||
with patch(
|
||||
"habluetooth.wrappers.get_platform_client_backend_type",
|
||||
return_value=FakeBleakClientFailsHCI0Only,
|
||||
):
|
||||
assert await client.connect() is False
|
||||
|
||||
with patch(
|
||||
"habluetooth.wrappers.get_platform_client_backend_type",
|
||||
return_value=FakeBleakClientFailsHCI0Only,
|
||||
):
|
||||
assert await client.connect() is False
|
||||
|
||||
# After two tries we should switch to hci1
|
||||
with patch(
|
||||
"habluetooth.wrappers.get_platform_client_backend_type",
|
||||
return_value=FakeBleakClientFailsHCI0Only,
|
||||
):
|
||||
assert await client.connect() is True
|
||||
|
||||
# ..and we remember that hci1 works as long as the client doesn't change
|
||||
with patch(
|
||||
"habluetooth.wrappers.get_platform_client_backend_type",
|
||||
return_value=FakeBleakClientFailsHCI0Only,
|
||||
):
|
||||
assert await client.connect() is True
|
||||
|
||||
# If we replace the client, we should try hci0 again
|
||||
client = bleak.BleakClient(ble_device)
|
||||
|
||||
with patch(
|
||||
"habluetooth.wrappers.get_platform_client_backend_type",
|
||||
return_value=FakeBleakClientFailsHCI0Only,
|
||||
):
|
||||
assert await client.connect() is False
|
||||
cancel_hci0()
|
||||
cancel_hci1()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "two_adapters")
|
||||
async def test_passing_subclassed_str_as_address(
|
||||
hass: HomeAssistant,
|
||||
install_bleak_catcher,
|
||||
) -> None:
|
||||
"""Ensure the client wrapper can handle a subclassed str as the address."""
|
||||
_, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices(hass)
|
||||
|
||||
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 True
|
||||
|
||||
with patch(
|
||||
"habluetooth.wrappers.get_platform_client_backend_type",
|
||||
return_value=FakeBleakClient,
|
||||
):
|
||||
assert await client.connect() is True
|
||||
|
||||
cancel_hci0()
|
||||
cancel_hci1()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "two_adapters")
|
||||
async def test_raise_after_shutdown(
|
||||
hass: HomeAssistant,
|
||||
install_bleak_catcher,
|
||||
mock_platform_client_that_raises_on_connect,
|
||||
) -> None:
|
||||
"""Ensure the slot gets released on connection exception."""
|
||||
manager = _get_manager()
|
||||
hci0_device_advs, cancel_hci0, cancel_hci1 = _generate_scanners_with_fake_devices(
|
||||
hass
|
||||
)
|
||||
# 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()
|
||||
Reference in New Issue
Block a user