Debian Codegraph @

tests/test_asyncio_adapter.py

raw ◀ ▶
1 Debian patch touch this file
1 import asyncio
2 import hashlib
3 import os
•4 import sys
5 from functools import wraps
6 from typing import Any, Callable, Coroutine, TypeVar, Union
7 from unittest.mock import Mock
8
9 import pytest
10
•11 if sys.version_info >= (3, 10):
12 from typing import ParamSpec
13 else:
14 from typing_extensions import ParamSpec
15
16 # timeout() function and typing code above with some imports was copied from
17 # the aiomisc project:
18 # https://github.com/aiokitchen/aiomisc/blob/master/aiomisc/timeout.py
19 # aiomisc is licensed under the MIT license with the copyright:
20 # Copyright © 2023 Dmitry Orlov <[email protected]>
21
22 T = TypeVar("T")
23 P = ParamSpec("P")
24 Number = Union[int, float]
25
26 def timeout(
27 value: Number,
28 ) -> Callable[
29 [Callable[P, Coroutine[Any, Any, T]]],
30 Callable[P, Coroutine[Any, Any, T]],
31 ]:
32 def decorator(
33 func: Callable[P, Coroutine[Any, Any, T]],
34 ) -> Callable[P, Coroutine[Any, Any, T]]:
35 if not asyncio.iscoroutinefunction(func):
36 raise TypeError("Function is not a coroutine function")
37
38 @wraps(func)
39 async def wrap(*args: P.args, **kwargs: P.kwargs) -> T:
40 return await asyncio.wait_for(
41 func(*args, **kwargs),
42 timeout=value,
43 )
44 return wrap
45 return decorator
46
47
•48 @timeout(5)
49 async def test_linux_uring_asyncio_forwards_context_kwargs():
50 uring_asyncio = pytest.importorskip("caio.linux_uring_asyncio")
51
52 async with uring_asyncio.AsyncioContext(
53 max_requests=8,
54 sqpoll=True,
55 deferred=True,
56 ) as context:
57 # Unsupported kernels/permissions may make the C context fall back
58 # to a regular ring. Reaching this point proves that the asyncio
59 # adapter forwarded the backend-specific option instead of rejecting
60 # it in _create_context().
61 assert context.context.sqpoll in (0, 1)
62 assert context.deferred is True
63
64
•65 @timeout(5)
66 async def test_adapter(tmp_path, async_context):
67 context = async_context
•68 with open(
69 str(tmp_path / "temp.bin"), "wb+"
70 ) as fp: # noqa: ASYNC230 (brief sync setup, not the operation under test)
71 fd = fp.fileno()
72
73 assert await context.read(32, fd, 0) == b""
74 s = b"Hello world"
75 assert await context.write(s, fd, 0) == len(s)
76 assert await context.read(32, fd, 0) == s
77
78 s = b"Hello real world"
79 assert await context.write(s, fd, 0) == len(s)
80 assert await context.read(32, fd, 0) == s
81
82 part = b"\x00\x01\x02\x03"
83 limit = 32
84 expected_hash = hashlib.md5(part * limit).hexdigest()
85
86 await asyncio.gather(
87 *[context.write(part, fd, len(part) * i) for i in range(limit)]
88 )
89
90 await context.fdsync(fd)
91
92 data = await context.read(limit * len(part), fd, 0)
93 assert data == part * limit
94
95 assert hashlib.md5(bytes(data)).hexdigest() == expected_hash
96
97
•98 @timeout(3)
99 async def test_bad_file_descritor(tmp_path, async_context):
100 context = async_context
•101 with open(
102 str(tmp_path / "temp.bin"), "wb+"
103 ) as fp: # noqa: ASYNC230 (brief sync setup, not the operation under test)
104 fd = fp.fileno()
105
106 with pytest.raises((SystemError, OSError, AssertionError, ValueError)):
107 assert await context.read(1, fd, 0) == b""
108
109 with pytest.raises((SystemError, OSError, AssertionError, ValueError)):
110 assert await context.write(b"hello", fd, 0)
111
112
113 @pytest.fixture
114 async def asyncio_exception_handler():
•115 handler = Mock(side_effect=lambda _loop, ctx: _loop.default_exception_handler(ctx))
116 event_loop = asyncio.get_running_loop()
117 current_handler = event_loop.get_exception_handler()
118 event_loop.set_exception_handler(handler=handler)
119 yield handler
120 event_loop.set_exception_handler(current_handler)
121
122
•123 @timeout(3)
124 async def test_operations_cancel_cleanly(
125 tmp_path, async_context, asyncio_exception_handler
126 ):
127 context = async_context
•128 with open(
129 str(tmp_path / "temp.bin"), "wb+"
130 ) as fp: # noqa: ASYNC230 (brief sync setup, not the operation under test)
131 fd = fp.fileno()
132
133 await context.write(b"\x00", fd, 1024**2 - 1)
134 assert os.stat(fd).st_size == 1024**2
135
136 for _ in range(50):
137 reads = [
138 asyncio.create_task(context.read(2**16, fd, 2**16 * i))
139 for i in range(16)
140 ]
•141 _, pending = await asyncio.wait(reads, return_when=asyncio.FIRST_COMPLETED)
142 for read in pending:
143 read.cancel()
144 if pending:
145 await asyncio.wait(pending)
146 asyncio_exception_handler.assert_not_called()
147
148
•149 @timeout(3)
150 async def test_write_operations_cancel_cleanly(
151 tmp_path, async_context, asyncio_exception_handler
152 ):
153 """Mirrors test_operations_cancel_cleanly but for writes - cancellation
154 handling shouldn't be read-specific."""
155 context = async_context
•156 with open(
157 str(tmp_path / "temp.bin"), "wb+"
158 ) as fp: # noqa: ASYNC230 (brief sync setup, not the operation under test)
159 fd = fp.fileno()
160
161 for _ in range(50):
162 writes = [
163 asyncio.create_task(
164 context.write(b"\x01" * 2**16, fd, 2**16 * i),
165 )
166 for i in range(16)
167 ]
•168 _, pending = await asyncio.wait(writes, return_when=asyncio.FIRST_COMPLETED)
169 for write in pending:
170 write.cancel()
171 if pending:
172 await asyncio.wait(pending)
173 asyncio_exception_handler.assert_not_called()
174
175
•176 @timeout(3)
177 async def test_cancel_before_first_step_runs(
178 tmp_path, async_context, asyncio_exception_handler
179 ):
180 """Cancelling right after the op's own first step (submit queued, still
181 suspended at `await future`) - covers context.cancel() raising ValueError
182 for an op the backend never actually got to submit to the kernel yet."""
183 context = async_context
184 with open(str(tmp_path / "temp.bin"), "wb+") as fp: # noqa: ASYNC230
185 fd = fp.fileno()
186 task = asyncio.ensure_future(context.write(b"x", fd, 0))
187 await asyncio.sleep(0)
188 task.cancel()
189 with pytest.raises(asyncio.CancelledError):
190 await task
191 asyncio_exception_handler.assert_not_called()
192
193
•194 @timeout(5)
195 async def test_zero_byte_read_and_write(tmp_path, async_context):
196 context = async_context
•197 with open(
198 str(tmp_path / "temp.bin"), "wb+"
199 ) as fp: # noqa: ASYNC230 (brief sync setup, not the operation under test)
200 fd = fp.fileno()
201
202 assert await context.write(b"", fd, 0) == 0
203 assert await context.read(0, fd, 0) == b""
204
205
•206 @timeout(5)
207 async def test_partial_read_at_eof(tmp_path, async_context):
208 """Requesting more bytes than the file actually has must return exactly
209 what's there, not garbage/padding out to the requested size - this
210 exercises the "kernel filled less than the whole buffer" slow path
211 that the fast, no-copy path (used when the buffer is filled
212 completely) doesn't."""
213 context = async_context
•214 with open(
215 str(tmp_path / "temp.bin"), "wb+"
216 ) as fp: # noqa: ASYNC230 (brief sync setup, not the operation under test)
217 fd = fp.fileno()
218
219 payload = b"hello"
220 assert await context.write(payload, fd, 0) == len(payload)
221
222 data = await context.read(len(payload) * 20, fd, 0)
223 assert data == payload
224 assert len(data) == len(payload)
225
226
•227 @timeout(5)
228 async def test_fsync_and_fdsync(tmp_path, async_context):
229 context = async_context
•230 with open(
231 str(tmp_path / "temp.bin"), "wb+"
232 ) as fp: # noqa: ASYNC230 (brief sync setup, not the operation under test)
233 fd = fp.fileno()
234
235 await context.write(b"data", fd, 0)
236 # Return value not asserted - None on some backends, b"" on others
237 # (python_aio), both meaningless here.
238 await context.fsync(fd)
239 await context.fdsync(fd)
240
241
•242 @timeout(15)
243 async def test_large_transfer(tmp_path, async_context):
244 context = async_context
•245 with open(
246 str(tmp_path / "temp.bin"), "wb+"
247 ) as fp: # noqa: ASYNC230 (brief sync setup, not the operation under test)
248 fd = fp.fileno()
249
250 payload = os.urandom(4 * 1024 * 1024)
251 expected_hash = hashlib.sha256(payload).hexdigest()
252
253 written = await context.write(payload, fd, 0)
254 assert written == len(payload)
255
256 data = await context.read(len(payload), fd, 0)
257 assert len(data) == len(payload)
258 assert hashlib.sha256(bytes(data)).hexdigest() == expected_hash
259
260
•261 @timeout(5)
262 async def test_write_extends_file_sparsely(tmp_path, async_context):
263 context = async_context
•264 with open(
265 str(tmp_path / "temp.bin"), "wb+"
266 ) as fp: # noqa: ASYNC230 (brief sync setup, not the operation under test)
267 fd = fp.fileno()
268
269 hole_size = 4 * 1024 * 1024
270 await context.write(b"\x01", fd, hole_size)
271 assert os.stat(fd).st_size == hole_size + 1
272
273 hole = await context.read(hole_size, fd, 0)
274 assert hole == b"\x00" * hole_size
275
276
•277 @timeout(10)
278 async def test_max_requests_backpressure(tmp_path, async_context_maker):
279 """A tiny max_requests must still let far more concurrent operations
280 complete correctly - the asyncio-level semaphore is responsible for
281 never handing the backend more in-flight operations than it was
282 configured for, so this must not surface a "queue full"/"ring full"
283 error from the backend itself."""
284 async with async_context_maker(max_requests=2) as context:
•285 with open(
286 str(tmp_path / "temp.bin"), "wb+"
287 ) as fp: # noqa: ASYNC230 (brief sync setup, not the operation under test)
288 fd = fp.fileno()
289
290 chunk = 4096
291 count = 40
292 expected = [bytes([i % 256]) * chunk for i in range(count)]
293
294 await asyncio.gather(
•295 *[context.write(expected[i], fd, i * chunk) for i in range(count)]
296 )
297
298 results = await asyncio.gather(
299 *[context.read(chunk, fd, i * chunk) for i in range(count)]
300 )
301 assert results == expected
302
303
•304 @timeout(10)
305 async def test_concurrent_non_overlapping_chunks(tmp_path, async_context):
306 """Writes distinct, non-overlapping regions concurrently, then reads
307 them back concurrently - if any backend's buffer handling ever aliased
308 two in-flight operations' memory (e.g. a zero-copy fast path reused
309 somewhere it shouldn't), this would show up as data from the wrong
310 chunk appearing in the wrong place."""
311 context = async_context
•312 with open(
313 str(tmp_path / "temp.bin"), "wb+"
314 ) as fp: # noqa: ASYNC230 (brief sync setup, not the operation under test)
315 fd = fp.fileno()
316
317 chunk = 8192
318 count = 32
•319 expected = [bytes([(i * 7 + 3) % 256]) * chunk for i in range(count)]
320
321 await asyncio.gather(
•322 *[context.write(expected[i], fd, i * chunk) for i in range(count)]
323 )
324
325 results = await asyncio.gather(
326 *[context.read(chunk, fd, i * chunk) for i in range(count)]
327 )
328
329 for i, (got, want) in enumerate(zip(results, expected)):
330 assert got == want, f"chunk {i} mismatch"