blob: f28f862c7638ec472683455d472fc63459670a8a [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
Benjamin Petersonee8712c2008-05-20 21:35:26 +000010from test import support
Fred Drake38c2ef02001-07-17 20:52:51 +000011
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012# Tests creating TESTFN
13class FileTests(unittest.TestCase):
14 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000015 if os.path.exists(support.TESTFN):
16 os.unlink(support.TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000017 tearDown = setUp
18
19 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000020 f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000021 os.close(f)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000022 self.assert_(os.access(support.TESTFN, os.W_OK))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000023
Christian Heimesfdab48e2008-01-20 09:06:41 +000024 def test_closerange(self):
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000025 first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
26 # We must allocate two consecutive file descriptors, otherwise
27 # it will mess up other file descriptors (perhaps even the three
28 # standard ones).
29 second = os.dup(first)
30 try:
31 retries = 0
32 while second != first + 1:
33 os.close(first)
34 retries += 1
35 if retries > 10:
36 # XXX test skipped
37 print("couldn't allocate two consecutive fds, "
38 "skipping test_closerange", file=sys.stderr)
39 return
40 first, second = second, os.dup(second)
41 finally:
42 os.close(second)
Christian Heimesfdab48e2008-01-20 09:06:41 +000043 # close a fd that is open, and one that isn't
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000044 os.closerange(first, first + 2)
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000045 self.assertRaises(OSError, os.write, first, b"a")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000046
Hirokazu Yamamoto4c19e6e2008-09-08 23:41:21 +000047 def test_rename(self):
48 path = support.TESTFN
49 old = sys.getrefcount(path)
50 self.assertRaises(TypeError, os.rename, path, 0)
51 new = sys.getrefcount(path)
52 self.assertEqual(old, new)
53
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000054 def test_read(self):
55 with open(support.TESTFN, "w+b") as fobj:
56 fobj.write(b"spam")
57 fobj.flush()
58 fd = fobj.fileno()
59 os.lseek(fd, 0, 0)
60 s = os.read(fd, 4)
61 self.assertEqual(type(s), bytes)
62 self.assertEqual(s, b"spam")
63
64 def test_write(self):
65 # os.write() accepts bytes- and buffer-like objects but not strings
66 fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY)
67 self.assertRaises(TypeError, os.write, fd, "beans")
68 os.write(fd, b"bacon\n")
69 os.write(fd, bytearray(b"eggs\n"))
70 os.write(fd, memoryview(b"spam\n"))
71 os.close(fd)
72 with open(support.TESTFN, "rb") as fobj:
Antoine Pitroud62269f2008-09-15 23:54:52 +000073 self.assertEqual(fobj.read().splitlines(),
74 [b"bacon", b"eggs", b"spam"])
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000075
76
Christian Heimesdd15f6c2008-03-16 00:07:10 +000077class TemporaryFileTests(unittest.TestCase):
78 def setUp(self):
79 self.files = []
Benjamin Petersonee8712c2008-05-20 21:35:26 +000080 os.mkdir(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000081
82 def tearDown(self):
83 for name in self.files:
84 os.unlink(name)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000085 os.rmdir(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000086
87 def check_tempfile(self, name):
88 # make sure it doesn't already exist:
89 self.failIf(os.path.exists(name),
90 "file already exists for temporary file")
91 # make sure we can create the file
92 open(name, "w")
93 self.files.append(name)
94
95 def test_tempnam(self):
96 if not hasattr(os, "tempnam"):
97 return
98 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
99 r"test_os$")
100 self.check_tempfile(os.tempnam())
101
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000102 name = os.tempnam(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000103 self.check_tempfile(name)
104
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000105 name = os.tempnam(support.TESTFN, "pfx")
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000106 self.assert_(os.path.basename(name)[:3] == "pfx")
107 self.check_tempfile(name)
108
109 def test_tmpfile(self):
110 if not hasattr(os, "tmpfile"):
111 return
112 # As with test_tmpnam() below, the Windows implementation of tmpfile()
113 # attempts to create a file in the root directory of the current drive.
114 # On Vista and Server 2008, this test will always fail for normal users
115 # as writing to the root directory requires elevated privileges. With
116 # XP and below, the semantics of tmpfile() are the same, but the user
117 # running the test is more likely to have administrative privileges on
118 # their account already. If that's the case, then os.tmpfile() should
119 # work. In order to make this test as useful as possible, rather than
120 # trying to detect Windows versions or whether or not the user has the
121 # right permissions, just try and create a file in the root directory
122 # and see if it raises a 'Permission denied' OSError. If it does, then
123 # test that a subsequent call to os.tmpfile() raises the same error. If
124 # it doesn't, assume we're on XP or below and the user running the test
125 # has administrative privileges, and proceed with the test as normal.
126 if sys.platform == 'win32':
127 name = '\\python_test_os_test_tmpfile.txt'
128 if os.path.exists(name):
129 os.remove(name)
130 try:
131 fp = open(name, 'w')
132 except IOError as first:
133 # open() failed, assert tmpfile() fails in the same way.
134 # Although open() raises an IOError and os.tmpfile() raises an
135 # OSError(), 'args' will be (13, 'Permission denied') in both
136 # cases.
137 try:
138 fp = os.tmpfile()
139 except OSError as second:
140 self.assertEqual(first.args, second.args)
141 else:
142 self.fail("expected os.tmpfile() to raise OSError")
143 return
144 else:
145 # open() worked, therefore, tmpfile() should work. Close our
146 # dummy file and proceed with the test as normal.
147 fp.close()
148 os.remove(name)
149
150 fp = os.tmpfile()
151 fp.write("foobar")
152 fp.seek(0,0)
153 s = fp.read()
154 fp.close()
155 self.assert_(s == "foobar")
156
157 def test_tmpnam(self):
158 import sys
159 if not hasattr(os, "tmpnam"):
160 return
161 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
162 r"test_os$")
163 name = os.tmpnam()
164 if sys.platform in ("win32",):
165 # The Windows tmpnam() seems useless. From the MS docs:
166 #
167 # The character string that tmpnam creates consists of
168 # the path prefix, defined by the entry P_tmpdir in the
169 # file STDIO.H, followed by a sequence consisting of the
170 # digit characters '0' through '9'; the numerical value
171 # of this string is in the range 1 - 65,535. Changing the
172 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
173 # change the operation of tmpnam.
174 #
175 # The really bizarre part is that, at least under MSVC6,
176 # P_tmpdir is "\\". That is, the path returned refers to
177 # the root of the current drive. That's a terrible place to
178 # put temp files, and, depending on privileges, the user
179 # may not even be able to open a file in the root directory.
180 self.failIf(os.path.exists(name),
181 "file already exists for temporary file")
182 else:
183 self.check_tempfile(name)
184
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000185 def fdopen_helper(self, *args):
186 fd = os.open(support.TESTFN, os.O_RDONLY)
187 fp2 = os.fdopen(fd, *args)
188 fp2.close()
189
190 def test_fdopen(self):
191 self.fdopen_helper()
192 self.fdopen_helper('r')
193 self.fdopen_helper('r', 100)
194
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000195# Test attributes on return values from os.*stat* family.
196class StatAttributeTests(unittest.TestCase):
197 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000198 os.mkdir(support.TESTFN)
199 self.fname = os.path.join(support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000200 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +0000201 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000202 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000203
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000204 def tearDown(self):
205 os.unlink(self.fname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000206 os.rmdir(support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000207
208 def test_stat_attributes(self):
209 if not hasattr(os, "stat"):
210 return
211
212 import stat
213 result = os.stat(self.fname)
214
215 # Make sure direct access works
216 self.assertEquals(result[stat.ST_SIZE], 3)
217 self.assertEquals(result.st_size, 3)
218
219 import sys
220
221 # Make sure all the attributes are there
222 members = dir(result)
223 for name in dir(stat):
224 if name[:3] == 'ST_':
225 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000226 if name.endswith("TIME"):
227 def trunc(x): return int(x)
228 else:
229 def trunc(x): return x
230 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000231 result[getattr(stat, name)])
232 self.assert_(attr in members)
233
234 try:
235 result[200]
236 self.fail("No exception thrown")
237 except IndexError:
238 pass
239
240 # Make sure that assignment fails
241 try:
242 result.st_mode = 1
243 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000244 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000245 pass
246
247 try:
248 result.st_rdev = 1
249 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000250 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000251 pass
252
253 try:
254 result.parrot = 1
255 self.fail("No exception thrown")
256 except AttributeError:
257 pass
258
259 # Use the stat_result constructor with a too-short tuple.
260 try:
261 result2 = os.stat_result((10,))
262 self.fail("No exception thrown")
263 except TypeError:
264 pass
265
266 # Use the constructr with a too-long tuple.
267 try:
268 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
269 except TypeError:
270 pass
271
Tim Peterse0c446b2001-10-18 21:57:37 +0000272
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000273 def test_statvfs_attributes(self):
274 if not hasattr(os, "statvfs"):
275 return
276
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000277 try:
278 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000279 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000280 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000281 if e.errno == errno.ENOSYS:
282 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000283
284 # Make sure direct access works
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000285 self.assertEquals(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000286
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000287 # Make sure all the attributes are there.
288 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
289 'ffree', 'favail', 'flag', 'namemax')
290 for value, member in enumerate(members):
291 self.assertEquals(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000292
293 # Make sure that assignment really fails
294 try:
295 result.f_bfree = 1
296 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000297 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000298 pass
299
300 try:
301 result.parrot = 1
302 self.fail("No exception thrown")
303 except AttributeError:
304 pass
305
306 # Use the constructor with a too-short tuple.
307 try:
308 result2 = os.statvfs_result((10,))
309 self.fail("No exception thrown")
310 except TypeError:
311 pass
312
313 # Use the constructr with a too-long tuple.
314 try:
315 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
316 except TypeError:
317 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000318
Thomas Wouters89f507f2006-12-13 04:49:30 +0000319 def test_utime_dir(self):
320 delta = 1000000
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000321 st = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000322 # round to int, because some systems may support sub-second
323 # time stamps in stat, but not in utime.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000324 os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
325 st2 = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000326 self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
327
328 # Restrict test to Win32, since there is no guarantee other
329 # systems support centiseconds
330 if sys.platform == 'win32':
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000331 def get_file_system(path):
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000332 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000333 import ctypes
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000334 kernel32 = ctypes.windll.kernel32
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000335 buf = ctypes.create_unicode_buffer("", 100)
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000336 if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000337 return buf.value
338
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000339 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000340 def test_1565150(self):
341 t1 = 1159195039.25
342 os.utime(self.fname, (t1, t1))
343 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000344
Guido van Rossumd8faa362007-04-27 19:54:29 +0000345 def test_1686475(self):
346 # Verify that an open file can be stat'ed
347 try:
348 os.stat(r"c:\pagefile.sys")
349 except WindowsError as e:
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000350 if e.errno == 2: # file does not exist; cannot run test
Guido van Rossumd8faa362007-04-27 19:54:29 +0000351 return
352 self.fail("Could not stat pagefile.sys")
353
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000354from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000355
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000356class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000357 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000358 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000359
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000360 def setUp(self):
361 self.__save = dict(os.environ)
Christian Heimes90333392007-11-01 19:08:42 +0000362 for key, value in self._reference().items():
363 os.environ[key] = value
364
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000365 def tearDown(self):
366 os.environ.clear()
367 os.environ.update(self.__save)
368
Christian Heimes90333392007-11-01 19:08:42 +0000369 def _reference(self):
370 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
371
372 def _empty_mapping(self):
373 os.environ.clear()
374 return os.environ
375
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000376 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000377 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000378 os.environ.clear()
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000379 if os.path.exists("/bin/sh"):
380 os.environ.update(HELLO="World")
381 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
382 self.assertEquals(value, "World")
383
Christian Heimes1a13d592007-11-08 14:16:55 +0000384 def test_os_popen_iter(self):
385 if os.path.exists("/bin/sh"):
386 popen = os.popen("/bin/sh -c 'echo \"line1\nline2\nline3\"'")
387 it = iter(popen)
388 self.assertEquals(next(it), "line1\n")
389 self.assertEquals(next(it), "line2\n")
390 self.assertEquals(next(it), "line3\n")
391 self.assertRaises(StopIteration, next, it)
392
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000393 # Verify environ keys and values from the OS are of the
394 # correct str type.
395 def test_keyvalue_types(self):
396 for key, val in os.environ.items():
397 self.assertEquals(type(key), str)
398 self.assertEquals(type(val), str)
399
Christian Heimes90333392007-11-01 19:08:42 +0000400 def test_items(self):
401 for key, value in self._reference().items():
402 self.assertEqual(os.environ.get(key), value)
403
Tim Petersc4e09402003-04-25 07:11:48 +0000404class WalkTests(unittest.TestCase):
405 """Tests for os.walk()."""
406
407 def test_traversal(self):
408 import os
409 from os.path import join
410
411 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000412 # TESTFN/
413 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000414 # tmp1
415 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000416 # tmp2
417 # SUB11/ no kids
418 # SUB2/ a file kid and a dirsymlink kid
419 # tmp3
420 # link/ a symlink to TESTFN.2
421 # TEST2/
422 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000423 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000424 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000425 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000426 sub2_path = join(walk_path, "SUB2")
427 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000428 tmp2_path = join(sub1_path, "tmp2")
429 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000430 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000431 t2_path = join(support.TESTFN, "TEST2")
432 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000433
434 # Create stuff.
435 os.makedirs(sub11_path)
436 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000437 os.makedirs(t2_path)
438 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000439 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000440 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
441 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000442 if hasattr(os, "symlink"):
443 os.symlink(os.path.abspath(t2_path), link_path)
444 sub2_tree = (sub2_path, ["link"], ["tmp3"])
445 else:
446 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000447
448 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000449 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000450 self.assertEqual(len(all), 4)
451 # We can't know which order SUB1 and SUB2 will appear in.
452 # Not flipped: TESTFN, SUB1, SUB11, SUB2
453 # flipped: TESTFN, SUB2, SUB1, SUB11
454 flipped = all[0][1][0] != "SUB1"
455 all[0][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000456 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000457 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
458 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000459 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000460
461 # Prune the search.
462 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000463 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000464 all.append((root, dirs, files))
465 # Don't descend into SUB1.
466 if 'SUB1' in dirs:
467 # Note that this also mutates the dirs we appended to all!
468 dirs.remove('SUB1')
469 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000470 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
471 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000472
473 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000474 all = list(os.walk(walk_path, topdown=False))
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: SUB11, SUB1, SUB2, TESTFN
478 # flipped: SUB2, SUB11, SUB1, TESTFN
479 flipped = all[3][1][0] != "SUB1"
480 all[3][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000481 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000482 self.assertEqual(all[flipped], (sub11_path, [], []))
483 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000484 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000485
Guido van Rossumd8faa362007-04-27 19:54:29 +0000486 if hasattr(os, "symlink"):
487 # Walk, following symlinks.
488 for root, dirs, files in os.walk(walk_path, followlinks=True):
489 if root == link_path:
490 self.assertEqual(dirs, [])
491 self.assertEqual(files, ["tmp4"])
492 break
493 else:
494 self.fail("Didn't follow symlink with followlinks=True")
495
496 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000497 # Tear everything down. This is a decent use for bottom-up on
498 # Windows, which doesn't have a recursive delete command. The
499 # (not so) subtlety is that rmdir will fail unless the dir's
500 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000501 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000502 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000503 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000504 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000505 dirname = os.path.join(root, name)
506 if not os.path.islink(dirname):
507 os.rmdir(dirname)
508 else:
509 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000510 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000511
Guido van Rossume7ba4952007-06-06 23:52:48 +0000512class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000513 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000514 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000515
516 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000517 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000518 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
519 os.makedirs(path) # Should work
520 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
521 os.makedirs(path)
522
523 # Try paths with a '.' in them
524 self.failUnlessRaises(OSError, os.makedirs, os.curdir)
525 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
526 os.makedirs(path)
527 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
528 'dir5', 'dir6')
529 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000530
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000531 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000532 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000533 'dir4', 'dir5', 'dir6')
534 # If the tests failed, the bottom-most directory ('../dir6')
535 # may not have been created, so we look for the outermost directory
536 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000537 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000538 path = os.path.dirname(path)
539
540 os.removedirs(path)
541
Guido van Rossume7ba4952007-06-06 23:52:48 +0000542class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000543 def test_devnull(self):
Alex Martelli01c77c62006-08-24 02:58:11 +0000544 f = open(os.devnull, 'w')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000545 f.write('hello')
546 f.close()
Alex Martelli01c77c62006-08-24 02:58:11 +0000547 f = open(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000548 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000549 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000550
Guido van Rossume7ba4952007-06-06 23:52:48 +0000551class URandomTests(unittest.TestCase):
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000552 def test_urandom(self):
553 try:
554 self.assertEqual(len(os.urandom(1)), 1)
555 self.assertEqual(len(os.urandom(10)), 10)
556 self.assertEqual(len(os.urandom(100)), 100)
557 self.assertEqual(len(os.urandom(1000)), 1000)
558 except NotImplementedError:
559 pass
560
Guido van Rossume7ba4952007-06-06 23:52:48 +0000561class ExecTests(unittest.TestCase):
562 def test_execvpe_with_bad_program(self):
Thomas Hellerbd315c52007-08-30 17:57:21 +0000563 self.assertRaises(OSError, os.execvpe, 'no such app-', ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000564
Thomas Heller6790d602007-08-30 17:15:14 +0000565 def test_execvpe_with_bad_arglist(self):
566 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
567
Thomas Wouters477c8d52006-05-27 19:21:47 +0000568class Win32ErrorTests(unittest.TestCase):
569 def test_rename(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000570 self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000571
572 def test_remove(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000573 self.assertRaises(WindowsError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000574
575 def test_chdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000576 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000577
578 def test_mkdir(self):
Benjamin Petersonf91df042009-02-13 02:50:59 +0000579 f = open(test_support.TESTFN, "w")
580 try:
581 self.assertRaises(WindowsError, os.mkdir, support.TESTFN)
582 finally:
583 f.close()
584 os.unlink(test_support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000585
586 def test_utime(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000587 self.assertRaises(WindowsError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000588
Thomas Wouters477c8d52006-05-27 19:21:47 +0000589 def test_chmod(self):
Benjamin Petersonf91df042009-02-13 02:50:59 +0000590 self.assertRaises(WindowsError, os.chmod, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000591
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000592class TestInvalidFD(unittest.TestCase):
Benjamin Peterson05e782f2009-01-19 15:15:02 +0000593 singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000594 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
595 #singles.append("close")
596 #We omit close because it doesn'r raise an exception on some platforms
597 def get_single(f):
598 def helper(self):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000599 if hasattr(os, f):
600 self.check(getattr(os, f))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000601 return helper
602 for f in singles:
603 locals()["test_"+f] = get_single(f)
604
Benjamin Peterson7522c742009-01-19 21:00:09 +0000605 def check(self, f, *args):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000606 try:
607 f(support.make_bad_fd(), *args)
608 except OSError as e:
609 self.assertEqual(e.errno, errno.EBADF)
610 else:
611 self.fail("%r didn't raise a OSError with a bad file descriptor"
612 % f)
Benjamin Peterson7522c742009-01-19 21:00:09 +0000613
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000614 def test_isatty(self):
615 if hasattr(os, "isatty"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000616 self.assertEqual(os.isatty(support.make_bad_fd()), False)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000617
618 def test_closerange(self):
619 if hasattr(os, "closerange"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000620 fd = support.make_bad_fd()
621 self.assertEqual(os.closerange(fd, fd + 10), None)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000622
623 def test_dup2(self):
624 if hasattr(os, "dup2"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000625 self.check(os.dup2, 20)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000626
627 def test_fchmod(self):
628 if hasattr(os, "fchmod"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000629 self.check(os.fchmod, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000630
631 def test_fchown(self):
632 if hasattr(os, "fchown"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000633 self.check(os.fchown, -1, -1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000634
635 def test_fpathconf(self):
636 if hasattr(os, "fpathconf"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000637 self.check(os.fpathconf, "PC_NAME_MAX")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000638
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000639 def test_ftruncate(self):
640 if hasattr(os, "ftruncate"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000641 self.check(os.ftruncate, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000642
643 def test_lseek(self):
644 if hasattr(os, "lseek"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000645 self.check(os.lseek, 0, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000646
647 def test_read(self):
648 if hasattr(os, "read"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000649 self.check(os.read, 1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000650
651 def test_tcsetpgrpt(self):
652 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000653 self.check(os.tcsetpgrp, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000654
655 def test_write(self):
656 if hasattr(os, "write"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000657 self.check(os.write, b" ")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000658
Thomas Wouters477c8d52006-05-27 19:21:47 +0000659if sys.platform != 'win32':
660 class Win32ErrorTests(unittest.TestCase):
661 pass
662
Fred Drake2e2be372001-09-20 21:33:42 +0000663def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000664 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000665 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000666 StatAttributeTests,
667 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000668 WalkTests,
669 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000670 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000671 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000672 ExecTests,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000673 Win32ErrorTests,
674 TestInvalidFD
Walter Dörwald21d3a322003-05-01 17:45:56 +0000675 )
Fred Drake2e2be372001-09-20 21:33:42 +0000676
677if __name__ == "__main__":
678 test_main()