1 # Adapted from test_file.py by Daniel Stutzbach
3 from __future__
import unicode_literals
9 from array
import array
10 from weakref
import proxy
11 from functools
import wraps
13 from test
.test_support
import (TESTFN
, findfile
, check_warnings
, run_unittest
,
15 from test
.test_support
import py3k_bytes
as bytes
17 from _io
import FileIO
as _FileIO
19 class AutoFileTests(unittest
.TestCase
):
20 # file tests for which a test file is automatically set up
23 self
.f
= _FileIO(TESTFN
, 'w')
30 def testWeakRefs(self
):
31 # verify weak references
33 p
.write(bytes(range(10)))
34 self
.assertEquals(self
.f
.tell(), p
.tell())
37 self
.assertRaises(ReferenceError, getattr, p
, 'tell')
39 def testSeekTell(self
):
40 self
.f
.write(bytes(range(20)))
41 self
.assertEquals(self
.f
.tell(), 20)
43 self
.assertEquals(self
.f
.tell(), 0)
45 self
.assertEquals(self
.f
.tell(), 10)
47 self
.assertEquals(self
.f
.tell(), 15)
49 self
.assertEquals(self
.f
.tell(), 10)
51 self
.assertEquals(self
.f
.tell(), 15)
53 def testAttributes(self
):
54 # verify expected attributes exist
57 self
.assertEquals(f
.mode
, "wb")
58 self
.assertEquals(f
.closed
, False)
60 # verify the attributes are readonly
61 for attr
in 'mode', 'closed':
62 self
.assertRaises((AttributeError, TypeError),
63 setattr, f
, attr
, 'oops')
65 def testReadinto(self
):
67 self
.f
.write(b
"\x01\x02")
69 a
= array(b
'b', b
'x'*10)
70 self
.f
= _FileIO(TESTFN
, 'r')
71 n
= self
.f
.readinto(a
)
72 self
.assertEquals(array(b
'b', [1, 2]), a
[:n
])
75 self
.assertEquals(repr(self
.f
), "<_io.FileIO name=%r mode='%s'>"
76 % (self
.f
.name
, self
.f
.mode
))
78 self
.assertEquals(repr(self
.f
), "<_io.FileIO fd=%r mode='%s'>"
79 % (self
.f
.fileno(), self
.f
.mode
))
81 self
.assertEquals(repr(self
.f
), "<_io.FileIO [closed]>")
85 self
.assertTrue(not f
.isatty())
86 self
.assertTrue(not f
.closed
)
87 #self.assertEquals(f.name, TESTFN)
88 self
.assertRaises(ValueError, f
.read
, 10) # Open for reading
90 self
.assertTrue(f
.closed
)
91 f
= _FileIO(TESTFN
, 'r')
92 self
.assertRaises(TypeError, f
.readinto
, "")
93 self
.assertTrue(not f
.closed
)
95 self
.assertTrue(f
.closed
)
97 def testMethods(self
):
98 methods
= ['fileno', 'isatty', 'read', 'readinto',
99 'seek', 'tell', 'truncate', 'write', 'seekable',
100 'readable', 'writable']
101 if sys
.platform
.startswith('atheos'):
102 methods
.remove('truncate')
105 self
.assertTrue(self
.f
.closed
)
107 for methodname
in methods
:
108 method
= getattr(self
.f
, methodname
)
109 # should raise on closed file
110 self
.assertRaises(ValueError, method
)
112 def testOpendir(self
):
113 # Issue 3703: opening a directory should fill the errno
114 # Windows always returns "[Errno 13]: Permission denied
115 # Unix calls dircheck() and returns "[Errno 21]: Is a directory"
119 self
.assertNotEqual(e
.errno
, 0)
120 self
.assertEqual(e
.filename
, ".")
122 self
.fail("Should have raised IOError")
124 #A set of functions testing that we get expected behaviour if someone has
125 #manually closed the internal file descriptor. First, a decorator:
129 #forcibly close the fd before invoking the problem function
141 def ClosedFDRaises(func
):
144 #forcibly close the fd before invoking the problem function
150 self
.assertEqual(e
.errno
, errno
.EBADF
)
152 self
.fail("Should have raised IOError")
161 def testErrnoOnClose(self
, f
):
165 def testErrnoOnClosedWrite(self
, f
):
169 def testErrnoOnClosedSeek(self
, f
):
173 def testErrnoOnClosedTell(self
, f
):
177 def testErrnoOnClosedTruncate(self
, f
):
181 def testErrnoOnClosedSeekable(self
, f
):
185 def testErrnoOnClosedReadable(self
, f
):
189 def testErrnoOnClosedWritable(self
, f
):
193 def testErrnoOnClosedFileno(self
, f
):
197 def testErrnoOnClosedIsatty(self
, f
):
198 self
.assertEqual(f
.isatty(), False)
200 def ReopenForRead(self
):
205 self
.f
= _FileIO(TESTFN
, 'r')
206 os
.close(self
.f
.fileno())
210 def testErrnoOnClosedRead(self
, f
):
211 f
= self
.ReopenForRead()
215 def testErrnoOnClosedReadall(self
, f
):
216 f
= self
.ReopenForRead()
220 def testErrnoOnClosedReadinto(self
, f
):
221 f
= self
.ReopenForRead()
222 a
= array(b
'b', b
'x'*10)
225 class OtherFileTests(unittest
.TestCase
):
229 f
= _FileIO(TESTFN
, "w")
230 self
.assertEquals(f
.readable(), False)
231 self
.assertEquals(f
.writable(), True)
232 self
.assertEquals(f
.seekable(), True)
235 f
= _FileIO(TESTFN
, "r")
236 self
.assertEquals(f
.readable(), True)
237 self
.assertEquals(f
.writable(), False)
238 self
.assertEquals(f
.seekable(), True)
241 f
= _FileIO(TESTFN
, "a+")
242 self
.assertEquals(f
.readable(), True)
243 self
.assertEquals(f
.writable(), True)
244 self
.assertEquals(f
.seekable(), True)
245 self
.assertEquals(f
.isatty(), False)
248 if sys
.platform
!= "win32":
250 f
= _FileIO("/dev/tty", "a")
251 except EnvironmentError:
252 # When run in a cron job there just aren't any
253 # ttys, so skip the test. This also handles other
254 # OS'es that don't support /dev/tty.
257 f
= _FileIO("/dev/tty", "a")
258 self
.assertEquals(f
.readable(), False)
259 self
.assertEquals(f
.writable(), True)
260 if sys
.platform
!= "darwin" and \
261 'bsd' not in sys
.platform
and \
262 not sys
.platform
.startswith('sunos'):
263 # Somehow /dev/tty appears seekable on some BSDs
264 self
.assertEquals(f
.seekable(), False)
265 self
.assertEquals(f
.isatty(), True)
270 def testModeStrings(self
):
271 # check invalid mode strings
272 for mode
in ("", "aU", "wU+", "rw", "rt"):
274 f
= _FileIO(TESTFN
, mode
)
279 self
.fail('%r is an invalid file mode' % mode
)
281 def testUnicodeOpen(self
):
282 # verify repr works for unicode too
283 f
= _FileIO(str(TESTFN
), "w")
287 def testBytesOpen(self
):
288 # Opening a bytes filename
290 fn
= TESTFN
.encode("ascii")
291 except UnicodeEncodeError:
298 with
open(TESTFN
, "rb") as f
:
299 self
.assertEquals(f
.read(), b
"abc")
303 def testInvalidFd(self
):
304 self
.assertRaises(ValueError, _FileIO
, -10)
305 self
.assertRaises(OSError, _FileIO
, make_bad_fd())
307 def testBadModeArgument(self
):
308 # verify that we get a sensible error message for bad mode argument
311 f
= _FileIO(TESTFN
, bad_mode
)
312 except ValueError as msg
:
315 if s
.find(TESTFN
) != -1 or s
.find(bad_mode
) == -1:
316 self
.fail("bad error message for invalid mode: %s" % s
)
317 # if msg.args[0] == 0, we're probably on Windows where there may be
318 # no obvious way to discover why open() failed.
321 self
.fail("no error for invalid mode: %s" % bad_mode
)
323 def testTruncateOnWindows(self
):
325 # SF bug <http://www.python.org/sf/801631>
326 # "file.truncate fault on windows"
327 f
= _FileIO(TESTFN
, 'w')
328 f
.write(bytes(range(11)))
331 f
= _FileIO(TESTFN
,'r+')
333 if data
!= bytes(range(5)):
334 self
.fail("Read on file opened for update failed %r" % data
)
336 self
.fail("File pos after read wrong %d" % f
.tell())
340 self
.fail("File pos after ftruncate wrong %d" % f
.tell())
343 size
= os
.path
.getsize(TESTFN
)
345 self
.fail("File size after ftruncate wrong %d" % size
)
352 def testAppend(self
):
354 f
= open(TESTFN
, 'wb')
357 f
= open(TESTFN
, 'ab')
360 f
= open(TESTFN
, 'rb')
363 self
.assertEqual(d
, b
'spameggs')
370 def testInvalidInit(self
):
371 self
.assertRaises(TypeError, _FileIO
, "1", 0, 0)
373 def testWarnings(self
):
374 with
check_warnings() as w
:
375 self
.assertEqual(w
.warnings
, [])
376 self
.assertRaises(TypeError, _FileIO
, [])
377 self
.assertEqual(w
.warnings
, [])
378 self
.assertRaises(ValueError, _FileIO
, "/some/invalid/name", "rt")
379 self
.assertEqual(w
.warnings
, [])
383 # Historically, these tests have been sloppy about removing TESTFN.
384 # So get rid of it no matter what.
386 run_unittest(AutoFileTests
, OtherFileTests
)
388 if os
.path
.exists(TESTFN
):
391 if __name__
== '__main__':