blob: 8b667bbc5bbede1f22c3c37e6005be620f664ddd [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
6import unittest
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +00007import warnings
Martin v. Löwis8e0d4942006-05-04 10:08:42 +00008import sys
Barry Warsaw1e13eb02012-02-20 20:42:21 -05009import subprocess
10
Walter Dörwald21d3a322003-05-01 17:45:56 +000011from test import test_support
Fred Drake38c2ef02001-07-17 20:52:51 +000012
Barry Warsaw60f01882001-08-22 19:24:42 +000013warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, __name__)
14warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, __name__)
15
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000016# Tests creating TESTFN
17class FileTests(unittest.TestCase):
18 def setUp(self):
19 if os.path.exists(test_support.TESTFN):
20 os.unlink(test_support.TESTFN)
21 tearDown = setUp
22
23 def test_access(self):
24 f = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
25 os.close(f)
26 self.assert_(os.access(test_support.TESTFN, os.W_OK))
Tim Peters16a39322006-07-03 08:23:19 +000027
Georg Brandl309501a2008-01-19 20:22:13 +000028 def test_closerange(self):
Antoine Pitroubebb18b2008-08-17 14:43:41 +000029 first = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
30 # We must allocate two consecutive file descriptors, otherwise
31 # it will mess up other file descriptors (perhaps even the three
32 # standard ones).
33 second = os.dup(first)
34 try:
35 retries = 0
36 while second != first + 1:
37 os.close(first)
38 retries += 1
39 if retries > 10:
40 # XXX test skipped
41 print >> sys.stderr, (
42 "couldn't allocate two consecutive fds, "
43 "skipping test_closerange")
44 return
45 first, second = second, os.dup(second)
46 finally:
47 os.close(second)
Georg Brandl309501a2008-01-19 20:22:13 +000048 # close a fd that is open, and one that isn't
Antoine Pitroubebb18b2008-08-17 14:43:41 +000049 os.closerange(first, first + 2)
50 self.assertRaises(OSError, os.write, first, "a")
Georg Brandl309501a2008-01-19 20:22:13 +000051
Hirokazu Yamamoto74ce88f2008-09-08 23:03:47 +000052 def test_rename(self):
53 path = unicode(test_support.TESTFN)
54 old = sys.getrefcount(path)
55 self.assertRaises(TypeError, os.rename, path, 0)
56 new = sys.getrefcount(path)
57 self.assertEqual(old, new)
58
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000059
Fred Drake38c2ef02001-07-17 20:52:51 +000060class TemporaryFileTests(unittest.TestCase):
61 def setUp(self):
62 self.files = []
Walter Dörwald21d3a322003-05-01 17:45:56 +000063 os.mkdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000064
65 def tearDown(self):
66 for name in self.files:
67 os.unlink(name)
Walter Dörwald21d3a322003-05-01 17:45:56 +000068 os.rmdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000069
70 def check_tempfile(self, name):
71 # make sure it doesn't already exist:
72 self.failIf(os.path.exists(name),
73 "file already exists for temporary file")
74 # make sure we can create the file
75 open(name, "w")
76 self.files.append(name)
77
78 def test_tempnam(self):
79 if not hasattr(os, "tempnam"):
80 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +000081 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +000082 r"test_os$")
Fred Drake38c2ef02001-07-17 20:52:51 +000083 self.check_tempfile(os.tempnam())
84
Walter Dörwald21d3a322003-05-01 17:45:56 +000085 name = os.tempnam(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000086 self.check_tempfile(name)
87
Walter Dörwald21d3a322003-05-01 17:45:56 +000088 name = os.tempnam(test_support.TESTFN, "pfx")
Fred Drake38c2ef02001-07-17 20:52:51 +000089 self.assert_(os.path.basename(name)[:3] == "pfx")
90 self.check_tempfile(name)
91
92 def test_tmpfile(self):
93 if not hasattr(os, "tmpfile"):
94 return
Martin v. Löwisd2bbe522008-03-06 06:55:22 +000095 # As with test_tmpnam() below, the Windows implementation of tmpfile()
96 # attempts to create a file in the root directory of the current drive.
97 # On Vista and Server 2008, this test will always fail for normal users
98 # as writing to the root directory requires elevated privileges. With
99 # XP and below, the semantics of tmpfile() are the same, but the user
100 # running the test is more likely to have administrative privileges on
101 # their account already. If that's the case, then os.tmpfile() should
102 # work. In order to make this test as useful as possible, rather than
103 # trying to detect Windows versions or whether or not the user has the
104 # right permissions, just try and create a file in the root directory
105 # and see if it raises a 'Permission denied' OSError. If it does, then
106 # test that a subsequent call to os.tmpfile() raises the same error. If
107 # it doesn't, assume we're on XP or below and the user running the test
108 # has administrative privileges, and proceed with the test as normal.
109 if sys.platform == 'win32':
110 name = '\\python_test_os_test_tmpfile.txt'
111 if os.path.exists(name):
112 os.remove(name)
113 try:
114 fp = open(name, 'w')
115 except IOError, first:
116 # open() failed, assert tmpfile() fails in the same way.
117 # Although open() raises an IOError and os.tmpfile() raises an
118 # OSError(), 'args' will be (13, 'Permission denied') in both
119 # cases.
120 try:
121 fp = os.tmpfile()
122 except OSError, second:
123 self.assertEqual(first.args, second.args)
124 else:
125 self.fail("expected os.tmpfile() to raise OSError")
126 return
127 else:
128 # open() worked, therefore, tmpfile() should work. Close our
129 # dummy file and proceed with the test as normal.
130 fp.close()
131 os.remove(name)
132
Fred Drake38c2ef02001-07-17 20:52:51 +0000133 fp = os.tmpfile()
134 fp.write("foobar")
135 fp.seek(0,0)
136 s = fp.read()
137 fp.close()
138 self.assert_(s == "foobar")
139
140 def test_tmpnam(self):
Tim Peters5501b5e2003-04-28 03:13:03 +0000141 import sys
Fred Drake38c2ef02001-07-17 20:52:51 +0000142 if not hasattr(os, "tmpnam"):
143 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +0000144 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +0000145 r"test_os$")
Tim Peters5501b5e2003-04-28 03:13:03 +0000146 name = os.tmpnam()
147 if sys.platform in ("win32",):
148 # The Windows tmpnam() seems useless. From the MS docs:
149 #
150 # The character string that tmpnam creates consists of
151 # the path prefix, defined by the entry P_tmpdir in the
152 # file STDIO.H, followed by a sequence consisting of the
153 # digit characters '0' through '9'; the numerical value
154 # of this string is in the range 1 - 65,535. Changing the
155 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
156 # change the operation of tmpnam.
157 #
158 # The really bizarre part is that, at least under MSVC6,
159 # P_tmpdir is "\\". That is, the path returned refers to
160 # the root of the current drive. That's a terrible place to
161 # put temp files, and, depending on privileges, the user
162 # may not even be able to open a file in the root directory.
163 self.failIf(os.path.exists(name),
164 "file already exists for temporary file")
165 else:
166 self.check_tempfile(name)
Tim Peters87cc0c32001-07-21 01:41:30 +0000167
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000168# Test attributes on return values from os.*stat* family.
169class StatAttributeTests(unittest.TestCase):
170 def setUp(self):
Walter Dörwald21d3a322003-05-01 17:45:56 +0000171 os.mkdir(test_support.TESTFN)
172 self.fname = os.path.join(test_support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000173 f = open(self.fname, 'wb')
174 f.write("ABC")
175 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000176
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000177 def tearDown(self):
178 os.unlink(self.fname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000179 os.rmdir(test_support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000180
181 def test_stat_attributes(self):
182 if not hasattr(os, "stat"):
183 return
184
185 import stat
186 result = os.stat(self.fname)
187
188 # Make sure direct access works
189 self.assertEquals(result[stat.ST_SIZE], 3)
190 self.assertEquals(result.st_size, 3)
191
192 import sys
193
194 # Make sure all the attributes are there
195 members = dir(result)
196 for name in dir(stat):
197 if name[:3] == 'ST_':
198 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000199 if name.endswith("TIME"):
200 def trunc(x): return int(x)
201 else:
202 def trunc(x): return x
203 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000204 result[getattr(stat, name)])
205 self.assert_(attr in members)
206
207 try:
208 result[200]
209 self.fail("No exception thrown")
210 except IndexError:
211 pass
212
213 # Make sure that assignment fails
214 try:
215 result.st_mode = 1
216 self.fail("No exception thrown")
217 except TypeError:
218 pass
219
220 try:
221 result.st_rdev = 1
222 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000223 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000224 pass
225
226 try:
227 result.parrot = 1
228 self.fail("No exception thrown")
229 except AttributeError:
230 pass
231
232 # Use the stat_result constructor with a too-short tuple.
233 try:
234 result2 = os.stat_result((10,))
235 self.fail("No exception thrown")
236 except TypeError:
237 pass
238
239 # Use the constructr with a too-long tuple.
240 try:
241 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
242 except TypeError:
243 pass
244
Tim Peterse0c446b2001-10-18 21:57:37 +0000245
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000246 def test_statvfs_attributes(self):
247 if not hasattr(os, "statvfs"):
248 return
249
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000250 try:
251 result = os.statvfs(self.fname)
252 except OSError, e:
253 # On AtheOS, glibc always returns ENOSYS
254 import errno
255 if e.errno == errno.ENOSYS:
256 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000257
258 # Make sure direct access works
Brett Cannon90f2cb42008-05-16 00:37:42 +0000259 self.assertEquals(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000260
Brett Cannon90f2cb42008-05-16 00:37:42 +0000261 # Make sure all the attributes are there.
262 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
263 'ffree', 'favail', 'flag', 'namemax')
264 for value, member in enumerate(members):
265 self.assertEquals(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000266
267 # Make sure that assignment really fails
268 try:
269 result.f_bfree = 1
270 self.fail("No exception thrown")
271 except TypeError:
272 pass
273
274 try:
275 result.parrot = 1
276 self.fail("No exception thrown")
277 except AttributeError:
278 pass
279
280 # Use the constructor with a too-short tuple.
281 try:
282 result2 = os.statvfs_result((10,))
283 self.fail("No exception thrown")
284 except TypeError:
285 pass
286
287 # Use the constructr with a too-long tuple.
288 try:
289 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
290 except TypeError:
291 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000292
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000293 def test_utime_dir(self):
294 delta = 1000000
295 st = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000296 # round to int, because some systems may support sub-second
297 # time stamps in stat, but not in utime.
298 os.utime(test_support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000299 st2 = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000300 self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000301
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000302 # Restrict test to Win32, since there is no guarantee other
303 # systems support centiseconds
304 if sys.platform == 'win32':
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000305 def get_file_system(path):
Hirokazu Yamamotoccfdcd02008-08-20 04:13:28 +0000306 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000307 import ctypes
Hirokazu Yamamotocd3b74d2008-08-20 16:15:28 +0000308 kernel32 = ctypes.windll.kernel32
309 buf = ctypes.create_string_buffer("", 100)
310 if kernel32.GetVolumeInformationA(root, None, 0, None, None, None, buf, len(buf)):
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000311 return buf.value
312
313 if get_file_system(test_support.TESTFN) == "NTFS":
314 def test_1565150(self):
315 t1 = 1159195039.25
316 os.utime(self.fname, (t1, t1))
317 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000318
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000319 def test_1686475(self):
320 # Verify that an open file can be stat'ed
321 try:
322 os.stat(r"c:\pagefile.sys")
323 except WindowsError, e:
Antoine Pitrou954ea642008-08-17 20:15:07 +0000324 if e.errno == 2: # file does not exist; cannot run test
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000325 return
326 self.fail("Could not stat pagefile.sys")
327
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000328from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000329
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000330class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000331 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000332 type2test = None
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000333 def _reference(self):
334 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
335 def _empty_mapping(self):
336 os.environ.clear()
337 return os.environ
338 def setUp(self):
339 self.__save = dict(os.environ)
340 os.environ.clear()
341 def tearDown(self):
342 os.environ.clear()
343 os.environ.update(self.__save)
344
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000345 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000346 def test_update2(self):
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000347 if os.path.exists("/bin/sh"):
348 os.environ.update(HELLO="World")
349 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
350 self.assertEquals(value, "World")
351
Tim Petersc4e09402003-04-25 07:11:48 +0000352class WalkTests(unittest.TestCase):
353 """Tests for os.walk()."""
354
355 def test_traversal(self):
356 import os
357 from os.path import join
358
359 # Build:
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000360 # TESTFN/
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000361 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000362 # tmp1
363 # SUB1/ a file kid and a directory kid
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000364 # tmp2
365 # SUB11/ no kids
366 # SUB2/ a file kid and a dirsymlink kid
367 # tmp3
368 # link/ a symlink to TESTFN.2
369 # TEST2/
370 # tmp4 a lone file
371 walk_path = join(test_support.TESTFN, "TEST1")
372 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000373 sub11_path = join(sub1_path, "SUB11")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000374 sub2_path = join(walk_path, "SUB2")
375 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000376 tmp2_path = join(sub1_path, "tmp2")
377 tmp3_path = join(sub2_path, "tmp3")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000378 link_path = join(sub2_path, "link")
379 t2_path = join(test_support.TESTFN, "TEST2")
380 tmp4_path = join(test_support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000381
382 # Create stuff.
383 os.makedirs(sub11_path)
384 os.makedirs(sub2_path)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000385 os.makedirs(t2_path)
386 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Tim Petersc4e09402003-04-25 07:11:48 +0000387 f = file(path, "w")
388 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
389 f.close()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000390 if hasattr(os, "symlink"):
391 os.symlink(os.path.abspath(t2_path), link_path)
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000392 sub2_tree = (sub2_path, ["link"], ["tmp3"])
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000393 else:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000394 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000395
396 # Walk top-down.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000397 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000398 self.assertEqual(len(all), 4)
399 # We can't know which order SUB1 and SUB2 will appear in.
400 # Not flipped: TESTFN, SUB1, SUB11, SUB2
401 # flipped: TESTFN, SUB2, SUB1, SUB11
402 flipped = all[0][1][0] != "SUB1"
403 all[0][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000404 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000405 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
406 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000407 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000408
409 # Prune the search.
410 all = []
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000411 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000412 all.append((root, dirs, files))
413 # Don't descend into SUB1.
414 if 'SUB1' in dirs:
415 # Note that this also mutates the dirs we appended to all!
416 dirs.remove('SUB1')
417 self.assertEqual(len(all), 2)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000418 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000419 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000420
421 # Walk bottom-up.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000422 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000423 self.assertEqual(len(all), 4)
424 # We can't know which order SUB1 and SUB2 will appear in.
425 # Not flipped: SUB11, SUB1, SUB2, TESTFN
426 # flipped: SUB2, SUB11, SUB1, TESTFN
427 flipped = all[3][1][0] != "SUB1"
428 all[3][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000429 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000430 self.assertEqual(all[flipped], (sub11_path, [], []))
431 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000432 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000433
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000434 if hasattr(os, "symlink"):
435 # Walk, following symlinks.
436 for root, dirs, files in os.walk(walk_path, followlinks=True):
437 if root == link_path:
438 self.assertEqual(dirs, [])
439 self.assertEqual(files, ["tmp4"])
440 break
441 else:
442 self.fail("Didn't follow symlink with followlinks=True")
Tim Petersc4e09402003-04-25 07:11:48 +0000443
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000444 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000445 # Tear everything down. This is a decent use for bottom-up on
446 # Windows, which doesn't have a recursive delete command. The
447 # (not so) subtlety is that rmdir will fail unless the dir's
448 # kids are removed first, so bottom up is essential.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000449 for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000450 for name in files:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000451 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000452 for name in dirs:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000453 dirname = os.path.join(root, name)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000454 if not os.path.islink(dirname):
455 os.rmdir(dirname)
456 else:
457 os.remove(dirname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000458 os.rmdir(test_support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000459
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000460class MakedirTests (unittest.TestCase):
461 def setUp(self):
462 os.mkdir(test_support.TESTFN)
463
464 def test_makedir(self):
465 base = test_support.TESTFN
466 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
467 os.makedirs(path) # Should work
468 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
469 os.makedirs(path)
470
471 # Try paths with a '.' in them
472 self.failUnlessRaises(OSError, os.makedirs, os.curdir)
473 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
474 os.makedirs(path)
475 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
476 'dir5', 'dir6')
477 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000478
Tim Peters58eb11c2004-01-18 20:29:55 +0000479
480
481
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000482 def tearDown(self):
483 path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
484 'dir4', 'dir5', 'dir6')
485 # If the tests failed, the bottom-most directory ('../dir6')
486 # may not have been created, so we look for the outermost directory
487 # that exists.
488 while not os.path.exists(path) and path != test_support.TESTFN:
489 path = os.path.dirname(path)
490
491 os.removedirs(path)
492
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000493class DevNullTests (unittest.TestCase):
494 def test_devnull(self):
495 f = file(os.devnull, 'w')
496 f.write('hello')
497 f.close()
498 f = file(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000499 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000500 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000501
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000502class URandomTests (unittest.TestCase):
503 def test_urandom(self):
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500504 with test_support.check_warnings():
505 self.assertEqual(len(os.urandom(1)), 1)
506 self.assertEqual(len(os.urandom(10)), 10)
507 self.assertEqual(len(os.urandom(100)), 100)
508 self.assertEqual(len(os.urandom(1000)), 1000)
509 # see http://bugs.python.org/issue3708
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)
513
514 def test_urandom_length(self):
515 self.assertEqual(len(os.urandom(0)), 0)
516 self.assertEqual(len(os.urandom(1)), 1)
517 self.assertEqual(len(os.urandom(10)), 10)
518 self.assertEqual(len(os.urandom(100)), 100)
519 self.assertEqual(len(os.urandom(1000)), 1000)
520
521 def test_urandom_value(self):
522 data1 = os.urandom(16)
523 data2 = os.urandom(16)
524 self.assertNotEqual(data1, data2)
525
526 def get_urandom_subprocess(self, count):
Barry Warsawb383e802012-02-22 17:26:50 -0500527 # We need to use repr() and eval() to avoid line ending conversions
528 # under Windows.
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500529 code = '\n'.join((
530 'import os, sys',
531 'data = os.urandom(%s)' % count,
Barry Warsawb383e802012-02-22 17:26:50 -0500532 'sys.stdout.write(repr(data))',
Barry Warsaw56fd6612012-02-22 13:50:04 -0500533 'sys.stdout.flush()',
534 'print >> sys.stderr, (len(data), data)'))
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500535 cmd_line = [sys.executable, '-c', code]
536 p = subprocess.Popen(cmd_line, stdin=subprocess.PIPE,
Barry Warsaw56fd6612012-02-22 13:50:04 -0500537 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500538 out, err = p.communicate()
Barry Warsaw56fd6612012-02-22 13:50:04 -0500539 self.assertEqual(p.wait(), 0, (p.wait(), err))
Barry Warsawb383e802012-02-22 17:26:50 -0500540 out = eval(out)
541 self.assertEqual(len(out), count, err)
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500542 return out
543
544 def test_urandom_subprocess(self):
545 data1 = self.get_urandom_subprocess(16)
546 data2 = self.get_urandom_subprocess(16)
547 self.assertNotEqual(data1, data2)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000548
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000549class Win32ErrorTests(unittest.TestCase):
550 def test_rename(self):
551 self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak")
552
553 def test_remove(self):
554 self.assertRaises(WindowsError, os.remove, test_support.TESTFN)
555
556 def test_chdir(self):
557 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
558
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000559 def test_mkdir(self):
560 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
561
562 def test_utime(self):
563 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, None)
564
565 def test_access(self):
566 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, 0)
567
568 def test_chmod(self):
569 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, 0)
570
Georg Brandl686d53e2009-01-14 00:08:09 +0000571class TestInvalidFD(unittest.TestCase):
Benjamin Petersonf5def212009-01-19 15:06:00 +0000572 singles = ["fchdir", "fdopen", "dup", "fdatasync", "fstat",
Georg Brandl686d53e2009-01-14 00:08:09 +0000573 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
Benjamin Petersonf5def212009-01-19 15:06:00 +0000574 #singles.append("close")
575 #We omit close because it doesn'r raise an exception on some platforms
Georg Brandl686d53e2009-01-14 00:08:09 +0000576 def get_single(f):
577 def helper(self):
Benjamin Peterson29d93812009-01-19 21:02:45 +0000578 if hasattr(os, f):
579 self.check(getattr(os, f))
Georg Brandl686d53e2009-01-14 00:08:09 +0000580 return helper
581 for f in singles:
582 locals()["test_"+f] = get_single(f)
583
Benjamin Peterson29d93812009-01-19 21:02:45 +0000584 def check(self, f, *args):
585 self.assertRaises(OSError, f, test_support.make_bad_fd(), *args)
586
Georg Brandl686d53e2009-01-14 00:08:09 +0000587 def test_isatty(self):
Benjamin Petersonf5def212009-01-19 15:06:00 +0000588 if hasattr(os, "isatty"):
Benjamin Peterson29d93812009-01-19 21:02:45 +0000589 self.assertEqual(os.isatty(test_support.make_bad_fd()), False)
Georg Brandl686d53e2009-01-14 00:08:09 +0000590
591 def test_closerange(self):
Benjamin Petersonf5def212009-01-19 15:06:00 +0000592 if hasattr(os, "closerange"):
Benjamin Peterson29d93812009-01-19 21:02:45 +0000593 fd = test_support.make_bad_fd()
R. David Murrayce28a012009-07-22 17:37:11 +0000594 # Make sure none of the descriptors we are about to close are
595 # currently valid (issue 6542).
596 for i in range(10):
597 try: os.fstat(fd+i)
598 except OSError:
599 pass
600 else:
601 break
602 if i < 2:
R. David Murraybce6d5e2009-07-27 01:14:38 +0000603 # Unable to acquire a range of invalid file descriptors,
604 # so skip the test (in 2.6+ this is a unittest.SkipTest).
605 return
R. David Murrayce28a012009-07-22 17:37:11 +0000606 self.assertEqual(os.closerange(fd, fd + i-1), None)
Georg Brandl686d53e2009-01-14 00:08:09 +0000607
608 def test_dup2(self):
Benjamin Petersonf5def212009-01-19 15:06:00 +0000609 if hasattr(os, "dup2"):
Benjamin Peterson29d93812009-01-19 21:02:45 +0000610 self.check(os.dup2, 20)
Georg Brandl686d53e2009-01-14 00:08:09 +0000611
612 def test_fchmod(self):
613 if hasattr(os, "fchmod"):
Benjamin Peterson29d93812009-01-19 21:02:45 +0000614 self.check(os.fchmod, 0)
Georg Brandl686d53e2009-01-14 00:08:09 +0000615
616 def test_fchown(self):
617 if hasattr(os, "fchown"):
Benjamin Peterson29d93812009-01-19 21:02:45 +0000618 self.check(os.fchown, -1, -1)
Georg Brandl686d53e2009-01-14 00:08:09 +0000619
620 def test_fpathconf(self):
621 if hasattr(os, "fpathconf"):
Benjamin Peterson29d93812009-01-19 21:02:45 +0000622 self.check(os.fpathconf, "PC_NAME_MAX")
Georg Brandl686d53e2009-01-14 00:08:09 +0000623
Benjamin Petersonf5def212009-01-19 15:06:00 +0000624 #this is a weird one, it raises IOError unlike the others
Georg Brandl686d53e2009-01-14 00:08:09 +0000625 def test_ftruncate(self):
626 if hasattr(os, "ftruncate"):
Benjamin Peterson29d93812009-01-19 21:02:45 +0000627 self.assertRaises(IOError, os.ftruncate, test_support.make_bad_fd(),
628 0)
Georg Brandl686d53e2009-01-14 00:08:09 +0000629
630 def test_lseek(self):
Benjamin Petersonf5def212009-01-19 15:06:00 +0000631 if hasattr(os, "lseek"):
Benjamin Peterson29d93812009-01-19 21:02:45 +0000632 self.check(os.lseek, 0, 0)
Georg Brandl686d53e2009-01-14 00:08:09 +0000633
634 def test_read(self):
Benjamin Petersonf5def212009-01-19 15:06:00 +0000635 if hasattr(os, "read"):
Benjamin Peterson29d93812009-01-19 21:02:45 +0000636 self.check(os.read, 1)
Georg Brandl686d53e2009-01-14 00:08:09 +0000637
638 def test_tcsetpgrpt(self):
639 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson29d93812009-01-19 21:02:45 +0000640 self.check(os.tcsetpgrp, 0)
Georg Brandl686d53e2009-01-14 00:08:09 +0000641
642 def test_write(self):
Benjamin Petersonf5def212009-01-19 15:06:00 +0000643 if hasattr(os, "write"):
Benjamin Peterson29d93812009-01-19 21:02:45 +0000644 self.check(os.write, " ")
Georg Brandl686d53e2009-01-14 00:08:09 +0000645
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000646if sys.platform != 'win32':
647 class Win32ErrorTests(unittest.TestCase):
648 pass
649
Gregory P. Smithdd7b6302009-04-06 06:47:37 +0000650 class PosixUidGidTests(unittest.TestCase):
651 if hasattr(os, 'setuid'):
652 def test_setuid(self):
653 if os.getuid() != 0:
654 self.assertRaises(os.error, os.setuid, 0)
655 self.assertRaises(OverflowError, os.setuid, 1<<32)
656
657 if hasattr(os, 'setgid'):
658 def test_setgid(self):
659 if os.getuid() != 0:
660 self.assertRaises(os.error, os.setgid, 0)
661 self.assertRaises(OverflowError, os.setgid, 1<<32)
662
663 if hasattr(os, 'seteuid'):
664 def test_seteuid(self):
665 if os.getuid() != 0:
666 self.assertRaises(os.error, os.seteuid, 0)
667 self.assertRaises(OverflowError, os.seteuid, 1<<32)
668
669 if hasattr(os, 'setegid'):
670 def test_setegid(self):
671 if os.getuid() != 0:
672 self.assertRaises(os.error, os.setegid, 0)
673 self.assertRaises(OverflowError, os.setegid, 1<<32)
674
675 if hasattr(os, 'setreuid'):
676 def test_setreuid(self):
677 if os.getuid() != 0:
678 self.assertRaises(os.error, os.setreuid, 0, 0)
679 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
680 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Gregory P. Smithb608e6f82010-03-07 05:58:43 +0000681
682 def test_setreuid_neg1(self):
683 # Needs to accept -1. We run this in a subprocess to avoid
684 # altering the test runner's process state (issue8045).
685 import subprocess
686 subprocess.check_call([
687 sys.executable, '-c',
688 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Gregory P. Smithdd7b6302009-04-06 06:47:37 +0000689
690 if hasattr(os, 'setregid'):
691 def test_setregid(self):
692 if os.getuid() != 0:
693 self.assertRaises(os.error, os.setregid, 0, 0)
694 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
695 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Gregory P. Smithb608e6f82010-03-07 05:58:43 +0000696
697 def test_setregid_neg1(self):
698 # Needs to accept -1. We run this in a subprocess to avoid
699 # altering the test runner's process state (issue8045).
700 import subprocess
701 subprocess.check_call([
702 sys.executable, '-c',
703 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Gregory P. Smithdd7b6302009-04-06 06:47:37 +0000704else:
705 class PosixUidGidTests(unittest.TestCase):
706 pass
707
Fred Drake2e2be372001-09-20 21:33:42 +0000708def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000709 test_support.run_unittest(
Martin v. Löwisee1e06d2006-07-02 18:44:00 +0000710 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000711 TemporaryFileTests,
712 StatAttributeTests,
713 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000714 WalkTests,
715 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000716 DevNullTests,
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000717 URandomTests,
Georg Brandl686d53e2009-01-14 00:08:09 +0000718 Win32ErrorTests,
Gregory P. Smithdd7b6302009-04-06 06:47:37 +0000719 TestInvalidFD,
720 PosixUidGidTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000721 )
Fred Drake2e2be372001-09-20 21:33:42 +0000722
723if __name__ == "__main__":
724 test_main()