Debian Codegraph @

Lib/test/test_fileio.py

raw
1 # Adapted from test_file.py by Daniel Stutzbach
2
3 import sys
4 import os
5 import io
6 import errno
7 import unittest
8 from array import array
9 from weakref import proxy
10 from functools import wraps
11
12 from test.support import (
13 cpython_only, swap_attr, gc_collect, is_wasi,
14 infinite_recursion, strace_helper
15 )
16 from test.support.os_helper import (
17 TESTFN, TESTFN_ASCII, TESTFN_UNICODE, make_bad_fd,
18 )
19 from test.support.warnings_helper import check_warnings
20 from test.support.import_helper import import_module
21 from collections import UserList
22
23 import _io # C implementation of io
24 import _pyio # Python implementation of io
25
26
27 _strace_flags=["--trace=%file,%desc"]
28
29
30 class AutoFileTests:
31 # file tests for which a test file is automatically set up
32
33 def setUp(self):
34 self.f = self.FileIO(TESTFN, 'w')
35
36 def tearDown(self):
37 if self.f:
38 self.f.close()
39 os.remove(TESTFN)
40
41 def testWeakRefs(self):
42 # verify weak references
43 p = proxy(self.f)
44 p.write(bytes(range(10)))
45 self.assertEqual(self.f.tell(), p.tell())
46 self.f.close()
47 self.f = None
48 gc_collect() # For PyPy or other GCs.
49 self.assertRaises(ReferenceError, getattr, p, 'tell')
50
51 def testSeekTell(self):
52 self.f.write(bytes(range(20)))
53 self.assertEqual(self.f.tell(), 20)
54 self.f.seek(0)
55 self.assertEqual(self.f.tell(), 0)
56 self.f.seek(10)
57 self.assertEqual(self.f.tell(), 10)
58 self.f.seek(5, 1)
59 self.assertEqual(self.f.tell(), 15)
60 self.f.seek(-5, 1)
61 self.assertEqual(self.f.tell(), 10)
62 self.f.seek(-5, 2)
63 self.assertEqual(self.f.tell(), 15)
64
65 def testAttributes(self):
66 # verify expected attributes exist
67 f = self.f
68
69 self.assertEqual(f.mode, "wb")
70 self.assertEqual(f.closed, False)
71
72 # verify the attributes are readonly
73 for attr in 'mode', 'closed':
74 self.assertRaises((AttributeError, TypeError),
75 setattr, f, attr, 'oops')
76
77 @unittest.skipIf(is_wasi, "WASI does not expose st_blksize.")
78 def testBlksize(self):
79 # test private _blksize attribute
80 blksize = io.DEFAULT_BUFFER_SIZE
81 # try to get preferred blksize from stat.st_blksize, if available
82 if hasattr(os, 'fstat'):
83 fst = os.fstat(self.f.fileno())
84 blksize = getattr(fst, 'st_blksize', blksize)
85 self.assertEqual(self.f._blksize, blksize)
86
87 # verify readinto
88 def testReadintoByteArray(self):
89 self.f.write(bytes([1, 2, 0, 255]))
90 self.f.close()
91
92 ba = bytearray(b'abcdefgh')
93 with self.FileIO(TESTFN, 'r') as f:
94 n = f.readinto(ba)
95 self.assertEqual(ba, b'\x01\x02\x00\xffefgh')
96 self.assertEqual(n, 4)
97
98 def _testReadintoMemoryview(self):
99 self.f.write(bytes([1, 2, 0, 255]))
100 self.f.close()
101
102 m = memoryview(bytearray(b'abcdefgh'))
103 with self.FileIO(TESTFN, 'r') as f:
104 n = f.readinto(m)
105 self.assertEqual(m, b'\x01\x02\x00\xffefgh')
106 self.assertEqual(n, 4)
107
108 m = memoryview(bytearray(b'abcdefgh')).cast('H', shape=[2, 2])
109 with self.FileIO(TESTFN, 'r') as f:
110 n = f.readinto(m)
111 self.assertEqual(bytes(m), b'\x01\x02\x00\xffefgh')
112 self.assertEqual(n, 4)
113
114 def _testReadintoArray(self):
115 self.f.write(bytes([1, 2, 0, 255]))
116 self.f.close()
117
118 a = array('B', b'abcdefgh')
119 with self.FileIO(TESTFN, 'r') as f:
120 n = f.readinto(a)
121 self.assertEqual(a, array('B', [1, 2, 0, 255, 101, 102, 103, 104]))
122 self.assertEqual(n, 4)
123
124 a = array('b', b'abcdefgh')
125 with self.FileIO(TESTFN, 'r') as f:
126 n = f.readinto(a)
127 self.assertEqual(a, array('b', [1, 2, 0, -1, 101, 102, 103, 104]))
128 self.assertEqual(n, 4)
129
130 a = array('I', b'abcdefgh')
131 with self.FileIO(TESTFN, 'r') as f:
132 n = f.readinto(a)
133 self.assertEqual(a, array('I', b'\x01\x02\x00\xffefgh'))
134 self.assertEqual(n, 4)
135
136 def testWritelinesList(self):
137 l = [b'123', b'456']
138 self.f.writelines(l)
139 self.f.close()
140 self.f = self.FileIO(TESTFN, 'rb')
141 buf = self.f.read()
142 self.assertEqual(buf, b'123456')
143
144 def testWritelinesUserList(self):
145 l = UserList([b'123', b'456'])
146 self.f.writelines(l)
147 self.f.close()
148 self.f = self.FileIO(TESTFN, 'rb')
149 buf = self.f.read()
150 self.assertEqual(buf, b'123456')
151
152 def testWritelinesError(self):
153 self.assertRaises(TypeError, self.f.writelines, [1, 2, 3])
154 self.assertRaises(TypeError, self.f.writelines, None)
155 self.assertRaises(TypeError, self.f.writelines, "abc")
156
157 def test_none_args(self):
158 self.f.write(b"hi\nbye\nabc")
159 self.f.close()
160 self.f = self.FileIO(TESTFN, 'r')
161 self.assertEqual(self.f.read(None), b"hi\nbye\nabc")
162 self.f.seek(0)
163 self.assertEqual(self.f.readline(None), b"hi\n")
164 self.assertEqual(self.f.readlines(None), [b"bye\n", b"abc"])
165
166 def test_reject(self):
167 self.assertRaises(TypeError, self.f.write, "Hello!")
168
169 def testRepr(self):
170 self.assertEqual(repr(self.f),
171 "<%s.FileIO name=%r mode=%r closefd=True>" %
172 (self.modulename, self.f.name, self.f.mode))
173 del self.f.name
174 self.assertEqual(repr(self.f),
175 "<%s.FileIO fd=%r mode=%r closefd=True>" %
176 (self.modulename, self.f.fileno(), self.f.mode))
177 self.f.close()
178 self.assertEqual(repr(self.f),
179 "<%s.FileIO [closed]>" % (self.modulename,))
180
181 def test_subclass_repr(self):
182 class TestSubclass(self.FileIO):
183 pass
184
185 f = TestSubclass(TESTFN)
186 with f:
187 self.assertIn(TestSubclass.__name__, repr(f))
188
189 self.assertIn(TestSubclass.__name__, repr(f))
190
191 def testReprNoCloseFD(self):
192 fd = os.open(TESTFN, os.O_RDONLY)
193 try:
194 with self.FileIO(fd, 'r', closefd=False) as f:
195 self.assertEqual(repr(f),
196 "<%s.FileIO name=%r mode=%r closefd=False>" %
197 (self.modulename, f.name, f.mode))
198 finally:
199 os.close(fd)
200
201 @infinite_recursion(25)
202 def testRecursiveRepr(self):
203 # Issue #25455
204 with swap_attr(self.f, 'name', self.f):
205 with self.assertRaises(RuntimeError):
206 repr(self.f) # Should not crash
207
208 def testErrors(self):
209 f = self.f
210 self.assertFalse(f.isatty())
211 self.assertFalse(f.closed)
212 #self.assertEqual(f.name, TESTFN)
213 self.assertRaises(ValueError, f.read, 10) # Open for reading
214 f.close()
215 self.assertTrue(f.closed)
216 f = self.FileIO(TESTFN, 'r')
217 self.assertRaises(TypeError, f.readinto, "")
218 self.assertFalse(f.closed)
219 f.close()
220 self.assertTrue(f.closed)
221
222 def testMethods(self):
223 methods = ['fileno', 'isatty', 'seekable', 'readable', 'writable',
224 'read', 'readall', 'readline', 'readlines',
225 'tell', 'truncate', 'flush']
226
227 self.f.close()
228 self.assertTrue(self.f.closed)
229
230 for methodname in methods:
231 method = getattr(self.f, methodname)
232 # should raise on closed file
233 self.assertRaises(ValueError, method)
234
235 self.assertRaises(TypeError, self.f.readinto)
236 self.assertRaises(ValueError, self.f.readinto, bytearray(1))
237 self.assertRaises(TypeError, self.f.seek)
238 self.assertRaises(ValueError, self.f.seek, 0)
239 self.assertRaises(TypeError, self.f.write)
240 self.assertRaises(ValueError, self.f.write, b'')
241 self.assertRaises(TypeError, self.f.writelines)
242 self.assertRaises(ValueError, self.f.writelines, b'')
243
244 def testOpendir(self):
245 # Issue 3703: opening a directory should fill the errno
246 # Windows always returns "[Errno 13]: Permission denied
247 # Unix uses fstat and returns "[Errno 21]: Is a directory"
248 try:
249 self.FileIO('.', 'r')
250 except OSError as e:
251 self.assertNotEqual(e.errno, 0)
252 self.assertEqual(e.filename, ".")
253 else:
254 self.fail("Should have raised OSError")
255
256 @unittest.skipIf(os.name == 'nt', "test only works on a POSIX-like system")
257 def testOpenDirFD(self):
258 fd = os.open('.', os.O_RDONLY)
259 with self.assertRaises(OSError) as cm:
260 self.FileIO(fd, 'r')
261 os.close(fd)
262 self.assertEqual(cm.exception.errno, errno.EISDIR)
263
264 #A set of functions testing that we get expected behaviour if someone has
265 #manually closed the internal file descriptor. First, a decorator:
266 def ClosedFD(func):
267 @wraps(func)
268 def wrapper(self):
269 #forcibly close the fd before invoking the problem function
270 f = self.f
271 os.close(f.fileno())
272 try:
273 func(self, f)
274 finally:
275 try:
276 self.f.close()
277 except OSError:
278 pass
279 return wrapper
280
281 def ClosedFDRaises(func):
282 @wraps(func)
283 def wrapper(self):
284 #forcibly close the fd before invoking the problem function
285 f = self.f
286 os.close(f.fileno())
287 try:
288 func(self, f)
289 except OSError as e:
290 self.assertEqual(e.errno, errno.EBADF)
291 else:
292 self.fail("Should have raised OSError")
293 finally:
294 try:
295 self.f.close()
296 except OSError:
297 pass
298 return wrapper
299
300 @ClosedFDRaises
301 def testErrnoOnClose(self, f):
302 f.close()
303
304 @ClosedFDRaises
305 def testErrnoOnClosedWrite(self, f):
306 f.write(b'a')
307
308 @ClosedFDRaises
309 def testErrnoOnClosedSeek(self, f):
310 f.seek(0)
311
312 @ClosedFDRaises
313 def testErrnoOnClosedTell(self, f):
314 f.tell()
315
316 @ClosedFDRaises
317 def testErrnoOnClosedTruncate(self, f):
318 f.truncate(0)
319
320 @ClosedFD
321 def testErrnoOnClosedSeekable(self, f):
322 f.seekable()
323
324 @ClosedFD
325 def testErrnoOnClosedReadable(self, f):
326 f.readable()
327
328 @ClosedFD
329 def testErrnoOnClosedWritable(self, f):
330 f.writable()
331
332 @ClosedFD
333 def testErrnoOnClosedFileno(self, f):
334 f.fileno()
335
336 @ClosedFD
337 def testErrnoOnClosedIsatty(self, f):
338 self.assertEqual(f.isatty(), False)
339
340 def ReopenForRead(self):
341 try:
342 self.f.close()
343 except OSError:
344 pass
345 self.f = self.FileIO(TESTFN, 'r')
346 os.close(self.f.fileno())
347 return self.f
348
349 @ClosedFDRaises
350 def testErrnoOnClosedRead(self, f):
351 f = self.ReopenForRead()
352 f.read(1)
353
354 @ClosedFDRaises
355 def testErrnoOnClosedReadall(self, f):
356 f = self.ReopenForRead()
357 f.readall()
358
359 @ClosedFDRaises
360 def testErrnoOnClosedReadinto(self, f):
361 f = self.ReopenForRead()
362 a = array('b', b'x'*10)
363 f.readinto(a)
364
365 @strace_helper.requires_strace()
366 def test_syscalls_read(self):
367 """Check set of system calls during common I/O patterns
368
369 It's expected as bits of the I/O implementation change, this will need
370 to change. The goal is to catch changes that unintentionally add
371 additional systemcalls (ex. additional calls have been looked at in
372 bpo-21679 and gh-120754).
373 """
374 self.f.write(b"Hello, World!")
375 self.f.close()
376
377
378 def check_readall(name, code, prelude="", cleanup="",
379 extra_checks=None):
380 with self.subTest(name=name):
381 syscalls = strace_helper.get_events(code, _strace_flags,
382 prelude=prelude,
383 cleanup=cleanup)
384
385 # Some system calls (ex. mmap) can be used for both File I/O and
386 # memory allocation. Filter out the ones used for memory
387 # allocation.
388 syscalls = strace_helper.filter_memory(syscalls)
389
390 # The first call should be an open that returns a
391 # file descriptor (fd). Afer that calls may vary. Once the file
392 # is opened, check calls refer to it by fd as the filename
393 # could be removed from the filesystem, renamed, etc. See:
394 # Time-of-check time-of-use (TOCTOU) software bug class.
395 #
396 # There are a number of related but distinct open system calls
397 # so not checking precise name here.
398 self.assertGreater(
399 len(syscalls),
400 1,
401 f"Should have had at least an open call|calls={syscalls}")
402 fd_str = syscalls[0].returncode
403
404 # All other calls should contain the fd in their argument set.
405 for ev in syscalls[1:]:
406 self.assertIn(
407 fd_str,
408 ev.args,
409 f"Looking for file descriptor in arguments|ev={ev}"
410 )
411
412 # There are a number of related syscalls used to implement
413 # behaviors in a libc (ex. fstat, newfstatat, statx, open, openat).
414 # Allow any that use the same substring.
415 def count_similarname(name):
416 return len([ev for ev in syscalls if name in ev.syscall])
417
418 checks = [
419 # Should open and close the file exactly once
420 ("open", 1),
421 ("close", 1),
422 # There should no longer be an isatty call (All files being
423 # tested are block devices / not character devices).
424 ('ioctl', 0),
425 # Should only have one fstat (bpo-21679, gh-120754)
426 # note: It's important this uses a fd rather than filename,
427 # That is validated by the `fd` check above.
428 # note: fstat, newfstatat, and statx have all been observed
429 # here in the underlying C library implementations.
430 ("stat", 1)
431 ]
432
433 if extra_checks:
434 checks += extra_checks
435
436 for call, count in checks:
437 self.assertEqual(
438 count_similarname(call),
439 count,
440 msg=f"call={call}|count={count}|syscalls={syscalls}"
441 )
442
443 # "open, read, close" file using different common patterns.
444 check_readall(
445 "open builtin with default options",
446 f"""
447 f = open('{TESTFN}')
448 f.read()
449 f.close()
450 """
451 )
452
453 check_readall(
454 "open in binary mode",
455 f"""
456 f = open('{TESTFN}', 'rb')
457 f.read()
458 f.close()
459 """
460 )
461
462 check_readall(
463 "open in text mode",
464 f"""
465 f = open('{TESTFN}', 'rt')
466 f.read()
467 f.close()
468 """,
469 # GH-122111: read_text uses BufferedIO which requires looking up
470 # position in file. `read_bytes` disables that buffering and avoids
471 # these calls which is tested the `pathlib read_bytes` case.
472 extra_checks=[("seek", 1)]
473 )
474
475 check_readall(
476 "pathlib read_bytes",
477 "p.read_bytes()",
478 prelude=f"""from pathlib import Path; p = Path("{TESTFN}")""",
479 # GH-122111: Buffering is disabled so these calls are avoided.
480 extra_checks=[("seek", 0)]
481 )
482
483 check_readall(
484 "pathlib read_text",
485 "p.read_text()",
486 prelude=f"""from pathlib import Path; p = Path("{TESTFN}")"""
487 )
488
489 # Focus on just `read()`.
490 calls = strace_helper.get_syscalls(
491 prelude=f"f = open('{TESTFN}')",
492 code="f.read()",
493 cleanup="f.close()",
494 strace_flags=_strace_flags
495 )
496 # One to read all the bytes
497 # One to read the EOF and get a size 0 return.
498 self.assertEqual(calls.count("read"), 2)
499
500
501
502 class CAutoFileTests(AutoFileTests, unittest.TestCase):
503 FileIO = _io.FileIO
504 modulename = '_io'
505
506 class PyAutoFileTests(AutoFileTests, unittest.TestCase):
507 FileIO = _pyio.FileIO
508 modulename = '_pyio'
509
510
511 class OtherFileTests:
512
513 def testAbles(self):
514 try:
515 f = self.FileIO(TESTFN, "w")
516 self.assertEqual(f.readable(), False)
517 self.assertEqual(f.writable(), True)
518 self.assertEqual(f.seekable(), True)
519 f.close()
520
521 f = self.FileIO(TESTFN, "r")
522 self.assertEqual(f.readable(), True)
523 self.assertEqual(f.writable(), False)
524 self.assertEqual(f.seekable(), True)
525 f.close()
526
527 f = self.FileIO(TESTFN, "a+")
528 self.assertEqual(f.readable(), True)
529 self.assertEqual(f.writable(), True)
530 self.assertEqual(f.seekable(), True)
531 self.assertEqual(f.isatty(), False)
532 f.close()
533
534 if sys.platform != "win32":
535 try:
536 f = self.FileIO("/dev/tty", "a")
537 except OSError:
538 # When run in a cron job there just aren't any
539 # ttys, so skip the test. This also handles other
540 # OS'es that don't support /dev/tty.
541 pass
542 else:
543 self.assertEqual(f.readable(), False)
544 self.assertEqual(f.writable(), True)
545 if sys.platform != "darwin" and \
546 'bsd' not in sys.platform and \
547 not sys.platform.startswith(('sunos', 'aix')):
548 # Somehow /dev/tty appears seekable on some BSDs
549 self.assertEqual(f.seekable(), False)
550 self.assertEqual(f.isatty(), True)
551 f.close()
552 finally:
553 os.unlink(TESTFN)
554
555 def testInvalidModeStrings(self):
556 # check invalid mode strings
557 for mode in ("", "aU", "wU+", "rw", "rt"):
558 try:
559 f = self.FileIO(TESTFN, mode)
560 except ValueError:
561 pass
562 else:
563 f.close()
564 self.fail('%r is an invalid file mode' % mode)
565
566 def testModeStrings(self):
567 # test that the mode attribute is correct for various mode strings
568 # given as init args
569 try:
570 for modes in [('w', 'wb'), ('wb', 'wb'), ('wb+', 'rb+'),
571 ('w+b', 'rb+'), ('a', 'ab'), ('ab', 'ab'),
572 ('ab+', 'ab+'), ('a+b', 'ab+'), ('r', 'rb'),
573 ('rb', 'rb'), ('rb+', 'rb+'), ('r+b', 'rb+')]:
574 # read modes are last so that TESTFN will exist first
575 with self.FileIO(TESTFN, modes[0]) as f:
576 self.assertEqual(f.mode, modes[1])
577 finally:
578 if os.path.exists(TESTFN):
579 os.unlink(TESTFN)
580
581 def testUnicodeOpen(self):
582 # verify repr works for unicode too
583 f = self.FileIO(str(TESTFN), "w")
584 f.close()
585 os.unlink(TESTFN)
586
587 def testBytesOpen(self):
588 # Opening a bytes filename
589 fn = TESTFN_ASCII.encode("ascii")
590 f = self.FileIO(fn, "w")
591 try:
592 f.write(b"abc")
593 f.close()
594 with self.open(TESTFN_ASCII, "rb") as f:
595 self.assertEqual(f.read(), b"abc")
596 finally:
597 os.unlink(TESTFN_ASCII)
598
599 @unittest.skipIf(sys.getfilesystemencoding() != 'utf-8',
600 "test only works for utf-8 filesystems")
601 def testUtf8BytesOpen(self):
602 # Opening a UTF-8 bytes filename
603 try:
604 fn = TESTFN_UNICODE.encode("utf-8")
605 except UnicodeEncodeError:
606 self.skipTest('could not encode %r to utf-8' % TESTFN_UNICODE)
607 f = self.FileIO(fn, "w")
608 try:
609 f.write(b"abc")
610 f.close()
611 with self.open(TESTFN_UNICODE, "rb") as f:
612 self.assertEqual(f.read(), b"abc")
613 finally:
614 os.unlink(TESTFN_UNICODE)
615
616 def testConstructorHandlesNULChars(self):
617 fn_with_NUL = 'foo\0bar'
618 self.assertRaises(ValueError, self.FileIO, fn_with_NUL, 'w')
619 self.assertRaises(ValueError, self.FileIO, bytes(fn_with_NUL, 'ascii'), 'w')
620
621 def testInvalidFd(self):
622 self.assertRaises(ValueError, self.FileIO, -10)
623 self.assertRaises(OSError, self.FileIO, make_bad_fd())
624 if sys.platform == 'win32':
625 import msvcrt
626 self.assertRaises(OSError, msvcrt.get_osfhandle, make_bad_fd())
627
628 def testBooleanFd(self):
629 for fd in False, True:
630 with self.assertWarnsRegex(RuntimeWarning,
631 'bool is used as a file descriptor') as cm:
632 f = self.FileIO(fd, closefd=False)
633 f.close()
634 self.assertEqual(cm.filename, __file__)
635
636 def testBadModeArgument(self):
637 # verify that we get a sensible error message for bad mode argument
638 bad_mode = "qwerty"
639 try:
640 f = self.FileIO(TESTFN, bad_mode)
641 except ValueError as msg:
642 if msg.args[0] != 0:
643 s = str(msg)
644 if TESTFN in s or bad_mode not in s:
645 self.fail("bad error message for invalid mode: %s" % s)
646 # if msg.args[0] == 0, we're probably on Windows where there may be
647 # no obvious way to discover why open() failed.
648 else:
649 f.close()
650 self.fail("no error for invalid mode: %s" % bad_mode)
651
652 def testTruncate(self):
653 f = self.FileIO(TESTFN, 'w')
654 f.write(bytes(bytearray(range(10))))
655 self.assertEqual(f.tell(), 10)
656 f.truncate(5)
657 self.assertEqual(f.tell(), 10)
658 self.assertEqual(f.seek(0, io.SEEK_END), 5)
659 f.truncate(15)
660 self.assertEqual(f.tell(), 5)
661 self.assertEqual(f.seek(0, io.SEEK_END), 15)
662 f.close()
663
664 def testTruncateOnWindows(self):
665 def bug801631():
666 # SF bug <https://bugs.python.org/issue801631>
667 # "file.truncate fault on windows"
668 f = self.FileIO(TESTFN, 'w')
669 f.write(bytes(range(11)))
670 f.close()
671
672 f = self.FileIO(TESTFN,'r+')
673 data = f.read(5)
674 if data != bytes(range(5)):
675 self.fail("Read on file opened for update failed %r" % data)
676 if f.tell() != 5:
677 self.fail("File pos after read wrong %d" % f.tell())
678
679 f.truncate()
680 if f.tell() != 5:
681 self.fail("File pos after ftruncate wrong %d" % f.tell())
682
683 f.close()
684 size = os.path.getsize(TESTFN)
685 if size != 5:
686 self.fail("File size after ftruncate wrong %d" % size)
687
688 try:
689 bug801631()
690 finally:
691 os.unlink(TESTFN)
692
693 def testAppend(self):
694 try:
695 f = self.FileIO(TESTFN, 'wb')
696 f.write(b'spam')
697 f.close()
698 f = self.FileIO(TESTFN, 'ab')
699 f.write(b'eggs')
700 f.close()
701 f = self.FileIO(TESTFN, 'rb')
702 d = f.read()
703 f.close()
704 self.assertEqual(d, b'spameggs')
705 finally:
706 try:
707 os.unlink(TESTFN)
708 except:
709 pass
710
711 def testInvalidInit(self):
712 self.assertRaises(TypeError, self.FileIO, "1", 0, 0)
713
714 def testWarnings(self):
715 with check_warnings(quiet=True) as w:
716 self.assertEqual(w.warnings, [])
717 self.assertRaises(TypeError, self.FileIO, [])
718 self.assertEqual(w.warnings, [])
719 self.assertRaises(ValueError, self.FileIO, "/some/invalid/name", "rt")
720 self.assertEqual(w.warnings, [])
721
722 def testUnclosedFDOnException(self):
723 class MyException(Exception): pass
724 class MyFileIO(self.FileIO):
725 def __setattr__(self, name, value):
726 if name == "name":
727 raise MyException("blocked setting name")
728 return super(MyFileIO, self).__setattr__(name, value)
729 fd = os.open(__file__, os.O_RDONLY)
730 self.assertRaises(MyException, MyFileIO, fd)
731 os.close(fd) # should not raise OSError(EBADF)
732
733
734 class COtherFileTests(OtherFileTests, unittest.TestCase):
735 FileIO = _io.FileIO
736 modulename = '_io'
737 open = _io.open
738
739 @cpython_only
740 def testInvalidFd_overflow(self):
741 # Issue 15989
742 _testcapi = import_module("_testcapi")
743 self.assertRaises(TypeError, self.FileIO, _testcapi.INT_MAX + 1)
744 self.assertRaises(TypeError, self.FileIO, _testcapi.INT_MIN - 1)
745
746 def test_open_code(self):
747 # Check that the default behaviour of open_code matches
748 # open("rb")
749 with self.FileIO(__file__, "rb") as f:
750 expected = f.read()
751 with _io.open_code(__file__) as f:
752 actual = f.read()
753 self.assertEqual(expected, actual)
754
755
756 class PyOtherFileTests(OtherFileTests, unittest.TestCase):
757 FileIO = _pyio.FileIO
758 modulename = '_pyio'
759 open = _pyio.open
760
761 def test_open_code(self):
762 # Check that the default behaviour of open_code matches
763 # open("rb")
764 with self.FileIO(__file__, "rb") as f:
765 expected = f.read()
766 with check_warnings(quiet=True) as w:
767 # Always test _open_code_with_warning
768 with _pyio._open_code_with_warning(__file__) as f:
769 actual = f.read()
770 self.assertEqual(expected, actual)
771 self.assertNotEqual(w.warnings, [])
772
773
774 def tearDownModule():
775 # Historically, these tests have been sloppy about removing TESTFN.
776 # So get rid of it no matter what.
777 if os.path.exists(TESTFN):
778 os.unlink(TESTFN)
779
780
781 if __name__ == '__main__':
782 unittest.main()