blob: 395402be66379839187a7be0afc459e990fb938e [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 Petersonc9c0f202009-06-30 23:06:06 +000023 self.assertTrue(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
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000038 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000039 first, second = second, os.dup(second)
40 finally:
41 os.close(second)
Christian Heimesfdab48e2008-01-20 09:06:41 +000042 # close a fd that is open, and one that isn't
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000043 os.closerange(first, first + 2)
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000044 self.assertRaises(OSError, os.write, first, b"a")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000045
Hirokazu Yamamoto4c19e6e2008-09-08 23:41:21 +000046 def test_rename(self):
47 path = support.TESTFN
48 old = sys.getrefcount(path)
49 self.assertRaises(TypeError, os.rename, path, 0)
50 new = sys.getrefcount(path)
51 self.assertEqual(old, new)
52
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000053 def test_read(self):
54 with open(support.TESTFN, "w+b") as fobj:
55 fobj.write(b"spam")
56 fobj.flush()
57 fd = fobj.fileno()
58 os.lseek(fd, 0, 0)
59 s = os.read(fd, 4)
60 self.assertEqual(type(s), bytes)
61 self.assertEqual(s, b"spam")
62
63 def test_write(self):
64 # os.write() accepts bytes- and buffer-like objects but not strings
65 fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY)
66 self.assertRaises(TypeError, os.write, fd, "beans")
67 os.write(fd, b"bacon\n")
68 os.write(fd, bytearray(b"eggs\n"))
69 os.write(fd, memoryview(b"spam\n"))
70 os.close(fd)
71 with open(support.TESTFN, "rb") as fobj:
Antoine Pitroud62269f2008-09-15 23:54:52 +000072 self.assertEqual(fobj.read().splitlines(),
73 [b"bacon", b"eggs", b"spam"])
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000074
75
Christian Heimesdd15f6c2008-03-16 00:07:10 +000076class TemporaryFileTests(unittest.TestCase):
77 def setUp(self):
78 self.files = []
Benjamin Petersonee8712c2008-05-20 21:35:26 +000079 os.mkdir(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000080
81 def tearDown(self):
82 for name in self.files:
83 os.unlink(name)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000084 os.rmdir(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000085
86 def check_tempfile(self, name):
87 # make sure it doesn't already exist:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000088 self.assertFalse(os.path.exists(name),
Christian Heimesdd15f6c2008-03-16 00:07:10 +000089 "file already exists for temporary file")
90 # make sure we can create the file
91 open(name, "w")
92 self.files.append(name)
93
94 def test_tempnam(self):
95 if not hasattr(os, "tempnam"):
96 return
97 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
98 r"test_os$")
99 self.check_tempfile(os.tempnam())
100
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000101 name = os.tempnam(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000102 self.check_tempfile(name)
103
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000104 name = os.tempnam(support.TESTFN, "pfx")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000105 self.assertTrue(os.path.basename(name)[:3] == "pfx")
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000106 self.check_tempfile(name)
107
108 def test_tmpfile(self):
109 if not hasattr(os, "tmpfile"):
110 return
111 # As with test_tmpnam() below, the Windows implementation of tmpfile()
112 # attempts to create a file in the root directory of the current drive.
113 # On Vista and Server 2008, this test will always fail for normal users
114 # as writing to the root directory requires elevated privileges. With
115 # XP and below, the semantics of tmpfile() are the same, but the user
116 # running the test is more likely to have administrative privileges on
117 # their account already. If that's the case, then os.tmpfile() should
118 # work. In order to make this test as useful as possible, rather than
119 # trying to detect Windows versions or whether or not the user has the
120 # right permissions, just try and create a file in the root directory
121 # and see if it raises a 'Permission denied' OSError. If it does, then
122 # test that a subsequent call to os.tmpfile() raises the same error. If
123 # it doesn't, assume we're on XP or below and the user running the test
124 # has administrative privileges, and proceed with the test as normal.
125 if sys.platform == 'win32':
126 name = '\\python_test_os_test_tmpfile.txt'
127 if os.path.exists(name):
128 os.remove(name)
129 try:
130 fp = open(name, 'w')
131 except IOError as first:
132 # open() failed, assert tmpfile() fails in the same way.
133 # Although open() raises an IOError and os.tmpfile() raises an
134 # OSError(), 'args' will be (13, 'Permission denied') in both
135 # cases.
136 try:
137 fp = os.tmpfile()
138 except OSError as second:
139 self.assertEqual(first.args, second.args)
140 else:
141 self.fail("expected os.tmpfile() to raise OSError")
142 return
143 else:
144 # open() worked, therefore, tmpfile() should work. Close our
145 # dummy file and proceed with the test as normal.
146 fp.close()
147 os.remove(name)
148
149 fp = os.tmpfile()
150 fp.write("foobar")
151 fp.seek(0,0)
152 s = fp.read()
153 fp.close()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000154 self.assertTrue(s == "foobar")
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000155
156 def test_tmpnam(self):
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000157 if not hasattr(os, "tmpnam"):
158 return
159 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
160 r"test_os$")
161 name = os.tmpnam()
162 if sys.platform in ("win32",):
163 # The Windows tmpnam() seems useless. From the MS docs:
164 #
165 # The character string that tmpnam creates consists of
166 # the path prefix, defined by the entry P_tmpdir in the
167 # file STDIO.H, followed by a sequence consisting of the
168 # digit characters '0' through '9'; the numerical value
169 # of this string is in the range 1 - 65,535. Changing the
170 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
171 # change the operation of tmpnam.
172 #
173 # The really bizarre part is that, at least under MSVC6,
174 # P_tmpdir is "\\". That is, the path returned refers to
175 # the root of the current drive. That's a terrible place to
176 # put temp files, and, depending on privileges, the user
177 # may not even be able to open a file in the root directory.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000178 self.assertFalse(os.path.exists(name),
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000179 "file already exists for temporary file")
180 else:
181 self.check_tempfile(name)
182
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000183 def fdopen_helper(self, *args):
184 fd = os.open(support.TESTFN, os.O_RDONLY)
185 fp2 = os.fdopen(fd, *args)
186 fp2.close()
187
188 def test_fdopen(self):
189 self.fdopen_helper()
190 self.fdopen_helper('r')
191 self.fdopen_helper('r', 100)
192
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000193# Test attributes on return values from os.*stat* family.
194class StatAttributeTests(unittest.TestCase):
195 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000196 os.mkdir(support.TESTFN)
197 self.fname = os.path.join(support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000198 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +0000199 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000200 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000201
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000202 def tearDown(self):
203 os.unlink(self.fname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000204 os.rmdir(support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000205
206 def test_stat_attributes(self):
207 if not hasattr(os, "stat"):
208 return
209
210 import stat
211 result = os.stat(self.fname)
212
213 # Make sure direct access works
214 self.assertEquals(result[stat.ST_SIZE], 3)
215 self.assertEquals(result.st_size, 3)
216
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000217 # Make sure all the attributes are there
218 members = dir(result)
219 for name in dir(stat):
220 if name[:3] == 'ST_':
221 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000222 if name.endswith("TIME"):
223 def trunc(x): return int(x)
224 else:
225 def trunc(x): return x
226 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000227 result[getattr(stat, name)])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000228 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000229
230 try:
231 result[200]
232 self.fail("No exception thrown")
233 except IndexError:
234 pass
235
236 # Make sure that assignment fails
237 try:
238 result.st_mode = 1
239 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000240 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000241 pass
242
243 try:
244 result.st_rdev = 1
245 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000246 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000247 pass
248
249 try:
250 result.parrot = 1
251 self.fail("No exception thrown")
252 except AttributeError:
253 pass
254
255 # Use the stat_result constructor with a too-short tuple.
256 try:
257 result2 = os.stat_result((10,))
258 self.fail("No exception thrown")
259 except TypeError:
260 pass
261
262 # Use the constructr with a too-long tuple.
263 try:
264 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
265 except TypeError:
266 pass
267
Tim Peterse0c446b2001-10-18 21:57:37 +0000268
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000269 def test_statvfs_attributes(self):
270 if not hasattr(os, "statvfs"):
271 return
272
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000273 try:
274 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000275 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000276 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000277 if e.errno == errno.ENOSYS:
278 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000279
280 # Make sure direct access works
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000281 self.assertEquals(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000282
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000283 # Make sure all the attributes are there.
284 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
285 'ffree', 'favail', 'flag', 'namemax')
286 for value, member in enumerate(members):
287 self.assertEquals(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000288
289 # Make sure that assignment really fails
290 try:
291 result.f_bfree = 1
292 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000293 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000294 pass
295
296 try:
297 result.parrot = 1
298 self.fail("No exception thrown")
299 except AttributeError:
300 pass
301
302 # Use the constructor with a too-short tuple.
303 try:
304 result2 = os.statvfs_result((10,))
305 self.fail("No exception thrown")
306 except TypeError:
307 pass
308
309 # Use the constructr with a too-long tuple.
310 try:
311 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
312 except TypeError:
313 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000314
Thomas Wouters89f507f2006-12-13 04:49:30 +0000315 def test_utime_dir(self):
316 delta = 1000000
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000317 st = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000318 # round to int, because some systems may support sub-second
319 # time stamps in stat, but not in utime.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000320 os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
321 st2 = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000322 self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
323
324 # Restrict test to Win32, since there is no guarantee other
325 # systems support centiseconds
326 if sys.platform == 'win32':
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000327 def get_file_system(path):
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000328 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000329 import ctypes
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000330 kernel32 = ctypes.windll.kernel32
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000331 buf = ctypes.create_unicode_buffer("", 100)
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000332 if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000333 return buf.value
334
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000335 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000336 def test_1565150(self):
337 t1 = 1159195039.25
338 os.utime(self.fname, (t1, t1))
339 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000340
Guido van Rossumd8faa362007-04-27 19:54:29 +0000341 def test_1686475(self):
342 # Verify that an open file can be stat'ed
343 try:
344 os.stat(r"c:\pagefile.sys")
345 except WindowsError as e:
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000346 if e.errno == 2: # file does not exist; cannot run test
Guido van Rossumd8faa362007-04-27 19:54:29 +0000347 return
348 self.fail("Could not stat pagefile.sys")
349
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000350from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000351
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000352class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000353 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000354 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000355
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000356 def setUp(self):
357 self.__save = dict(os.environ)
Christian Heimes90333392007-11-01 19:08:42 +0000358 for key, value in self._reference().items():
359 os.environ[key] = value
360
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000361 def tearDown(self):
362 os.environ.clear()
363 os.environ.update(self.__save)
364
Christian Heimes90333392007-11-01 19:08:42 +0000365 def _reference(self):
366 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
367
368 def _empty_mapping(self):
369 os.environ.clear()
370 return os.environ
371
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000372 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000373 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000374 os.environ.clear()
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000375 if os.path.exists("/bin/sh"):
376 os.environ.update(HELLO="World")
377 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
378 self.assertEquals(value, "World")
379
Christian Heimes1a13d592007-11-08 14:16:55 +0000380 def test_os_popen_iter(self):
381 if os.path.exists("/bin/sh"):
382 popen = os.popen("/bin/sh -c 'echo \"line1\nline2\nline3\"'")
383 it = iter(popen)
384 self.assertEquals(next(it), "line1\n")
385 self.assertEquals(next(it), "line2\n")
386 self.assertEquals(next(it), "line3\n")
387 self.assertRaises(StopIteration, next, it)
388
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000389 # Verify environ keys and values from the OS are of the
390 # correct str type.
391 def test_keyvalue_types(self):
392 for key, val in os.environ.items():
393 self.assertEquals(type(key), str)
394 self.assertEquals(type(val), str)
395
Christian Heimes90333392007-11-01 19:08:42 +0000396 def test_items(self):
397 for key, value in self._reference().items():
398 self.assertEqual(os.environ.get(key), value)
399
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000400 # Issue 7310
401 def test___repr__(self):
402 """Check that the repr() of os.environ looks like environ({...})."""
403 env = os.environ
404 self.assertTrue(isinstance(env.data, dict))
405 self.assertEqual(repr(env), 'environ({!r})'.format(env.data))
406
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000407 def test_get_exec_path(self):
408 defpath_list = os.defpath.split(os.pathsep)
409 test_path = ['/monty', '/python', '', '/flying/circus']
410 test_env = {'PATH': os.pathsep.join(test_path)}
411
412 saved_environ = os.environ
413 try:
414 os.environ = dict(test_env)
415 # Test that defaulting to os.environ works.
416 self.assertSequenceEqual(test_path, os.get_exec_path())
417 self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
418 finally:
419 os.environ = saved_environ
420
421 # No PATH environment variable
422 self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
423 # Empty PATH environment variable
424 self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
425 # Supplied PATH environment variable
426 self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
427
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000428
Tim Petersc4e09402003-04-25 07:11:48 +0000429class WalkTests(unittest.TestCase):
430 """Tests for os.walk()."""
431
432 def test_traversal(self):
433 import os
434 from os.path import join
435
436 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000437 # TESTFN/
438 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000439 # tmp1
440 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000441 # tmp2
442 # SUB11/ no kids
443 # SUB2/ a file kid and a dirsymlink kid
444 # tmp3
445 # link/ a symlink to TESTFN.2
446 # TEST2/
447 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000448 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000449 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000450 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000451 sub2_path = join(walk_path, "SUB2")
452 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000453 tmp2_path = join(sub1_path, "tmp2")
454 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000455 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000456 t2_path = join(support.TESTFN, "TEST2")
457 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000458
459 # Create stuff.
460 os.makedirs(sub11_path)
461 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000462 os.makedirs(t2_path)
463 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000464 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000465 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
466 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000467 if hasattr(os, "symlink"):
468 os.symlink(os.path.abspath(t2_path), link_path)
469 sub2_tree = (sub2_path, ["link"], ["tmp3"])
470 else:
471 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000472
473 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000474 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000475 self.assertEqual(len(all), 4)
476 # We can't know which order SUB1 and SUB2 will appear in.
477 # Not flipped: TESTFN, SUB1, SUB11, SUB2
478 # flipped: TESTFN, SUB2, SUB1, SUB11
479 flipped = all[0][1][0] != "SUB1"
480 all[0][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000481 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000482 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
483 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000484 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000485
486 # Prune the search.
487 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000488 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000489 all.append((root, dirs, files))
490 # Don't descend into SUB1.
491 if 'SUB1' in dirs:
492 # Note that this also mutates the dirs we appended to all!
493 dirs.remove('SUB1')
494 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000495 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
496 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000497
498 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000499 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000500 self.assertEqual(len(all), 4)
501 # We can't know which order SUB1 and SUB2 will appear in.
502 # Not flipped: SUB11, SUB1, SUB2, TESTFN
503 # flipped: SUB2, SUB11, SUB1, TESTFN
504 flipped = all[3][1][0] != "SUB1"
505 all[3][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000506 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000507 self.assertEqual(all[flipped], (sub11_path, [], []))
508 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000509 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000510
Guido van Rossumd8faa362007-04-27 19:54:29 +0000511 if hasattr(os, "symlink"):
512 # Walk, following symlinks.
513 for root, dirs, files in os.walk(walk_path, followlinks=True):
514 if root == link_path:
515 self.assertEqual(dirs, [])
516 self.assertEqual(files, ["tmp4"])
517 break
518 else:
519 self.fail("Didn't follow symlink with followlinks=True")
520
521 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000522 # Tear everything down. This is a decent use for bottom-up on
523 # Windows, which doesn't have a recursive delete command. The
524 # (not so) subtlety is that rmdir will fail unless the dir's
525 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000526 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000527 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000528 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000529 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000530 dirname = os.path.join(root, name)
531 if not os.path.islink(dirname):
532 os.rmdir(dirname)
533 else:
534 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000535 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000536
Guido van Rossume7ba4952007-06-06 23:52:48 +0000537class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000538 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000539 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000540
541 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000542 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000543 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
544 os.makedirs(path) # Should work
545 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
546 os.makedirs(path)
547
548 # Try paths with a '.' in them
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000549 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000550 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
551 os.makedirs(path)
552 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
553 'dir5', 'dir6')
554 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000555
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000556 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000557 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000558 'dir4', 'dir5', 'dir6')
559 # If the tests failed, the bottom-most directory ('../dir6')
560 # may not have been created, so we look for the outermost directory
561 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000562 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000563 path = os.path.dirname(path)
564
565 os.removedirs(path)
566
Guido van Rossume7ba4952007-06-06 23:52:48 +0000567class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000568 def test_devnull(self):
Alex Martelli01c77c62006-08-24 02:58:11 +0000569 f = open(os.devnull, 'w')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000570 f.write('hello')
571 f.close()
Alex Martelli01c77c62006-08-24 02:58:11 +0000572 f = open(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000573 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000574 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000575
Guido van Rossume7ba4952007-06-06 23:52:48 +0000576class URandomTests(unittest.TestCase):
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000577 def test_urandom(self):
578 try:
579 self.assertEqual(len(os.urandom(1)), 1)
580 self.assertEqual(len(os.urandom(10)), 10)
581 self.assertEqual(len(os.urandom(100)), 100)
582 self.assertEqual(len(os.urandom(1000)), 1000)
583 except NotImplementedError:
584 pass
585
Guido van Rossume7ba4952007-06-06 23:52:48 +0000586class ExecTests(unittest.TestCase):
587 def test_execvpe_with_bad_program(self):
Thomas Hellerbd315c52007-08-30 17:57:21 +0000588 self.assertRaises(OSError, os.execvpe, 'no such app-', ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000589
Thomas Heller6790d602007-08-30 17:15:14 +0000590 def test_execvpe_with_bad_arglist(self):
591 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
592
Antoine Pitrou1119a642010-01-17 12:16:23 +0000593class ArgTests(unittest.TestCase):
594 def test_bytearray(self):
595 # Issue #7561: posix module didn't release bytearray exports properly.
596 b = bytearray(os.sep.encode('ascii'))
597 self.assertRaises(OSError, os.mkdir, b)
598 # Check object is still resizable.
599 b[:] = b''
600
Thomas Wouters477c8d52006-05-27 19:21:47 +0000601class Win32ErrorTests(unittest.TestCase):
602 def test_rename(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000603 self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000604
605 def test_remove(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000606 self.assertRaises(WindowsError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000607
608 def test_chdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000609 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000610
611 def test_mkdir(self):
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +0000612 f = open(support.TESTFN, "w")
Benjamin Petersonf91df042009-02-13 02:50:59 +0000613 try:
614 self.assertRaises(WindowsError, os.mkdir, support.TESTFN)
615 finally:
616 f.close()
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +0000617 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000618
619 def test_utime(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000620 self.assertRaises(WindowsError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000621
Thomas Wouters477c8d52006-05-27 19:21:47 +0000622 def test_chmod(self):
Benjamin Petersonf91df042009-02-13 02:50:59 +0000623 self.assertRaises(WindowsError, os.chmod, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000624
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000625class TestInvalidFD(unittest.TestCase):
Benjamin Peterson05e782f2009-01-19 15:15:02 +0000626 singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000627 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
628 #singles.append("close")
629 #We omit close because it doesn'r raise an exception on some platforms
630 def get_single(f):
631 def helper(self):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000632 if hasattr(os, f):
633 self.check(getattr(os, f))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000634 return helper
635 for f in singles:
636 locals()["test_"+f] = get_single(f)
637
Benjamin Peterson7522c742009-01-19 21:00:09 +0000638 def check(self, f, *args):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000639 try:
640 f(support.make_bad_fd(), *args)
641 except OSError as e:
642 self.assertEqual(e.errno, errno.EBADF)
643 else:
644 self.fail("%r didn't raise a OSError with a bad file descriptor"
645 % f)
Benjamin Peterson7522c742009-01-19 21:00:09 +0000646
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000647 def test_isatty(self):
648 if hasattr(os, "isatty"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000649 self.assertEqual(os.isatty(support.make_bad_fd()), False)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000650
651 def test_closerange(self):
652 if hasattr(os, "closerange"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000653 fd = support.make_bad_fd()
R. David Murray630cc482009-07-22 15:20:27 +0000654 # Make sure none of the descriptors we are about to close are
655 # currently valid (issue 6542).
656 for i in range(10):
657 try: os.fstat(fd+i)
658 except OSError:
659 pass
660 else:
661 break
662 if i < 2:
663 raise unittest.SkipTest(
664 "Unable to acquire a range of invalid file descriptors")
665 self.assertEqual(os.closerange(fd, fd + i-1), None)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000666
667 def test_dup2(self):
668 if hasattr(os, "dup2"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000669 self.check(os.dup2, 20)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000670
671 def test_fchmod(self):
672 if hasattr(os, "fchmod"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000673 self.check(os.fchmod, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000674
675 def test_fchown(self):
676 if hasattr(os, "fchown"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000677 self.check(os.fchown, -1, -1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000678
679 def test_fpathconf(self):
680 if hasattr(os, "fpathconf"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000681 self.check(os.fpathconf, "PC_NAME_MAX")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000682
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000683 def test_ftruncate(self):
684 if hasattr(os, "ftruncate"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000685 self.check(os.ftruncate, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000686
687 def test_lseek(self):
688 if hasattr(os, "lseek"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000689 self.check(os.lseek, 0, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000690
691 def test_read(self):
692 if hasattr(os, "read"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000693 self.check(os.read, 1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000694
695 def test_tcsetpgrpt(self):
696 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000697 self.check(os.tcsetpgrp, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000698
699 def test_write(self):
700 if hasattr(os, "write"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000701 self.check(os.write, b" ")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000702
Thomas Wouters477c8d52006-05-27 19:21:47 +0000703if sys.platform != 'win32':
704 class Win32ErrorTests(unittest.TestCase):
705 pass
706
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000707 class PosixUidGidTests(unittest.TestCase):
708 if hasattr(os, 'setuid'):
709 def test_setuid(self):
710 if os.getuid() != 0:
711 self.assertRaises(os.error, os.setuid, 0)
712 self.assertRaises(OverflowError, os.setuid, 1<<32)
713
714 if hasattr(os, 'setgid'):
715 def test_setgid(self):
716 if os.getuid() != 0:
717 self.assertRaises(os.error, os.setgid, 0)
718 self.assertRaises(OverflowError, os.setgid, 1<<32)
719
720 if hasattr(os, 'seteuid'):
721 def test_seteuid(self):
722 if os.getuid() != 0:
723 self.assertRaises(os.error, os.seteuid, 0)
724 self.assertRaises(OverflowError, os.seteuid, 1<<32)
725
726 if hasattr(os, 'setegid'):
727 def test_setegid(self):
728 if os.getuid() != 0:
729 self.assertRaises(os.error, os.setegid, 0)
730 self.assertRaises(OverflowError, os.setegid, 1<<32)
731
732 if hasattr(os, 'setreuid'):
733 def test_setreuid(self):
734 if os.getuid() != 0:
735 self.assertRaises(os.error, os.setreuid, 0, 0)
736 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
737 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000738
739 def test_setreuid_neg1(self):
740 # Needs to accept -1. We run this in a subprocess to avoid
741 # altering the test runner's process state (issue8045).
742 import subprocess
743 subprocess.check_call([
744 sys.executable, '-c',
745 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000746
747 if hasattr(os, 'setregid'):
748 def test_setregid(self):
749 if os.getuid() != 0:
750 self.assertRaises(os.error, os.setregid, 0, 0)
751 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
752 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000753
754 def test_setregid_neg1(self):
755 # Needs to accept -1. We run this in a subprocess to avoid
756 # altering the test runner's process state (issue8045).
757 import subprocess
758 subprocess.check_call([
759 sys.executable, '-c',
760 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Martin v. Löwis011e8422009-05-05 04:43:17 +0000761
Mark Dickinson70613682009-05-05 21:34:59 +0000762 @unittest.skipIf(sys.platform == 'darwin', "tests don't apply to OS X")
Martin v. Löwis011e8422009-05-05 04:43:17 +0000763 class Pep383Tests(unittest.TestCase):
764 filenames = [b'foo\xf6bar', 'foo\xf6bar'.encode("utf-8")]
765
766 def setUp(self):
767 self.fsencoding = sys.getfilesystemencoding()
768 sys.setfilesystemencoding("utf-8")
769 self.dir = support.TESTFN
Martin v. Löwis43c57782009-05-10 08:15:24 +0000770 self.bdir = self.dir.encode("utf-8", "surrogateescape")
Martin v. Löwis011e8422009-05-05 04:43:17 +0000771 os.mkdir(self.dir)
772 self.unicodefn = []
773 for fn in self.filenames:
774 f = open(os.path.join(self.bdir, fn), "w")
775 f.close()
Martin v. Löwis43c57782009-05-10 08:15:24 +0000776 self.unicodefn.append(fn.decode("utf-8", "surrogateescape"))
Martin v. Löwis011e8422009-05-05 04:43:17 +0000777
778 def tearDown(self):
779 shutil.rmtree(self.dir)
780 sys.setfilesystemencoding(self.fsencoding)
781
782 def test_listdir(self):
783 expected = set(self.unicodefn)
784 found = set(os.listdir(support.TESTFN))
785 self.assertEquals(found, expected)
786
787 def test_open(self):
788 for fn in self.unicodefn:
789 f = open(os.path.join(self.dir, fn))
790 f.close()
791
792 def test_stat(self):
793 for fn in self.unicodefn:
794 os.stat(os.path.join(self.dir, fn))
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000795else:
796 class PosixUidGidTests(unittest.TestCase):
797 pass
Martin v. Löwis011e8422009-05-05 04:43:17 +0000798 class Pep383Tests(unittest.TestCase):
799 pass
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000800
Fred Drake2e2be372001-09-20 21:33:42 +0000801def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000802 support.run_unittest(
Antoine Pitrou1119a642010-01-17 12:16:23 +0000803 ArgTests,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000804 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000805 StatAttributeTests,
806 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000807 WalkTests,
808 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000809 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000810 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000811 ExecTests,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000812 Win32ErrorTests,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000813 TestInvalidFD,
Martin v. Löwis011e8422009-05-05 04:43:17 +0000814 PosixUidGidTests,
815 Pep383Tests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000816 )
Fred Drake2e2be372001-09-20 21:33:42 +0000817
818if __name__ == "__main__":
819 test_main()