Debian Codegraph @

tests/channels/test_bluez.py

raw
1 """Tests for the BlueZ management API module."""
2
3 from __future__ import annotations
4
5 import asyncio
6 import logging
7 from typing import TYPE_CHECKING, Any
8 from unittest.mock import ANY, Mock, patch
9
10 import pytest
11 from btsocket.btmgmt_socket import BluetoothSocketError
12
13 from habluetooth.channels.bluez import (
14 IO_CAPABILITY_NO_INPUT_NO_OUTPUT,
15 MGMT_OP_ADD_ADV_PATTERNS_MONITOR,
16 MGMT_OP_DISCONNECT,
17 MGMT_OP_LOAD_LONG_TERM_KEYS,
18 MGMT_OP_PAIR_DEVICE,
19 MGMT_OP_REMOVE_ADV_MONITOR,
20 MGMT_OP_START_DISCOVERY,
21 MGMT_OP_STOP_DISCOVERY,
22 MGMT_OP_UNPAIR_DEVICE,
23 MGMT_OP_USER_CONFIRM_NEG_REPLY,
24 MGMT_OP_USER_CONFIRM_REPLY,
25 MGMT_OP_USER_PASSKEY_NEG_REPLY,
26 MGMT_OP_USER_PASSKEY_REPLY,
27 SCAN_TYPE_LE,
28 AuthenticationFailed,
29 BluetoothMGMTProtocol,
30 LongTermKey,
31 MGMTBluetoothCtl,
32 NewLongTermKey,
33 UserConfirmationRequest,
34 UserPasskeyRequest,
35 bytes_mac_to_str,
36 make_bluez_details,
37 )
38 from habluetooth.const import (
39 BDADDR_LE_PUBLIC,
40 BDADDR_LE_RANDOM,
41 FAST_CONN_LATENCY,
42 FAST_CONN_TIMEOUT,
43 FAST_MAX_CONN_INTERVAL,
44 FAST_MIN_CONN_INTERVAL,
45 MEDIUM_CONN_LATENCY,
46 MEDIUM_CONN_TIMEOUT,
47 MEDIUM_MAX_CONN_INTERVAL,
48 MEDIUM_MIN_CONN_INTERVAL,
49 ConnectParams,
50 )
51 from habluetooth.scanner_bleak import HaScanner
52
53 if TYPE_CHECKING:
54 from collections.abc import Callable
55
56 from habluetooth.base_scanner import BaseHaScanner
57
58
59 class MockHaScanner(HaScanner):
60 """Mock HaScanner for testing with Cython."""
61
62 def __init__(self):
63 """Initialize without calling parent __init__ to avoid BleakScanner setup."""
64 self.source = "test"
65 self.adapter = "hci0"
66 self.connectable = True
67 # Mock the method that will be called
68 self._async_on_raw_advertisement: Any = Mock()
69
70
71 @pytest.fixture
72 def event_loop():
73 """Create and manage event loop for tests."""
74 loop = asyncio.new_event_loop()
75 yield loop
76 loop.close()
77
78
79 @pytest.fixture
80 def mock_scanner() -> MockHaScanner:
81 """Create a mock scanner for testing."""
82 return MockHaScanner()
83
84
85 @pytest.fixture
86 def mock_transport() -> Mock:
87 """Create a mock transport."""
88 transport = Mock()
89 transport.write = Mock()
90 # Create a mock socket for direct writes
91 mock_socket = Mock()
92 mock_socket.send = Mock(return_value=6) # Default to successful send
93 transport.get_extra_info = Mock(return_value=mock_socket)
94 return transport
95
96
97 def test_connection_made(
98 event_loop: asyncio.AbstractEventLoop, mock_transport: Mock
99 ) -> None:
100 """Test connection_made sets up the protocol correctly."""
101 future = event_loop.create_future()
102 scanners: dict[int, BaseHaScanner] = {}
103 on_connection_lost = Mock()
104
105 is_shutting_down = Mock(return_value=False)
106 mock_sock = Mock()
107 protocol = BluetoothMGMTProtocol(
108 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
109 )
110 protocol.connection_made(mock_transport)
111
112 assert protocol.transport is mock_transport
113 assert future.done()
114 assert future.result() is None
115
116
117 def test_connection_lost(
118 event_loop: asyncio.AbstractEventLoop, mock_transport: Mock
119 ) -> None:
120 """Test connection_lost handles disconnection."""
121 future = event_loop.create_future()
122 scanners: dict[int, BaseHaScanner] = {}
123 on_connection_lost = Mock()
124
125 is_shutting_down = Mock(return_value=False)
126 mock_sock = Mock()
127 protocol = BluetoothMGMTProtocol(
128 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
129 )
130 protocol.connection_made(mock_transport)
131
132 # Test with exception
133 protocol.connection_lost(Exception("Test error"))
134 assert protocol.transport is None
135 on_connection_lost.assert_called_once()
136
137
138 def test_connection_lost_no_exception(
139 event_loop: asyncio.AbstractEventLoop,
140 mock_transport: Mock,
141 caplog: pytest.LogCaptureFixture,
142 ) -> None:
143 """Test connection_lost without exception."""
144 future = event_loop.create_future()
145 scanners: dict[int, BaseHaScanner] = {}
146 on_connection_lost = Mock()
147
148 is_shutting_down = Mock(return_value=False)
149 mock_sock = Mock()
150 protocol = BluetoothMGMTProtocol(
151 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
152 )
153 protocol.connection_made(mock_transport)
154
155 # Test without exception
156 protocol.connection_lost(None)
157 assert "Bluetooth management socket connection closed" in caplog.text
158
159
160 def test_data_received_device_found(
161 event_loop: asyncio.AbstractEventLoop, mock_scanner: MockHaScanner
162 ) -> None:
163 """Test data_received handles DEVICE_FOUND event."""
164 future = event_loop.create_future()
165 scanners: dict[int, BaseHaScanner] = {0: mock_scanner}
166 on_connection_lost = Mock()
167
168 is_shutting_down = Mock(return_value=False)
169 mock_sock = Mock()
170 protocol = BluetoothMGMTProtocol(
171 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
172 )
173
174 # Create a DEVICE_FOUND event (event_code 0x0012). Header layout is
175 # event_code (2), controller_idx (2), param_len (2); params layout
176 # is address (6), address_type (1), rssi (1), flags (4),
177 # ad_data_len (2), then ad_data.
178 ad_data = b"\x02\x01\x06" # Simple advertisement data
179 param_len = 6 + 1 + 1 + 4 + 2 + len(ad_data)
180
181 header = b"\x12\x00" # DEVICE_FOUND
182 header += b"\x00\x00" # controller_idx = 0
183 header += param_len.to_bytes(2, "little")
184
185 params = b"\xaa\xbb\xcc\xdd\xee\xff" # address (reversed)
186 params += b"\x01" # address_type
187 params += b"\xc8" # rssi = -56 (200 - 256)
188 params += b"\x00\x00\x00\x00" # flags
189 params += len(ad_data).to_bytes(2, "little") # ad_data_len
190 params += ad_data
191
192 protocol.data_received(header + params)
193
194 expected_address = bytes_mac_to_str(b"\xaa\xbb\xcc\xdd\xee\xff")
195 mock_scanner._async_on_raw_advertisement.assert_called_once_with(
196 expected_address,
197 -56,
198 ad_data,
199 make_bluez_details(expected_address, "hci0"),
200 ANY,
201 )
202
203
204 @pytest.mark.parametrize(
205 ("rssi_byte", "expected_rssi"),
206 [
207 (b"\x00", 0), # 0
208 (b"\x64", 100), # +100
209 (b"\x7f", 127), # +127 (mgmt "RSSI not available" sentinel, unchanged)
210 (b"\x80", -128), # int8 floor — must convert, not stay +128
211 (b"\x81", -127),
212 (b"\xc8", -56), # 200 - 256
213 (b"\xff", -1), # -1
214 ],
215 )
216 def test_data_received_device_found_rssi_int8_conversion(
217 event_loop: asyncio.AbstractEventLoop,
218 mock_scanner: MockHaScanner,
219 rssi_byte: bytes,
220 expected_rssi: int,
221 ) -> None:
222 """The raw rssi byte must be decoded as a signed int8 (0x80 -> -128)."""
223 future = event_loop.create_future()
224 scanners: dict[int, BaseHaScanner] = {0: mock_scanner}
225 protocol = BluetoothMGMTProtocol(
226 future, scanners, Mock(), Mock(return_value=False), Mock(), {}
227 )
228
229 ad_data = b"\x02\x01\x06"
230 param_len = 6 + 1 + 1 + 4 + 2 + len(ad_data)
231
232 header = b"\x12\x00" # DEVICE_FOUND
233 header += b"\x00\x00" # controller_idx = 0
234 header += param_len.to_bytes(2, "little")
235
236 params = b"\xaa\xbb\xcc\xdd\xee\xff" # address (reversed)
237 params += b"\x01" # address_type
238 params += rssi_byte # rssi
239 params += b"\x00\x00\x00\x00" # flags
240 params += len(ad_data).to_bytes(2, "little") # ad_data_len
241 params += ad_data
242
243 protocol.data_received(header + params)
244
245 expected_address = bytes_mac_to_str(b"\xaa\xbb\xcc\xdd\xee\xff")
246 mock_scanner._async_on_raw_advertisement.assert_called_once_with(
247 expected_address,
248 expected_rssi,
249 ad_data,
250 make_bluez_details(expected_address, "hci0"),
251 ANY,
252 )
253
254
255 def test_data_received_adv_monitor_device_found(
256 event_loop: asyncio.AbstractEventLoop, mock_scanner: MockHaScanner
257 ) -> None:
258 """Test data_received handles ADV_MONITOR_DEVICE_FOUND event."""
259 future = event_loop.create_future()
260 scanners: dict[int, BaseHaScanner] = {0: mock_scanner}
261 on_connection_lost = Mock()
262
263 is_shutting_down = Mock(return_value=False)
264 mock_sock = Mock()
265 protocol = BluetoothMGMTProtocol(
266 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
267 )
268
269 # Create an ADV_MONITOR_DEVICE_FOUND event (event_code 0x002F)
270 # Has 2 extra bytes at the beginning of params
271 ad_data = b"\x02\x01\x06"
272 param_len = 2 + 6 + 1 + 1 + 4 + 2 + len(ad_data)
273
274 header = b"\x2f\x00" # ADV_MONITOR_DEVICE_FOUND
275 header += b"\x00\x00" # controller_idx = 0
276 header += param_len.to_bytes(2, "little")
277
278 params = b"\x00\x00" # 2 extra bytes
279 params += b"\xaa\xbb\xcc\xdd\xee\xff" # address
280 params += b"\x02" # address_type
281 params += b"\x64" # rssi = 100 (positive, no conversion needed)
282 params += b"\x00\x00\x00\x00" # flags
283 params += len(ad_data).to_bytes(2, "little")
284 params += ad_data
285
286 protocol.data_received(header + params)
287
288 expected_address = bytes_mac_to_str(b"\xaa\xbb\xcc\xdd\xee\xff")
289 mock_scanner._async_on_raw_advertisement.assert_called_once_with(
290 expected_address,
291 100,
292 ad_data,
293 make_bluez_details(expected_address, "hci0"),
294 ANY,
295 )
296
297
298 def test_data_received_cmd_complete_success(
299 event_loop: asyncio.AbstractEventLoop,
300 caplog: pytest.LogCaptureFixture,
301 ) -> None:
302 """Test data_received handles successful MGMT_EV_CMD_COMPLETE."""
303 future = event_loop.create_future()
304 scanners: dict[int, BaseHaScanner] = {}
305 on_connection_lost = Mock()
306
307 is_shutting_down = Mock(return_value=False)
308 mock_sock = Mock()
309 protocol = BluetoothMGMTProtocol(
310 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
311 )
312
313 # Create a CMD_COMPLETE event for LOAD_CONN_PARAM
314 header = b"\x01\x00" # MGMT_EV_CMD_COMPLETE
315 header += b"\x00\x00" # controller_idx = 0
316 header += b"\x03\x00" # param_len = 3
317
318 params = b"\x35\x00" # opcode = MGMT_OP_LOAD_CONN_PARAM
319 params += b"\x00" # status = 0 (success)
320
321 protocol.data_received(header + params)
322
323 assert "Connection parameters loaded successfully" in caplog.text
324
325
326 def test_data_received_cmd_complete_failure(
327 event_loop: asyncio.AbstractEventLoop,
328 caplog: pytest.LogCaptureFixture,
329 ) -> None:
330 """Test data_received handles failed MGMT_EV_CMD_COMPLETE."""
331 future = event_loop.create_future()
332 scanners: dict[int, BaseHaScanner] = {}
333 on_connection_lost = Mock()
334
335 is_shutting_down = Mock(return_value=False)
336 mock_sock = Mock()
337 protocol = BluetoothMGMTProtocol(
338 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
339 )
340
341 # Create a CMD_COMPLETE event with failure
342 header = b"\x01\x00" # MGMT_EV_CMD_COMPLETE
343 header += b"\x01\x00" # controller_idx = 1
344 header += b"\x03\x00" # param_len = 3
345
346 params = b"\x35\x00" # opcode = MGMT_OP_LOAD_CONN_PARAM
347 params += b"\x0c" # status = 12 (Not Supported)
348
349 protocol.data_received(header + params)
350
351 assert "Failed to load conn params: status=12" in caplog.text
352
353
354 def test_data_received_cmd_status(
355 event_loop: asyncio.AbstractEventLoop, caplog: pytest.LogCaptureFixture
356 ) -> None:
357 """Test data_received handles MGMT_EV_CMD_STATUS."""
358 future = event_loop.create_future()
359 scanners: dict[int, BaseHaScanner] = {}
360 on_connection_lost = Mock()
361
362 is_shutting_down = Mock(return_value=False)
363 mock_sock = Mock()
364 protocol = BluetoothMGMTProtocol(
365 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
366 )
367
368 # Create a CMD_STATUS event
369 header = b"\x02\x00" # MGMT_EV_CMD_STATUS
370 header += b"\x00\x00" # controller_idx = 0
371 header += b"\x03\x00" # param_len = 3
372
373 params = b"\x35\x00" # opcode = MGMT_OP_LOAD_CONN_PARAM
374 params += b"\x01" # status = 1 (Unknown Command)
375
376 protocol.data_received(header + params)
377
378 assert "Failed to load conn params: status=1" in caplog.text
379
380
381 def test_data_received_partial_data(
382 event_loop: asyncio.AbstractEventLoop, mock_scanner: MockHaScanner
383 ) -> None:
384 """Test data_received handles partial data correctly."""
385 future = event_loop.create_future()
386 scanners: dict[int, BaseHaScanner] = {0: mock_scanner}
387 on_connection_lost = Mock()
388
389 is_shutting_down = Mock(return_value=False)
390 mock_sock = Mock()
391 protocol = BluetoothMGMTProtocol(
392 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
393 )
394
395 # Create a DEVICE_FOUND event but send it in chunks
396 ad_data = b"\x02\x01\x06"
397 param_len = 6 + 1 + 1 + 4 + 2 + len(ad_data)
398
399 full_data = b"\x12\x00\x00\x00" + param_len.to_bytes(2, "little")
400 full_data += b"\xaa\xbb\xcc\xdd\xee\xff\x01\xc8\x00\x00\x00\x00"
401 full_data += len(ad_data).to_bytes(2, "little") + ad_data
402
403 # Send header first
404 protocol.data_received(full_data[:6])
405 mock_scanner._async_on_raw_advertisement.assert_not_called()
406
407 # Send rest of data
408 protocol.data_received(full_data[6:])
409 mock_scanner._async_on_raw_advertisement.assert_called_once()
410
411
412 def test_data_received_partial_data_split_in_params(
413 event_loop: asyncio.AbstractEventLoop, mock_scanner: MockHaScanner
414 ) -> None:
415 """Test data_received handles data split in the middle of params."""
416 future = event_loop.create_future()
417 scanners: dict[int, BaseHaScanner] = {0: mock_scanner}
418 on_connection_lost = Mock()
419
420 is_shutting_down = Mock(return_value=False)
421 mock_sock = Mock()
422 protocol = BluetoothMGMTProtocol(
423 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
424 )
425
426 # Create a DEVICE_FOUND event
427 ad_data = b"\x02\x01\x06\x03\xff\x00\x01" # Longer ad data
428 param_len = 6 + 1 + 1 + 4 + 2 + len(ad_data)
429
430 full_data = b"\x12\x00\x00\x00" + param_len.to_bytes(2, "little")
431 full_data += b"\xaa\xbb\xcc\xdd\xee\xff\x01\xc8\x00\x00\x00\x00"
432 full_data += len(ad_data).to_bytes(2, "little") + ad_data
433
434 # Split in the middle of the address
435 protocol.data_received(full_data[:10]) # Header + part of address
436 mock_scanner._async_on_raw_advertisement.assert_not_called()
437
438 # Send rest of data
439 protocol.data_received(full_data[10:])
440 expected_address = bytes_mac_to_str(b"\xaa\xbb\xcc\xdd\xee\xff")
441 mock_scanner._async_on_raw_advertisement.assert_called_once_with(
442 expected_address,
443 -56,
444 ad_data,
445 make_bluez_details(expected_address, "hci0"),
446 ANY,
447 )
448
449
450 def test_data_received_multiple_small_chunks(
451 event_loop: asyncio.AbstractEventLoop, mock_scanner: MockHaScanner
452 ) -> None:
453 """Test data_received handles data sent in many small chunks."""
454 future = event_loop.create_future()
455 scanners: dict[int, BaseHaScanner] = {0: mock_scanner}
456 on_connection_lost = Mock()
457
458 is_shutting_down = Mock(return_value=False)
459 mock_sock = Mock()
460 protocol = BluetoothMGMTProtocol(
461 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
462 )
463
464 # Create a DEVICE_FOUND event
465 ad_data = b"\x02\x01\x06"
466 param_len = 6 + 1 + 1 + 4 + 2 + len(ad_data)
467
468 full_data = b"\x12\x00\x00\x00" + param_len.to_bytes(2, "little")
469 full_data += b"\xaa\xbb\xcc\xdd\xee\xff\x01\xc8\x00\x00\x00\x00"
470 full_data += len(ad_data).to_bytes(2, "little") + ad_data
471
472 # Send data byte by byte
473 for i in range(len(full_data)):
474 protocol.data_received(full_data[i : i + 1])
475 if i < len(full_data) - 1:
476 mock_scanner._async_on_raw_advertisement.assert_not_called()
477
478 # After all bytes are sent, callback should be called once
479 mock_scanner._async_on_raw_advertisement.assert_called_once()
480
481
482 def test_data_received_multiple_events_in_one_chunk(
483 event_loop: asyncio.AbstractEventLoop,
484 mock_scanner: Mock,
485 caplog: pytest.LogCaptureFixture,
486 ) -> None:
487 """Test data_received handles multiple events in one data chunk."""
488 future = event_loop.create_future()
489 scanners: dict[int, BaseHaScanner] = {0: mock_scanner}
490 on_connection_lost = Mock()
491
492 is_shutting_down = Mock(return_value=False)
493 mock_sock = Mock()
494 protocol = BluetoothMGMTProtocol(
495 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
496 )
497
498 # Create two events: a DEVICE_FOUND and a CMD_COMPLETE
499 ad_data = b"\x02\x01\x06"
500 param_len1 = 6 + 1 + 1 + 4 + 2 + len(ad_data)
501
502 event1 = b"\x12\x00\x00\x00" + param_len1.to_bytes(2, "little")
503 event1 += b"\xaa\xbb\xcc\xdd\xee\xff\x01\xc8\x00\x00\x00\x00"
504 event1 += len(ad_data).to_bytes(2, "little") + ad_data
505
506 event2 = b"\x01\x00\x00\x00\x03\x00" # CMD_COMPLETE header
507 event2 += b"\x35\x00\x00" # LOAD_CONN_PARAM success
508
509 # Send both events in one chunk
510 protocol.data_received(event1 + event2)
511
512 # Both events should be processed
513 mock_scanner._async_on_raw_advertisement.assert_called_once()
514 assert "Connection parameters loaded successfully" in caplog.text
515
516
517 def test_data_received_partial_then_multiple_events(
518 event_loop: asyncio.AbstractEventLoop, mock_scanner: MockHaScanner
519 ) -> None:
520 """Test partial data followed by multiple complete events."""
521 future = event_loop.create_future()
522 scanners: dict[int, BaseHaScanner] = {0: mock_scanner}
523 on_connection_lost = Mock()
524
525 is_shutting_down = Mock(return_value=False)
526 mock_sock = Mock()
527 protocol = BluetoothMGMTProtocol(
528 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
529 )
530
531 # First event (DEVICE_FOUND)
532 ad_data1 = b"\x02\x01\x06"
533 param_len1 = 6 + 1 + 1 + 4 + 2 + len(ad_data1)
534 event1 = b"\x12\x00\x00\x00" + param_len1.to_bytes(2, "little")
535 event1 += b"\x11\x22\x33\x44\x55\x66\x01\xc8\x00\x00\x00\x00"
536 event1 += len(ad_data1).to_bytes(2, "little") + ad_data1
537
538 # Second event (ADV_MONITOR_DEVICE_FOUND)
539 ad_data2 = b"\x03\xff\x00\x01"
540 param_len2 = 2 + 6 + 1 + 1 + 4 + 2 + len(ad_data2)
541 event2 = b"\x2f\x00\x00\x00" + param_len2.to_bytes(2, "little")
542 event2 += b"\x00\x00" # Extra 2 bytes
543 event2 += b"\x77\x88\x99\xaa\xbb\xcc\x02\x64\x00\x00\x00\x00"
544 event2 += len(ad_data2).to_bytes(2, "little") + ad_data2
545
546 # Send partial first event
547 protocol.data_received(event1[:15])
548 mock_scanner._async_on_raw_advertisement.assert_not_called()
549
550 # Send rest of first event + second event
551 protocol.data_received(event1[15:] + event2)
552
553 # Both callbacks should be called
554 assert mock_scanner._async_on_raw_advertisement.call_count == 2
555 calls = mock_scanner._async_on_raw_advertisement.call_args_list
556
557 # First call
558 first_address = bytes_mac_to_str(b"\x11\x22\x33\x44\x55\x66")
559 assert calls[0][0] == (
560 first_address,
561 -56,
562 ad_data1,
563 make_bluez_details(first_address, "hci0"),
564 ANY,
565 )
566
567 # Second call
568 second_address = bytes_mac_to_str(b"\x77\x88\x99\xaa\xbb\xcc")
569 assert calls[1][0] == (
570 second_address,
571 100,
572 ad_data2,
573 make_bluez_details(second_address, "hci0"),
574 ANY,
575 )
576
577
578 def test_data_received_cmd_complete_different_opcode(
579 event_loop: asyncio.AbstractEventLoop, caplog: pytest.LogCaptureFixture
580 ) -> None:
581 """Test data_received handles CMD_COMPLETE for different opcodes."""
582 future = event_loop.create_future()
583 scanners: dict[int, BaseHaScanner] = {}
584 on_connection_lost = Mock()
585
586 is_shutting_down = Mock(return_value=False)
587 mock_sock = Mock()
588 protocol = BluetoothMGMTProtocol(
589 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
590 )
591
592 # Create a CMD_COMPLETE event for a different opcode (e.g., 0x0004 - Add UUID)
593 header = b"\x01\x00" # MGMT_EV_CMD_COMPLETE
594 header += b"\x00\x00" # controller_idx = 0
595 header += b"\x03\x00" # param_len = 3
596
597 params = b"\x04\x00" # opcode = 0x0004 (not MGMT_OP_LOAD_CONN_PARAM)
598 params += b"\x00" # status = 0 (success)
599
600 protocol.data_received(header + params)
601
602 # Should not log anything about connection parameters
603 assert "Connection parameters" not in caplog.text
604
605
606 def test_data_received_cmd_status_different_opcode(
607 event_loop: asyncio.AbstractEventLoop, caplog: pytest.LogCaptureFixture
608 ) -> None:
609 """Test data_received handles CMD_STATUS for different opcodes."""
610 future = event_loop.create_future()
611 scanners: dict[int, BaseHaScanner] = {}
612 on_connection_lost = Mock()
613
614 is_shutting_down = Mock(return_value=False)
615 mock_sock = Mock()
616 protocol = BluetoothMGMTProtocol(
617 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
618 )
619
620 # Create a CMD_STATUS event for a different opcode
621 header = b"\x02\x00" # MGMT_EV_CMD_STATUS
622 header += b"\x00\x00" # controller_idx = 0
623 header += b"\x03\x00" # param_len = 3
624
625 params = b"\x05\x00" # opcode = 0x0005 (not MGMT_OP_LOAD_CONN_PARAM)
626 params += b"\x01" # status = 1 (failure)
627
628 protocol.data_received(header + params)
629
630 # Should not log anything about connection parameters
631 assert "conn params" not in caplog.text
632
633
634 def test_data_received_cmd_complete_short_params(
635 event_loop: asyncio.AbstractEventLoop, caplog: pytest.LogCaptureFixture
636 ) -> None:
637 """Test data_received handles CMD_COMPLETE with param_len < 3."""
638 future = event_loop.create_future()
639 scanners: dict[int, BaseHaScanner] = {}
640 on_connection_lost = Mock()
641
642 is_shutting_down = Mock(return_value=False)
643 mock_sock = Mock()
644 protocol = BluetoothMGMTProtocol(
645 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
646 )
647
648 # Create a CMD_COMPLETE event with param_len < 3
649 header = b"\x01\x00" # MGMT_EV_CMD_COMPLETE
650 header += b"\x00\x00" # controller_idx = 0
651 header += b"\x02\x00" # param_len = 2 (too short to contain opcode + status)
652
653 params = b"\x00\x00" # Just 2 bytes
654
655 protocol.data_received(header + params)
656
657 # Should not log anything (no opcode to check)
658 assert "conn params" not in caplog.text
659
660
661 def test_data_received_cmd_status_param_len_1(
662 event_loop: asyncio.AbstractEventLoop, caplog: pytest.LogCaptureFixture
663 ) -> None:
664 """Test data_received handles CMD_STATUS with param_len = 1."""
665 future = event_loop.create_future()
666 scanners: dict[int, BaseHaScanner] = {}
667 on_connection_lost = Mock()
668
669 is_shutting_down = Mock(return_value=False)
670 mock_sock = Mock()
671 protocol = BluetoothMGMTProtocol(
672 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
673 )
674
675 # Create a CMD_STATUS event with param_len = 1
676 header = b"\x02\x00" # MGMT_EV_CMD_STATUS
677 header += b"\x00\x00" # controller_idx = 0
678 header += b"\x01\x00" # param_len = 1 (too short)
679
680 params = b"\x00" # Just 1 byte
681
682 protocol.data_received(header + params)
683
684 # Should not log anything (no opcode to check)
685 assert "conn params" not in caplog.text
686
687
688 def test_data_received_cmd_complete_param_len_0(
689 event_loop: asyncio.AbstractEventLoop, caplog: pytest.LogCaptureFixture
690 ) -> None:
691 """Test data_received handles CMD_COMPLETE with param_len = 0."""
692 future = event_loop.create_future()
693 scanners: dict[int, BaseHaScanner] = {}
694 on_connection_lost = Mock()
695
696 is_shutting_down = Mock(return_value=False)
697 mock_sock = Mock()
698 protocol = BluetoothMGMTProtocol(
699 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
700 )
701
702 # Create a CMD_COMPLETE event with param_len = 0
703 header = b"\x01\x00" # MGMT_EV_CMD_COMPLETE
704 header += b"\x00\x00" # controller_idx = 0
705 header += b"\x00\x00" # param_len = 0 (no params at all)
706
707 protocol.data_received(header)
708
709 # Should not log anything (no opcode to check)
710 assert "conn params" not in caplog.text
711
712
713 def test_data_received_unknown_event(event_loop: asyncio.AbstractEventLoop) -> None:
714 """Test data_received ignores unknown events."""
715 future = event_loop.create_future()
716 scanners: dict[int, BaseHaScanner] = {}
717 on_connection_lost = Mock()
718
719 is_shutting_down = Mock(return_value=False)
720 mock_sock = Mock()
721 protocol = BluetoothMGMTProtocol(
722 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
723 )
724
725 # Create an unknown event
726 header = b"\xff\x00" # Unknown event code
727 header += b"\x00\x00" # controller_idx = 0
728 header += b"\x04\x00" # param_len = 4
729 params = b"\x00\x00\x00\x00"
730
731 # Should not raise any exception
732 protocol.data_received(header + params)
733
734
735 def test_data_received_no_scanner_for_controller(
736 event_loop: asyncio.AbstractEventLoop,
737 ) -> None:
738 """Test data_received handles missing scanner gracefully."""
739 future = event_loop.create_future()
740 scanners: dict[int, BaseHaScanner] = {} # No scanner for controller 0
741 on_connection_lost = Mock()
742
743 is_shutting_down = Mock(return_value=False)
744 mock_sock = Mock()
745 protocol = BluetoothMGMTProtocol(
746 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
747 )
748
749 # Create a DEVICE_FOUND event for controller 0
750 ad_data = b"\x02\x01\x06"
751 param_len = 6 + 1 + 1 + 4 + 2 + len(ad_data)
752
753 header = b"\x12\x00\x00\x00" + param_len.to_bytes(2, "little")
754 params = b"\xaa\xbb\xcc\xdd\xee\xff\x01\xc8\x00\x00\x00\x00"
755 params += len(ad_data).to_bytes(2, "little") + ad_data
756
757 # Should not raise any exception
758 protocol.data_received(header + params)
759
760
761 @pytest.mark.asyncio
762 async def test_setup_success() -> None:
763 """Test successful setup."""
764 mock_sock = Mock()
765 mock_sock.fileno.return_value = 1 # Mock socket file descriptor
766 mock_protocol = Mock(spec=BluetoothMGMTProtocol)
767 mock_transport = Mock()
768 mock_protocol.transport = mock_transport
769
770 # Mock the future that gets created and set
771 loop = asyncio.get_running_loop()
772 mock_future = loop.create_future()
773
774 async def mock_create_connection(*args, **kwargs):
775 # Set the future result to simulate connection made
776 mock_future.set_result(None)
777 return mock_transport, mock_protocol
778
779 with (
780 patch("habluetooth.channels.bluez.btmgmt_socket.open", return_value=mock_sock),
781 patch.object(
782 asyncio.get_running_loop(),
783 "_create_connection_transport",
784 side_effect=mock_create_connection,
785 ),
786 patch.object(
787 asyncio.get_running_loop(),
788 "create_future",
789 side_effect=[
790 mock_future,
791 loop.create_future(),
792 ], # First for connection, second for on_connection_lost
793 ),
794 patch.object(
795 MGMTBluetoothCtl,
796 "_check_capabilities",
797 return_value=True, # Mock successful capability check
798 ),
799 ):
800 ctl = MGMTBluetoothCtl(5.0, {})
801 await ctl.setup()
802
803 assert ctl.sock is mock_sock
804 assert ctl.protocol is mock_protocol
805 assert ctl._reconnect_task is not None
806
807 # Clean up
808 ctl._reconnect_task.cancel()
809 with pytest.raises(asyncio.CancelledError):
810 await ctl._reconnect_task
811
812
813 @pytest.mark.asyncio
814 async def test_setup_timeout() -> None:
815 """Test setup timeout."""
816 mock_sock = Mock()
817
818 async def slow_connect(*args, **kwargs):
819 await asyncio.sleep(10)
820
821 with (
822 patch("habluetooth.channels.bluez.btmgmt_socket.open", return_value=mock_sock),
823 patch.object(
824 asyncio.get_running_loop(),
825 "_create_connection_transport",
826 side_effect=slow_connect,
827 ),
828 patch("habluetooth.channels.bluez.btmgmt_socket.close") as mock_close,
829 ):
830 ctl = MGMTBluetoothCtl(0.1, {})
831 with pytest.raises(TimeoutError):
832 await ctl.setup()
833
834 mock_close.assert_called_once_with(mock_sock)
835
836
837 @pytest.mark.asyncio
838 async def test_load_conn_params_fast() -> None:
839 """Test loading fast connection parameters."""
840 mock_sock = Mock()
841 mock_protocol = Mock(spec=BluetoothMGMTProtocol)
842 mock_transport = Mock()
843 mock_protocol.transport = mock_transport
844 # Mock the _write_to_socket method
845 mock_protocol._write_to_socket = Mock()
846
847 ctl = MGMTBluetoothCtl(5.0, {})
848 ctl.protocol = mock_protocol
849 ctl.sock = mock_sock
850
851 result = ctl.load_conn_params(
852 0, # adapter_idx
853 "AA:BB:CC:DD:EE:FF", # address
854 BDADDR_LE_PUBLIC, # address_type
855 ConnectParams.FAST,
856 )
857
858 assert result is True
859
860 # Verify the command was sent
861 mock_protocol._write_to_socket.assert_called_once()
862 call_args = mock_protocol._write_to_socket.call_args[0][0]
863
864 # Check header (6 bytes)
865 assert call_args[0:2] == b"\x35\x00" # MGMT_OP_LOAD_CONN_PARAM
866 assert call_args[2:4] == b"\x00\x00" # adapter_idx = 0
867 assert call_args[4:6] == b"\x11\x00" # param_len = 17 (2 + 15)
868
869 # Check command data
870 assert call_args[6:8] == b"\x01\x00" # param_count = 1
871 assert call_args[8:14] == b"\xff\xee\xdd\xcc\xbb\xaa" # address (reversed)
872 assert call_args[14] == BDADDR_LE_PUBLIC # address_type
873 assert call_args[15:17] == FAST_MIN_CONN_INTERVAL.to_bytes(2, "little")
874 assert call_args[17:19] == FAST_MAX_CONN_INTERVAL.to_bytes(2, "little")
875 assert call_args[19:21] == FAST_CONN_LATENCY.to_bytes(2, "little")
876 assert call_args[21:23] == FAST_CONN_TIMEOUT.to_bytes(2, "little")
877
878
879 @pytest.mark.asyncio
880 async def test_load_conn_params_medium() -> None:
881 """Test loading medium connection parameters."""
882 mock_sock = Mock()
883 mock_protocol = Mock(spec=BluetoothMGMTProtocol)
884 mock_transport = Mock()
885 mock_protocol.transport = mock_transport
886 # Mock the _write_to_socket method
887 mock_protocol._write_to_socket = Mock()
888
889 ctl = MGMTBluetoothCtl(5.0, {})
890 ctl.protocol = mock_protocol
891 ctl.sock = mock_sock
892
893 result = ctl.load_conn_params(
894 1, # adapter_idx
895 "11:22:33:44:55:66", # address
896 BDADDR_LE_RANDOM, # address_type
897 ConnectParams.MEDIUM,
898 )
899
900 assert result is True
901
902 # Verify the command was sent
903 mock_protocol._write_to_socket.assert_called_once()
904 call_args = mock_protocol._write_to_socket.call_args[0][0]
905
906 # Check header
907 assert call_args[0:2] == b"\x35\x00" # MGMT_OP_LOAD_CONN_PARAM
908 assert call_args[2:4] == b"\x01\x00" # adapter_idx = 1
909
910 # Check parameters
911 assert call_args[8:14] == b"\x66\x55\x44\x33\x22\x11" # address (reversed)
912 assert call_args[14] == BDADDR_LE_RANDOM # address_type
913 assert call_args[15:17] == MEDIUM_MIN_CONN_INTERVAL.to_bytes(2, "little")
914 assert call_args[17:19] == MEDIUM_MAX_CONN_INTERVAL.to_bytes(2, "little")
915 assert call_args[19:21] == MEDIUM_CONN_LATENCY.to_bytes(2, "little")
916 assert call_args[21:23] == MEDIUM_CONN_TIMEOUT.to_bytes(2, "little")
917
918
919 def test_load_conn_params_no_protocol(caplog: pytest.LogCaptureFixture) -> None:
920 """Test load_conn_params when protocol is not connected."""
921 ctl = MGMTBluetoothCtl(5.0, {})
922
923 result = ctl.load_conn_params(
924 0,
925 "AA:BB:CC:DD:EE:FF",
926 BDADDR_LE_PUBLIC,
927 ConnectParams.FAST,
928 )
929
930 assert result is False
931 assert "Cannot load conn params: no connection" in caplog.text
932
933
934 def test_load_conn_params_invalid_address(caplog: pytest.LogCaptureFixture) -> None:
935 """Test load_conn_params with invalid MAC address."""
936 mock_protocol = Mock(spec=BluetoothMGMTProtocol)
937 mock_transport = Mock()
938 mock_protocol.transport = mock_transport
939
940 ctl = MGMTBluetoothCtl(5.0, {})
941 ctl.protocol = mock_protocol
942
943 # Test with too short address
944 result = ctl.load_conn_params(
945 0,
946 "AA:BB",
947 BDADDR_LE_PUBLIC,
948 ConnectParams.FAST,
949 )
950
951 assert result is False
952 assert "Invalid MAC address: AA:BB" in caplog.text
953
954
955 def test_load_conn_params_transport_error(caplog: pytest.LogCaptureFixture) -> None:
956 """Test load_conn_params with transport write error."""
957 mock_protocol = Mock(spec=BluetoothMGMTProtocol)
958 mock_transport = Mock()
959 mock_socket = Mock()
960 mock_socket.send.side_effect = Exception("Transport error")
961 mock_transport.get_extra_info = Mock(return_value=mock_socket)
962 mock_protocol.transport = mock_transport
963 mock_protocol._sock = mock_socket
964 mock_protocol._write_to_socket = Mock(side_effect=Exception("Transport error"))
965
966 ctl = MGMTBluetoothCtl(5.0, {})
967 ctl.protocol = mock_protocol
968
969 result = ctl.load_conn_params(
970 0,
971 "AA:BB:CC:DD:EE:FF",
972 BDADDR_LE_PUBLIC,
973 ConnectParams.FAST,
974 )
975
976 assert result is False
977 assert "Failed to load conn params" in caplog.text
978
979
980 @pytest.mark.asyncio
981 async def test_load_conn_params_explicit() -> None:
982 """Test loading explicit connection parameters."""
983 mock_sock = Mock()
984 mock_protocol = Mock(spec=BluetoothMGMTProtocol)
985 mock_transport = Mock()
986 mock_protocol.transport = mock_transport
987 mock_protocol._write_to_socket = Mock()
988
989 ctl = MGMTBluetoothCtl(5.0, {})
990 ctl.protocol = mock_protocol
991 ctl.sock = mock_sock
992
993 result = ctl.load_conn_params_explicit(
994 0, # adapter_idx
995 "AA:BB:CC:DD:EE:FF", # address
996 BDADDR_LE_PUBLIC, # address_type
997 800, # min_interval
998 800, # max_interval
999 0, # latency
1000 300, # timeout
1001 )
1002
1003 assert result is True
1004
1005 mock_protocol._write_to_socket.assert_called_once()
1006 call_args = mock_protocol._write_to_socket.call_args[0][0]
1007
1008 # Check header (6 bytes)
1009 assert call_args[0:2] == b"\x35\x00" # MGMT_OP_LOAD_CONN_PARAM
1010 assert call_args[2:4] == b"\x00\x00" # adapter_idx = 0
1011 assert call_args[4:6] == b"\x11\x00" # param_len = 17 (2 + 15)
1012
1013 # Check command data
1014 assert call_args[6:8] == b"\x01\x00" # param_count = 1
1015 assert call_args[8:14] == b"\xff\xee\xdd\xcc\xbb\xaa" # address (reversed)
1016 assert call_args[14] == BDADDR_LE_PUBLIC # address_type
1017 assert call_args[15:17] == (800).to_bytes(2, "little") # min_interval
1018 assert call_args[17:19] == (800).to_bytes(2, "little") # max_interval
1019 assert call_args[19:21] == (0).to_bytes(2, "little") # latency
1020 assert call_args[21:23] == (300).to_bytes(2, "little") # timeout
1021
1022
1023 def test_load_conn_params_explicit_no_protocol(
1024 caplog: pytest.LogCaptureFixture,
1025 ) -> None:
1026 """Test load_conn_params_explicit when protocol is not connected."""
1027 ctl = MGMTBluetoothCtl(5.0, {})
1028
1029 result = ctl.load_conn_params_explicit(
1030 0, "AA:BB:CC:DD:EE:FF", BDADDR_LE_PUBLIC, 800, 800, 0, 300
1031 )
1032
1033 assert result is False
1034 assert "Cannot load conn params: no connection" in caplog.text
1035
1036
1037 def test_load_conn_params_explicit_invalid_address(
1038 caplog: pytest.LogCaptureFixture,
1039 ) -> None:
1040 """Test load_conn_params_explicit with invalid MAC address."""
1041 mock_protocol = Mock(spec=BluetoothMGMTProtocol)
1042 mock_transport = Mock()
1043 mock_protocol.transport = mock_transport
1044
1045 ctl = MGMTBluetoothCtl(5.0, {})
1046 ctl.protocol = mock_protocol
1047
1048 result = ctl.load_conn_params_explicit(
1049 0, "AA:BB", BDADDR_LE_PUBLIC, 800, 800, 0, 300
1050 )
1051
1052 assert result is False
1053 assert "Invalid MAC address: AA:BB" in caplog.text
1054
1055
1056 def test_load_conn_params_explicit_transport_error(
1057 caplog: pytest.LogCaptureFixture,
1058 ) -> None:
1059 """Test load_conn_params_explicit with transport write error."""
1060 mock_protocol = Mock(spec=BluetoothMGMTProtocol)
1061 mock_transport = Mock()
1062 mock_protocol.transport = mock_transport
1063 mock_protocol._write_to_socket = Mock(side_effect=Exception("Transport error"))
1064
1065 ctl = MGMTBluetoothCtl(5.0, {})
1066 ctl.protocol = mock_protocol
1067
1068 result = ctl.load_conn_params_explicit(
1069 0, "AA:BB:CC:DD:EE:FF", BDADDR_LE_PUBLIC, 800, 800, 0, 300
1070 )
1071
1072 assert result is False
1073 assert "Failed to load conn params" in caplog.text
1074
1075
1076 def test_kernel_bug_workaround_send_returns_zero(
1077 event_loop: asyncio.AbstractEventLoop, caplog: pytest.LogCaptureFixture
1078 ) -> None:
1079 """Test that the kernel bug workaround handles send returning 0."""
1080 future = event_loop.create_future()
1081 scanners: dict[int, BaseHaScanner] = {}
1082 on_connection_lost = Mock()
1083 is_shutting_down = Mock(return_value=False)
1084
1085 # Create a mock socket that returns 0 (kernel bug behavior)
1086 mock_socket = Mock()
1087 mock_socket.send = Mock(return_value=0)
1088 protocol = BluetoothMGMTProtocol(
1089 future, scanners, on_connection_lost, is_shutting_down, mock_socket, {}
1090 )
1091
1092 # Send some data
1093 test_data = b"\x25\x00\x00\x00\x00\x00"
1094 with caplog.at_level(logging.DEBUG):
1095 protocol._write_to_socket(test_data)
1096
1097 # Verify the send was called and the workaround logged
1098 mock_socket.send.assert_called_once_with(test_data)
1099 assert "kernel bug fix" in caplog.text
1100
1101
1102 def test_kernel_bug_workaround_send_raises_exception(
1103 event_loop: asyncio.AbstractEventLoop, caplog: pytest.LogCaptureFixture
1104 ) -> None:
1105 """Test that _write_to_socket handles and re-raises exceptions."""
1106 future = event_loop.create_future()
1107 scanners: dict[int, BaseHaScanner] = {}
1108 on_connection_lost = Mock()
1109 is_shutting_down = Mock(return_value=False)
1110
1111 # Create a mock socket that raises an exception
1112 mock_socket = Mock()
1113 mock_socket.send = Mock(side_effect=OSError("Socket error"))
1114 protocol = BluetoothMGMTProtocol(
1115 future, scanners, on_connection_lost, is_shutting_down, mock_socket, {}
1116 )
1117
1118 # Send some data and expect the exception to be re-raised
1119 test_data = b"\x25\x00\x00\x00\x00\x00"
1120 with pytest.raises(OSError, match="Socket error"):
1121 protocol._write_to_socket(test_data)
1122
1123 # Verify the error was logged; the traceback carries the OSError text.
1124 assert "Failed to write to mgmt socket" in caplog.text
1125 assert "Socket error" in caplog.text
1126 mock_socket.send.assert_called_once_with(test_data)
1127
1128
1129 def test_close() -> None:
1130 """Test close method."""
1131 mock_protocol = Mock(spec=BluetoothMGMTProtocol)
1132 mock_transport = Mock()
1133 mock_protocol.transport = mock_transport
1134 mock_sock = Mock()
1135 mock_reconnect_task = Mock()
1136
1137 ctl = MGMTBluetoothCtl(5.0, {})
1138 ctl.protocol = mock_protocol
1139 ctl.sock = mock_sock
1140 ctl._reconnect_task = mock_reconnect_task
1141
1142 with patch("habluetooth.channels.bluez.btmgmt_socket.close") as mock_close:
1143 ctl.close()
1144
1145 mock_reconnect_task.cancel.assert_called_once()
1146 mock_transport.close.assert_called_once()
1147 mock_close.assert_called_once_with(mock_sock)
1148 assert ctl.protocol is None
1149
1150
1151 def test_close_no_protocol() -> None:
1152 """Test close when protocol is not set."""
1153 ctl = MGMTBluetoothCtl(5.0, {})
1154 # Should not raise any exception
1155 with patch("habluetooth.channels.bluez.btmgmt_socket.close"):
1156 ctl.close()
1157
1158
1159 @pytest.mark.asyncio
1160 async def test_on_connection_lost() -> None:
1161 """Test _on_connection_lost callback."""
1162 ctl = MGMTBluetoothCtl(5.0, {})
1163 loop = asyncio.get_running_loop()
1164 ctl._on_connection_lost_future = loop.create_future()
1165
1166 ctl._on_connection_lost()
1167
1168 # _on_connection_lost sets the future to None after setting result
1169 assert ctl._on_connection_lost_future is None
1170
1171
1172 @pytest.mark.asyncio
1173 async def test_on_connection_lost_during_shutdown(
1174 caplog: pytest.LogCaptureFixture,
1175 ) -> None:
1176 """Test _on_connection_lost callback during shutdown."""
1177 ctl = MGMTBluetoothCtl(5.0, {})
1178 loop = asyncio.get_running_loop()
1179 ctl._on_connection_lost_future = loop.create_future()
1180 ctl._shutting_down = True
1181
1182 with caplog.at_level(logging.DEBUG):
1183 ctl._on_connection_lost()
1184
1185 # Should log shutdown message
1186 assert "Bluetooth management socket connection lost during shutdown" in caplog.text
1187 # Should not log reconnecting message
1188 assert "reconnecting" not in caplog.text
1189 # _on_connection_lost sets the future to None after setting result
1190 assert ctl._on_connection_lost_future is None
1191
1192
1193 @pytest.mark.asyncio
1194 async def test_reconnect_task() -> None:
1195 """Test reconnect_task behavior."""
1196 mock_protocol = Mock(spec=BluetoothMGMTProtocol)
1197 mock_transport = Mock()
1198 mock_protocol.transport = mock_transport
1199
1200 establish_count = 0
1201
1202 ctl = MGMTBluetoothCtl(5.0, {})
1203
1204 async def mock_establish_connection() -> None:
1205 nonlocal establish_count
1206 establish_count += 1
1207 if establish_count == 1:
1208 # First call succeeds
1209 ctl.protocol = mock_protocol
1210 ctl._on_connection_lost_future = asyncio.get_running_loop().create_future()
1211 elif establish_count == 2:
1212 # Second call fails
1213 msg = "Test error"
1214 raise BluetoothSocketError(msg)
1215 else:
1216 # Stop the test
1217 raise asyncio.CancelledError
1218
1219 with patch.object(
1220 ctl, "_establish_connection", side_effect=mock_establish_connection
1221 ):
1222 # Start the reconnect task
1223 task = asyncio.create_task(ctl.reconnect_task())
1224
1225 # Trigger reconnection by calling _on_connection_lost
1226 await asyncio.sleep(0.1)
1227 ctl._on_connection_lost()
1228
1229 # Wait for reconnection attempt
1230 await asyncio.sleep(1.5)
1231
1232 # Cancel the task
1233 task.cancel()
1234 with pytest.raises(asyncio.CancelledError):
1235 await task
1236
1237 assert establish_count >= 2
1238
1239
1240 @pytest.mark.asyncio
1241 async def test_reconnect_task_timeout() -> None:
1242 """Test reconnect_task with connection timeout."""
1243
1244 async def mock_establish_connection() -> None:
1245 msg = "Connection timeout"
1246 raise TimeoutError(msg)
1247
1248 ctl = MGMTBluetoothCtl(5.0, {})
1249 ctl._on_connection_lost_future = None
1250
1251 with patch.object(
1252 ctl, "_establish_connection", side_effect=mock_establish_connection
1253 ):
1254 # Run reconnect_task briefly
1255 task = asyncio.create_task(ctl.reconnect_task())
1256 await asyncio.sleep(0.1)
1257
1258 # Cancel the task
1259 task.cancel()
1260 with pytest.raises(asyncio.CancelledError):
1261 await task
1262
1263
1264 @pytest.mark.asyncio
1265 async def test_reconnect_task_shutdown() -> None:
1266 """Test reconnect_task exits when shutting down."""
1267 ctl = MGMTBluetoothCtl(5.0, {})
1268 loop = asyncio.get_running_loop()
1269
1270 establish_called = False
1271
1272 async def mock_establish_connection() -> None:
1273 nonlocal establish_called
1274 establish_called = True
1275 # Should not be called since we're shutting down
1276 msg = "Should not be called"
1277 raise AssertionError(msg)
1278
1279 with patch.object(
1280 ctl, "_establish_connection", side_effect=mock_establish_connection
1281 ):
1282 # Set up connection lost future
1283 ctl._on_connection_lost_future = loop.create_future()
1284
1285 # Start the reconnect task
1286 task = asyncio.create_task(ctl.reconnect_task())
1287
1288 # Give it a moment to start
1289 await asyncio.sleep(0)
1290
1291 # Simulate shutdown
1292 ctl._shutting_down = True
1293
1294 # Trigger the future to wake up the task
1295 ctl._on_connection_lost_future.set_result(None)
1296
1297 # Task should exit cleanly
1298 await task
1299
1300 # _establish_connection should not have been called
1301 assert not establish_called
1302
1303
1304 @pytest.mark.asyncio
1305 async def test_command_response_context_manager() -> None:
1306 """Test the command_response context manager."""
1307 future = asyncio.get_running_loop().create_future()
1308 future.set_result(None) # Mark connection as made
1309 scanners: dict[int, BaseHaScanner] = {}
1310 on_connection_lost = Mock()
1311 is_shutting_down = Mock(return_value=False)
1312
1313 mock_sock = Mock()
1314 protocol = BluetoothMGMTProtocol(
1315 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
1316 )
1317
1318 # Test successful command response
1319 opcode = 0x0015 # MGMT_OP_GET_CONNECTIONS
1320 async with protocol.command_response(opcode, 0) as response_future:
1321 # Verify we got a future
1322 assert response_future is not None
1323 assert isinstance(response_future, asyncio.Future)
1324
1325 # Simulate receiving a response
1326 response_data = (
1327 b"\x01\x00" # MGMT_EV_CMD_COMPLETE
1328 b"\x00\x00" # controller index
1329 b"\x03\x00" # param_len (3 bytes: opcode=2 + status=1)
1330 + opcode.to_bytes(2, "little") # opcode
1331 + b"\x00" # status (success)
1332 )
1333
1334 protocol.data_received(response_data)
1335
1336 # Get the result
1337 status, _data = await response_future
1338 assert status == 0 # Success
1339
1340 # After context exits, future should be resolved
1341 assert response_future.done()
1342
1343
1344 @pytest.mark.asyncio
1345 async def test_command_response_cleanup_on_exception() -> None:
1346 """Test that command_response cleans up even if an exception occurs."""
1347 future = asyncio.get_running_loop().create_future()
1348 scanners: dict[int, BaseHaScanner] = {}
1349 on_connection_lost = Mock()
1350 is_shutting_down = Mock(return_value=False)
1351
1352 mock_sock = Mock()
1353 protocol = BluetoothMGMTProtocol(
1354 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
1355 )
1356
1357 opcode = 0x0015 # MGMT_OP_GET_CONNECTIONS
1358
1359 # Test cleanup on exception
1360 async def _raise_inside_command_response() -> None:
1361 async with protocol.command_response(opcode, 0) as response_future:
1362 assert response_future is not None
1363 msg = "Test exception"
1364 raise ValueError(msg)
1365
1366 with pytest.raises(ValueError, match="Test exception"):
1367 await _raise_inside_command_response()
1368
1369 # The future should still exist after exception
1370 # (cleanup just removes it from internal tracking)
1371
1372
1373 @pytest.mark.asyncio
1374 async def test_get_connections_response_handling() -> None:
1375 """Test handling of GET_CONNECTIONS command response."""
1376 future = asyncio.get_running_loop().create_future()
1377 scanners: dict[int, BaseHaScanner] = {}
1378 on_connection_lost = Mock()
1379 is_shutting_down = Mock(return_value=False)
1380
1381 mock_sock = Mock()
1382 protocol = BluetoothMGMTProtocol(
1383 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
1384 )
1385
1386 opcode = 0x0015 # MGMT_OP_GET_CONNECTIONS
1387
1388 # Use the command_response context manager to register the command
1389 async with protocol.command_response(opcode, 0) as response_future:
1390 # Test with permission denied status (0x14)
1391 response_data = (
1392 b"\x01\x00" # MGMT_EV_CMD_COMPLETE
1393 b"\x00\x00" # controller index
1394 b"\x03\x00" # param_len
1395 + opcode.to_bytes(2, "little") # opcode
1396 + b"\x14" # status (permission denied)
1397 )
1398
1399 protocol.data_received(response_data)
1400
1401 # Verify the future was resolved with the status
1402 status, data = await response_future
1403 assert status == 0x14 # Permission denied
1404 assert data == b"" # No additional data for param_len <= 3
1405
1406
1407 @pytest.mark.asyncio
1408 async def test_get_connections_response_with_data() -> None:
1409 """Test GET_CONNECTIONS response with additional data."""
1410 future = asyncio.get_running_loop().create_future()
1411 scanners: dict[int, BaseHaScanner] = {}
1412 on_connection_lost = Mock()
1413 is_shutting_down = Mock(return_value=False)
1414
1415 mock_sock = Mock()
1416 protocol = BluetoothMGMTProtocol(
1417 future, scanners, on_connection_lost, is_shutting_down, mock_sock, {}
1418 )
1419
1420 opcode = 0x0015 # MGMT_OP_GET_CONNECTIONS
1421
1422 # Use the command_response context manager to register the command
1423 async with protocol.command_response(opcode, 0) as response_future:
1424 # Test with success status and additional data
1425 extra_data = b"\x01\x02\x03\x04"
1426 response_data = (
1427 b"\x01\x00" # MGMT_EV_CMD_COMPLETE
1428 b"\x00\x00" # controller index
1429 + (3 + len(extra_data)).to_bytes(
1430 2, "little"
1431 ) # param_len (opcode=2 + status=1 + extra_data)
1432 + opcode.to_bytes(2, "little") # opcode
1433 + b"\x00" # status (success)
1434 + extra_data # additional response data
1435 )
1436
1437 protocol.data_received(response_data)
1438
1439 # Verify the future was resolved with status and data
1440 status, data = await response_future
1441 assert status == 0 # Success
1442 assert data == extra_data
1443
1444
1445 @pytest.mark.asyncio
1446 async def test_has_mgmt_capabilities_from_status() -> None:
1447 """Test _has_mgmt_capabilities_from_status helper function."""
1448 mgmt_ctl = MGMTBluetoothCtl(timeout=5.0, scanners={})
1449
1450 # Test permission denied
1451 assert mgmt_ctl._has_mgmt_capabilities_from_status(0x14) is False
1452
1453 # Test success
1454 assert mgmt_ctl._has_mgmt_capabilities_from_status(0x00) is True
1455
1456 # Test invalid index (still has permissions)
1457 assert mgmt_ctl._has_mgmt_capabilities_from_status(0x11) is True
1458
1459 # Test unknown status (assumes no permissions)
1460 assert mgmt_ctl._has_mgmt_capabilities_from_status(0xFF) is False
1461 assert mgmt_ctl._has_mgmt_capabilities_from_status(0x01) is False
1462 assert mgmt_ctl._has_mgmt_capabilities_from_status(0x0D) is False
1463
1464
1465 @pytest.mark.asyncio
1466 async def test_check_capabilities_success() -> None:
1467 """Test _check_capabilities when permissions are available."""
1468 mgmt_ctl = MGMTBluetoothCtl(timeout=5.0, scanners={})
1469
1470 # Mock the protocol and transport
1471 mock_protocol = Mock(spec=BluetoothMGMTProtocol)
1472 mock_transport = Mock()
1473 mock_protocol.transport = mock_transport
1474 mgmt_ctl.protocol = mock_protocol
1475
1476 # Mock command_response to return success
1477 def mock_command_response(opcode: int, controller_idx: int) -> object:
1478 future = asyncio.get_running_loop().create_future()
1479 future.set_result((0x00, b"")) # Success status
1480
1481 class MockContext:
1482 async def __aenter__(self) -> asyncio.Future[tuple[int, bytes]]:
1483 return future
1484
1485 async def __aexit__(self, *args: object) -> None:
1486 pass
1487
1488 return MockContext()
1489
1490 mock_protocol.command_response = mock_command_response
1491 # Mock the _write_to_socket method
1492 mock_protocol._write_to_socket = Mock()
1493
1494 # Test capability check
1495 result = await mgmt_ctl._check_capabilities()
1496 assert result is True
1497
1498 # Verify the command was sent
1499 mock_protocol._write_to_socket.assert_called_once()
1500 sent_data = mock_protocol._write_to_socket.call_args[0][0]
1501 # Check that it's a GET_CONNECTIONS command (opcode at bytes 0-1)
1502 assert sent_data[0:2] == b"\x15\x00" # MGMT_OP_GET_CONNECTIONS little-endian
1503
1504
1505 @pytest.mark.asyncio
1506 async def test_check_capabilities_permission_denied() -> None:
1507 """Test _check_capabilities when permissions are denied."""
1508 mgmt_ctl = MGMTBluetoothCtl(timeout=5.0, scanners={})
1509
1510 # Mock the protocol and transport
1511 mock_protocol = Mock(spec=BluetoothMGMTProtocol)
1512 mock_transport = Mock()
1513 mock_protocol.transport = mock_transport
1514 mgmt_ctl.protocol = mock_protocol
1515
1516 # Mock command_response to return permission denied
1517 def mock_command_response(opcode: int, controller_idx: int) -> object:
1518 future = asyncio.get_running_loop().create_future()
1519 future.set_result((0x14, b"")) # Permission denied status
1520
1521 class MockContext:
1522 async def __aenter__(self) -> asyncio.Future[tuple[int, bytes]]:
1523 return future
1524
1525 async def __aexit__(self, *args: object) -> None:
1526 pass
1527
1528 return MockContext()
1529
1530 mock_protocol.command_response = mock_command_response
1531
1532 # Test capability check
1533 result = await mgmt_ctl._check_capabilities()
1534 assert result is False
1535
1536
1537 @pytest.mark.asyncio
1538 async def test_check_capabilities_invalid_index() -> None:
1539 """Test _check_capabilities with invalid adapter index (still has permissions)."""
1540 mgmt_ctl = MGMTBluetoothCtl(timeout=5.0, scanners={})
1541
1542 # Mock the protocol and transport
1543 mock_protocol = Mock(spec=BluetoothMGMTProtocol)
1544 mock_transport = Mock()
1545 mock_protocol.transport = mock_transport
1546 mgmt_ctl.protocol = mock_protocol
1547
1548 # Mock command_response to return invalid index
1549 def mock_command_response(opcode: int, controller_idx: int) -> object:
1550 future = asyncio.get_running_loop().create_future()
1551 future.set_result((0x11, b"")) # Invalid index
1552
1553 class MockContext:
1554 async def __aenter__(self) -> asyncio.Future[tuple[int, bytes]]:
1555 return future
1556
1557 async def __aexit__(self, *args: object) -> None:
1558 pass
1559
1560 return MockContext()
1561
1562 mock_protocol.command_response = mock_command_response
1563
1564 # Test capability check - invalid index means adapter doesn't exist
1565 # but we still have permissions
1566 result = await mgmt_ctl._check_capabilities()
1567 assert result is True
1568
1569
1570 @pytest.mark.asyncio
1571 async def test_check_capabilities_unknown_status() -> None:
1572 """Test _check_capabilities with unknown status code."""
1573 mgmt_ctl = MGMTBluetoothCtl(timeout=5.0, scanners={})
1574
1575 # Mock the protocol and transport
1576 mock_protocol = Mock(spec=BluetoothMGMTProtocol)
1577 mock_transport = Mock()
1578 mock_protocol.transport = mock_transport
1579 mgmt_ctl.protocol = mock_protocol
1580
1581 # Mock command_response to return unknown status
1582 def mock_command_response(opcode: int, controller_idx: int) -> object:
1583 future = asyncio.get_running_loop().create_future()
1584 future.set_result((0xFF, b"")) # Unknown status
1585
1586 class MockContext:
1587 async def __aenter__(self) -> asyncio.Future[tuple[int, bytes]]:
1588 return future
1589
1590 async def __aexit__(self, *args: object) -> None:
1591 pass
1592
1593 return MockContext()
1594
1595 mock_protocol.command_response = mock_command_response
1596
1597 # Test capability check - unknown status assumes no permissions
1598 result = await mgmt_ctl._check_capabilities()
1599 assert result is False
1600
1601
1602 @pytest.mark.asyncio
1603 async def test_check_capabilities_timeout() -> None:
1604 """Test _check_capabilities when command times out."""
1605 mgmt_ctl = MGMTBluetoothCtl(timeout=5.0, scanners={})
1606
1607 # Mock the protocol and transport
1608 mock_protocol = Mock(spec=BluetoothMGMTProtocol)
1609 mock_transport = Mock()
1610 mock_protocol.transport = mock_transport
1611 mgmt_ctl.protocol = mock_protocol
1612
1613 # Mock command_response to timeout
1614 def mock_command_response(opcode: int, controller_idx: int) -> object:
1615 future = asyncio.get_running_loop().create_future()
1616 # Never resolve the future
1617
1618 class MockContext:
1619 async def __aenter__(self) -> asyncio.Future[tuple[int, bytes]]:
1620 return future
1621
1622 async def __aexit__(self, *args: object) -> None:
1623 pass
1624
1625 return MockContext()
1626
1627 mock_protocol.command_response = mock_command_response
1628
1629 # Test capability check with a very short timeout
1630 with patch("habluetooth.channels.bluez.asyncio_timeout") as mock_timeout:
1631 # Make timeout raise immediately
1632 mock_timeout.side_effect = TimeoutError("Test timeout")
1633
1634 result = await mgmt_ctl._check_capabilities()
1635 assert result is False
1636
1637
1638 @pytest.mark.asyncio
1639 async def test_check_capabilities_no_protocol() -> None:
1640 """Test _check_capabilities when protocol is not set."""
1641 mgmt_ctl = MGMTBluetoothCtl(timeout=5.0, scanners={})
1642
1643 # No protocol set
1644 mgmt_ctl.protocol = None
1645
1646 result = await mgmt_ctl._check_capabilities()
1647 assert result is False
1648
1649
1650 @pytest.mark.asyncio
1651 async def test_check_capabilities_no_transport() -> None:
1652 """Test _check_capabilities when transport is not set."""
1653 mgmt_ctl = MGMTBluetoothCtl(timeout=5.0, scanners={})
1654
1655 # Mock protocol with no transport
1656 mock_protocol = Mock(spec=BluetoothMGMTProtocol)
1657 mock_protocol.transport = None
1658 mgmt_ctl.protocol = mock_protocol
1659
1660 result = await mgmt_ctl._check_capabilities()
1661 assert result is False
1662
1663
1664 @pytest.mark.asyncio
1665 async def test_setup_with_failed_capabilities() -> None:
1666 """Test setup raises PermissionError when capabilities check fails."""
1667 with (
1668 patch("habluetooth.channels.bluez.btmgmt_socket") as mock_btmgmt,
1669 patch.object(MGMTBluetoothCtl, "_establish_connection") as mock_establish,
1670 patch.object(MGMTBluetoothCtl, "_check_capabilities", return_value=False),
1671 ):
1672 mock_socket = Mock()
1673 mock_socket.fileno.return_value = 99
1674 mock_btmgmt.open.return_value = mock_socket
1675
1676 mgmt_ctl = MGMTBluetoothCtl(timeout=5.0, scanners={})
1677
1678 # Mock successful connection establishment
1679 mock_establish.return_value = None
1680
1681 # Set the socket on mgmt_ctl
1682 mgmt_ctl.sock = mock_socket
1683
1684 # Mock protocol for close operation
1685 mock_protocol = Mock()
1686 mock_transport = Mock()
1687 mock_protocol.transport = mock_transport
1688 mgmt_ctl.protocol = mock_protocol
1689
1690 # Setup should raise PermissionError
1691 with pytest.raises(PermissionError) as exc_info:
1692 await mgmt_ctl.setup()
1693
1694 assert "Missing NET_ADMIN/NET_RAW capabilities" in str(exc_info.value)
1695
1696 # Verify cleanup
1697 assert mgmt_ctl._shutting_down is True
1698 mock_transport.close.assert_called_once()
1699 mock_btmgmt.close.assert_called_once_with(mock_socket)
1700
1701
1702 def _stub_command_response(
1703 status: int, data: bytes = b""
1704 ) -> Callable[[int, int], object]:
1705 """Build a command_response stub that resolves with (status, data)."""
1706
1707 def _command_response(opcode: int, controller_idx: int) -> object:
1708 future = asyncio.get_running_loop().create_future()
1709 future.set_result((status, data))
1710
1711 class MockContext:
1712 async def __aenter__(self) -> asyncio.Future[tuple[int, bytes]]:
1713 return future
1714
1715 async def __aexit__(self, *args: object) -> None:
1716 pass
1717
1718 return MockContext()
1719
1720 return _command_response
1721
1722
1723 def _mgmt_ctl_with_mock_protocol() -> tuple[MGMTBluetoothCtl, Mock]:
1724 """Return a MGMTBluetoothCtl wired to a mock protocol/transport."""
1725 mgmt_ctl = MGMTBluetoothCtl(timeout=5.0, scanners={})
1726 mock_protocol = Mock(spec=BluetoothMGMTProtocol)
1727 mock_protocol.transport = Mock()
1728 mock_protocol._write_to_socket = Mock()
1729 mgmt_ctl.protocol = mock_protocol
1730 return mgmt_ctl, mock_protocol
1731
1732
1733 @pytest.mark.asyncio
1734 @pytest.mark.parametrize("status", [0x00, 0x0A])
1735 async def test_start_discovery_success(status: int) -> None:
1736 """start_discovery returns True on success or busy and sends the LE bitmask."""
1737 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
1738 mock_protocol.command_response = _stub_command_response(status)
1739
1740 assert await mgmt_ctl.start_discovery(0) is True
1741
1742 sent = mock_protocol._write_to_socket.call_args[0][0]
1743 # header opcode (2) + controller_idx (2) + param_len (2) + address-type byte
1744 assert sent[0:2] == MGMT_OP_START_DISCOVERY.to_bytes(2, "little")
1745 assert sent[2:4] == b"\x00\x00"
1746 assert sent[6] == SCAN_TYPE_LE
1747
1748
1749 @pytest.mark.asyncio
1750 async def test_start_discovery_failure() -> None:
1751 """start_discovery returns False on an error status."""
1752 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
1753 mock_protocol.command_response = _stub_command_response(0x0C)
1754
1755 assert await mgmt_ctl.start_discovery(0) is False
1756
1757
1758 @pytest.mark.asyncio
1759 async def test_stop_discovery_success() -> None:
1760 """stop_discovery returns True and targets the requested controller."""
1761 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
1762 mock_protocol.command_response = _stub_command_response(0x00)
1763
1764 assert await mgmt_ctl.stop_discovery(2) is True
1765
1766 sent = mock_protocol._write_to_socket.call_args[0][0]
1767 assert sent[0:2] == MGMT_OP_STOP_DISCOVERY.to_bytes(2, "little")
1768 assert sent[2:4] == (2).to_bytes(2, "little")
1769
1770
1771 @pytest.mark.asyncio
1772 async def test_stop_discovery_busy_is_not_success() -> None:
1773 """BUSY on stop means discovery did not stop, so it must report False."""
1774 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
1775 mock_protocol.command_response = _stub_command_response(0x0A)
1776
1777 assert await mgmt_ctl.stop_discovery(0) is False
1778
1779
1780 @pytest.mark.asyncio
1781 async def test_discovery_command_timeout() -> None:
1782 """A command whose response never arrives times out and reports failure."""
1783 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
1784 mgmt_ctl.timeout = 0.01
1785
1786 def _never_resolving(opcode: int, controller_idx: int) -> object:
1787 future = asyncio.get_running_loop().create_future() # never resolved
1788
1789 class MockContext:
1790 async def __aenter__(self) -> asyncio.Future[tuple[int, bytes]]:
1791 return future
1792
1793 async def __aexit__(self, *args: object) -> None:
1794 pass
1795
1796 return MockContext()
1797
1798 mock_protocol.command_response = _never_resolving
1799
1800 assert await mgmt_ctl.start_discovery(0) is False
1801
1802
1803 @pytest.mark.asyncio
1804 async def test_discovery_no_connection() -> None:
1805 """Discovery and monitor commands fail gracefully when the socket is down."""
1806 mgmt_ctl = MGMTBluetoothCtl(timeout=5.0, scanners={})
1807 assert mgmt_ctl.protocol is None
1808 assert await mgmt_ctl.start_discovery(0) is False
1809 assert await mgmt_ctl.stop_discovery(0) is False
1810 assert await mgmt_ctl.add_adv_pattern_monitor(0) is None
1811 assert await mgmt_ctl.remove_adv_monitor(0, 7) is False
1812
1813
1814 @pytest.mark.asyncio
1815 @pytest.mark.parametrize("exc_type", [OSError, BluetoothSocketError])
1816 async def test_discovery_command_response_error(exc_type: type[Exception]) -> None:
1817 """
1818 A socket error while sending a command is handled, not raised.
1819
1820 BluetoothSocketError is not an OSError subclass, so it must be caught
1821 explicitly; _write_to_socket can raise either one.
1822 """
1823 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
1824
1825 def _raising_command_response(opcode: int, controller_idx: int) -> object:
1826 class MockContext:
1827 async def __aenter__(self) -> asyncio.Future[tuple[int, bytes]]:
1828 msg = "socket gone"
1829 raise exc_type(msg)
1830
1831 async def __aexit__(self, *args: object) -> None:
1832 pass
1833
1834 return MockContext()
1835
1836 mock_protocol.command_response = _raising_command_response
1837
1838 assert await mgmt_ctl.start_discovery(0) is False
1839 assert await mgmt_ctl.add_adv_pattern_monitor(0) is None
1840 assert await mgmt_ctl.remove_adv_monitor(0, 7) is False
1841
1842
1843 @pytest.mark.asyncio
1844 async def test_command_response_skips_already_resolved_future() -> None:
1845 """A command-complete for an already-resolved future does not re-set it."""
1846 future: asyncio.Future[None] = asyncio.get_running_loop().create_future()
1847 future.set_result(None)
1848 protocol = BluetoothMGMTProtocol(
1849 future, {}, Mock(), Mock(return_value=False), Mock(), {}
1850 )
1851 async with protocol.command_response(MGMT_OP_START_DISCOVERY, 0) as fut:
1852 # Resolve early, then deliver a late response for the same command.
1853 fut.set_result((0x00, b""))
1854 protocol.data_received(
1855 b"\x01\x00" # MGMT_EV_CMD_COMPLETE
1856 b"\x00\x00" # controller index 0
1857 b"\x03\x00" # param_len
1858 + MGMT_OP_START_DISCOVERY.to_bytes(2, "little")
1859 + b"\x05" # different status, must be ignored
1860 )
1861 assert fut.result() == (0x00, b"")
1862
1863
1864 @pytest.mark.asyncio
1865 async def test_command_response_for_unregistered_command_is_ignored() -> None:
1866 """A command-complete with no waiter is dropped without breaking later ones."""
1867 future: asyncio.Future[None] = asyncio.get_running_loop().create_future()
1868 future.set_result(None)
1869 protocol = BluetoothMGMTProtocol(
1870 future, {}, Mock(), Mock(return_value=False), Mock(), {}
1871 )
1872 # No command_response registered for this opcode/controller: must not raise.
1873 protocol.data_received(
1874 b"\x01\x00" # MGMT_EV_CMD_COMPLETE
1875 b"\x00\x00" # controller index 0
1876 b"\x03\x00" # param_len
1877 + MGMT_OP_START_DISCOVERY.to_bytes(2, "little")
1878 + b"\x00" # status success
1879 )
1880 # A subsequently registered command still resolves normally.
1881 async with protocol.command_response(MGMT_OP_STOP_DISCOVERY, 0) as fut:
1882 protocol.data_received(
1883 b"\x01\x00"
1884 b"\x00\x00"
1885 b"\x03\x00" + MGMT_OP_STOP_DISCOVERY.to_bytes(2, "little") + b"\x00"
1886 )
1887 status, _ = await fut
1888 assert status == 0x00
1889
1890
1891 @pytest.mark.asyncio
1892 async def test_add_adv_pattern_monitor_success() -> None:
1893 """add_adv_pattern_monitor returns the handle and sends a match-all monitor."""
1894 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
1895 # Command complete returns the assigned monitor handle (uint16 little-endian).
1896 mock_protocol.command_response = _stub_command_response(0x00, b"\x07\x00")
1897
1898 assert await mgmt_ctl.add_adv_pattern_monitor(0) == 7
1899
1900 sent = mock_protocol._write_to_socket.call_args[0][0]
1901 assert sent[0:2] == MGMT_OP_ADD_ADV_PATTERNS_MONITOR.to_bytes(2, "little")
1902 # param_len 1, pattern_count 0 (match all)
1903 assert sent[4:6] == b"\x01\x00"
1904 assert sent[6] == 0x00
1905
1906
1907 @pytest.mark.asyncio
1908 async def test_add_adv_pattern_monitor_failure() -> None:
1909 """add_adv_pattern_monitor returns None on an error status."""
1910 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
1911 mock_protocol.command_response = _stub_command_response(0x0C, b"")
1912
1913 assert await mgmt_ctl.add_adv_pattern_monitor(0) is None
1914
1915
1916 @pytest.mark.asyncio
1917 async def test_add_adv_pattern_monitor_success_without_handle() -> None:
1918 """A success response missing the 2-byte handle is reported as failure."""
1919 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
1920 mock_protocol.command_response = _stub_command_response(0x00, b"")
1921
1922 assert await mgmt_ctl.add_adv_pattern_monitor(0) is None
1923
1924
1925 @pytest.mark.asyncio
1926 async def test_remove_adv_monitor() -> None:
1927 """remove_adv_monitor returns True on success and sends the handle."""
1928 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
1929 mock_protocol.command_response = _stub_command_response(0x00)
1930
1931 assert await mgmt_ctl.remove_adv_monitor(0, 7) is True
1932
1933 sent = mock_protocol._write_to_socket.call_args[0][0]
1934 assert sent[0:2] == MGMT_OP_REMOVE_ADV_MONITOR.to_bytes(2, "little")
1935 assert sent[6:8] == (7).to_bytes(2, "little")
1936
1937
1938 @pytest.mark.asyncio
1939 async def test_remove_adv_monitor_failure() -> None:
1940 """remove_adv_monitor returns False on an error status."""
1941 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
1942 mock_protocol.command_response = _stub_command_response(0x0C)
1943
1944 assert await mgmt_ctl.remove_adv_monitor(0, 7) is False
1945
1946
1947 @pytest.mark.asyncio
1948 async def test_per_controller_command_response_isolation() -> None:
1949 """Concurrent same-opcode commands on two controllers do not collide."""
1950 future: asyncio.Future[None] = asyncio.get_running_loop().create_future()
1951 future.set_result(None)
1952 protocol = BluetoothMGMTProtocol(
1953 future, {}, Mock(), Mock(return_value=False), Mock(), {}
1954 )
1955
1956 async with (
1957 protocol.command_response(MGMT_OP_START_DISCOVERY, 0) as fut0,
1958 protocol.command_response(MGMT_OP_START_DISCOVERY, 1) as fut1,
1959 ):
1960 # Command complete for controller 1 only.
1961 protocol.data_received(
1962 b"\x01\x00" # MGMT_EV_CMD_COMPLETE
1963 b"\x01\x00" # controller index 1
1964 b"\x03\x00" # param_len
1965 + MGMT_OP_START_DISCOVERY.to_bytes(2, "little")
1966 + b"\x00" # status success
1967 )
1968 assert fut1.done()
1969 assert not fut0.done()
1970 status, _ = await fut1
1971 assert status == 0x00
1972
1973
1974 def test_bytes_mac_to_str() -> None:
1975 """Test bytes_mac_to_str."""
1976 assert bytes_mac_to_str(b"\xff\xee\xdd\xcc\xbb\xaa") == "AA:BB:CC:DD:EE:FF"
1977 assert bytes_mac_to_str(b"\xff\xee\xdd\xcc\xbb\xaa") == "AA:BB:CC:DD:EE:FF"
1978
1979
1980 def test_make_bluez_details() -> None:
1981 """Test make_bluez_details."""
1982 assert make_bluez_details("AA:BB:CC:DD:EE:FF", "hci0") == {
1983 "path": "/org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF",
1984 "props": {"Adapter": "/org/bluez/hci0"},
1985 }
1986
1987
1988 # -- pairing / disconnect commands ----------------------------------------
1989 @pytest.mark.asyncio
1990 async def test_pair_device_success() -> None:
1991 """pair_device sends bdaddr + type + IO capability and returns True."""
1992 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
1993 mock_protocol.command_response = _stub_command_response(0x00)
1994
1995 assert await mgmt_ctl.pair_device(0, "AA:BB:CC:DD:EE:FF", BDADDR_LE_RANDOM) is True
1996
1997 sent = mock_protocol._write_to_socket.call_args[0][0]
1998 assert sent[0:2] == MGMT_OP_PAIR_DEVICE.to_bytes(2, "little")
1999 assert sent[2:4] == b"\x00\x00" # controller idx
2000 assert sent[6:12] == bytes([0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA]) # reversed
2001 assert sent[12] == BDADDR_LE_RANDOM
2002 assert sent[13] == IO_CAPABILITY_NO_INPUT_NO_OUTPUT
2003
2004
2005 @pytest.mark.asyncio
2006 async def test_pair_device_failure() -> None:
2007 """pair_device returns False on a non-success status."""
2008 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
2009 mock_protocol.command_response = _stub_command_response(0x03)
2010 assert await mgmt_ctl.pair_device(0, "AA:BB:CC:DD:EE:FF", BDADDR_LE_PUBLIC) is False
2011
2012
2013 @pytest.mark.asyncio
2014 async def test_unpair_device_success() -> None:
2015 """unpair_device sends bdaddr + type + disconnect flag and returns True."""
2016 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
2017 mock_protocol.command_response = _stub_command_response(0x00)
2018
2019 assert (
2020 await mgmt_ctl.unpair_device(0, "AA:BB:CC:DD:EE:FF", BDADDR_LE_PUBLIC) is True
2021 )
2022
2023 sent = mock_protocol._write_to_socket.call_args[0][0]
2024 assert sent[0:2] == MGMT_OP_UNPAIR_DEVICE.to_bytes(2, "little")
2025 assert sent[6:12] == bytes([0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA])
2026 assert sent[12] == BDADDR_LE_PUBLIC
2027 assert sent[13] == 1 # disconnect default
2028
2029
2030 @pytest.mark.asyncio
2031 async def test_unpair_device_without_disconnect() -> None:
2032 """unpair_device(disconnect=False) clears the disconnect flag."""
2033 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
2034 mock_protocol.command_response = _stub_command_response(0x00)
2035
2036 assert (
2037 await mgmt_ctl.unpair_device(
2038 0, "AA:BB:CC:DD:EE:FF", BDADDR_LE_PUBLIC, disconnect=False
2039 )
2040 is True
2041 )
2042 assert mock_protocol._write_to_socket.call_args[0][0][13] == 0
2043
2044
2045 @pytest.mark.asyncio
2046 async def test_disconnect_device_success() -> None:
2047 """disconnect_device sends bdaddr + type and returns True."""
2048 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
2049 mock_protocol.command_response = _stub_command_response(0x00)
2050
2051 assert (
2052 await mgmt_ctl.disconnect_device(0, "AA:BB:CC:DD:EE:FF", BDADDR_LE_RANDOM)
2053 is True
2054 )
2055
2056 sent = mock_protocol._write_to_socket.call_args[0][0]
2057 assert sent[0:2] == MGMT_OP_DISCONNECT.to_bytes(2, "little")
2058 assert sent[6:12] == bytes([0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA])
2059 assert sent[12] == BDADDR_LE_RANDOM
2060
2061
2062 @pytest.mark.asyncio
2063 async def test_disconnect_device_no_response() -> None:
2064 """A command with no response (timeout) returns False."""
2065 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
2066 mock_protocol.transport = None # no connection -> _send_command_await None
2067 assert (
2068 await mgmt_ctl.disconnect_device(0, "AA:BB:CC:DD:EE:FF", BDADDR_LE_PUBLIC)
2069 is False
2070 )
2071
2072
2073 @pytest.mark.asyncio
2074 async def test_unpair_device_failure() -> None:
2075 """unpair_device returns False on a non-success status."""
2076 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
2077 mock_protocol.command_response = _stub_command_response(0x03)
2078 assert (
2079 await mgmt_ctl.unpair_device(0, "AA:BB:CC:DD:EE:FF", BDADDR_LE_PUBLIC) is False
2080 )
2081
2082
2083 @pytest.mark.asyncio
2084 @pytest.mark.parametrize(
2085 "command",
2086 ["pair_device", "unpair_device", "disconnect_device"],
2087 )
2088 @pytest.mark.parametrize(
2089 "bad_address",
2090 ["AA:BB", "ZZ:BB:CC:DD:EE:FF"], # too short, and non-hex
2091 )
2092 async def test_pairing_commands_reject_invalid_address(
2093 command: str, bad_address: str
2094 ) -> None:
2095 """A malformed address is a soft failure, not an exception."""
2096 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
2097 mock_protocol.command_response = _stub_command_response(0x00)
2098 assert await getattr(mgmt_ctl, command)(0, bad_address, BDADDR_LE_PUBLIC) is False
2099 mock_protocol._write_to_socket.assert_not_called()
2100
2101
2102 # -- load long-term keys --------------------------------------------------
2103 def _ltk(address: str = "AA:BB:CC:DD:EE:FF") -> LongTermKey:
2104 return LongTermKey(
2105 address=address,
2106 address_type=BDADDR_LE_RANDOM,
2107 key_type=1,
2108 central=False,
2109 encryption_size=16,
2110 ediv=0x1234,
2111 rand=bytes(range(8)),
2112 value=bytes(range(16)),
2113 )
2114
2115
2116 @pytest.mark.asyncio
2117 async def test_load_long_term_keys_success() -> None:
2118 """load_long_term_keys packs the count and a 36 byte record per key."""
2119 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
2120 mock_protocol.command_response = _stub_command_response(0x00)
2121
2122 assert await mgmt_ctl.load_long_term_keys(0, [_ltk()]) is True
2123
2124 sent = mock_protocol._write_to_socket.call_args[0][0]
2125 assert sent[0:2] == MGMT_OP_LOAD_LONG_TERM_KEYS.to_bytes(2, "little")
2126 assert sent[6:8] == (1).to_bytes(2, "little") # key_count
2127 record = sent[8:]
2128 assert len(record) == 36
2129 assert record[0:6] == bytes([0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA]) # reversed
2130 assert record[6] == BDADDR_LE_RANDOM
2131 assert record[7] == 1 # key_type
2132 assert record[8] == 0 # central flag (False)
2133 assert record[9] == 16 # encryption_size
2134 assert record[10:12] == (0x1234).to_bytes(2, "little") # ediv
2135 assert record[12:20] == bytes(range(8)) # rand
2136 assert record[20:36] == bytes(range(16)) # value
2137
2138
2139 @pytest.mark.asyncio
2140 async def test_load_long_term_keys_empty_clears() -> None:
2141 """An empty key list sends a zero count (clears the controller's keys)."""
2142 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
2143 mock_protocol.command_response = _stub_command_response(0x00)
2144
2145 assert await mgmt_ctl.load_long_term_keys(0, []) is True
2146 sent = mock_protocol._write_to_socket.call_args[0][0]
2147 assert sent[6:8] == (0).to_bytes(2, "little")
2148 assert len(sent[8:]) == 0
2149
2150
2151 @pytest.mark.asyncio
2152 async def test_load_long_term_keys_failure() -> None:
2153 """A non-success status returns False."""
2154 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
2155 mock_protocol.command_response = _stub_command_response(0x03)
2156 assert await mgmt_ctl.load_long_term_keys(0, [_ltk()]) is False
2157
2158
2159 @pytest.mark.asyncio
2160 async def test_load_long_term_keys_rejects_invalid_address() -> None:
2161 """A malformed address in a key is a soft failure with nothing sent."""
2162 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
2163 mock_protocol.command_response = _stub_command_response(0x00)
2164 assert await mgmt_ctl.load_long_term_keys(0, [_ltk("AA:BB")]) is False
2165 mock_protocol._write_to_socket.assert_not_called()
2166
2167
2168 @pytest.mark.asyncio
2169 @pytest.mark.parametrize(
2170 "key",
2171 [
2172 LongTermKey("AA:BB:CC:DD:EE:FF", 1, 1, False, 16, 0, b"\x00" * 7, b"\x00" * 16),
2173 LongTermKey("AA:BB:CC:DD:EE:FF", 1, 1, False, 16, 0, b"\x00" * 8, b"\x00" * 15),
2174 ],
2175 )
2176 async def test_load_long_term_keys_rejects_malformed_key(key: LongTermKey) -> None:
2177 """A key with the wrong rand/value length is rejected without sending."""
2178 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
2179 mock_protocol.command_response = _stub_command_response(0x00)
2180 assert await mgmt_ctl.load_long_term_keys(0, [key]) is False
2181 mock_protocol._write_to_socket.assert_not_called()
2182
2183
2184 @pytest.mark.asyncio
2185 async def test_load_long_term_keys_rejects_out_of_range_field() -> None:
2186 """An out-of-range integer field is a soft failure, not a struct.error."""
2187 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
2188 mock_protocol.command_response = _stub_command_response(0x00)
2189 bad = LongTermKey(
2190 "AA:BB:CC:DD:EE:FF", 1, 300, False, 16, 0, b"\x00" * 8, b"\x00" * 16
2191 ) # key_type 300 does not fit in a byte
2192 assert await mgmt_ctl.load_long_term_keys(0, [bad]) is False
2193 mock_protocol._write_to_socket.assert_not_called()
2194
2195
2196 # -- pairing event capture ------------------------------------------------
2197 def _new_ltk_frame(
2198 *,
2199 store_hint: int = 1,
2200 address: bytes = b"\xff\xee\xdd\xcc\xbb\xaa", # little-endian AA:BB:..:FF
2201 controller_idx: int = 0,
2202 ) -> bytes:
2203 ltk_info = (
2204 address
2205 + bytes([0x01, 0x05, 0x00, 0x10]) # type, key_type, central, enc_size
2206 + (0x1234).to_bytes(2, "little") # ediv
2207 + bytes(range(8)) # rand
2208 + bytes(range(16)) # value
2209 )
2210 param = bytes([store_hint]) + ltk_info
2211 header = (
2212 (0x000A).to_bytes(2, "little")
2213 + controller_idx.to_bytes(2, "little")
2214 + len(param).to_bytes(2, "little")
2215 )
2216 return header + param
2217
2218
2219 def _protocol_with_handlers(
2220 event_loop: asyncio.AbstractEventLoop,
2221 handlers: dict[tuple[int, str], Callable[..., None]],
2222 ) -> BluetoothMGMTProtocol:
2223 return BluetoothMGMTProtocol(
2224 event_loop.create_future(),
2225 {},
2226 Mock(),
2227 Mock(return_value=False),
2228 Mock(),
2229 handlers,
2230 )
2231
2232
2233 def test_data_received_new_long_term_key(
2234 event_loop: asyncio.AbstractEventLoop,
2235 ) -> None:
2236 """A NEW_LONG_TERM_KEY event is decoded and routed to its handler."""
2237 received: list[object] = []
2238 handlers = {(0, "AA:BB:CC:DD:EE:FF"): received.append}
2239 protocol = _protocol_with_handlers(event_loop, handlers)
2240
2241 protocol.data_received(_new_ltk_frame())
2242
2243 assert len(received) == 1
2244 event = received[0]
2245 assert isinstance(event, NewLongTermKey)
2246 assert event.store_hint == 1
2247 key = event.key
2248 assert key == LongTermKey(
2249 address="AA:BB:CC:DD:EE:FF",
2250 address_type=0x01,
2251 key_type=0x05,
2252 central=False,
2253 encryption_size=0x10,
2254 ediv=0x1234,
2255 rand=bytes(range(8)),
2256 value=bytes(range(16)),
2257 )
2258
2259
2260 def test_data_received_auth_failed(event_loop: asyncio.AbstractEventLoop) -> None:
2261 """An AUTHENTICATION_FAILED event is decoded and routed to its handler."""
2262 received: list[object] = []
2263 handlers = {(0, "AA:BB:CC:DD:EE:FF"): received.append}
2264 protocol = _protocol_with_handlers(event_loop, handlers)
2265
2266 param = b"\xff\xee\xdd\xcc\xbb\xaa" + bytes([0x01, 0x05]) # type, status
2267 header = (
2268 (0x0011).to_bytes(2, "little") + b"\x00\x00" + len(param).to_bytes(2, "little")
2269 )
2270 protocol.data_received(header + param)
2271
2272 assert received == [AuthenticationFailed("AA:BB:CC:DD:EE:FF", 0x01, 0x05)]
2273
2274
2275 def test_pairing_event_without_handler_is_dropped(
2276 event_loop: asyncio.AbstractEventLoop,
2277 ) -> None:
2278 """An event for an unregistered peer is dropped without error."""
2279 protocol = _protocol_with_handlers(event_loop, {})
2280 protocol.data_received(_new_ltk_frame()) # no handlers -> no-op
2281 auth_param = b"\xff\xee\xdd\xcc\xbb\xaa" + bytes([0x01, 0x05])
2282 auth_header = (
2283 (0x0011).to_bytes(2, "little")
2284 + b"\x00\x00"
2285 + len(auth_param).to_bytes(2, "little")
2286 )
2287 protocol.data_received(auth_header + auth_param) # no handlers -> no-op
2288
2289
2290 def test_truncated_new_long_term_key_is_dropped(
2291 event_loop: asyncio.AbstractEventLoop,
2292 ) -> None:
2293 """A NEW_LONG_TERM_KEY event too short to hold a key is dropped."""
2294 received: list[object] = []
2295 handlers = {(0, "AA:BB:CC:DD:EE:FF"): received.append}
2296 protocol = _protocol_with_handlers(event_loop, handlers)
2297
2298 param = b"\x01\xff\xee" # store_hint + 2 bytes (well short of 1 + 36)
2299 header = (
2300 (0x000A).to_bytes(2, "little") + b"\x00\x00" + len(param).to_bytes(2, "little")
2301 )
2302 protocol.data_received(header + param)
2303 assert received == []
2304
2305
2306 def test_truncated_auth_failed_is_dropped(
2307 event_loop: asyncio.AbstractEventLoop,
2308 ) -> None:
2309 """An AUTHENTICATION_FAILED event shorter than 8 bytes is dropped."""
2310 received: list[object] = []
2311 handlers = {(0, "AA:BB:CC:DD:EE:FF"): received.append}
2312 protocol = _protocol_with_handlers(event_loop, handlers)
2313
2314 param = b"\xff\xee\xdd" # 3 bytes, short of 8
2315 header = (
2316 (0x0011).to_bytes(2, "little") + b"\x00\x00" + len(param).to_bytes(2, "little")
2317 )
2318 protocol.data_received(header + param)
2319 assert received == []
2320
2321
2322 def test_pairing_handler_exception_is_isolated(
2323 event_loop: asyncio.AbstractEventLoop,
2324 caplog: pytest.LogCaptureFixture,
2325 ) -> None:
2326 """A raising handler is logged, not allowed to break the read loop."""
2327
2328 def boom(_event: object) -> None:
2329 msg = "handler exploded"
2330 raise RuntimeError(msg)
2331
2332 handlers = {(0, "AA:BB:CC:DD:EE:FF"): boom}
2333 protocol = _protocol_with_handlers(event_loop, handlers)
2334 with caplog.at_level("ERROR", logger="habluetooth.channels.bluez"):
2335 # Neither dispatch path should raise out of data_received.
2336 protocol.data_received(_new_ltk_frame())
2337 auth_param = b"\xff\xee\xdd\xcc\xbb\xaa" + bytes([0x01, 0x05])
2338 auth_header = (
2339 (0x0011).to_bytes(2, "little")
2340 + b"\x00\x00"
2341 + len(auth_param).to_bytes(2, "little")
2342 )
2343 protocol.data_received(auth_header + auth_param)
2344 assert caplog.text.count("Error in") == 2 # both handlers logged
2345
2346
2347 @pytest.mark.asyncio
2348 async def test_register_pairing_handler_normalizes_and_unregisters() -> None:
2349 """register_pairing_handler normalizes the address and unregisters cleanly."""
2350 mgmt_ctl = MGMTBluetoothCtl(timeout=5.0, scanners={})
2351 handler = Mock()
2352 unregister = mgmt_ctl.register_pairing_handler(0, "aa:bb:cc:dd:ee:ff", handler)
2353 assert mgmt_ctl._pairing_handlers[(0, "AA:BB:CC:DD:EE:FF")] is handler
2354 unregister()
2355 assert (0, "AA:BB:CC:DD:EE:FF") not in mgmt_ctl._pairing_handlers
2356 unregister() # idempotent, does not raise
2357
2358
2359 @pytest.mark.asyncio
2360 async def test_register_pairing_handler_last_wins() -> None:
2361 """A second registration replaces the first; the first's unregister no-ops."""
2362 mgmt_ctl = MGMTBluetoothCtl(timeout=5.0, scanners={})
2363 first, second = Mock(), Mock()
2364 key = (0, "AA:BB:CC:DD:EE:FF")
2365 unregister_first = mgmt_ctl.register_pairing_handler(0, "AA:BB:CC:DD:EE:FF", first)
2366 mgmt_ctl.register_pairing_handler(0, "AA:BB:CC:DD:EE:FF", second)
2367 assert mgmt_ctl._pairing_handlers[key] is second
2368 unregister_first() # must not remove the newer handler
2369 assert mgmt_ctl._pairing_handlers[key] is second
2370
2371
2372 # -- interactive pairing replies + request events -------------------------
2373 _REV_PEER = b"\xff\xee\xdd\xcc\xbb\xaa" # little-endian AA:BB:CC:DD:EE:FF
2374 _PEER_STR = "AA:BB:CC:DD:EE:FF"
2375
2376
2377 @pytest.mark.asyncio
2378 @pytest.mark.parametrize(
2379 ("accept", "opcode"),
2380 [(True, MGMT_OP_USER_CONFIRM_REPLY), (False, MGMT_OP_USER_CONFIRM_NEG_REPLY)],
2381 )
2382 async def test_user_confirmation_reply(accept: bool, opcode: int) -> None:
2383 """Confirmation accept/reject send the right opcode with addr + type."""
2384 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
2385 mock_protocol.command_response = _stub_command_response(0x00)
2386 assert (
2387 await mgmt_ctl.user_confirmation_reply(
2388 0, _PEER_STR, BDADDR_LE_RANDOM, accept=accept
2389 )
2390 is True
2391 )
2392 sent = mock_protocol._write_to_socket.call_args[0][0]
2393 assert sent[0:2] == opcode.to_bytes(2, "little")
2394 assert sent[6:12] == _REV_PEER
2395 assert sent[12] == BDADDR_LE_RANDOM
2396
2397
2398 @pytest.mark.asyncio
2399 async def test_user_passkey_reply() -> None:
2400 """Passkey reply carries the addr, type, and uint32 passkey."""
2401 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
2402 mock_protocol.command_response = _stub_command_response(0x00)
2403 assert (
2404 await mgmt_ctl.user_passkey_reply(0, _PEER_STR, BDADDR_LE_RANDOM, 123456)
2405 is True
2406 )
2407 sent = mock_protocol._write_to_socket.call_args[0][0]
2408 assert sent[0:2] == MGMT_OP_USER_PASSKEY_REPLY.to_bytes(2, "little")
2409 assert sent[6:12] == _REV_PEER
2410 assert sent[12] == BDADDR_LE_RANDOM
2411 assert sent[13:17] == (123456).to_bytes(4, "little")
2412
2413
2414 @pytest.mark.asyncio
2415 async def test_user_passkey_negative_reply() -> None:
2416 """Passkey negative reply sends addr + type with the negative opcode."""
2417 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
2418 mock_protocol.command_response = _stub_command_response(0x00)
2419 assert (
2420 await mgmt_ctl.user_passkey_negative_reply(0, _PEER_STR, BDADDR_LE_PUBLIC)
2421 is True
2422 )
2423 sent = mock_protocol._write_to_socket.call_args[0][0]
2424 assert sent[0:2] == MGMT_OP_USER_PASSKEY_NEG_REPLY.to_bytes(2, "little")
2425
2426
2427 @pytest.mark.asyncio
2428 async def test_user_reply_failure() -> None:
2429 """A non-success status returns False."""
2430 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
2431 mock_protocol.command_response = _stub_command_response(0x03)
2432 assert (
2433 await mgmt_ctl.user_confirmation_reply(0, _PEER_STR, BDADDR_LE_PUBLIC) is False
2434 )
2435
2436
2437 @pytest.mark.asyncio
2438 async def test_user_reply_rejects_invalid_address() -> None:
2439 """A malformed address is a soft failure with nothing sent."""
2440 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
2441 mock_protocol.command_response = _stub_command_response(0x00)
2442 assert await mgmt_ctl.user_passkey_reply(0, "AA:BB", BDADDR_LE_PUBLIC, 1) is False
2443 mock_protocol._write_to_socket.assert_not_called()
2444
2445
2446 def test_data_received_user_confirmation_request(
2447 event_loop: asyncio.AbstractEventLoop,
2448 ) -> None:
2449 """A USER_CONFIRMATION_REQUEST event decodes the comparison value."""
2450 received: list[object] = []
2451 protocol = _protocol_with_handlers(event_loop, {(0, _PEER_STR): received.append})
2452 param = _REV_PEER + bytes([0x01, 0x01]) + (123456).to_bytes(4, "little")
2453 header = (
2454 (0x000F).to_bytes(2, "little") + b"\x00\x00" + len(param).to_bytes(2, "little")
2455 )
2456 protocol.data_received(header + param)
2457 assert received == [UserConfirmationRequest(_PEER_STR, 0x01, 0x01, 123456)]
2458
2459
2460 def test_data_received_user_passkey_request(
2461 event_loop: asyncio.AbstractEventLoop,
2462 ) -> None:
2463 """A USER_PASSKEY_REQUEST event routes to the handler."""
2464 received: list[object] = []
2465 protocol = _protocol_with_handlers(event_loop, {(0, _PEER_STR): received.append})
2466 param = _REV_PEER + bytes([0x01])
2467 header = (
2468 (0x0010).to_bytes(2, "little") + b"\x00\x00" + len(param).to_bytes(2, "little")
2469 )
2470 protocol.data_received(header + param)
2471 assert received == [UserPasskeyRequest(_PEER_STR, 0x01)]
2472
2473
2474 @pytest.mark.parametrize(
2475 ("event_code", "param"),
2476 [(0x000F, b"\xff\xee\xdd"), (0x0010, b"\xff\xee")],
2477 )
2478 def test_truncated_user_request_is_dropped(
2479 event_loop: asyncio.AbstractEventLoop, event_code: int, param: bytes
2480 ) -> None:
2481 """A user-request event too short to parse is dropped, not mis-read."""
2482 received: list[object] = []
2483 protocol = _protocol_with_handlers(event_loop, {(0, _PEER_STR): received.append})
2484 header = (
2485 event_code.to_bytes(2, "little")
2486 + b"\x00\x00"
2487 + len(param).to_bytes(2, "little")
2488 )
2489 protocol.data_received(header + param)
2490 assert received == []
2491
2492
2493 @pytest.mark.parametrize(
2494 ("event_code", "param"),
2495 [
2496 (0x000F, _REV_PEER + bytes([0x01, 0x01]) + (1).to_bytes(4, "little")),
2497 (0x0010, _REV_PEER + bytes([0x01])),
2498 ],
2499 )
2500 def test_user_request_without_handler_is_dropped(
2501 event_loop: asyncio.AbstractEventLoop, event_code: int, param: bytes
2502 ) -> None:
2503 """A user-request event for an unregistered peer is dropped without error."""
2504 protocol = _protocol_with_handlers(event_loop, {})
2505 header = (
2506 event_code.to_bytes(2, "little")
2507 + b"\x00\x00"
2508 + len(param).to_bytes(2, "little")
2509 )
2510 protocol.data_received(header + param) # no handlers -> no-op
2511
2512
2513 @pytest.mark.asyncio
2514 async def test_user_reply_rejects_out_of_range_passkey() -> None:
2515 """A passkey that does not fit a uint32 is a soft failure, not a struct.error."""
2516 mgmt_ctl, mock_protocol = _mgmt_ctl_with_mock_protocol()
2517 mock_protocol.command_response = _stub_command_response(0x00)
2518 assert (
2519 await mgmt_ctl.user_passkey_reply(0, _PEER_STR, BDADDR_LE_PUBLIC, 2**32)
2520 is False
2521 )
2522 mock_protocol._write_to_socket.assert_not_called()