From 23505437c98529f692ab2dc0f5c3bdb5c9b7e3bd Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Tue, 16 Apr 2024 16:27:49 -0500 Subject: [PATCH] fix: ensure discovered_devices returns an empty list for offline scanners (#35) --- src/habluetooth/scanner.py | 10 +++++----- tests/test_scanner.py | 9 +++++++++ 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/habluetooth/scanner.py b/src/habluetooth/scanner.py index 316e66c..bc22945 100644 --- a/src/habluetooth/scanner.py +++ b/src/habluetooth/scanner.py @@ -4,7 +4,7 @@ import asyncio import logging import platform -from typing import TYPE_CHECKING, Any, Coroutine, Iterable +from typing import Any, Coroutine, Iterable import bleak from bleak import BleakError @@ -166,8 +166,8 @@ def _create_background_task(self, coro: Coroutine[Any, Any, None]) -> None: @property def discovered_devices(self) -> list[BLEDevice]: """Return a list of discovered devices.""" - if TYPE_CHECKING: - assert self.scanner is not None + if not self.scanner: + return [] return self.scanner.discovered_devices @property @@ -175,8 +175,8 @@ def discovered_devices_and_advertisement_data( self, ) -> dict[str, tuple[BLEDevice, AdvertisementData]]: """Return a list of discovered devices and advertisement data.""" - if TYPE_CHECKING: - assert self.scanner is not None + if not self.scanner: + return {} return self.scanner.discovered_devices_and_advertisement_data @property diff --git a/tests/test_scanner.py b/tests/test_scanner.py index 58c97b9..95a8111 100644 --- a/tests/test_scanner.py +++ b/tests/test_scanner.py @@ -55,6 +55,15 @@ def manager(): return manager +@pytest.mark.asyncio +async def test_empty_data_no_scanner() -> None: + """Test we handle empty data.""" + scanner = HaScanner(BluetoothScanningMode.ACTIVE, "hci0", "AA:BB:CC:DD:EE:FF") + scanner.async_setup() + assert scanner.discovered_devices == [] + assert scanner.discovered_devices_and_advertisement_data == {} + + @pytest.mark.asyncio @pytest.mark.skipif("platform.system() != 'Linux'") async def test_dbus_socket_missing_in_container(