Debian Codegraph @

pypy/module/_io/test/test_bufferedio.py

raw symbols SCIP
1 from __future__ import with_statement
2 from rpython import rlib
3 from pypy.interpreter.error import oefmt
4 from pypy.interpreter.gateway import interp2app
5 from rpython.tool.udir import udir
6 from pypy.module._io import interp_bufferedio
7 from pypy.interpreter.error import OperationError
8 import py.test
9 import os
10
11
12 class AppTestBufferedReader:
13 spaceconfig = dict(usemodules=['_io'])
14 if os.name != 'nt':
15 spaceconfig['usemodules'].append('fcntl')
16
17 def setup_class(cls):
18 tmpfile = udir.join('tmpfile')
19 tmpfile.write("a\nb\nc", mode='wb')
20 cls.w_tmpfile = cls.space.wrap(str(tmpfile))
21 bigtmpfile = udir.join('bigtmpfile')
22 bigtmpfile.write("a\nb\nc" * 20, mode='wb')
23 cls.w_bigtmpfile = cls.space.wrap(str(bigtmpfile))
24 #
25 cls.w_posix = cls.space.appexec([], """():
26 import %s as m;
27 return m""" % os.name)
28
29 def test_simple_read(self):
30 import _io
31 raw = _io.FileIO(self.tmpfile)
32 f = _io.BufferedReader(raw)
33 assert f.read() == b"a\nb\nc"
34 raises(ValueError, f.read, -2)
35 f.close()
36 #
37 raw = _io.FileIO(self.tmpfile, 'r+')
38 f = _io.BufferedReader(raw)
39 r = f.read(4)
40 assert r == b"a\nb\n"
41 assert f.readable() is True
42 assert f.writable() is False
43 f.close()
44
45 def test_read_pieces(self):
46 import _io
47 raw = _io.FileIO(self.tmpfile)
48 f = _io.BufferedReader(raw)
49 assert f.read(3) == b"a\nb"
50 assert f.read(3) == b"\nc"
51 assert f.read(3) == b""
52 assert f.read(3) == b""
53 f.close()
54
55 def test_slow_provider(self):
56 import _io
57 class MockIO(_io._IOBase):
58 def readable(self):
59 return True
60 def readinto(self, buf):
61 buf[:3] = b"abc"
62 return 3
63 bufio = _io.BufferedReader(MockIO())
64 r = bufio.read(5)
65 assert r == b"abcab"
66
67 def test_read_past_eof(self):
68 import _io
69 class MockIO(_io._IOBase):
70 stack = [b"abc", b"d", b"efg"]
71 def readable(self):
72 return True
73 def readinto(self, buf):
74 if self.stack:
75 data = self.stack.pop(0)
76 buf[:len(data)] = data
77 return len(data)
78 else:
79 return 0
80 bufio = _io.BufferedReader(MockIO())
81 assert bufio.read(9000) == b"abcdefg"
82
83 def test_valid_buffer(self):
84 import _io
85
86 class MockIO(_io._IOBase):
87 def readable(self):
88 return True
89
90 def readinto(self, buf):
91 # Check that `buf` is a valid memoryview object
92 assert buf.itemsize == 1
93 assert buf.strides == (1,)
94 assert buf.shape == (len(buf),)
95 return len(bytes(buf))
96
97 bufio = _io.BufferedReader(MockIO())
98 assert len(bufio.read(5)) == 5 # Note: PyPy zeros the buffer, CPython does not
99
100 def test_buffering(self):
101 import _io
102 data = b"abcdefghi"
103 dlen = len(data)
104 class MockFileIO(_io.BytesIO):
105 def __init__(self, data):
106 self.read_history = []
107 _io.BytesIO.__init__(self, data)
108
109 def read(self, n=None):
110 res = _io.BytesIO.read(self, n)
111 self.read_history.append(None if res is None else len(res))
112 return res
113
114 def readinto(self, b):
115 res = _io.BytesIO.readinto(self, b)
116 self.read_history.append(res)
117 return res
118
119
120 tests = [
121 [ 100, [ 3, 1, 4, 8 ], [ dlen, 0 ] ],
122 [ 100, [ 3, 3, 3], [ dlen ] ],
123 [ 4, [ 1, 2, 4, 2 ], [ 4, 4, 1 ] ],
124 ]
125
126 for bufsize, buf_read_sizes, raw_read_sizes in tests:
127 rawio = MockFileIO(data)
128 bufio = _io.BufferedReader(rawio, buffer_size=bufsize)
129 pos = 0
130 for nbytes in buf_read_sizes:
131 assert bufio.read(nbytes) == data[pos:pos+nbytes]
132 pos += nbytes
133 # this is mildly implementation-dependent
134 assert rawio.read_history == raw_read_sizes
135
136 def test_peek(self):
137 import _io
138 raw = _io.FileIO(self.tmpfile)
139 f = _io.BufferedReader(raw)
140 assert f.read(2) == b'a\n'
141 assert f.peek().startswith(b'b\nc')
142 assert f.read(3) == b'b\nc'
143 assert f.peek() == b''
144
145 def test_read1(self):
146 import _io
147 class RecordingFileIO(_io.FileIO):
148 def read(self, size=-1):
149 self.nbreads += 1
150 return _io.FileIO.read(self, size)
151 def readinto(self, buf):
152 self.nbreads += 1
153 return _io.FileIO.readinto(self, buf)
154 raw = RecordingFileIO(self.tmpfile)
155 raw.nbreads = 0
156 f = _io.BufferedReader(raw, buffer_size=3)
157 assert f.read(1) == b'a'
158 assert f.read1(1) == b'\n'
159 assert raw.nbreads == 1
160 assert f.read1(100) == b'b'
161 assert raw.nbreads == 1
162 assert f.read1(100) == b'\nc'
163 assert raw.nbreads == 2
164 assert f.read1(100) == b''
165 assert raw.nbreads == 3
166 f.close()
167
168 # a negative argument (or no argument) leads to using the default
169 # buffer size
170 raw = _io.BytesIO(b'aaaa\nbbbb\ncccc\n')
171 f = _io.BufferedReader(raw, buffer_size=3)
172 assert f.read1(-1) == b'aaa'
173 assert f.read1() == b'a\nb'
174
175
176 def test_readinto(self):
177 import _io
178 for methodname in ["readinto", "readinto1"]:
179 a = bytearray(b'x' * 10)
180 raw = _io.FileIO(self.tmpfile)
181 f = _io.BufferedReader(raw)
182 readinto = getattr(f, methodname)
183 assert readinto(a) == 5
184 f.seek(0)
185 m = memoryview(bytearray(b"hello"))
186 assert readinto(m) == 5
187 #
188 exc = raises(TypeError, readinto, u"hello")
189 msg = str(exc.value)
190 # print(msg)
191 assert " read-write b" in msg and msg.endswith(", not str")
192 #
193 exc = raises(TypeError, readinto, memoryview(b"hello"))
194 msg = str(exc.value)
195 # print(msg)
196 assert " read-write b" in msg and msg.endswith(", not memoryview")
197 #
198 f.close()
199 assert a == b'a\nb\ncxxxxx'
200
201 def test_readinto_buffer_overflow(self):
202 import _io
203 class BadReader(_io._BufferedIOBase):
204 def read(self, n=-1):
205 return b'x' * 10**6
206 bufio = BadReader()
207 b = bytearray(2)
208 raises(ValueError, bufio.readinto, b)
209
210 def test_readinto1(self):
211 import _io
212
213 class MockIO(_io._IOBase):
214 def readable(self):
215 return True
216
217 def readinto(self, buf):
218 buf[:3] = b"abc"
219 return 3
220
221 def writable(self):
222 return True
223
224 def write(self, b):
225 return len(b)
226
227 def seekable(self):
228 return True
229
230 def seek(self, pos, whence):
231 return 0
232
233 bufio = _io.BufferedReader(MockIO(), buffer_size=5)
234 buf = bytearray(10)
235 bufio.read(2)
236 n = bufio.readinto1(buf)
237 assert n == 4
238 assert buf[:n] == b'cabc'
239
240 # Yes, CPython's observable behavior depends on buffer_size!
241 bufio = _io.BufferedReader(MockIO(), buffer_size=20)
242 buf = bytearray(10)
243 bufio.read(2)
244 n = bufio.readinto1(buf)
245 assert n == 1
246 assert buf[:n] == b'c'
247
248 bufio = _io.BufferedReader(MockIO(), buffer_size=20)
249 buf = bytearray(2)
250 bufio.peek(3)
251 assert bufio.readinto1(buf) == 2
252 assert buf == b'ab'
253 n = bufio.readinto1(buf)
254 assert n == 1
255 assert buf[:n] == b'c'
256
257 bufio = _io.BufferedRandom(MockIO(), buffer_size=10)
258 buf = bytearray(20)
259 bufio.peek(3)
260 assert bufio.readinto1(buf) == 6
261 assert buf[:6] == b'abcabc'
262
263 bufio = _io.BufferedWriter(MockIO(), buffer_size=10)
264 raises(_io.UnsupportedOperation, bufio.readinto1, bytearray(10))
265
266 def test_seek(self):
267 import _io
268 raw = _io.FileIO(self.tmpfile)
269 f = _io.BufferedReader(raw)
270 assert f.read() == b"a\nb\nc"
271 f.seek(0)
272 assert f.read() == b"a\nb\nc"
273 f.seek(-2, 2)
274 assert f.read() == b"\nc"
275 f.close()
276
277 def test_readlines(self):
278 import _io
279 raw = _io.FileIO(self.tmpfile)
280 f = _io.BufferedReader(raw)
281 assert f.readlines() == [b'a\n', b'b\n', b'c']
282
283 def test_detach(self):
284 import _io
285 raw = _io.FileIO(self.tmpfile)
286 f = _io.BufferedReader(raw)
287 assert f.fileno() == raw.fileno()
288 assert f.detach() is raw
289 raises(ValueError, f.fileno)
290 raises(ValueError, f.close)
291 raises(ValueError, f.detach)
292 raises(ValueError, f.flush)
293 assert not raw.closed
294 raw.close()
295
296 def test_detached(self):
297 import _io
298 class MockRawIO(_io._RawIOBase):
299 def readable(self):
300 return True
301 raw = MockRawIO()
302 buf = _io.BufferedReader(raw)
303 assert buf.detach() is raw
304 raises(ValueError, buf.detach)
305
306 raises(ValueError, getattr, buf, 'mode')
307 raises(ValueError, buf.isatty)
308 repr(buf) # Should still work
309
310 def test_detach_warn(self):
311 import _io, warnings
312 warnings.resetwarnings()
313 raw = _io.FileIO(self.tmpfile)
314 f = _io.BufferedReader(raw)
315 raw2 = f.detach()
316 assert raw2 == raw
317 raw.close()
318 with raises(RuntimeError):
319 f._dealloc_warn(1)
320
321 def test_tell(self):
322 import _io
323 raw = _io.FileIO(self.tmpfile)
324 f = _io.BufferedReader(raw, buffer_size=2)
325 assert f.tell() == 0
326 d1 = f.read(1)
327 assert f.tell() == 1
328 d2 = f.read(2)
329 assert f.tell() == 3
330 assert f.seek(0) == 0
331 assert f.tell() == 0
332 d3 = f.read(3)
333 assert f.tell() == 3
334 assert d1 + d2 == d3
335 f.close()
336
337 def test_repr(self):
338 import _io
339 raw = _io.FileIO(self.tmpfile)
340 f = _io.BufferedReader(raw)
341 assert repr(f) == '<_io.BufferedReader name=%r>' % (self.tmpfile,)
342 f.close()
343
344 def test_read_interrupted(self):
345 import _io, errno
346 class MockRawIO(_io._RawIOBase):
347 def __init__(self):
348 self.count = 0
349 def readable(self):
350 return True
351 def readinto(self, buf):
352 self.count += 1
353 if self.count < 3:
354 raise IOError(errno.EINTR, "interrupted")
355 else:
356 buf[:3] = b"abc"
357 return 3
358 rawio = MockRawIO()
359 bufio = _io.BufferedReader(rawio)
360 r = bufio.read(4)
361 assert r == b"abca"
362 assert rawio.count == 4
363
364 def test_unseekable(self):
365 import _io
366 class Unseekable(_io.BytesIO):
367 def seekable(self):
368 return False
369 def seek(self, *args):
370 raise _io.UnsupportedOperation("not seekable")
371 def tell(self, *args):
372 raise _io.UnsupportedOperation("not seekable")
373 bufio = _io.BufferedReader(Unseekable(b"A" * 10))
374 raises(_io.UnsupportedOperation, bufio.tell)
375 raises(_io.UnsupportedOperation, bufio.seek, 0)
376 bufio.read(1)
377 raises(_io.UnsupportedOperation, bufio.seek, 0)
378 raises(_io.UnsupportedOperation, bufio.tell)
379
380 def test_bufio_write_through(self):
381 import _io as io
382 # Issue #21396: write_through=True doesn't force a flush()
383 # on the underlying binary buffered object.
384 flush_called, write_called = [], []
385 class BufferedWriter(io.BufferedWriter):
386 def flush(self, *args, **kwargs):
387 flush_called.append(True)
388 return super().flush(*args, **kwargs)
389 def write(self, *args, **kwargs):
390 write_called.append(True)
391 return super().write(*args, **kwargs)
392
393 rawio = io.BytesIO()
394 data = b"a"
395 bufio = BufferedWriter(rawio, len(data)*2)
396 textio = io.TextIOWrapper(bufio, encoding='ascii',
397 write_through=True)
398 # write to the buffered io but don't overflow the buffer
399 text = data.decode('ascii')
400 textio.write(text)
401
402 # buffer.flush is not called with write_through=True
403 assert not flush_called
404 # buffer.write *is* called with write_through=True
405 assert write_called
406 assert rawio.getvalue() == b"" # no flush
407
408 write_called = [] # reset
409 textio.write(text * 10) # total content is larger than bufio buffer
410 assert write_called
411 assert rawio.getvalue() == data * 11 # all flushed
412
413 def test_readline_issue3042(self):
414 import _io as io
415 try:
416 import fcntl
417 except ImportError:
418 skip('fcntl missing')
419 fdin, fdout = self.posix.pipe()
420 f = io.open(fdin, "rb")
421 fl = fcntl.fcntl(f, fcntl.F_GETFL)
422 fcntl.fcntl(f, fcntl.F_SETFL, fl | self.posix.O_NONBLOCK)
423 s = f.readline()
424 assert s == b''
425 f.close()
426 self.posix.close(fdout)
427
428 def test_read_nonblocking_crash(self):
429 import _io as io
430 try:
431 import fcntl
432 except ImportError:
433 skip('fcntl missing')
434 fdin, fdout = self.posix.pipe()
435 f = io.open(fdin, "rb")
436 fl = fcntl.fcntl(f, fcntl.F_GETFL)
437 fcntl.fcntl(f, fcntl.F_SETFL, fl | self.posix.O_NONBLOCK)
438 s = f.read(12)
439 assert s == None
440 self.posix.close(fdout)
441
442 s = f.read(12)
443 assert s == b''
444 f.close()
445
446 def test_device_like(self):
447 # CPython GH-95782
448 import _io
449 class MockDevice(_io.BytesIO):
450 def seek(self, *args):
451 return 0
452
453 def tell(self, *args):
454 return 0
455
456 fd = MockDevice(b"aaaa")
457 bufio = _io.BufferedReader(fd, 4)
458 textio = _io.TextIOWrapper(bufio)
459 val = textio.read(1)
460 assert val == "a", val
461 t = textio.tell()
462 assert t == 0, t
463 assert textio.seek(0) == 0
464
465
466 class AppTestBufferedReaderWithThreads(AppTestBufferedReader):
467 spaceconfig = dict(usemodules=['_io', 'thread', 'time'])
468 if os.name != 'nt':
469 spaceconfig['usemodules'].append('fcntl')
470
471
472 def test_readinto_small_parts(self):
473 import _io, os, _thread, time
474 read_fd, write_fd = os.pipe()
475 raw = _io.FileIO(read_fd)
476 f = _io.BufferedReader(raw)
477 a = bytearray(b'x' * 10)
478 os.write(write_fd, b"abcde")
479 def write_more():
480 time.sleep(0.5)
481 os.write(write_fd, b"fghij")
482 _thread.start_new_thread(write_more, ())
483 assert f.readinto(a) == 10
484 assert a == b'abcdefghij'
485
486 @py.test.yield_fixture
487 def forbid_nonmoving_raw_ptr_for_resizable_list(space):
488 orig_nonmoving_raw_ptr_for_resizable_list = rlib.buffer.nonmoving_raw_ptr_for_resizable_list
489 def fail(l):
490 raise oefmt(space.w_ValueError, "rgc.nonmoving_raw_ptr_for_resizable_list() not supported under RevDB")
491 rlib.buffer.nonmoving_raw_ptr_for_resizable_list = fail
492 yield
493 rlib.buffer.nonmoving_raw_ptr_for_resizable_list = orig_nonmoving_raw_ptr_for_resizable_list
494
495 @py.test.mark.usefixtures('forbid_nonmoving_raw_ptr_for_resizable_list')
496 class AppTestForbidRawPtrForResizableList(object):
497 spaceconfig = dict(usemodules=['_io'])
498
499 @py.test.mark.skipif("py.test.config.option.runappdirect")
500 def test_monkeypatch_works(self):
501 import _io, os
502 raw = _io.FileIO(os.devnull)
503 f = _io.BufferedReader(raw)
504 with raises(ValueError) as e:
505 f.read(1024)
506 assert e.value.args[0] == "rgc.nonmoving_raw_ptr_for_resizable_list() not supported under RevDB"
507
508 @py.test.mark.usefixtures('forbid_nonmoving_raw_ptr_for_resizable_list')
509 class AppTestBufferedReaderOnRevDB(AppTestBufferedReader):
510 spaceconfig = {'usemodules': ['_io'], 'translation.reverse_debugger': True}
511
512
513 class AppTestBufferedWriter:
514 spaceconfig = dict(usemodules=['_io', 'thread'])
515
516 def setup_class(cls):
517 tmpfile = udir.join('tmpfile')
518 cls.w_tmpfile = cls.space.wrap(str(tmpfile))
519
520 def w_readfile(self):
521 with open(self.tmpfile, 'rb') as f:
522 return f.read()
523
524 def test_write(self):
525 import _io
526 raw = _io.FileIO(self.tmpfile, 'w+')
527 f = _io.BufferedWriter(raw)
528 f.write(b"abcd")
529 raises(TypeError, f.write, u"cd")
530 assert f.writable() is True
531 assert f.readable() is False
532 f.close()
533 assert self.readfile() == b"abcd"
534
535 def test_largewrite(self):
536 import _io
537 raw = _io.FileIO(self.tmpfile, 'w')
538 f = _io.BufferedWriter(raw)
539 f.write(b"abcd" * 5000)
540 f.close()
541 assert self.readfile() == b"abcd" * 5000
542
543 def test_incomplete(self):
544 import _io
545 raw = _io.FileIO(self.tmpfile)
546 b = _io.BufferedWriter.__new__(_io.BufferedWriter)
547 raises(IOError, b.__init__, raw) # because file is not writable
548 raises(ValueError, getattr, b, 'closed')
549 raises(ValueError, b.flush)
550 raises(ValueError, b.close)
551
552 def test_check_several_writes(self):
553 import _io
554 raw = _io.FileIO(self.tmpfile, 'w')
555 b = _io.BufferedWriter(raw, 13)
556
557 for i in range(4):
558 assert b.write(b'x' * 10) == 10
559 b.flush()
560 assert self.readfile() == b'x' * 40
561
562 def test_destructor_1(self):
563 import _io
564
565 record = []
566 class MyIO(_io.BufferedWriter):
567 def __del__(self):
568 record.append(1)
569 # doesn't call the inherited __del__, so file not closed
570 def close(self):
571 record.append(2)
572 super(MyIO, self).close()
573 def flush(self):
574 record.append(3)
575 super(MyIO, self).flush()
576 raw = _io.FileIO(self.tmpfile, 'w')
577 MyIO(raw)
578 import gc; gc.collect()
579 assert record == [1]
580
581 def test_destructor_2(self):
582 import _io
583
584 record = []
585 class MyIO(_io.BufferedWriter):
586 def __del__(self):
587 record.append(1)
588 super(MyIO, self).__del__()
589 def close(self):
590 record.append(2)
591 super(MyIO, self).close()
592 def flush(self):
593 record.append(3)
594 super(MyIO, self).flush()
595 raw = _io.FileIO(self.tmpfile, 'w')
596 MyIO(raw)
597 import gc; gc.collect()
598 assert record == [1, 2, 3]
599
600 def test_truncate(self):
601 import _io
602 raw = _io.FileIO(self.tmpfile, 'w+')
603 raw.write(b'x' * 20)
604 b = _io.BufferedRandom(raw)
605 assert b.seek(8) == 8
606 assert b.truncate() == 8
607 assert b.tell() == 8
608
609 def test_truncate_after_write(self):
610 import _io
611 raw = _io.FileIO(self.tmpfile, 'rb+')
612 raw.write(b'\x00' * 50)
613 raw.seek(0)
614 b = _io.BufferedRandom(raw, 10)
615 b.write(b'\x00' * 11)
616 b.read(1)
617 b.truncate()
618 assert b.tell() == 12
619
620 def test_write_non_blocking(self):
621 import _io, io
622 class MockNonBlockWriterIO(io.RawIOBase):
623 def __init__(self):
624 self._write_stack = []
625 self._blocker_char = None
626
627 def writable(self):
628 return True
629 closed = False
630
631 def pop_written(self):
632 s = b''.join(self._write_stack)
633 self._write_stack[:] = []
634 return s
635
636 def block_on(self, char):
637 """Block when a given char is encountered."""
638 self._blocker_char = char
639
640 def write(self, b):
641 try:
642 b = b.tobytes()
643 except AttributeError:
644 pass
645 n = -1
646 if self._blocker_char:
647 try:
648 n = b.index(self._blocker_char)
649 except ValueError:
650 pass
651 else:
652 if n > 0:
653 # write data up to the first blocker
654 self._write_stack.append(b[:n])
655 return n
656 else:
657 # cancel blocker and indicate would block
658 self._blocker_char = None
659 return None
660 self._write_stack.append(b)
661 return len(b)
662
663 raw = MockNonBlockWriterIO()
664 bufio = _io.BufferedWriter(raw, 8)
665
666 assert bufio.write(b"abcd") == 4
667 assert bufio.write(b"efghi") == 5
668 # 1 byte will be written, the rest will be buffered
669 raw.block_on(b"k")
670 assert bufio.write(b"jklmn") == 5
671
672 # 8 bytes will be written, 8 will be buffered and the rest will be lost
673 raw.block_on(b"0")
674 try:
675 bufio.write(b"opqrwxyz0123456789")
676 except _io.BlockingIOError as e:
677 written = e.characters_written
678 else:
679 self.fail("BlockingIOError should have been raised")
680 assert written == 16
681 assert raw.pop_written() == b"abcdefghijklmnopqrwxyz"
682
683 assert bufio.write(b"ABCDEFGHI") == 9
684 s = raw.pop_written()
685 # Previously buffered bytes were flushed
686 assert s.startswith(b"01234567A")
687
688 def test_nonblock_pipe_write_bigbuf(self):
689 self.test_nonblock_pipe_write(16*1024)
690
691 def test_nonblock_pipe_write_smallbuf(self):
692 self.test_nonblock_pipe_write(1024)
693
694 def w_test_nonblock_pipe_write(self, bufsize):
695 import _io as io
696 class NonBlockingPipe(io._BufferedIOBase):
697 "write() returns None when buffer is full"
698 def __init__(self, buffersize=4096):
699 self.buffersize = buffersize
700 self.buffer = b''
701 def readable(self): return True
702 def writable(self): return True
703
704 def write(self, data):
705 available = self.buffersize - len(self.buffer)
706 if available <= 0:
707 return None
708 add_data = data[:available]
709 if isinstance(add_data, memoryview):
710 add_data = add_data.tobytes()
711 self.buffer += add_data
712 return len(add_data)
713 def read(self, size=-1):
714 if not self.buffer:
715 return None
716 if size == -1:
717 size = len(self.buffer)
718 data = self.buffer[:size]
719 self.buffer = self.buffer[size:]
720 return data
721
722 sent = []
723 received = []
724 pipe = NonBlockingPipe()
725 rf = io.BufferedReader(pipe, bufsize)
726 wf = io.BufferedWriter(pipe, bufsize)
727
728 for N in 9999, 7574:
729 try:
730 i = 0
731 while True:
732 msg = bytes([i % 26 + 97] * N)
733 sent.append(msg)
734 wf.write(msg)
735 i += 1
736 except io.BlockingIOError as e:
737 sent[-1] = sent[-1][:e.characters_written]
738 received.append(rf.read())
739 msg = b'BLOCKED'
740 wf.write(msg)
741 sent.append(msg)
742 while True:
743 try:
744 wf.flush()
745 break
746 except io.BlockingIOError as e:
747 received.append(rf.read())
748 received += iter(rf.read, None)
749 rf.close()
750 wf.close()
751 sent, received = b''.join(sent), b''.join(received)
752 assert sent == received
753
754 def test_read_non_blocking(self):
755 import _io
756 class MockRawIO(_io._RawIOBase):
757 def __init__(self, read_stack=()):
758 self._read_stack = list(read_stack)
759 def readable(self):
760 return True
761 def readinto(self, buf):
762 max_len = len(buf)
763 try:
764 data = self._read_stack[0]
765 except IndexError:
766 self._extraneous_reads += 1
767 return 0
768 if data is None:
769 del self._read_stack[0]
770 return None
771 n = len(data)
772 if len(data) <= max_len:
773 del self._read_stack[0]
774 buf[:n] = data
775 return n
776 else:
777 buf[:] = data[:max_len]
778 self._read_stack[0] = data[max_len:]
779 return max_len
780 def read(self, n=None):
781 try:
782 return self._read_stack.pop(0)
783 except IndexError:
784 return b""
785 # Inject some None's in there to simulate EWOULDBLOCK
786 rawio = MockRawIO((b"abc", b"d", None, b"efg", None, None, None))
787 bufio = _io.BufferedReader(rawio)
788
789 assert bufio.read(6) == b"abcd"
790 assert bufio.read(1) == b"e"
791 assert bufio.read() == b"fg"
792 assert bufio.peek(1) == b""
793 assert bufio.read() is None
794 assert bufio.read() == b""
795
796 def test_write_interrupted(self):
797 import _io, errno
798 class MockRawIO(_io._RawIOBase):
799 def __init__(self):
800 self.count = 0
801 def writable(self):
802 return True
803 def write(self, data):
804 self.count += 1
805 if self.count < 3:
806 raise IOError(errno.EINTR, "interrupted")
807 else:
808 return len(data)
809 rawio = MockRawIO()
810 bufio = _io.BufferedWriter(rawio)
811 assert bufio.write(b"test") == 4
812 bufio.flush()
813 assert rawio.count == 3
814
815 def test_reentrant_write(self):
816 import _thread # Reentrant-safe is only enabled with threads
817 import _io, errno
818 class MockRawIO(_io._RawIOBase):
819 def writable(self):
820 return True
821 def write(self, data):
822 bufio.write(b"something else")
823 return len(data)
824
825 rawio = MockRawIO()
826 bufio = _io.BufferedWriter(rawio)
827 bufio.write(b"test")
828 exc = raises(RuntimeError, bufio.flush)
829 assert "reentrant" in str(exc.value) # And not e.g. recursion limit.
830
831 def test_write_error_on_close(self):
832 import _io
833 class MockRawIO(_io._RawIOBase):
834 def writable(self):
835 return True
836 def write(self, data):
837 raise IOError()
838 raw = MockRawIO()
839 b = _io.BufferedWriter(raw)
840 b.write(b'spam')
841 raises(IOError, b.close) # exception not swallowed
842 assert b.closed
843
844 def test_close_error_on_close(self):
845 import _io
846 class MockRawIO(_io._RawIOBase):
847 def writable(self):
848 return True
849 def close(self):
850 raise IOError('close')
851 def bad_flush():
852 raise IOError('flush')
853 raw = MockRawIO()
854 b = _io.BufferedWriter(raw)
855 b.flush = bad_flush
856 err = raises(IOError, b.close) # exception not swallowed
857 assert err.value.args == ('close',)
858 assert err.value.__context__.args == ('flush',)
859 assert not b.closed
860
861 def test_truncate_after_close(self):
862 import _io
863 raw = _io.FileIO(self.tmpfile, 'w+')
864 b = _io.BufferedWriter(raw)
865 b.close()
866 with raises(ValueError) as exc:
867 b.truncate()
868 assert exc.value.args[0] == "truncate of closed file"
869
870 class AppTestBufferedRWPair:
871 def test_pair(self):
872 import _io
873 pair = _io.BufferedRWPair(_io.BytesIO(b"abc"), _io.BytesIO())
874 assert not pair.closed
875 assert pair.readable()
876 assert pair.writable()
877 assert not pair.isatty()
878 assert pair.read() == b"abc"
879 assert pair.write(b"abc") == 3
880
881 def test_constructor_with_not_readable(self):
882 import _io
883 class NotReadable:
884 def readable(self):
885 return False
886
887 raises(IOError, _io.BufferedRWPair, NotReadable(), _io.BytesIO())
888
889 def test_constructor_with_not_writable(self):
890 import _io
891 class NotWritable:
892 def writable(self):
893 return False
894
895 raises(IOError, _io.BufferedRWPair, _io.BytesIO(), NotWritable())
896
897 def test_writer_close_error_on_close(self):
898 import _io
899 class MockRawIO(_io._IOBase):
900 def readable(self):
901 return True
902 def writable(self):
903 return True
904 def writer_close():
905 writer_non_existing
906 reader = MockRawIO()
907 writer = MockRawIO()
908 writer.close = writer_close
909 pair = _io.BufferedRWPair(reader, writer)
910 err = raises(NameError, pair.close)
911 assert 'writer_non_existing' in str(err.value)
912 assert not pair.closed
913 assert reader.closed
914 assert not writer.closed
915
916 def test_reader_writer_close_error_on_close(self):
917 import _io
918 class MockRawIO(_io._IOBase):
919 def readable(self):
920 return True
921 def writable(self):
922 return True
923 def reader_close():
924 reader_non_existing
925 def writer_close():
926 writer_non_existing
927 reader = MockRawIO()
928 reader.close = reader_close
929 writer = MockRawIO()
930 writer.close = writer_close
931 pair = _io.BufferedRWPair(reader, writer)
932 err = raises(NameError, pair.close)
933 assert 'reader_non_existing' in str(err.value)
934 assert 'writer_non_existing' in str(err.value.__context__)
935 assert not pair.closed
936 assert not reader.closed
937 assert not writer.closed
938
939 class AppTestBufferedRandom:
940 spaceconfig = dict(usemodules=['_io'])
941
942 def setup_class(cls):
943 tmpfile = udir.join('tmpfile')
944 tmpfile.write(b"a\nb\nc", mode='wb')
945 cls.w_tmpfile = cls.space.wrap(str(tmpfile))
946
947 def test_simple_read(self):
948 import _io
949 raw = _io.FileIO(self.tmpfile, 'rb+')
950 f = _io.BufferedRandom(raw)
951 assert f.read(3) == b'a\nb'
952 f.write(b'xxxx')
953 f.seek(0)
954 assert f.read() == b'a\nbxxxx'
955
956 def test_simple_read_after_write(self):
957 import _io
958 raw = _io.FileIO(self.tmpfile, 'wb+')
959 f = _io.BufferedRandom(raw)
960 f.write(b'abc')
961 f.seek(0)
962 assert f.read() == b'abc'
963
964 def test_write_rewind_write(self):
965 # Various combinations of reading / writing / seeking
966 # backwards / writing again
967 import _io, errno
968 def mutate(bufio, pos1, pos2):
969 assert pos2 >= pos1
970 # Fill the buffer
971 bufio.seek(pos1)
972 bufio.read(pos2 - pos1)
973 bufio.write(b'\x02')
974 # This writes earlier than the previous write, but still inside
975 # the buffer.
976 bufio.seek(pos1)
977 bufio.write(b'\x01')
978
979 b = b"\x80\x81\x82\x83\x84"
980 for i in range(0, len(b)):
981 for j in range(i, len(b)):
982 raw = _io.BytesIO(b)
983 bufio = _io.BufferedRandom(raw, 100)
984 mutate(bufio, i, j)
985 bufio.flush()
986 expected = bytearray(b)
987 expected[j] = 2
988 expected[i] = 1
989 assert raw.getvalue() == expected
990
991 def test_interleaved_read_write(self):
992 import _io as io
993 # Test for issue #12213
994 with io.BytesIO(b'abcdefgh') as raw:
995 with io.BufferedRandom(raw, 100) as f:
996 f.write(b"1")
997 assert f.read(1) == b'b'
998 f.write(b'2')
999 assert f.read1(1) == b'd'
1000 f.write(b'3')
1001 buf = bytearray(1)
1002 f.readinto(buf)
1003 assert buf == b'f'
1004 f.write(b'4')
1005 assert f.peek(1) == b'h'
1006 f.flush()
1007 assert raw.getvalue() == b'1b2d3f4h'
1008
1009 with io.BytesIO(b'abc') as raw:
1010 with io.BufferedRandom(raw, 100) as f:
1011 assert f.read(1) == b'a'
1012 f.write(b"2")
1013 assert f.read(1) == b'c'
1014 f.flush()
1015 assert raw.getvalue() == b'a2c'
1016
1017 def test_interleaved_readline_write(self):
1018 import _io as io
1019 with io.BytesIO(b'ab\ncdef\ng\n') as raw:
1020 with io.BufferedRandom(raw) as f:
1021 f.write(b'1')
1022 assert f.readline() == b'b\n'
1023 f.write(b'2')
1024 assert f.readline() == b'def\n'
1025 f.write(b'3')
1026 assert f.readline() == b'\n'
1027 f.flush()
1028 assert raw.getvalue() == b'1b\n2def\n3\n'
1029
1030 def test_readline(self):
1031 import _io as io
1032 with io.BytesIO(b"abc\ndef\nxyzzy\nfoo\x00bar\nanother line") as raw:
1033 with io.BufferedRandom(raw, buffer_size=10) as f:
1034 assert f.readline() == b"abc\n"
1035 assert f.readline(10) == b"def\n"
1036 assert f.readline(2) == b"xy"
1037 assert f.readline(4) == b"zzy\n"
1038 assert f.readline() == b"foo\x00bar\n"
1039 assert f.readline(None) == b"another line"
1040 raises(TypeError, f.readline, 5.3)
1041
1042
1043 class AppTestMaxBuffer:
1044
1045 def w_check_max_buffer_size_removal(self, test):
1046 import _io
1047 raises(TypeError, test, _io.BytesIO(), 8, 12)
1048
1049 def test_max_buffer_size_removal(self):
1050 import _io
1051 self.check_max_buffer_size_removal(_io.BufferedWriter)
1052 self.check_max_buffer_size_removal(_io.BufferedRandom)
1053 self.check_max_buffer_size_removal (
1054 lambda raw, *args: _io.BufferedRWPair(raw, raw, *args))
1055
1056
1057 class TestNonReentrantLock:
1058 spaceconfig = dict(usemodules=['thread'])
1059
1060 def test_trylock(self, space):
1061 lock = interp_bufferedio.TryLock(space)
1062 with lock:
1063 pass
1064 with lock:
1065 exc = py.test.raises(OperationError, "with lock: pass")
1066 assert exc.value.match(space, space.w_RuntimeError)
1067
1068 def test_fast_closed_check(self, space):
1069 from pypy.module._io.interp_fileio import W_FileIO
1070 from pypy.module._io.interp_bufferedio import W_BufferedRandom
1071 tmpfile = udir.join('tmpfile')
1072 tmpfile.write("a\nb\nc", mode='wb')
1073 w_fn = space.appexec([space.newtext(str(tmpfile))], """(fn):
1074 return open(fn, "rb")""")
1075 assert w_fn._fast_closed_check == True
1076