Debian Codegraph @

tests/__init__.py

raw
1 import asyncio
2 import time
3 import types
4 from collections.abc import Generator
5 from contextlib import contextmanager
6 from datetime import UTC, datetime
7 from functools import partial
8 from typing import Any
9 from unittest.mock import MagicMock, patch
10
11 from bleak.backends.scanner import (
12 AdvertisementData,
13 AdvertisementDataCallback,
14 BLEDevice,
15 )
16 from bluetooth_data_tools import monotonic_time_coarse
17
18 from habluetooth import BaseHaRemoteScanner, get_manager
19 from habluetooth.models import BluetoothServiceInfoBleak
20
21 utcnow = partial(datetime.now, UTC)
22
23 HCI0_SOURCE_ADDRESS = "AA:BB:CC:DD:EE:00"
24 HCI1_SOURCE_ADDRESS = "AA:BB:CC:DD:EE:11"
25 NON_CONNECTABLE_REMOTE_SOURCE_ADDRESS = "AA:BB:CC:DD:EE:FF"
26
27 _MONOTONIC_RESOLUTION = time.get_clock_info("monotonic").resolution
28
29 ADVERTISEMENT_DATA_DEFAULTS = {
30 "local_name": "Unknown",
31 "manufacturer_data": {},
32 "service_data": {},
33 "service_uuids": [],
34 "rssi": -127,
35 "platform_data": ((),),
36 "tx_power": -127,
37 }
38
39
40 BLE_DEVICE_DEFAULTS = {
41 "name": None,
42 "details": None,
43 }
44
45
46 def generate_advertisement_data(**kwargs: Any) -> AdvertisementData:
47 """Generate advertisement data with defaults."""
48 new = kwargs.copy()
49 for key, value in ADVERTISEMENT_DATA_DEFAULTS.items():
50 new.setdefault(key, value)
51 return AdvertisementData(**new)
52
53
54 def generate_ble_device(
55 address: str | None = None,
56 name: str | None = None,
57 details: Any | None = None,
58 **kwargs: Any,
59 ) -> BLEDevice:
60 """
61 Generate a BLEDevice with defaults.
62
63 Extra kwargs (e.g. legacy ``rssi``) are silently dropped — bleak 3.0
64 removed those fields from BLEDevice, and passing them now warns.
65 """
66 new: dict[str, Any] = {}
67 if address is not None:
68 new["address"] = address
69 if name is not None:
70 new["name"] = name
71 if details is not None:
72 new["details"] = details
73 for key, value in BLE_DEVICE_DEFAULTS.items():
74 new.setdefault(key, value)
75 # Only forward kwargs BLEDevice still accepts in bleak 3.0+.
76 for key in ("address", "name", "details"):
77 if key in kwargs:
78 new[key] = kwargs[key]
79 return BLEDevice(**new)
80
81
82 @contextmanager
83 def patch_bluetooth_time(mock_time: float) -> Generator[Any, None, None]:
84 """Patch the bluetooth time."""
85 with (
86 patch("habluetooth.base_scanner.monotonic_time_coarse", return_value=mock_time),
87 patch("habluetooth.manager.monotonic_time_coarse", return_value=mock_time),
88 patch(
89 "habluetooth.scanner_bleak.monotonic_time_coarse", return_value=mock_time
90 ),
91 ):
92 yield
93
94
95 def async_fire_time_changed(utc_datetime: datetime) -> None:
96 timestamp = utc_datetime.timestamp()
97 loop = asyncio.get_running_loop()
98 for task in list(loop._scheduled): # type: ignore[attr-defined]
99 if not isinstance(task, asyncio.TimerHandle):
100 continue
101 if task.cancelled():
102 continue
103
104 mock_seconds_into_future = timestamp - time.time()
105 future_seconds = task.when() - (loop.time() + _MONOTONIC_RESOLUTION)
106
107 if mock_seconds_into_future >= future_seconds:
108 task._run()
109 task.cancel()
110
111
112 class MockBleakClient:
113 pass
114
115
116 class MockBleakScanner:
117 """
118 Drop-in fake for ``bleak.BleakScanner`` that satisfies ``HaScanner``.
119
120 Provides the four attributes ``HaScanner`` actually touches
121 (``start`` / ``stop`` / ``discovered_devices`` /
122 ``register_detection_callback``) plus a ``_backend`` namespace
123 with ``_scanning_mode`` for the active-window toggle path.
124
125 Subclass to override individual methods for failure injection
126 (e.g. ``async def start(self): raise BleakError(...)``); each
127 instance owns its own ``_backend`` so mutations don't leak
128 between tests.
129 """
130
131 def __init__(self) -> None:
132 # Typed as ``Any`` so subclasses can substitute custom backend
133 # objects (e.g. for AttributeError injection tests).
134 self._backend: Any = types.SimpleNamespace(_scanning_mode="passive")
135
136 async def start(self) -> None:
137 """No-op start."""
138
139 async def stop(self) -> None:
140 """No-op stop."""
141
142 @property
143 def discovered_devices(self) -> list[BLEDevice]:
144 """No devices by default; override for fixture-style fakes."""
145 return []
146
147 @property
148 def discovered_devices_and_advertisement_data(
149 self,
150 ) -> dict[str, tuple[BLEDevice, AdvertisementData]]:
151 """No discoveries by default; override for fixture-style fakes."""
152 return {}
153
154 def register_detection_callback(self, callback: AdvertisementDataCallback) -> None:
155 """No-op detection-callback registration."""
156
157
158 class InjectableRemoteScanner(BaseHaRemoteScanner):
159 """
160 Remote scanner that exposes test-only ``inject_advertisement`` helpers.
161
162 Replaces the near-identical ``FakeScanner`` / ``_SeedFakeScanner``
163 classes that used to live in test_base_scanner / test_name_cache /
164 test_wrappers. ``device.details`` (when present) is merged into the
165 advertisement ``details`` dict so callers that route via DBus paths
166 (e.g. test_wrappers) keep the path key, while callers that pass a
167 ``details``-less device (the default) see only the test marker.
168 """
169
170 def inject_advertisement(
171 self,
172 device: BLEDevice,
173 advertisement_data: AdvertisementData,
174 now: float | None = None,
175 ) -> None:
176 """Inject an advertisement through the scanner's normal entry point."""
177 self._async_on_advertisement(
178 device.address,
179 advertisement_data.rssi,
180 device.name,
181 advertisement_data.service_uuids,
182 advertisement_data.service_data,
183 advertisement_data.manufacturer_data,
184 advertisement_data.tx_power,
185 (device.details or {}) | {"scanner_specific_data": "test"},
186 now if now is not None else monotonic_time_coarse(),
187 )
188
189 def inject_raw_advertisement(
190 self,
191 address: str,
192 rssi: int,
193 adv: bytes,
194 now: float | None = None,
195 ) -> None:
196 """Inject a raw advertisement through the scanner's normal entry point."""
197 self._async_on_raw_advertisement(
198 address,
199 rssi,
200 adv,
201 {"scanner_specific_data": "test"},
202 now if now is not None else monotonic_time_coarse(),
203 )
204
205
206 def patch_bleak_scanner_factory(factory: Any) -> Any:
207 """
208 Patch ``OriginalBleakScanner`` to call ``factory(*args, **kwargs)``.
209
210 Convenience wrapper to avoid the noisy
211 ``patch(..., side_effect=lambda *_a, **_kw: factory())`` ritual
212 used at every mock-scanner site.
213 """
214 return patch(
215 "habluetooth.scanner_bleak.OriginalBleakScanner",
216 side_effect=lambda *_a, **_kw: factory(),
217 )
218
219
220 def inject_advertisement(device: BLEDevice, adv: AdvertisementData) -> None:
221 """Inject an advertisement into the manager."""
222 return inject_advertisement_with_source(device, adv, "local")
223
224
225 def inject_advertisement_with_source(
226 device: BLEDevice, adv: AdvertisementData, source: str
227 ) -> None:
228 """Inject an advertisement into the manager from a specific source."""
229 inject_advertisement_with_time_and_source(device, adv, time.monotonic(), source)
230
231
232 def inject_advertisement_with_time_and_source(
233 device: BLEDevice,
234 adv: AdvertisementData,
235 time: float,
236 source: str,
237 ) -> None:
238 """Inject an advertisement into the manager from a specific source at a time."""
239 inject_advertisement_with_time_and_source_connectable(
240 device, adv, time, source, True
241 )
242
243
244 def inject_advertisement_with_time_and_source_connectable(
245 device: BLEDevice,
246 adv: AdvertisementData,
247 time: float,
248 source: str,
249 connectable: bool,
250 ) -> None:
251 """
252 Inject an advertisement into the manager from a specific source at a time.
253
254 As well as and connectable status.
255 """
256 manager = get_manager()
257
258 manager.scanner_adv_received(
259 BluetoothServiceInfoBleak(
260 name=adv.local_name or device.name or device.address,
261 address=device.address,
262 rssi=adv.rssi,
263 manufacturer_data=adv.manufacturer_data,
264 service_data=adv.service_data,
265 service_uuids=adv.service_uuids,
266 source=source,
267 device=device,
268 advertisement=adv,
269 connectable=connectable,
270 time=time,
271 tx_power=adv.tx_power,
272 )
273 )
274
275
276 @contextmanager
277 def patch_discovered_devices(
278 mock_discovered: list[BLEDevice],
279 ) -> Generator[None, None, None]:
280 """Mock the combined best path to discovered devices from all the scanners."""
281 manager = get_manager()
282 original_all_history = manager._all_history
283 original_connectable_history = manager._connectable_history
284 manager._connectable_history = {}
285 manager._all_history = {
286 device.address: MagicMock(device=device) for device in mock_discovered
287 }
288 yield
289 manager._all_history = original_all_history
290 manager._connectable_history = original_connectable_history