Debian Codegraph @

tests/test_aio.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 json
4 import os
5 from base64 import b64encode
6 from io import BytesIO
7 from pathlib import Path
8 from random import shuffle
9 from typing import cast
10 from unittest.mock import Mock, call
11 from uuid import uuid4
12
13 import caio
14 import pytest
15
16 from aiofile import AIOFile, clone
17 from aiofile.aio import DEFAULT_CONTEXT_STORE, create_context
18 from aiofile.utils import (
19 BinaryFileWrapper, LineReader, Reader, TextFileWrapper, Writer,
20 )
21
22 from .impl import split_by
23
24
25 class CoroutineMock(Mock):
26 async def __call__(self, *args, **kwargs):
27 return super().__call__(*args, **kwargs)
28
29
30 @pytest.fixture
31 def temp_file(tmp_path):
32 path = str(tmp_path / "file.bin")
33 with open(path, "wb"):
34 pass
35
36 return path
37
38
39 def test_default_context_closed_with_event_loop(monkeypatch):
40 loop = asyncio.new_event_loop()
41 context = Mock()
42
43 monkeypatch.setattr(asyncio, "get_event_loop", lambda: loop)
44 monkeypatch.setattr(caio, "AsyncioContext", Mock(return_value=context))
45
46 assert create_context() is context
47 assert DEFAULT_CONTEXT_STORE[id(loop)] is context
48
49 loop.close()
50
51 context.close.assert_called_once_with()
52 assert id(loop) not in DEFAULT_CONTEXT_STORE
53 assert loop.is_closed()
54
55
56 @pytest.fixture
57 def uuid(tmp_path):
58 return str(uuid4())
59
60
61 async def test_read(aio_file_maker, temp_file, uuid):
62 with open(temp_file, "w") as f:
63 f.write(uuid)
64
65 aio_file = await aio_file_maker(temp_file, "r")
66
67 data = await aio_file.read()
68
69 assert data == uuid
70
71
72 async def test_read_write(aio_file_maker, temp_file, uuid):
73 r_file = await aio_file_maker(temp_file, "r")
74 w_file = await aio_file_maker(temp_file, "w")
75
76 await w_file.write(uuid)
77 await w_file.fsync()
78
79 data = await r_file.read()
80
81 assert data == uuid
82
83
84 async def test_read_write_pathlib(aio_file_maker, temp_file, uuid):
85 r_file = await aio_file_maker(Path(temp_file), "r")
86 w_file = await aio_file_maker(Path(temp_file), "w")
87
88 await w_file.write(uuid)
89 await w_file.fsync()
90
91 data = await r_file.read()
92
93 assert data == uuid
94
95
96 @pytest.mark.parametrize("count", [2, 3, 5, 10, 20, 100])
97 async def test_read_offset(count, aio_file_maker, temp_file, uuid):
98 with open(temp_file, "w") as f:
99 for _ in range(count):
100 f.write(uuid)
101
102 aio_file = await aio_file_maker(temp_file, "r")
103
104 data = await aio_file.read(
105 offset=len(uuid),
106 size=len(uuid),
107 )
108
109 assert data == uuid
110
111
112 @pytest.mark.parametrize("count", [2, 3, 5, 10, 20, 100])
113 async def test_read_write_offset(count, aio_file_maker, temp_file, uuid):
114 r_file = await aio_file_maker(temp_file, "r")
115 w_file = await aio_file_maker(temp_file, "w")
116
117 for i in range(count):
118 await w_file.write(uuid, offset=i * len(uuid))
119
120 await w_file.fsync()
121
122 data = await r_file.read(
123 offset=len(uuid),
124 size=len(uuid),
125 )
126
127 assert data == uuid
128
129
130 @pytest.mark.parametrize("count", [1, 2, 3, 5, 10, 20, 100])
131 async def test_reader_writer(count, aio_file_maker, temp_file, uuid):
132 r_file = await aio_file_maker(temp_file, "rb")
133 w_file = await aio_file_maker(temp_file, "wb")
134
135 chunk_size = 16
136 payload = os.urandom(chunk_size * count)
137 writer = Writer(w_file)
138
139 await writer(payload)
140 await w_file.fsync()
141
142 buff = BytesIO(payload)
143
144 async for chunk in Reader(r_file, chunk_size=chunk_size):
145 if not chunk:
146 break
147
148 assert chunk == buff.read(chunk_size)
149
150 assert not buff.read()
151
152
153 @pytest.mark.parametrize("count", [1, 2, 3, 5, 10, 20, 100, 1000])
154 async def test_reader_writer2(count, aio_file_maker, temp_file, uuid):
155 r_file = await aio_file_maker(temp_file, "r")
156 w_file = await aio_file_maker(temp_file, "w")
157
158 writer = Writer(w_file)
159
160 for _ in range(count):
161 await writer(uuid)
162
163 await w_file.fsync()
164
165 async for chunk in Reader(r_file, chunk_size=len(uuid)):
166 assert chunk == uuid
167
168
169 async def test_parallel_writer(aio_file_maker, temp_file, uuid):
170 w_file = await aio_file_maker(temp_file, "w")
171 r_file = await aio_file_maker(temp_file, "r")
172
173 futures = list()
174
175 for i in range(1000):
176 futures.append(w_file.write(uuid, i * len(uuid)))
177
178 shuffle(futures)
179
180 await asyncio.gather(*futures)
181 await w_file.fsync()
182
183 count = 0
184 async for chunk in Reader(r_file, chunk_size=len(uuid)):
185 assert chunk == uuid
186 count += 1
187
188 assert count == 1000
189
190
191 @pytest.mark.parametrize("count", [1, 2, 3, 5, 10, 20, 100, 1000])
192 async def test_parallel_writer_ordering(
193 count, aio_file_maker, temp_file, uuid,
194 ):
195 w_file = await aio_file_maker(temp_file, "wb")
196 r_file = await aio_file_maker(temp_file, "rb")
197
198 chunk_size = 1024
199
200 data = os.urandom(chunk_size * count)
201
202 futures = list()
203
204 for idx, chunk in enumerate(split_by(data, chunk_size)):
205 futures.append(w_file.write(chunk, idx * chunk_size))
206
207 shuffle(futures)
208
209 await asyncio.gather(*futures)
210 await w_file.fsync()
211
212 result: bytes = b""
213
214 async for chunk in Reader(r_file, chunk_size=chunk_size):
215 result += cast(bytes, chunk)
216
217 assert data == result
218
219
220 async def test_non_existent_file_ctx(aio_file_maker):
221 with pytest.raises(FileNotFoundError):
222 async with aio_file_maker("/c/windows/NonExistent.file", "r"):
223 pass
224
225
226 async def test_sequential_open(aio_file_maker, temp_file):
227 file = aio_file_maker(temp_file, "r")
228 try:
229 assert isinstance(await file.open(), int)
230 assert await file.open() is None
231 finally:
232 await file.close()
233
234 with pytest.raises(asyncio.InvalidStateError):
235 await file.open()
236
237
238 async def test_double_close(aio_file_maker, temp_file):
239 file = aio_file_maker(temp_file, "w")
240 await file.open()
241 await file.close()
242 await file.close()
243
244
245 async def test_closed_attribute(aio_file_maker, temp_file):
246 file = aio_file_maker(temp_file, "w")
247 assert file.closed
248 await file.open()
249 assert not file.closed
250 await file.close()
251 assert file.closed
252
253
254 async def test_closed_attribute_wrapper(async_open, temp_file):
255 fp = async_open(temp_file, "w")
256 assert fp.closed
257 await fp
258 assert not fp.closed
259 await fp.close()
260 assert fp.closed
261
262
263 async def test_parallel_open(aio_file_maker, temp_file):
264 file = aio_file_maker(temp_file, "r")
265 try:
266 # open() returns a file descriptor if it has opened a file, otherwise
267 # None. Only one of multiple parallel calls should actually open a file.
268 opens = await asyncio.gather(*(file.open() for _ in range(3)))
269 assert len([fd for fd in opens if fd is not None]) == 1
270 finally:
271 await file.close()
272
273
274 async def test_line_reader(aio_file_maker, temp_file, uuid):
275 afp = await aio_file_maker(temp_file, "w+")
276
277 writer = Writer(afp)
278
279 max_length = 1000
280 chunk = b64encode(os.urandom(max_length)).decode()
281 lines = [chunk[:i] for i in range(max_length)]
282
283 line: str | bytes
284
285 for line in lines:
286 await writer(line)
287 await writer("\n")
288
289 await afp.fsync()
290 read_lines = []
291
292 async for line in LineReader(afp):
293 read_lines.append(line[:-1])
294
295 def hash_data(data_lines):
296 return hashlib.md5("\n".join(data_lines).encode()).hexdigest()
297
298 assert hash_data(read_lines) == hash_data(lines)
299
300
301 @pytest.mark.parametrize("size", [1, 2, 3, 5, 10, 20, 100, 1000, 2000, 5000])
302 async def test_line_reader_one_line(size, aio_file_maker, temp_file):
303 afp = await aio_file_maker(temp_file, "w+")
304
305 writer = Writer(afp)
306
307 payload = " ".join(uuid4().hex for _ in range(size))
308
309 await writer(payload)
310
311 read_lines = []
312
313 async for line in LineReader(afp):
314 read_lines.append(line)
315
316 assert payload == read_lines[0]
317
318
319 async def test_truncate(aio_file_maker, temp_file):
320 afp = await aio_file_maker(temp_file, "w+")
321
322 await afp.write("hello")
323 await afp.fsync()
324
325 assert (await afp.read()) == "hello"
326
327 await afp.truncate(0)
328
329 assert (await afp.read()) == ""
330
331
332 @pytest.mark.parametrize("size", [1, 2, 3, 5, 10, 20, 100, 1000, 2000, 5000])
333 async def test_modes(size, aio_file_maker, tmpdir):
334 tmpfile = tmpdir.join("test.txt")
335
336 async with aio_file_maker(tmpfile, "w") as afp:
337 await afp.write("foo")
338 await afp.fsync()
339
340 async with aio_file_maker(tmpfile, "r") as afp:
341 assert await afp.read() == "foo"
342
343 async with aio_file_maker(tmpfile, "a+") as afp:
344 assert await afp.read() == "foo"
345
346 async with aio_file_maker(tmpfile, "r+") as afp:
347 assert await afp.read() == "foo"
348
349 data = dict((str(i), i)for i in range(size))
350
351 tmpfile = tmpdir.join("test.json")
352 async with aio_file_maker(tmpfile, "w") as afp:
353 await afp.write(json.dumps(data, indent=1))
354
355 async with aio_file_maker(tmpfile, "r") as afp:
356 result = json.loads(await afp.read())
357
358 assert result == data
359
360
361 async def test_unicode_reader(aio_file_maker, temp_file):
362 async with aio_file_maker(temp_file, "w+") as afp:
363 await afp.write("한글")
364
365 async with aio_file_maker(temp_file, "r") as afp:
366 reader = Reader(afp, chunk_size=1)
367 assert await reader.read_chunk() == "한"
368 assert await reader.read_chunk() == "글"
369
370
371 async def test_unicode_writer(aio_file_maker, temp_file):
372 async with aio_file_maker(temp_file, "w+") as afp:
373 writer = Writer(afp)
374 await writer("한")
375 await writer("글")
376
377 async with aio_file_maker(temp_file, "r") as afp:
378 reader = Reader(afp, chunk_size=1)
379 assert await reader.read_chunk() == "한"
380 assert await reader.read_chunk() == "글"
381
382
383 @pytest.mark.parametrize(("mode", "data"), [("w+", ""), ("wb+", b"")])
384 async def test_write_read_nothing(aio_file_maker, temp_file, mode, data):
385 async with aio_file_maker(temp_file, mode) as afp:
386 assert await afp.write(data) == 0
387 assert await afp.read() == data
388
389
390 async def test_partial_writes(temp_file, event_loop):
391 ctx = Mock(caio.AbstractContext)
392 ctx.loop = event_loop
393 ctx.fdsync = CoroutineMock(return_value=None)
394 ctx.write = CoroutineMock(side_effect=asyncio.InvalidStateError)
395
396 async with AIOFile(temp_file, "w", context=ctx) as afp:
397 # 1. writing first three bytes then last four
398 return_iter = iter((3, 4))
399 ctx.write.side_effect = lambda *_, **__: next(return_iter)
400 await afp.write("aiofile", offset=0)
401 # 2. then writing 12 bytes then one and the last 6.
402 return_iter = iter((12, 1, 6))
403 ctx.write.side_effect = lambda *_, **__: next(return_iter)
404 await afp.write("test_partial_writes", offset=8)
405
406 # compare all chunks against expected
407 assert ctx.write.call_args_list == [
408 # 1
409 call(b"aiofile", afp.fileno(), 0),
410 call(b"file", afp.fileno(), 3),
411 # 2
412 call(b"test_partial_writes", afp.fileno(), 8),
413 call(b"_writes", afp.fileno(), 20),
414 call(b"writes", afp.fileno(), 21),
415 ]
416
417
418 async def test_write_returned_negative(temp_file, event_loop):
419 ctx = Mock(caio.AbstractContext)
420 ctx.loop = event_loop
421 ctx.fdsync = CoroutineMock(return_value=None)
422 ctx.write = CoroutineMock(side_effect=asyncio.InvalidStateError)
423
424 async with AIOFile(temp_file, "w", context=ctx) as afp:
425 return_iter = iter((3, -27))
426 ctx.write.side_effect = lambda *_, **__: next(return_iter)
427 with pytest.raises(OSError) as raises:
428 await afp.write("aiofile")
429 assert raises.value.errno == 27
430 assert raises.value.filename == temp_file
431
432 ctx.write.reset_mock(side_effect=True)
433 ctx.write.return_value = -122
434 with pytest.raises(OSError) as raises:
435 await afp.write("aiofile")
436 assert raises.value.errno == 122
437 assert raises.value.filename == temp_file
438
439
440 async def test_write_returned_zero(temp_file, event_loop):
441 ctx = Mock(caio.AbstractContext)
442 ctx.loop = event_loop
443 ctx.fdsync = CoroutineMock(return_value=None)
444 ctx.write = CoroutineMock(side_effect=asyncio.InvalidStateError)
445
446 async with AIOFile(temp_file, "w", context=ctx) as afp:
447 return_iter = iter((3, 0))
448 ctx.write.side_effect = lambda *_, **__: next(return_iter)
449 with pytest.raises(RuntimeError, match="Write operation returned 0"):
450 await afp.write("aiofile")
451
452 ctx.write.reset_mock(side_effect=True)
453 ctx.write.return_value = 0
454 with pytest.raises(RuntimeError, match="Write operation returned 0"):
455 await afp.write("aiofile")
456
457
458 async def test_text_io_wrapper(aio_file_maker, temp_file):
459 async with aio_file_maker(temp_file, "w+") as afp:
460 data = "💾💀"
461 await afp.write(data * 5)
462
463 with open(temp_file, "a+", encoding="utf-8") as fp:
464 assert not fp.read(1)
465 fp.seek(0)
466 assert fp.read() == data * 5
467
468 fp.seek(0)
469 assert fp.read(1) == "💾"
470 assert fp.tell() == 4
471
472 async with TextFileWrapper(aio_file_maker(temp_file, "a+")) as fp:
473 assert not await fp.read(1)
474 fp.seek(0)
475 chunk = await fp.read()
476 assert chunk == data * 5
477
478 fp.seek(0)
479 assert await fp.read(1) == "💾"
480 assert fp.tell() == 4
481
482
483 async def test_text_io_wrapper_read_length_multibyte(aio_file_maker, temp_file):
484 data = (
485 "世界人権宣言前文人類社会のすべての構成員の固有の尊厳と平等で"
486 "譲ることのできない権利とを承認する"
487 )
488
489 async with aio_file_maker(temp_file, "w+") as afp:
490 await afp.write(data)
491
492 collected = ""
493 async with TextFileWrapper(aio_file_maker(temp_file, "r")) as fp:
494 while chunk := await fp.read(12):
495 assert len(chunk) <= 12
496 collected += chunk
497
498 assert collected == data
499
500
501 async def test_binary_io_wrapper(aio_file_maker, temp_file):
502 async with aio_file_maker(temp_file, "wb+") as afp:
503 data = b"\x01\x02\x03"
504 await afp.write(data * 32)
505
506 with open(temp_file, "ab+") as fp:
507 assert not fp.read(1)
508 fp.seek(0)
509 assert fp.read() == data * 32
510
511 fp.seek(0)
512 assert fp.read(1) == b"\x01"
513 assert fp.tell() == 1
514
515 async with BinaryFileWrapper(aio_file_maker(temp_file, "ab+")) as fp:
516 assert not await fp.read(1)
517 fp.seek(0)
518 assert await fp.read() == data * 32
519
520 fp.seek(0)
521 assert await fp.read(1) == b"\x01"
522 assert fp.tell() == 1
523
524
525 async def test_async_open(async_open, temp_file):
526 async with async_open(temp_file, "wb+") as afp:
527 data = b"\x01\x02\x03" + "🦠📱".encode()
528 await afp.write(data * 32)
529
530 assert isinstance(async_open(temp_file, "ab+"), BinaryFileWrapper)
531
532 async with async_open(temp_file, "ab+") as fp:
533 assert not await fp.read(1)
534 fp.seek(3)
535 assert await fp.read(8) == "🦠📱".encode()
536
537 assert isinstance(async_open(temp_file, "a+"), TextFileWrapper)
538
539 async with async_open(temp_file, "a+") as fp:
540 assert not await fp.read(1)
541 fp.seek(3)
542 assert await fp.read(2) == "🦠📱"
543
544
545 async def test_async_open_unicode(aio_file_maker, async_open, temp_file):
546 async with aio_file_maker(temp_file, "w+") as afp:
547 data = "🏁💾🏴‍☠️"
548 await afp.write(data)
549
550 async with async_open(temp_file, "a+") as afp:
551 with open(temp_file, "a+", encoding="utf-8") as fp:
552 assert not await afp.read(1)
553 assert not fp.read(1)
554
555 afp.seek(0)
556 fp.seek(0)
557
558 assert await afp.read(1) == fp.read(1)
559 assert await afp.read(1) == fp.read(1)
560 assert await afp.read(1) == fp.read(1)
561 assert await afp.read(1) == fp.read(1)
562
563 afp.seek(0)
564 fp.seek(0)
565
566 assert await afp.read(3) == fp.read(3)
567 assert afp.tell() == fp.tell()
568
569
570 async def test_async_open_readline(aio_file_maker, async_open, temp_file):
571 async with aio_file_maker(temp_file, "w+") as afp:
572 data = "Hello\nworld\n" + ("h" * 10000)
573 await afp.write(data)
574
575 async with async_open(temp_file, "a+") as afp:
576 with open(temp_file, "a+", encoding="utf-8") as fp:
577 afp.seek(0)
578 fp.seek(0)
579
580 assert await afp.readline() == fp.readline()
581 assert await afp.readline() == fp.readline()
582 assert await afp.readline() == fp.readline()
583
584 async with async_open(temp_file, "ab+") as afp:
585 with open(temp_file, "ab+") as fp:
586 assert not await afp.read(1)
587 assert not fp.read(1)
588
589 afp.seek(0)
590 fp.seek(0)
591
592 assert await afp.readline() == fp.readline()
593 assert await afp.readline() == fp.readline()
594 assert await afp.readline() == fp.readline()
595
596
597 async def test_async_open_fp(async_open, tmp_path: Path):
598 data = "Hello\nworld\n"
599
600 with open(tmp_path / "file.txt", "w+") as fp:
601 async with async_open(fp) as afp:
602 await afp.write(data)
603 afp.seek(0)
604 assert await afp.read() == data
605 assert not afp.file.mode.binary
606
607 assert not fp.closed
608
609 with open(tmp_path / "file.txt", "rb") as fp:
610 async with async_open(fp) as afp:
611 assert afp.file.mode.binary
612
613 assert fp.read().decode() == data
614
615
616 @pytest.mark.parametrize("sizes", [[1, 2], [2, 10], [10, 20], [100, 500]])
617 async def test_async_open_line_iter(sizes, async_open, tmp_path: Path):
618 async with async_open(tmp_path / "file.txt", "w+") as afp:
619 for i in range(*sizes):
620 await afp.write(str(i))
621 await afp.write("\n")
622
623 afp.seek(0)
624 idx = sizes[0]
625 async for line in afp:
626 assert line.endswith("\n")
627 assert int(line.strip()) == idx
628 idx += 1
629
630 async with async_open(tmp_path / "file.bin", "wb+") as afp:
631 for i in range(*sizes):
632 await afp.write(str(i).encode())
633 await afp.write(b"\n")
634
635 afp.seek(0)
636 idx = sizes[0]
637 async for line in afp:
638 assert line.endswith(b"\n")
639 assert int(line.decode().strip()) == idx
640 idx += 1
641
642
643 @pytest.mark.parametrize("size", [1, 2, 3, 5, 10, 20, 100, 1000, 2000, 5000])
644 async def test_async_open_iter_chunked(size, async_open, tmp_path: Path):
645 src_path = tmp_path / "src.txt"
646 dst_path = tmp_path / "dst.txt"
647
648 async with async_open(src_path, "w") as afp:
649 for i in range(0, size):
650 await afp.write(str(i))
651 await afp.write("\n")
652
653 async with async_open(src_path, "r") as src, \
654 async_open(dst_path, "w") as dest:
655 async for chunk in src.iter_chunked():
656 await dest.write(chunk)
657
658 assert src_path.stat().st_size == dst_path.stat().st_size
659
660 def hash_file(path):
661 with open(path, "rb") as fp:
662 hasher = hashlib.md5()
663 chunk = fp.read(65535)
664 while chunk:
665 hasher.update(chunk)
666 chunk = fp.read(65535)
667 return hasher.hexdigest()
668
669 assert hash_file(src_path) == hash_file(dst_path)
670
671
672 async def test_open_non_existent_file_with_append(
673 async_open, tmp_path: Path,
674 ):
675 tmp_fpath = tmp_path / "numbers.txt"
676
677 async with async_open(tmp_fpath, "a+") as afp:
678 for i in range(10):
679 await afp.write(str(i))
680 await afp.write("\n")
681
682 async with async_open(tmp_fpath, "a+") as afp:
683 for i in range(10, 20):
684 await afp.write(str(i))
685 await afp.write("\n")
686
687 numbers = []
688 async with async_open(tmp_fpath, "r") as afp:
689 async for line in afp:
690 numbers.append(int(line.strip()))
691
692 assert numbers == list(range(20))
693
694
695 async def test_clone(
696 async_open, tmp_path: Path,
697 ):
698 tmp_fpath = tmp_path / "test.txt"
699
700 async with async_open(tmp_fpath, "w") as afp:
701 for i in range(1000, 1003):
702 await afp.write(str(i))
703 await afp.write("\n")
704
705 async with async_open(tmp_fpath, "r") as afp:
706 assert await afp.read(5) == "1000\n"
707
708 async with clone(afp) as cloned:
709 assert await cloned.read(5) == "1000\n"
710
711 async with clone(afp) as cloned2:
712 assert await cloned2.read(5) == "1000\n"
713
714 assert await cloned.read(5) == await afp.read(5) == "1001\n"
715
716
717 async def test_clone_close(
718 async_open, tmp_path: Path,
719 ):
720 tmp_fpath = tmp_path / "test.txt"
721
722 async with async_open(tmp_fpath, "w") as afp:
723 for i in range(10):
724 await afp.write(str(i))
725 await afp.write("\n")
726
727 async with async_open(tmp_fpath, "r") as afp:
728 await afp.read(10)
729
730 afp_clone = await clone(afp)
731 await afp_clone.close()
732
733 assert await afp.read()
734
735 async with async_open(tmp_fpath, "r") as afp:
736 await afp.read(10)
737
738 async with clone(afp):
739 assert await afp.read()