Debian Codegraph @

tests/test_asyncio_adapter.py

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