blob: 014d874f4d3d82b40e4205297ea0e1acef76ffc4 [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 Peterson5c6d7872009-02-06 02:40:07 +00006import errno
Fred Drake38c2ef02001-07-17 20:52:51 +00007import unittest
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +00008import warnings
Thomas Wouters477c8d52006-05-27 19:21:47 +00009import sys
Martin v. Löwis011e8422009-05-05 04:43:17 +000010import shutil
Benjamin Petersonee8712c2008-05-20 21:35:26 +000011from test import support
Fred Drake38c2ef02001-07-17 20:52:51 +000012
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013# Tests creating TESTFN
14class FileTests(unittest.TestCase):
15 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000016 if os.path.exists(support.TESTFN):
17 os.unlink(support.TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000018 tearDown = setUp
19
20 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000021 f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000022 os.close(f)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000023 self.assert_(os.access(support.TESTFN, os.W_OK))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000024
Christian Heimesfdab48e2008-01-20 09:06:41 +000025 def test_closerange(self):
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000026 first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
27 # We must allocate two consecutive file descriptors, otherwise
28 # it will mess up other file descriptors (perhaps even the three
29 # standard ones).
30 second = os.dup(first)
31 try:
32 retries = 0
33 while second != first + 1:
34 os.close(first)
35 retries += 1
36 if retries > 10:
37 # XXX test skipped
38 print("couldn't allocate two consecutive fds, "
39 "skipping test_closerange", file=sys.stderr)
40 return
41 first, second = second, os.dup(second)
42 finally:
43 os.close(second)
Christian Heimesfdab48e2008-01-20 09:06:41 +000044 # close a fd that is open, and one that isn't
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000045 os.closerange(first, first + 2)
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000046 self.assertRaises(OSError, os.write, first, b"a")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000047
Hirokazu Yamamoto4c19e6e2008-09-08 23:41:21 +000048 def test_rename(self):
49 path = support.TESTFN
50 old = sys.getrefcount(path)
51 self.assertRaises(TypeError, os.rename, path, 0)
52 new = sys.getrefcount(path)
53 self.assertEqual(old, new)
54
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000055 def test_read(self):
56 with open(support.TESTFN, "w+b") as fobj:
57 fobj.write(b"spam")
58 fobj.flush()
59 fd = fobj.fileno()
60 os.lseek(fd, 0, 0)
61 s = os.read(fd, 4)
62 self.assertEqual(type(s), bytes)
63 self.assertEqual(s, b"spam")
64
65 def test_write(self):
66 # os.write() accepts bytes- and buffer-like objects but not strings
67 fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY)
68 self.assertRaises(TypeError, os.write, fd, "beans")
69 os.write(fd, b"bacon\n")
70 os.write(fd, bytearray(b"eggs\n"))
71 os.write(fd, memoryview(b"spam\n"))
72 os.close(fd)
73 with open(support.TESTFN, "rb") as fobj:
Antoine Pitroud62269f2008-09-15 23:54:52 +000074 self.assertEqual(fobj.read().splitlines(),
75 [b"bacon", b"eggs", b"spam"])
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000076
77
Christian Heimesdd15f6c2008-03-16 00:07:10 +000078class TemporaryFileTests(unittest.TestCase):
79 def setUp(self):
80 self.files = []
Benjamin Petersonee8712c2008-05-20 21:35:26 +000081 os.mkdir(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000082
83 def tearDown(self):
84 for name in self.files:
85 os.unlink(name)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000086 os.rmdir(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000087
88 def check_tempfile(self, name):
89 # make sure it doesn't already exist:
90 self.failIf(os.path.exists(name),
91 "file already exists for temporary file")
92 # make sure we can create the file
93 open(name, "w")
94 self.files.append(name)
95
96 def test_tempnam(self):
97 if not hasattr(os, "tempnam"):
98 return
99 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
100 r"test_os$")
101 self.check_tempfile(os.tempnam())
102
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000103 name = os.tempnam(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000104 self.check_tempfile(name)
105
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000106 name = os.tempnam(support.TESTFN, "pfx")
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000107 self.assert_(os.path.basename(name)[:3] == "pfx")
108 self.check_tempfile(name)
109
110 def test_tmpfile(self):
111 if not hasattr(os, "tmpfile"):
112 return
113 # As with test_tmpnam() below, the Windows implementation of tmpfile()
114 # attempts to create a file in the root directory of the current drive.
115 # On Vista and Server 2008, this test will always fail for normal users
116 # as writing to the root directory requires elevated privileges. With
117 # XP and below, the semantics of tmpfile() are the same, but the user
118 # running the test is more likely to have administrative privileges on
119 # their account already. If that's the case, then os.tmpfile() should
120 # work. In order to make this test as useful as possible, rather than
121 # trying to detect Windows versions or whether or not the user has the
122 # right permissions, just try and create a file in the root directory
123 # and see if it raises a 'Permission denied' OSError. If it does, then
124 # test that a subsequent call to os.tmpfile() raises the same error. If
125 # it doesn't, assume we're on XP or below and the user running the test
126 # has administrative privileges, and proceed with the test as normal.
127 if sys.platform == 'win32':
128 name = '\\python_test_os_test_tmpfile.txt'
129 if os.path.exists(name):
130 os.remove(name)
131 try:
132 fp = open(name, 'w')
133 except IOError as first:
134 # open() failed, assert tmpfile() fails in the same way.
135 # Although open() raises an IOError and os.tmpfile() raises an
136 # OSError(), 'args' will be (13, 'Permission denied') in both
137 # cases.
138 try:
139 fp = os.tmpfile()
140 except OSError as second:
141 self.assertEqual(first.args, second.args)
142 else:
143 self.fail("expected os.tmpfile() to raise OSError")
144 return
145 else:
146 # open() worked, therefore, tmpfile() should work. Close our
147 # dummy file and proceed with the test as normal.
148 fp.close()
149 os.remove(name)
150
151 fp = os.tmpfile()
152 fp.write("foobar")
153 fp.seek(0,0)
154 s = fp.read()
155 fp.close()
156 self.assert_(s == "foobar")
157
158 def test_tmpnam(self):
159 import sys
160 if not hasattr(os, "tmpnam"):
161 return
162 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
163 r"test_os$")
164 name = os.tmpnam()
165 if sys.platform in ("win32",):
166 # The Windows tmpnam() seems useless. From the MS docs:
167 #
168 # The character string that tmpnam creates consists of
169 # the path prefix, defined by the entry P_tmpdir in the
170 # file STDIO.H, followed by a sequence consisting of the
171 # digit characters '0' through '9'; the numerical value
172 # of this string is in the range 1 - 65,535. Changing the
173 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
174 # change the operation of tmpnam.
175 #
176 # The really bizarre part is that, at least under MSVC6,
177 # P_tmpdir is "\\". That is, the path returned refers to
178 # the root of the current drive. That's a terrible place to
179 # put temp files, and, depending on privileges, the user
180 # may not even be able to open a file in the root directory.
181 self.failIf(os.path.exists(name),
182 "file already exists for temporary file")
183 else:
184 self.check_tempfile(name)
185
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000186 def fdopen_helper(self, *args):
187 fd = os.open(support.TESTFN, os.O_RDONLY)
188 fp2 = os.fdopen(fd, *args)
189 fp2.close()
190
191 def test_fdopen(self):
192 self.fdopen_helper()
193 self.fdopen_helper('r')
194 self.fdopen_helper('r', 100)
195
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000196# Test attributes on return values from os.*stat* family.
197class StatAttributeTests(unittest.TestCase):
198 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000199 os.mkdir(support.TESTFN)
200 self.fname = os.path.join(support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000201 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +0000202 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000203 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000204
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000205 def tearDown(self):
206 os.unlink(self.fname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000207 os.rmdir(support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000208
209 def test_stat_attributes(self):
210 if not hasattr(os, "stat"):
211 return
212
213 import stat
214 result = os.stat(self.fname)
215
216 # Make sure direct access works
217 self.assertEquals(result[stat.ST_SIZE], 3)
218 self.assertEquals(result.st_size, 3)
219
220 import sys
221
222 # Make sure all the attributes are there
223 members = dir(result)
224 for name in dir(stat):
225 if name[:3] == 'ST_':
226 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000227 if name.endswith("TIME"):
228 def trunc(x): return int(x)
229 else:
230 def trunc(x): return x
231 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000232 result[getattr(stat, name)])
233 self.assert_(attr in members)
234
235 try:
236 result[200]
237 self.fail("No exception thrown")
238 except IndexError:
239 pass
240
241 # Make sure that assignment fails
242 try:
243 result.st_mode = 1
244 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000245 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000246 pass
247
248 try:
249 result.st_rdev = 1
250 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000251 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000252 pass
253
254 try:
255 result.parrot = 1
256 self.fail("No exception thrown")
257 except AttributeError:
258 pass
259
260 # Use the stat_result constructor with a too-short tuple.
261 try:
262 result2 = os.stat_result((10,))
263 self.fail("No exception thrown")
264 except TypeError:
265 pass
266
267 # Use the constructr with a too-long tuple.
268 try:
269 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
270 except TypeError:
271 pass
272
Tim Peterse0c446b2001-10-18 21:57:37 +0000273
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000274 def test_statvfs_attributes(self):
275 if not hasattr(os, "statvfs"):
276 return
277
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000278 try:
279 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000280 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000281 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000282 if e.errno == errno.ENOSYS:
283 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000284
285 # Make sure direct access works
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000286 self.assertEquals(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000287
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000288 # Make sure all the attributes are there.
289 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
290 'ffree', 'favail', 'flag', 'namemax')
291 for value, member in enumerate(members):
292 self.assertEquals(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000293
294 # Make sure that assignment really fails
295 try:
296 result.f_bfree = 1
297 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000298 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000299 pass
300
301 try:
302 result.parrot = 1
303 self.fail("No exception thrown")
304 except AttributeError:
305 pass
306
307 # Use the constructor with a too-short tuple.
308 try:
309 result2 = os.statvfs_result((10,))
310 self.fail("No exception thrown")
311 except TypeError:
312 pass
313
314 # Use the constructr with a too-long tuple.
315 try:
316 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
317 except TypeError:
318 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000319
Thomas Wouters89f507f2006-12-13 04:49:30 +0000320 def test_utime_dir(self):
321 delta = 1000000
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000322 st = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000323 # round to int, because some systems may support sub-second
324 # time stamps in stat, but not in utime.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000325 os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
326 st2 = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000327 self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
328
329 # Restrict test to Win32, since there is no guarantee other
330 # systems support centiseconds
331 if sys.platform == 'win32':
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000332 def get_file_system(path):
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000333 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000334 import ctypes
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000335 kernel32 = ctypes.windll.kernel32
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000336 buf = ctypes.create_unicode_buffer("", 100)
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000337 if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000338 return buf.value
339
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000340 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000341 def test_1565150(self):
342 t1 = 1159195039.25
343 os.utime(self.fname, (t1, t1))
344 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000345
Guido van Rossumd8faa362007-04-27 19:54:29 +0000346 def test_1686475(self):
347 # Verify that an open file can be stat'ed
348 try:
349 os.stat(r"c:\pagefile.sys")
350 except WindowsError as e:
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000351 if e.errno == 2: # file does not exist; cannot run test
Guido van Rossumd8faa362007-04-27 19:54:29 +0000352 return
353 self.fail("Could not stat pagefile.sys")
354
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000355from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000356
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000357class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000358 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000359 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000360
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000361 def setUp(self):
362 self.__save = dict(os.environ)
Christian Heimes90333392007-11-01 19:08:42 +0000363 for key, value in self._reference().items():
364 os.environ[key] = value
365
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000366 def tearDown(self):
367 os.environ.clear()
368 os.environ.update(self.__save)
369
Christian Heimes90333392007-11-01 19:08:42 +0000370 def _reference(self):
371 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
372
373 def _empty_mapping(self):
374 os.environ.clear()
375 return os.environ
376
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000377 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000378 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000379 os.environ.clear()
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000380 if os.path.exists("/bin/sh"):
381 os.environ.update(HELLO="World")
382 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
383 self.assertEquals(value, "World")
384
Christian Heimes1a13d592007-11-08 14:16:55 +0000385 def test_os_popen_iter(self):
386 if os.path.exists("/bin/sh"):
387 popen = os.popen("/bin/sh -c 'echo \"line1\nline2\nline3\"'")
388 it = iter(popen)
389 self.assertEquals(next(it), "line1\n")
390 self.assertEquals(next(it), "line2\n")
391 self.assertEquals(next(it), "line3\n")
392 self.assertRaises(StopIteration, next, it)
393
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000394 # Verify environ keys and values from the OS are of the
395 # correct str type.
396 def test_keyvalue_types(self):
397 for key, val in os.environ.items():
398 self.assertEquals(type(key), str)
399 self.assertEquals(type(val), str)
400
Christian Heimes90333392007-11-01 19:08:42 +0000401 def test_items(self):
402 for key, value in self._reference().items():
403 self.assertEqual(os.environ.get(key), value)
404
Tim Petersc4e09402003-04-25 07:11:48 +0000405class WalkTests(unittest.TestCase):
406 """Tests for os.walk()."""
407
408 def test_traversal(self):
409 import os
410 from os.path import join
411
412 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000413 # TESTFN/
414 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000415 # tmp1
416 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000417 # tmp2
418 # SUB11/ no kids
419 # SUB2/ a file kid and a dirsymlink kid
420 # tmp3
421 # link/ a symlink to TESTFN.2
422 # TEST2/
423 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000424 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000425 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000426 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000427 sub2_path = join(walk_path, "SUB2")
428 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000429 tmp2_path = join(sub1_path, "tmp2")
430 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000431 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000432 t2_path = join(support.TESTFN, "TEST2")
433 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000434
435 # Create stuff.
436 os.makedirs(sub11_path)
437 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000438 os.makedirs(t2_path)
439 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000440 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000441 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
442 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000443 if hasattr(os, "symlink"):
444 os.symlink(os.path.abspath(t2_path), link_path)
445 sub2_tree = (sub2_path, ["link"], ["tmp3"])
446 else:
447 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000448
449 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000450 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000451 self.assertEqual(len(all), 4)
452 # We can't know which order SUB1 and SUB2 will appear in.
453 # Not flipped: TESTFN, SUB1, SUB11, SUB2
454 # flipped: TESTFN, SUB2, SUB1, SUB11
455 flipped = all[0][1][0] != "SUB1"
456 all[0][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000457 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000458 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
459 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000460 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000461
462 # Prune the search.
463 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000464 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000465 all.append((root, dirs, files))
466 # Don't descend into SUB1.
467 if 'SUB1' in dirs:
468 # Note that this also mutates the dirs we appended to all!
469 dirs.remove('SUB1')
470 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000471 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
472 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000473
474 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000475 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000476 self.assertEqual(len(all), 4)
477 # We can't know which order SUB1 and SUB2 will appear in.
478 # Not flipped: SUB11, SUB1, SUB2, TESTFN
479 # flipped: SUB2, SUB11, SUB1, TESTFN
480 flipped = all[3][1][0] != "SUB1"
481 all[3][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000482 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000483 self.assertEqual(all[flipped], (sub11_path, [], []))
484 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000485 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000486
Guido van Rossumd8faa362007-04-27 19:54:29 +0000487 if hasattr(os, "symlink"):
488 # Walk, following symlinks.
489 for root, dirs, files in os.walk(walk_path, followlinks=True):
490 if root == link_path:
491 self.assertEqual(dirs, [])
492 self.assertEqual(files, ["tmp4"])
493 break
494 else:
495 self.fail("Didn't follow symlink with followlinks=True")
496
497 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000498 # Tear everything down. This is a decent use for bottom-up on
499 # Windows, which doesn't have a recursive delete command. The
500 # (not so) subtlety is that rmdir will fail unless the dir's
501 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000502 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000503 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000504 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000505 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000506 dirname = os.path.join(root, name)
507 if not os.path.islink(dirname):
508 os.rmdir(dirname)
509 else:
510 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000511 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000512
Guido van Rossume7ba4952007-06-06 23:52:48 +0000513class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000514 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000515 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000516
517 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000518 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000519 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
520 os.makedirs(path) # Should work
521 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
522 os.makedirs(path)
523
524 # Try paths with a '.' in them
525 self.failUnlessRaises(OSError, os.makedirs, os.curdir)
526 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
527 os.makedirs(path)
528 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
529 'dir5', 'dir6')
530 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000531
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000532 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000533 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000534 'dir4', 'dir5', 'dir6')
535 # If the tests failed, the bottom-most directory ('../dir6')
536 # may not have been created, so we look for the outermost directory
537 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000538 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000539 path = os.path.dirname(path)
540
541 os.removedirs(path)
542
Guido van Rossume7ba4952007-06-06 23:52:48 +0000543class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000544 def test_devnull(self):
Alex Martelli01c77c62006-08-24 02:58:11 +0000545 f = open(os.devnull, 'w')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000546 f.write('hello')
547 f.close()
Alex Martelli01c77c62006-08-24 02:58:11 +0000548 f = open(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000549 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000550 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000551
Guido van Rossume7ba4952007-06-06 23:52:48 +0000552class URandomTests(unittest.TestCase):
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000553 def test_urandom(self):
554 try:
555 self.assertEqual(len(os.urandom(1)), 1)
556 self.assertEqual(len(os.urandom(10)), 10)
557 self.assertEqual(len(os.urandom(100)), 100)
558 self.assertEqual(len(os.urandom(1000)), 1000)
559 except NotImplementedError:
560 pass
561
Guido van Rossume7ba4952007-06-06 23:52:48 +0000562class ExecTests(unittest.TestCase):
563 def test_execvpe_with_bad_program(self):
Thomas Hellerbd315c52007-08-30 17:57:21 +0000564 self.assertRaises(OSError, os.execvpe, 'no such app-', ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000565
Thomas Heller6790d602007-08-30 17:15:14 +0000566 def test_execvpe_with_bad_arglist(self):
567 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
568
Thomas Wouters477c8d52006-05-27 19:21:47 +0000569class Win32ErrorTests(unittest.TestCase):
570 def test_rename(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000571 self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000572
573 def test_remove(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000574 self.assertRaises(WindowsError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000575
576 def test_chdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000577 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000578
579 def test_mkdir(self):
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +0000580 f = open(support.TESTFN, "w")
Benjamin Petersonf91df042009-02-13 02:50:59 +0000581 try:
582 self.assertRaises(WindowsError, os.mkdir, support.TESTFN)
583 finally:
584 f.close()
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +0000585 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000586
587 def test_utime(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000588 self.assertRaises(WindowsError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000589
Thomas Wouters477c8d52006-05-27 19:21:47 +0000590 def test_chmod(self):
Benjamin Petersonf91df042009-02-13 02:50:59 +0000591 self.assertRaises(WindowsError, os.chmod, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000592
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000593class TestInvalidFD(unittest.TestCase):
Benjamin Peterson05e782f2009-01-19 15:15:02 +0000594 singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000595 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
596 #singles.append("close")
597 #We omit close because it doesn'r raise an exception on some platforms
598 def get_single(f):
599 def helper(self):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000600 if hasattr(os, f):
601 self.check(getattr(os, f))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000602 return helper
603 for f in singles:
604 locals()["test_"+f] = get_single(f)
605
Benjamin Peterson7522c742009-01-19 21:00:09 +0000606 def check(self, f, *args):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000607 try:
608 f(support.make_bad_fd(), *args)
609 except OSError as e:
610 self.assertEqual(e.errno, errno.EBADF)
611 else:
612 self.fail("%r didn't raise a OSError with a bad file descriptor"
613 % f)
Benjamin Peterson7522c742009-01-19 21:00:09 +0000614
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000615 def test_isatty(self):
616 if hasattr(os, "isatty"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000617 self.assertEqual(os.isatty(support.make_bad_fd()), False)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000618
619 def test_closerange(self):
620 if hasattr(os, "closerange"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000621 fd = support.make_bad_fd()
622 self.assertEqual(os.closerange(fd, fd + 10), None)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000623
624 def test_dup2(self):
625 if hasattr(os, "dup2"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000626 self.check(os.dup2, 20)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000627
628 def test_fchmod(self):
629 if hasattr(os, "fchmod"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000630 self.check(os.fchmod, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000631
632 def test_fchown(self):
633 if hasattr(os, "fchown"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000634 self.check(os.fchown, -1, -1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000635
636 def test_fpathconf(self):
637 if hasattr(os, "fpathconf"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000638 self.check(os.fpathconf, "PC_NAME_MAX")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000639
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000640 def test_ftruncate(self):
641 if hasattr(os, "ftruncate"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000642 self.check(os.ftruncate, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000643
644 def test_lseek(self):
645 if hasattr(os, "lseek"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000646 self.check(os.lseek, 0, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000647
648 def test_read(self):
649 if hasattr(os, "read"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000650 self.check(os.read, 1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000651
652 def test_tcsetpgrpt(self):
653 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000654 self.check(os.tcsetpgrp, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000655
656 def test_write(self):
657 if hasattr(os, "write"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000658 self.check(os.write, b" ")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000659
Thomas Wouters477c8d52006-05-27 19:21:47 +0000660if sys.platform != 'win32':
661 class Win32ErrorTests(unittest.TestCase):
662 pass
663
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000664 class PosixUidGidTests(unittest.TestCase):
665 if hasattr(os, 'setuid'):
666 def test_setuid(self):
667 if os.getuid() != 0:
668 self.assertRaises(os.error, os.setuid, 0)
669 self.assertRaises(OverflowError, os.setuid, 1<<32)
670
671 if hasattr(os, 'setgid'):
672 def test_setgid(self):
673 if os.getuid() != 0:
674 self.assertRaises(os.error, os.setgid, 0)
675 self.assertRaises(OverflowError, os.setgid, 1<<32)
676
677 if hasattr(os, 'seteuid'):
678 def test_seteuid(self):
679 if os.getuid() != 0:
680 self.assertRaises(os.error, os.seteuid, 0)
681 self.assertRaises(OverflowError, os.seteuid, 1<<32)
682
683 if hasattr(os, 'setegid'):
684 def test_setegid(self):
685 if os.getuid() != 0:
686 self.assertRaises(os.error, os.setegid, 0)
687 self.assertRaises(OverflowError, os.setegid, 1<<32)
688
689 if hasattr(os, 'setreuid'):
690 def test_setreuid(self):
691 if os.getuid() != 0:
692 self.assertRaises(os.error, os.setreuid, 0, 0)
693 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
694 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
695
696 if hasattr(os, 'setregid'):
697 def test_setregid(self):
698 if os.getuid() != 0:
699 self.assertRaises(os.error, os.setregid, 0, 0)
700 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
701 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Martin v. Löwis011e8422009-05-05 04:43:17 +0000702
Mark Dickinson70613682009-05-05 21:34:59 +0000703 @unittest.skipIf(sys.platform == 'darwin', "tests don't apply to OS X")
Martin v. Löwis011e8422009-05-05 04:43:17 +0000704 class Pep383Tests(unittest.TestCase):
705 filenames = [b'foo\xf6bar', 'foo\xf6bar'.encode("utf-8")]
706
707 def setUp(self):
708 self.fsencoding = sys.getfilesystemencoding()
709 sys.setfilesystemencoding("utf-8")
710 self.dir = support.TESTFN
711 self.bdir = self.dir.encode("utf-8", "utf8b")
712 os.mkdir(self.dir)
713 self.unicodefn = []
714 for fn in self.filenames:
715 f = open(os.path.join(self.bdir, fn), "w")
716 f.close()
717 self.unicodefn.append(fn.decode("utf-8", "utf8b"))
718
719 def tearDown(self):
720 shutil.rmtree(self.dir)
721 sys.setfilesystemencoding(self.fsencoding)
722
723 def test_listdir(self):
724 expected = set(self.unicodefn)
725 found = set(os.listdir(support.TESTFN))
726 self.assertEquals(found, expected)
727
728 def test_open(self):
729 for fn in self.unicodefn:
730 f = open(os.path.join(self.dir, fn))
731 f.close()
732
733 def test_stat(self):
734 for fn in self.unicodefn:
735 os.stat(os.path.join(self.dir, fn))
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000736else:
737 class PosixUidGidTests(unittest.TestCase):
738 pass
Martin v. Löwis011e8422009-05-05 04:43:17 +0000739 class Pep383Tests(unittest.TestCase):
740 pass
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000741
Fred Drake2e2be372001-09-20 21:33:42 +0000742def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000743 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000744 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000745 StatAttributeTests,
746 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000747 WalkTests,
748 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000749 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000750 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000751 ExecTests,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000752 Win32ErrorTests,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000753 TestInvalidFD,
Martin v. Löwis011e8422009-05-05 04:43:17 +0000754 PosixUidGidTests,
755 Pep383Tests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000756 )
Fred Drake2e2be372001-09-20 21:33:42 +0000757
758if __name__ == "__main__":
759 test_main()