Debian Codegraph @

tests/test_util.py

raw
1 """Tests for habluetooth.util."""
2
3 from __future__ import annotations
4
5 import asyncio
6 from typing import TYPE_CHECKING
7 from unittest.mock import AsyncMock, patch
8
9 import pytest
10
11 from habluetooth.util import (
12 async_reset_adapter,
13 coalesce_concurrent_future,
14 is_docker_env,
15 )
16
17 if TYPE_CHECKING:
18 from collections.abc import Iterator
19
20
21 @pytest.fixture
22 def mock_recover_adapter() -> Iterator[AsyncMock]:
23 """Patch habluetooth.util.recover_adapter with an AsyncMock."""
24 mock = AsyncMock()
25 with patch("habluetooth.util.recover_adapter", mock):
26 yield mock
27
28
29 @pytest.mark.asyncio
30 async def test_async_reset_adapter_with_hci_adapter(
31 mock_recover_adapter: AsyncMock,
32 ) -> None:
33 """An hciN adapter delegates to bluetooth_auto_recovery.recover_adapter."""
34 mock_recover_adapter.return_value = True
35 assert await async_reset_adapter("hci3", "AA:BB:CC:DD:EE:FF", True) is True
36 mock_recover_adapter.assert_awaited_once_with(3, "AA:BB:CC:DD:EE:FF", True)
37
38
39 @pytest.mark.asyncio
40 async def test_async_reset_adapter_returns_false_when_adapter_is_none(
41 mock_recover_adapter: AsyncMock,
42 ) -> None:
43 """No adapter → recover_adapter is not invoked, returns False."""
44 assert await async_reset_adapter(None, "AA:BB:CC:DD:EE:FF", False) is False
45 mock_recover_adapter.assert_not_called()
46
47
48 @pytest.mark.asyncio
49 async def test_async_reset_adapter_returns_false_for_non_hci_adapter(
50 mock_recover_adapter: AsyncMock,
51 ) -> None:
52 """A non-hci adapter (e.g. CoreBluetooth) returns False without recovery."""
53 assert (
54 await async_reset_adapter("Core Bluetooth", "AA:BB:CC:DD:EE:FF", False) is False
55 )
56 mock_recover_adapter.assert_not_called()
57
58
59 def test_is_docker_env_true(monkeypatch: pytest.MonkeyPatch) -> None:
60 """/.dockerenv present → True."""
61 is_docker_env.cache_clear()
62 monkeypatch.setattr("habluetooth.util.Path.exists", lambda self: True)
63 assert is_docker_env() is True
64 is_docker_env.cache_clear()
65
66
67 def test_is_docker_env_false(monkeypatch: pytest.MonkeyPatch) -> None:
68 """/.dockerenv missing → False."""
69 is_docker_env.cache_clear()
70 monkeypatch.setattr("habluetooth.util.Path.exists", lambda self: False)
71 assert is_docker_env() is False
72 is_docker_env.cache_clear()
73
74
75 class _Coalesced:
76 """Test fixture instance for the coalesce_concurrent_future decorator."""
77
78 def __init__(self) -> None:
79 self._fut: asyncio.Future[int] | None = None
80 self.call_count = 0
81 self.started = asyncio.Event()
82 self.release = asyncio.Event()
83 self.return_value = 42
84 self.raise_exc: BaseException | None = None
85
86 @coalesce_concurrent_future("_fut")
87 async def work(self) -> int:
88 self.call_count += 1
89 self.started.set()
90 await self.release.wait()
91 if self.raise_exc is not None:
92 raise self.raise_exc
93 return self.return_value
94
95
96 @pytest.mark.asyncio
97 async def test_coalesce_concurrent_future_single_call_returns_result() -> None:
98 """A lone caller runs the wrapped coroutine and gets its result."""
99 obj = _Coalesced()
100 obj.release.set()
101 assert await obj.work() == 42
102 assert obj.call_count == 1
103 assert obj._fut is None
104
105
106 @pytest.mark.asyncio
107 async def test_coalesce_concurrent_future_concurrent_callers_share_one_call() -> None:
108 """Concurrent callers share a single underlying invocation."""
109 obj = _Coalesced()
110 leader = asyncio.create_task(obj.work())
111 await obj.started.wait()
112 waiter_a = asyncio.create_task(obj.work())
113 waiter_b = asyncio.create_task(obj.work())
114 await asyncio.sleep(0)
115 obj.release.set()
116 assert await leader == 42
117 assert await waiter_a == 42
118 assert await waiter_b == 42
119 assert obj.call_count == 1
120 assert obj._fut is None
121
122
123 @pytest.mark.asyncio
124 async def test_coalesce_concurrent_future_propagates_exception_to_waiters() -> None:
125 """Leader exception is observed by every concurrent waiter."""
126 obj = _Coalesced()
127 obj.raise_exc = RuntimeError("boom")
128 leader = asyncio.create_task(obj.work())
129 await obj.started.wait()
130 waiter = asyncio.create_task(obj.work())
131 await asyncio.sleep(0)
132 obj.release.set()
133 with pytest.raises(RuntimeError, match="boom"):
134 await leader
135 with pytest.raises(RuntimeError, match="boom"):
136 await waiter
137 assert obj._fut is None
138
139
140 @pytest.mark.asyncio
141 async def test_coalesce_concurrent_future_leader_cancellation_surfaces_to_waiters() -> (
142 None
143 ):
144 """Leader cancellation propagates to waiters, future is cleared."""
145 obj = _Coalesced()
146 leader = asyncio.create_task(obj.work())
147 await obj.started.wait()
148 waiter = asyncio.create_task(obj.work())
149 await asyncio.sleep(0)
150 leader.cancel()
151 with pytest.raises(asyncio.CancelledError):
152 await leader
153 with pytest.raises(asyncio.CancelledError):
154 await waiter
155 assert obj._fut is None
156
157
158 @pytest.mark.asyncio
159 async def test_coalesce_concurrent_future_waiter_cancel_does_not_strand_leader() -> (
160 None
161 ):
162 """Cancelling a waiter does not poison the shared future."""
163 obj = _Coalesced()
164 leader = asyncio.create_task(obj.work())
165 await obj.started.wait()
166 waiter_a = asyncio.create_task(obj.work())
167 waiter_b = asyncio.create_task(obj.work())
168 await asyncio.sleep(0)
169 waiter_a.cancel()
170 with pytest.raises(asyncio.CancelledError):
171 await waiter_a
172 obj.release.set()
173 assert await leader == 42
174 assert await waiter_b == 42
175 assert obj._fut is None
176
177
178 @pytest.mark.asyncio
179 async def test_coalesce_concurrent_future_resets_between_sequential_calls() -> None:
180 """Future state resets so a later call runs fresh."""
181 obj = _Coalesced()
182 obj.release.set()
183 assert await obj.work() == 42
184 assert obj._fut is None
185 obj.return_value = 7
186 assert await obj.work() == 7
187 assert obj.call_count == 2
188
189
190 @pytest.mark.asyncio
191 async def test_coalesce_concurrent_future_requires_attribute_initialised() -> None:
192 """Missing attribute on the instance raises AttributeError."""
193
194 class _Missing:
195 @coalesce_concurrent_future("_fut")
196 async def work(self) -> int:
197 return 1
198
199 with pytest.raises(AttributeError):
200 await _Missing().work()