blob: 983fcb41bf147b221112b157c3341cfcea4c7730 [file] [log] [blame]
Guido van Rossumde3bc7c2007-03-08 01:02:00 +00001# Adapted from test_file.py by Daniel Stutzbach
Guido van Rossuma9e20242007-03-08 00:43:48 +00002
3import sys
4import os
5import unittest
6from array import array
7from weakref import proxy
8
9from test.test_support import TESTFN, findfile, run_unittest
10from UserList import UserList
11
12import _fileio
13
14class AutoFileTests(unittest.TestCase):
15 # file tests for which a test file is automatically set up
16
17 def setUp(self):
18 self.f = _fileio._FileIO(TESTFN, 'w')
19
20 def tearDown(self):
21 if self.f:
22 self.f.close()
23 os.remove(TESTFN)
24
25 def testWeakRefs(self):
26 # verify weak references
27 p = proxy(self.f)
28 p.write(bytes(range(10)))
29 self.assertEquals(self.f.tell(), p.tell())
30 self.f.close()
31 self.f = None
32 self.assertRaises(ReferenceError, getattr, p, 'tell')
33
34 def testSeekTell(self):
35 self.f.write(bytes(range(20)))
36 self.assertEquals(self.f.tell(), 20)
37 self.f.seek(0)
38 self.assertEquals(self.f.tell(), 0)
39 self.f.seek(10)
40 self.assertEquals(self.f.tell(), 10)
41 self.f.seek(5, 1)
42 self.assertEquals(self.f.tell(), 15)
43 self.f.seek(-5, 1)
44 self.assertEquals(self.f.tell(), 10)
45 self.f.seek(-5, 2)
46 self.assertEquals(self.f.tell(), 15)
47
48 def testAttributes(self):
49 # verify expected attributes exist
50 f = self.f
Guido van Rossuma9e20242007-03-08 00:43:48 +000051
Guido van Rossum31c3a572007-04-12 14:51:49 +000052 self.assertEquals(f.mode, "w")
53 self.assertEquals(f.closed, False)
54
55 # verify the attributes are readonly
56 for attr in 'mode', 'closed':
57 self.assertRaises((AttributeError, TypeError),
58 setattr, f, attr, 'oops')
Guido van Rossuma9e20242007-03-08 00:43:48 +000059
60 def testReadinto(self):
61 # verify readinto
62 self.f.write(bytes([1, 2]))
63 self.f.close()
64 a = array('b', 'x'*10)
65 self.f = _fileio._FileIO(TESTFN, 'r')
66 n = self.f.readinto(a)
67 self.assertEquals(array('b', [1, 2]), a[:n])
68
69 def testRepr(self):
70 # verify repr works
71 return # XXX doesn't work yet
72 self.assert_(repr(self.f).startswith("<open file '" + TESTFN))
73
74 def testErrors(self):
75 f = self.f
76 self.assert_(not f.isatty())
Guido van Rossum31c3a572007-04-12 14:51:49 +000077 self.assert_(not f.closed)
Guido van Rossuma9e20242007-03-08 00:43:48 +000078 #self.assertEquals(f.name, TESTFN)
Guido van Rossum31c3a572007-04-12 14:51:49 +000079 self.assertRaises(ValueError, f.read, 10) # Open for reading
Guido van Rossuma9e20242007-03-08 00:43:48 +000080 f.close()
Guido van Rossum31c3a572007-04-12 14:51:49 +000081 self.assert_(f.closed)
82 f = _fileio._FileIO(TESTFN, 'r')
83 self.assertRaises(TypeError, f.readinto, "")
84 self.assert_(not f.closed)
85 f.close()
86 self.assert_(f.closed)
Guido van Rossuma9e20242007-03-08 00:43:48 +000087
88 def testMethods(self):
89 methods = ['fileno', 'isatty', 'read', 'readinto',
90 'seek', 'tell', 'truncate', 'write', 'seekable',
91 'readable', 'writable']
92 if sys.platform.startswith('atheos'):
93 methods.remove('truncate')
94
Guido van Rossum31c3a572007-04-12 14:51:49 +000095 self.f.close()
96 self.assert_(self.f.closed)
Guido van Rossuma9e20242007-03-08 00:43:48 +000097
98 for methodname in methods:
99 method = getattr(self.f, methodname)
100 # should raise on closed file
101 self.assertRaises(ValueError, method)
102
Guido van Rossuma9e20242007-03-08 00:43:48 +0000103
104class OtherFileTests(unittest.TestCase):
105
106 def testAbles(self):
107 try:
108 f = _fileio._FileIO(TESTFN, "w")
109 self.assertEquals(f.readable(), False)
110 self.assertEquals(f.writable(), True)
111 self.assertEquals(f.seekable(), True)
112 f.close()
113
114 f = _fileio._FileIO(TESTFN, "r")
115 self.assertEquals(f.readable(), True)
116 self.assertEquals(f.writable(), False)
117 self.assertEquals(f.seekable(), True)
118 f.close()
119
120 f = _fileio._FileIO(TESTFN, "a+")
121 self.assertEquals(f.readable(), True)
122 self.assertEquals(f.writable(), True)
123 self.assertEquals(f.seekable(), True)
124 self.assertEquals(f.isatty(), False)
125 f.close()
126
127 f = _fileio._FileIO("/dev/tty", "a") # XXX, won't work on e.g., Windows
128 self.assertEquals(f.readable(), False)
129 self.assertEquals(f.writable(), True)
130 ##self.assertEquals(f.seekable(), False) # XXX True on OSX!?
131 self.assertEquals(f.isatty(), True)
132 f.close()
133 finally:
134 os.unlink(TESTFN)
135
136 def testModeStrings(self):
137 # check invalid mode strings
138 for mode in ("", "aU", "wU+", "rb", "rt"):
139 try:
140 f = _fileio._FileIO(TESTFN, mode)
141 except ValueError:
142 pass
143 else:
144 f.close()
145 self.fail('%r is an invalid file mode' % mode)
146
147 def testStdin(self):
148 ## This causes the interpreter to exit on OSF1 v5.1.
149 #if sys.platform != 'osf1V5':
150 # self.assertRaises(IOError, sys.stdin.seek, -1)
151 #else:
152 # print((
153 # ' Skipping sys.stdin.seek(-1), it may crash the interpreter.'
154 # ' Test manually.'), file=sys.__stdout__)
155 #self.assertRaises(IOError, sys.stdin.truncate)
156 # XXX Comment this out since sys.stdin is currently an old style file
157 pass
158
159 def testUnicodeOpen(self):
160 # verify repr works for unicode too
161 f = _fileio._FileIO(unicode(TESTFN), "w")
162 # XXX doesn't work yet:
163 ##self.assert_(repr(f).startswith("<open file u'" + TESTFN))
164 f.close()
165 os.unlink(TESTFN)
166
167 def testBadModeArgument(self):
168 # verify that we get a sensible error message for bad mode argument
169 bad_mode = "qwerty"
170 try:
171 f = _fileio._FileIO(TESTFN, bad_mode)
172 except ValueError as msg:
173 if msg.message != 0:
174 s = str(msg)
175 if s.find(TESTFN) != -1 or s.find(bad_mode) == -1:
176 self.fail("bad error message for invalid mode: %s" % s)
177 # if msg[0] == 0, we're probably on Windows where there may be
178 # no obvious way to discover why open() failed.
179 else:
180 f.close()
181 self.fail("no error for invalid mode: %s" % bad_mode)
182
183 def testTruncateOnWindows(self):
184 def bug801631():
185 # SF bug <http://www.python.org/sf/801631>
186 # "file.truncate fault on windows"
187 f = _fileio._FileIO(TESTFN, 'w')
188 f.write(bytes(range(11)))
189 f.close()
190
191 f = _fileio._FileIO(TESTFN,'r+')
192 data = f.read(5)
193 if data != bytes(range(5)):
194 self.fail("Read on file opened for update failed %r" % data)
195 if f.tell() != 5:
196 self.fail("File pos after read wrong %d" % f.tell())
197
198 f.truncate()
199 if f.tell() != 5:
200 self.fail("File pos after ftruncate wrong %d" % f.tell())
201
202 f.close()
203 size = os.path.getsize(TESTFN)
204 if size != 5:
205 self.fail("File size after ftruncate wrong %d" % size)
206
207 try:
208 bug801631()
209 finally:
210 os.unlink(TESTFN)
211
212def test_main():
213 # Historically, these tests have been sloppy about removing TESTFN.
214 # So get rid of it no matter what.
215 try:
216 run_unittest(AutoFileTests, OtherFileTests)
217 finally:
218 if os.path.exists(TESTFN):
219 os.unlink(TESTFN)
220
221if __name__ == '__main__':
222 test_main()