blob: 64b29ead2412a327b4cd148fd8f3fc16e2a91fc1 [file] [log] [blame]
Fred Drake38c2ef02001-07-17 20:52:51 +00001# As a test suite for the os module, this is woefully inadequate, but this
2# does add tests for a few functions which have been determined to be more
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00003# portable than they had been thought to be.
Fred Drake38c2ef02001-07-17 20:52:51 +00004
5import os
Benjamin Peterson1de05e92009-01-31 01:42:55 +00006import errno
Fred Drake38c2ef02001-07-17 20:52:51 +00007import unittest
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +00008import warnings
Martin v. Löwis8e0d4942006-05-04 10:08:42 +00009import sys
Walter Dörwald21d3a322003-05-01 17:45:56 +000010from test import test_support
Fred Drake38c2ef02001-07-17 20:52:51 +000011
Barry Warsaw60f01882001-08-22 19:24:42 +000012warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, __name__)
13warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, __name__)
14
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000015# Tests creating TESTFN
16class FileTests(unittest.TestCase):
17 def setUp(self):
18 if os.path.exists(test_support.TESTFN):
19 os.unlink(test_support.TESTFN)
20 tearDown = setUp
21
22 def test_access(self):
23 f = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
24 os.close(f)
25 self.assert_(os.access(test_support.TESTFN, os.W_OK))
Tim Peters16a39322006-07-03 08:23:19 +000026
Georg Brandl309501a2008-01-19 20:22:13 +000027 def test_closerange(self):
Antoine Pitroubebb18b2008-08-17 14:43:41 +000028 first = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
29 # We must allocate two consecutive file descriptors, otherwise
30 # it will mess up other file descriptors (perhaps even the three
31 # standard ones).
32 second = os.dup(first)
33 try:
34 retries = 0
35 while second != first + 1:
36 os.close(first)
37 retries += 1
38 if retries > 10:
39 # XXX test skipped
40 print >> sys.stderr, (
41 "couldn't allocate two consecutive fds, "
42 "skipping test_closerange")
43 return
44 first, second = second, os.dup(second)
45 finally:
46 os.close(second)
Georg Brandl309501a2008-01-19 20:22:13 +000047 # close a fd that is open, and one that isn't
Antoine Pitroubebb18b2008-08-17 14:43:41 +000048 os.closerange(first, first + 2)
49 self.assertRaises(OSError, os.write, first, "a")
Georg Brandl309501a2008-01-19 20:22:13 +000050
Hirokazu Yamamoto74ce88f2008-09-08 23:03:47 +000051 def test_rename(self):
52 path = unicode(test_support.TESTFN)
53 old = sys.getrefcount(path)
54 self.assertRaises(TypeError, os.rename, path, 0)
55 new = sys.getrefcount(path)
56 self.assertEqual(old, new)
57
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000058
Fred Drake38c2ef02001-07-17 20:52:51 +000059class TemporaryFileTests(unittest.TestCase):
60 def setUp(self):
61 self.files = []
Walter Dörwald21d3a322003-05-01 17:45:56 +000062 os.mkdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000063
64 def tearDown(self):
65 for name in self.files:
66 os.unlink(name)
Walter Dörwald21d3a322003-05-01 17:45:56 +000067 os.rmdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000068
69 def check_tempfile(self, name):
70 # make sure it doesn't already exist:
71 self.failIf(os.path.exists(name),
72 "file already exists for temporary file")
73 # make sure we can create the file
74 open(name, "w")
75 self.files.append(name)
76
77 def test_tempnam(self):
78 if not hasattr(os, "tempnam"):
79 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +000080 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +000081 r"test_os$")
Fred Drake38c2ef02001-07-17 20:52:51 +000082 self.check_tempfile(os.tempnam())
83
Walter Dörwald21d3a322003-05-01 17:45:56 +000084 name = os.tempnam(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000085 self.check_tempfile(name)
86
Walter Dörwald21d3a322003-05-01 17:45:56 +000087 name = os.tempnam(test_support.TESTFN, "pfx")
Fred Drake38c2ef02001-07-17 20:52:51 +000088 self.assert_(os.path.basename(name)[:3] == "pfx")
89 self.check_tempfile(name)
90
91 def test_tmpfile(self):
92 if not hasattr(os, "tmpfile"):
93 return
Martin v. Löwisd2bbe522008-03-06 06:55:22 +000094 # As with test_tmpnam() below, the Windows implementation of tmpfile()
95 # attempts to create a file in the root directory of the current drive.
96 # On Vista and Server 2008, this test will always fail for normal users
97 # as writing to the root directory requires elevated privileges. With
98 # XP and below, the semantics of tmpfile() are the same, but the user
99 # running the test is more likely to have administrative privileges on
100 # their account already. If that's the case, then os.tmpfile() should
101 # work. In order to make this test as useful as possible, rather than
102 # trying to detect Windows versions or whether or not the user has the
103 # right permissions, just try and create a file in the root directory
104 # and see if it raises a 'Permission denied' OSError. If it does, then
105 # test that a subsequent call to os.tmpfile() raises the same error. If
106 # it doesn't, assume we're on XP or below and the user running the test
107 # has administrative privileges, and proceed with the test as normal.
108 if sys.platform == 'win32':
109 name = '\\python_test_os_test_tmpfile.txt'
110 if os.path.exists(name):
111 os.remove(name)
112 try:
113 fp = open(name, 'w')
114 except IOError, first:
115 # open() failed, assert tmpfile() fails in the same way.
116 # Although open() raises an IOError and os.tmpfile() raises an
117 # OSError(), 'args' will be (13, 'Permission denied') in both
118 # cases.
119 try:
120 fp = os.tmpfile()
121 except OSError, second:
122 self.assertEqual(first.args, second.args)
123 else:
124 self.fail("expected os.tmpfile() to raise OSError")
125 return
126 else:
127 # open() worked, therefore, tmpfile() should work. Close our
128 # dummy file and proceed with the test as normal.
129 fp.close()
130 os.remove(name)
131
Fred Drake38c2ef02001-07-17 20:52:51 +0000132 fp = os.tmpfile()
133 fp.write("foobar")
134 fp.seek(0,0)
135 s = fp.read()
136 fp.close()
137 self.assert_(s == "foobar")
138
139 def test_tmpnam(self):
Tim Peters5501b5e2003-04-28 03:13:03 +0000140 import sys
Fred Drake38c2ef02001-07-17 20:52:51 +0000141 if not hasattr(os, "tmpnam"):
142 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +0000143 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +0000144 r"test_os$")
Tim Peters5501b5e2003-04-28 03:13:03 +0000145 name = os.tmpnam()
146 if sys.platform in ("win32",):
147 # The Windows tmpnam() seems useless. From the MS docs:
148 #
149 # The character string that tmpnam creates consists of
150 # the path prefix, defined by the entry P_tmpdir in the
151 # file STDIO.H, followed by a sequence consisting of the
152 # digit characters '0' through '9'; the numerical value
153 # of this string is in the range 1 - 65,535. Changing the
154 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
155 # change the operation of tmpnam.
156 #
157 # The really bizarre part is that, at least under MSVC6,
158 # P_tmpdir is "\\". That is, the path returned refers to
159 # the root of the current drive. That's a terrible place to
160 # put temp files, and, depending on privileges, the user
161 # may not even be able to open a file in the root directory.
162 self.failIf(os.path.exists(name),
163 "file already exists for temporary file")
164 else:
165 self.check_tempfile(name)
Tim Peters87cc0c32001-07-21 01:41:30 +0000166
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000167# Test attributes on return values from os.*stat* family.
168class StatAttributeTests(unittest.TestCase):
169 def setUp(self):
Walter Dörwald21d3a322003-05-01 17:45:56 +0000170 os.mkdir(test_support.TESTFN)
171 self.fname = os.path.join(test_support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000172 f = open(self.fname, 'wb')
173 f.write("ABC")
174 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000175
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000176 def tearDown(self):
177 os.unlink(self.fname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000178 os.rmdir(test_support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000179
180 def test_stat_attributes(self):
181 if not hasattr(os, "stat"):
182 return
183
184 import stat
185 result = os.stat(self.fname)
186
187 # Make sure direct access works
188 self.assertEquals(result[stat.ST_SIZE], 3)
189 self.assertEquals(result.st_size, 3)
190
191 import sys
192
193 # Make sure all the attributes are there
194 members = dir(result)
195 for name in dir(stat):
196 if name[:3] == 'ST_':
197 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000198 if name.endswith("TIME"):
199 def trunc(x): return int(x)
200 else:
201 def trunc(x): return x
202 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000203 result[getattr(stat, name)])
204 self.assert_(attr in members)
205
206 try:
207 result[200]
208 self.fail("No exception thrown")
209 except IndexError:
210 pass
211
212 # Make sure that assignment fails
213 try:
214 result.st_mode = 1
215 self.fail("No exception thrown")
216 except TypeError:
217 pass
218
219 try:
220 result.st_rdev = 1
221 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000222 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000223 pass
224
225 try:
226 result.parrot = 1
227 self.fail("No exception thrown")
228 except AttributeError:
229 pass
230
231 # Use the stat_result constructor with a too-short tuple.
232 try:
233 result2 = os.stat_result((10,))
234 self.fail("No exception thrown")
235 except TypeError:
236 pass
237
238 # Use the constructr with a too-long tuple.
239 try:
240 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
241 except TypeError:
242 pass
243
Tim Peterse0c446b2001-10-18 21:57:37 +0000244
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000245 def test_statvfs_attributes(self):
246 if not hasattr(os, "statvfs"):
247 return
248
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000249 try:
250 result = os.statvfs(self.fname)
251 except OSError, e:
252 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000253 if e.errno == errno.ENOSYS:
254 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000255
256 # Make sure direct access works
Brett Cannon90f2cb42008-05-16 00:37:42 +0000257 self.assertEquals(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000258
Brett Cannon90f2cb42008-05-16 00:37:42 +0000259 # Make sure all the attributes are there.
260 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
261 'ffree', 'favail', 'flag', 'namemax')
262 for value, member in enumerate(members):
263 self.assertEquals(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000264
265 # Make sure that assignment really fails
266 try:
267 result.f_bfree = 1
268 self.fail("No exception thrown")
269 except TypeError:
270 pass
271
272 try:
273 result.parrot = 1
274 self.fail("No exception thrown")
275 except AttributeError:
276 pass
277
278 # Use the constructor with a too-short tuple.
279 try:
280 result2 = os.statvfs_result((10,))
281 self.fail("No exception thrown")
282 except TypeError:
283 pass
284
285 # Use the constructr with a too-long tuple.
286 try:
287 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
288 except TypeError:
289 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000290
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000291 def test_utime_dir(self):
292 delta = 1000000
293 st = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000294 # round to int, because some systems may support sub-second
295 # time stamps in stat, but not in utime.
296 os.utime(test_support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000297 st2 = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000298 self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000299
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000300 # Restrict test to Win32, since there is no guarantee other
301 # systems support centiseconds
302 if sys.platform == 'win32':
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000303 def get_file_system(path):
Hirokazu Yamamotoccfdcd02008-08-20 04:13:28 +0000304 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000305 import ctypes
Hirokazu Yamamotocd3b74d2008-08-20 16:15:28 +0000306 kernel32 = ctypes.windll.kernel32
307 buf = ctypes.create_string_buffer("", 100)
308 if kernel32.GetVolumeInformationA(root, None, 0, None, None, None, buf, len(buf)):
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000309 return buf.value
310
311 if get_file_system(test_support.TESTFN) == "NTFS":
312 def test_1565150(self):
313 t1 = 1159195039.25
314 os.utime(self.fname, (t1, t1))
315 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000316
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000317 def test_1686475(self):
318 # Verify that an open file can be stat'ed
319 try:
320 os.stat(r"c:\pagefile.sys")
321 except WindowsError, e:
Antoine Pitrou954ea642008-08-17 20:15:07 +0000322 if e.errno == 2: # file does not exist; cannot run test
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000323 return
324 self.fail("Could not stat pagefile.sys")
325
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000326from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000327
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000328class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000329 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000330 type2test = None
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000331 def _reference(self):
332 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
333 def _empty_mapping(self):
334 os.environ.clear()
335 return os.environ
336 def setUp(self):
337 self.__save = dict(os.environ)
338 os.environ.clear()
339 def tearDown(self):
340 os.environ.clear()
341 os.environ.update(self.__save)
342
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000343 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000344 def test_update2(self):
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000345 if os.path.exists("/bin/sh"):
346 os.environ.update(HELLO="World")
347 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
348 self.assertEquals(value, "World")
349
Tim Petersc4e09402003-04-25 07:11:48 +0000350class WalkTests(unittest.TestCase):
351 """Tests for os.walk()."""
352
353 def test_traversal(self):
354 import os
355 from os.path import join
356
357 # Build:
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000358 # TESTFN/
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000359 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000360 # tmp1
361 # SUB1/ a file kid and a directory kid
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000362 # tmp2
363 # SUB11/ no kids
364 # SUB2/ a file kid and a dirsymlink kid
365 # tmp3
366 # link/ a symlink to TESTFN.2
367 # TEST2/
368 # tmp4 a lone file
369 walk_path = join(test_support.TESTFN, "TEST1")
370 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000371 sub11_path = join(sub1_path, "SUB11")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000372 sub2_path = join(walk_path, "SUB2")
373 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000374 tmp2_path = join(sub1_path, "tmp2")
375 tmp3_path = join(sub2_path, "tmp3")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000376 link_path = join(sub2_path, "link")
377 t2_path = join(test_support.TESTFN, "TEST2")
378 tmp4_path = join(test_support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000379
380 # Create stuff.
381 os.makedirs(sub11_path)
382 os.makedirs(sub2_path)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000383 os.makedirs(t2_path)
384 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Tim Petersc4e09402003-04-25 07:11:48 +0000385 f = file(path, "w")
386 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
387 f.close()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000388 if hasattr(os, "symlink"):
389 os.symlink(os.path.abspath(t2_path), link_path)
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000390 sub2_tree = (sub2_path, ["link"], ["tmp3"])
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000391 else:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000392 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000393
394 # Walk top-down.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000395 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000396 self.assertEqual(len(all), 4)
397 # We can't know which order SUB1 and SUB2 will appear in.
398 # Not flipped: TESTFN, SUB1, SUB11, SUB2
399 # flipped: TESTFN, SUB2, SUB1, SUB11
400 flipped = all[0][1][0] != "SUB1"
401 all[0][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000402 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000403 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
404 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000405 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000406
407 # Prune the search.
408 all = []
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000409 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000410 all.append((root, dirs, files))
411 # Don't descend into SUB1.
412 if 'SUB1' in dirs:
413 # Note that this also mutates the dirs we appended to all!
414 dirs.remove('SUB1')
415 self.assertEqual(len(all), 2)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000416 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000417 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000418
419 # Walk bottom-up.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000420 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000421 self.assertEqual(len(all), 4)
422 # We can't know which order SUB1 and SUB2 will appear in.
423 # Not flipped: SUB11, SUB1, SUB2, TESTFN
424 # flipped: SUB2, SUB11, SUB1, TESTFN
425 flipped = all[3][1][0] != "SUB1"
426 all[3][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000427 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000428 self.assertEqual(all[flipped], (sub11_path, [], []))
429 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000430 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000431
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000432 if hasattr(os, "symlink"):
433 # Walk, following symlinks.
434 for root, dirs, files in os.walk(walk_path, followlinks=True):
435 if root == link_path:
436 self.assertEqual(dirs, [])
437 self.assertEqual(files, ["tmp4"])
438 break
439 else:
440 self.fail("Didn't follow symlink with followlinks=True")
Tim Petersc4e09402003-04-25 07:11:48 +0000441
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000442 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000443 # Tear everything down. This is a decent use for bottom-up on
444 # Windows, which doesn't have a recursive delete command. The
445 # (not so) subtlety is that rmdir will fail unless the dir's
446 # kids are removed first, so bottom up is essential.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000447 for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000448 for name in files:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000449 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000450 for name in dirs:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000451 dirname = os.path.join(root, name)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000452 if not os.path.islink(dirname):
453 os.rmdir(dirname)
454 else:
455 os.remove(dirname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000456 os.rmdir(test_support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000457
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000458class MakedirTests (unittest.TestCase):
459 def setUp(self):
460 os.mkdir(test_support.TESTFN)
461
462 def test_makedir(self):
463 base = test_support.TESTFN
464 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
465 os.makedirs(path) # Should work
466 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
467 os.makedirs(path)
468
469 # Try paths with a '.' in them
470 self.failUnlessRaises(OSError, os.makedirs, os.curdir)
471 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
472 os.makedirs(path)
473 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
474 'dir5', 'dir6')
475 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000476
Tim Peters58eb11c2004-01-18 20:29:55 +0000477
478
479
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000480 def tearDown(self):
481 path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
482 'dir4', 'dir5', 'dir6')
483 # If the tests failed, the bottom-most directory ('../dir6')
484 # may not have been created, so we look for the outermost directory
485 # that exists.
486 while not os.path.exists(path) and path != test_support.TESTFN:
487 path = os.path.dirname(path)
488
489 os.removedirs(path)
490
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000491class DevNullTests (unittest.TestCase):
492 def test_devnull(self):
493 f = file(os.devnull, 'w')
494 f.write('hello')
495 f.close()
496 f = file(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000497 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000498 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000499
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000500class URandomTests (unittest.TestCase):
501 def test_urandom(self):
502 try:
503 self.assertEqual(len(os.urandom(1)), 1)
504 self.assertEqual(len(os.urandom(10)), 10)
505 self.assertEqual(len(os.urandom(100)), 100)
506 self.assertEqual(len(os.urandom(1000)), 1000)
Gregory P. Smithd7122032008-09-02 05:36:11 +0000507 # see http://bugs.python.org/issue3708
Benjamin Peterson1f01cd02009-01-19 21:08:37 +0000508 with test_support.check_warnings():
509 # silence deprecation warnings about float arguments
510 self.assertEqual(len(os.urandom(0.9)), 0)
511 self.assertEqual(len(os.urandom(1.1)), 1)
512 self.assertEqual(len(os.urandom(2.0)), 2)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000513 except NotImplementedError:
514 pass
515
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000516class Win32ErrorTests(unittest.TestCase):
517 def test_rename(self):
518 self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak")
519
520 def test_remove(self):
521 self.assertRaises(WindowsError, os.remove, test_support.TESTFN)
522
523 def test_chdir(self):
524 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
525
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000526 def test_mkdir(self):
Kristján Valur Jónssone20f54f2009-02-06 10:17:34 +0000527 f = open(test_support.TESTFN, "w")
528 try:
529 self.assertRaises(WindowsError, os.mkdir, test_support.TESTFN)
530 finally:
531 f.close()
532 os.unlink(test_support.TESTFN)
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000533
534 def test_utime(self):
535 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, None)
536
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000537 def test_chmod(self):
Kristján Valur Jónssone20f54f2009-02-06 10:17:34 +0000538 self.assertRaises(WindowsError, os.chmod, test_support.TESTFN, 0)
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000539
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000540class TestInvalidFD(unittest.TestCase):
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000541 singles = ["fchdir", "fdopen", "dup", "fdatasync", "fstat",
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000542 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000543 #singles.append("close")
544 #We omit close because it doesn'r raise an exception on some platforms
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000545 def get_single(f):
546 def helper(self):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000547 if hasattr(os, f):
548 self.check(getattr(os, f))
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000549 return helper
550 for f in singles:
551 locals()["test_"+f] = get_single(f)
552
Benjamin Peterson5539c782009-01-19 17:37:42 +0000553 def check(self, f, *args):
Benjamin Peterson1de05e92009-01-31 01:42:55 +0000554 try:
555 f(test_support.make_bad_fd(), *args)
556 except OSError as e:
557 self.assertEqual(e.errno, errno.EBADF)
558 else:
559 self.fail("%r didn't raise a OSError with a bad file descriptor"
560 % f)
Benjamin Peterson5539c782009-01-19 17:37:42 +0000561
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000562 def test_isatty(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000563 if hasattr(os, "isatty"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000564 self.assertEqual(os.isatty(test_support.make_bad_fd()), False)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000565
566 def test_closerange(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000567 if hasattr(os, "closerange"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000568 fd = test_support.make_bad_fd()
569 self.assertEqual(os.closerange(fd, fd + 10), None)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000570
571 def test_dup2(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000572 if hasattr(os, "dup2"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000573 self.check(os.dup2, 20)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000574
575 def test_fchmod(self):
576 if hasattr(os, "fchmod"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000577 self.check(os.fchmod, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000578
579 def test_fchown(self):
580 if hasattr(os, "fchown"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000581 self.check(os.fchown, -1, -1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000582
583 def test_fpathconf(self):
584 if hasattr(os, "fpathconf"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000585 self.check(os.fpathconf, "PC_NAME_MAX")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000586
587 def test_ftruncate(self):
588 if hasattr(os, "ftruncate"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000589 self.check(os.ftruncate, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000590
591 def test_lseek(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000592 if hasattr(os, "lseek"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000593 self.check(os.lseek, 0, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000594
595 def test_read(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000596 if hasattr(os, "read"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000597 self.check(os.read, 1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000598
599 def test_tcsetpgrpt(self):
600 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000601 self.check(os.tcsetpgrp, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000602
603 def test_write(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000604 if hasattr(os, "write"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000605 self.check(os.write, " ")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000606
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000607if sys.platform != 'win32':
608 class Win32ErrorTests(unittest.TestCase):
609 pass
610
Fred Drake2e2be372001-09-20 21:33:42 +0000611def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000612 test_support.run_unittest(
Martin v. Löwisee1e06d2006-07-02 18:44:00 +0000613 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000614 TemporaryFileTests,
615 StatAttributeTests,
616 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000617 WalkTests,
618 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000619 DevNullTests,
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000620 URandomTests,
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000621 Win32ErrorTests,
622 TestInvalidFD
Walter Dörwald21d3a322003-05-01 17:45:56 +0000623 )
Fred Drake2e2be372001-09-20 21:33:42 +0000624
625if __name__ == "__main__":
626 test_main()