blob: e9b0652ab0dc737f07b4bbf5f03fb46e26a57a97 [file] [log] [blame]
Fred Drake38c2ef02001-07-17 20:52:51 +00001# As a test suite for the os module, this is woefully inadequate, but this
2# does add tests for a few functions which have been determined to be more
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00003# portable than they had been thought to be.
Fred Drake38c2ef02001-07-17 20:52:51 +00004
5import os
6import unittest
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +00007import warnings
Thomas Wouters477c8d52006-05-27 19:21:47 +00008import sys
Benjamin Petersonee8712c2008-05-20 21:35:26 +00009from test import support
Fred Drake38c2ef02001-07-17 20:52:51 +000010
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011# Tests creating TESTFN
12class FileTests(unittest.TestCase):
13 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000014 if os.path.exists(support.TESTFN):
15 os.unlink(support.TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000016 tearDown = setUp
17
18 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000019 f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000020 os.close(f)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000021 self.assert_(os.access(support.TESTFN, os.W_OK))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000022
Christian Heimesfdab48e2008-01-20 09:06:41 +000023 def test_closerange(self):
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000024 first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
25 # We must allocate two consecutive file descriptors, otherwise
26 # it will mess up other file descriptors (perhaps even the three
27 # standard ones).
28 second = os.dup(first)
29 try:
30 retries = 0
31 while second != first + 1:
32 os.close(first)
33 retries += 1
34 if retries > 10:
35 # XXX test skipped
36 print("couldn't allocate two consecutive fds, "
37 "skipping test_closerange", file=sys.stderr)
38 return
39 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)
44 self.assertRaises(OSError, os.write, first, "a")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000045
Christian Heimesdd15f6c2008-03-16 00:07:10 +000046class TemporaryFileTests(unittest.TestCase):
47 def setUp(self):
48 self.files = []
Benjamin Petersonee8712c2008-05-20 21:35:26 +000049 os.mkdir(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000050
51 def tearDown(self):
52 for name in self.files:
53 os.unlink(name)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000054 os.rmdir(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000055
56 def check_tempfile(self, name):
57 # make sure it doesn't already exist:
58 self.failIf(os.path.exists(name),
59 "file already exists for temporary file")
60 # make sure we can create the file
61 open(name, "w")
62 self.files.append(name)
63
64 def test_tempnam(self):
65 if not hasattr(os, "tempnam"):
66 return
67 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
68 r"test_os$")
69 self.check_tempfile(os.tempnam())
70
Benjamin Petersonee8712c2008-05-20 21:35:26 +000071 name = os.tempnam(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000072 self.check_tempfile(name)
73
Benjamin Petersonee8712c2008-05-20 21:35:26 +000074 name = os.tempnam(support.TESTFN, "pfx")
Christian Heimesdd15f6c2008-03-16 00:07:10 +000075 self.assert_(os.path.basename(name)[:3] == "pfx")
76 self.check_tempfile(name)
77
78 def test_tmpfile(self):
79 if not hasattr(os, "tmpfile"):
80 return
81 # As with test_tmpnam() below, the Windows implementation of tmpfile()
82 # attempts to create a file in the root directory of the current drive.
83 # On Vista and Server 2008, this test will always fail for normal users
84 # as writing to the root directory requires elevated privileges. With
85 # XP and below, the semantics of tmpfile() are the same, but the user
86 # running the test is more likely to have administrative privileges on
87 # their account already. If that's the case, then os.tmpfile() should
88 # work. In order to make this test as useful as possible, rather than
89 # trying to detect Windows versions or whether or not the user has the
90 # right permissions, just try and create a file in the root directory
91 # and see if it raises a 'Permission denied' OSError. If it does, then
92 # test that a subsequent call to os.tmpfile() raises the same error. If
93 # it doesn't, assume we're on XP or below and the user running the test
94 # has administrative privileges, and proceed with the test as normal.
95 if sys.platform == 'win32':
96 name = '\\python_test_os_test_tmpfile.txt'
97 if os.path.exists(name):
98 os.remove(name)
99 try:
100 fp = open(name, 'w')
101 except IOError as first:
102 # open() failed, assert tmpfile() fails in the same way.
103 # Although open() raises an IOError and os.tmpfile() raises an
104 # OSError(), 'args' will be (13, 'Permission denied') in both
105 # cases.
106 try:
107 fp = os.tmpfile()
108 except OSError as second:
109 self.assertEqual(first.args, second.args)
110 else:
111 self.fail("expected os.tmpfile() to raise OSError")
112 return
113 else:
114 # open() worked, therefore, tmpfile() should work. Close our
115 # dummy file and proceed with the test as normal.
116 fp.close()
117 os.remove(name)
118
119 fp = os.tmpfile()
120 fp.write("foobar")
121 fp.seek(0,0)
122 s = fp.read()
123 fp.close()
124 self.assert_(s == "foobar")
125
126 def test_tmpnam(self):
127 import sys
128 if not hasattr(os, "tmpnam"):
129 return
130 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
131 r"test_os$")
132 name = os.tmpnam()
133 if sys.platform in ("win32",):
134 # The Windows tmpnam() seems useless. From the MS docs:
135 #
136 # The character string that tmpnam creates consists of
137 # the path prefix, defined by the entry P_tmpdir in the
138 # file STDIO.H, followed by a sequence consisting of the
139 # digit characters '0' through '9'; the numerical value
140 # of this string is in the range 1 - 65,535. Changing the
141 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
142 # change the operation of tmpnam.
143 #
144 # The really bizarre part is that, at least under MSVC6,
145 # P_tmpdir is "\\". That is, the path returned refers to
146 # the root of the current drive. That's a terrible place to
147 # put temp files, and, depending on privileges, the user
148 # may not even be able to open a file in the root directory.
149 self.failIf(os.path.exists(name),
150 "file already exists for temporary file")
151 else:
152 self.check_tempfile(name)
153
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000154 def fdopen_helper(self, *args):
155 fd = os.open(support.TESTFN, os.O_RDONLY)
156 fp2 = os.fdopen(fd, *args)
157 fp2.close()
158
159 def test_fdopen(self):
160 self.fdopen_helper()
161 self.fdopen_helper('r')
162 self.fdopen_helper('r', 100)
163
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000164# Test attributes on return values from os.*stat* family.
165class StatAttributeTests(unittest.TestCase):
166 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000167 os.mkdir(support.TESTFN)
168 self.fname = os.path.join(support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000169 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +0000170 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000171 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000172
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000173 def tearDown(self):
174 os.unlink(self.fname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000175 os.rmdir(support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000176
177 def test_stat_attributes(self):
178 if not hasattr(os, "stat"):
179 return
180
181 import stat
182 result = os.stat(self.fname)
183
184 # Make sure direct access works
185 self.assertEquals(result[stat.ST_SIZE], 3)
186 self.assertEquals(result.st_size, 3)
187
188 import sys
189
190 # Make sure all the attributes are there
191 members = dir(result)
192 for name in dir(stat):
193 if name[:3] == 'ST_':
194 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000195 if name.endswith("TIME"):
196 def trunc(x): return int(x)
197 else:
198 def trunc(x): return x
199 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000200 result[getattr(stat, name)])
201 self.assert_(attr in members)
202
203 try:
204 result[200]
205 self.fail("No exception thrown")
206 except IndexError:
207 pass
208
209 # Make sure that assignment fails
210 try:
211 result.st_mode = 1
212 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000213 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000214 pass
215
216 try:
217 result.st_rdev = 1
218 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000219 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000220 pass
221
222 try:
223 result.parrot = 1
224 self.fail("No exception thrown")
225 except AttributeError:
226 pass
227
228 # Use the stat_result constructor with a too-short tuple.
229 try:
230 result2 = os.stat_result((10,))
231 self.fail("No exception thrown")
232 except TypeError:
233 pass
234
235 # Use the constructr with a too-long tuple.
236 try:
237 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
238 except TypeError:
239 pass
240
Tim Peterse0c446b2001-10-18 21:57:37 +0000241
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000242 def test_statvfs_attributes(self):
243 if not hasattr(os, "statvfs"):
244 return
245
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000246 try:
247 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000248 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000249 # On AtheOS, glibc always returns ENOSYS
250 import errno
251 if e.errno == errno.ENOSYS:
252 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000253
254 # Make sure direct access works
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000255 self.assertEquals(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000256
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000257 # Make sure all the attributes are there.
258 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
259 'ffree', 'favail', 'flag', 'namemax')
260 for value, member in enumerate(members):
261 self.assertEquals(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000262
263 # Make sure that assignment really fails
264 try:
265 result.f_bfree = 1
266 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000267 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000268 pass
269
270 try:
271 result.parrot = 1
272 self.fail("No exception thrown")
273 except AttributeError:
274 pass
275
276 # Use the constructor with a too-short tuple.
277 try:
278 result2 = os.statvfs_result((10,))
279 self.fail("No exception thrown")
280 except TypeError:
281 pass
282
283 # Use the constructr with a too-long tuple.
284 try:
285 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
286 except TypeError:
287 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000288
Thomas Wouters89f507f2006-12-13 04:49:30 +0000289 def test_utime_dir(self):
290 delta = 1000000
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000291 st = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000292 # round to int, because some systems may support sub-second
293 # time stamps in stat, but not in utime.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000294 os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
295 st2 = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000296 self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
297
298 # Restrict test to Win32, since there is no guarantee other
299 # systems support centiseconds
300 if sys.platform == 'win32':
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000301 def get_file_system(path):
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000302 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000303 import ctypes
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000304 kernel32 = ctypes.windll.kernel32
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000305 buf = ctypes.create_unicode_buffer("", 100)
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000306 if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000307 return buf.value
308
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000309 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000310 def test_1565150(self):
311 t1 = 1159195039.25
312 os.utime(self.fname, (t1, t1))
313 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000314
Guido van Rossumd8faa362007-04-27 19:54:29 +0000315 def test_1686475(self):
316 # Verify that an open file can be stat'ed
317 try:
318 os.stat(r"c:\pagefile.sys")
319 except WindowsError as e:
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000320 if e.errno == 2: # file does not exist; cannot run test
Guido van Rossumd8faa362007-04-27 19:54:29 +0000321 return
322 self.fail("Could not stat pagefile.sys")
323
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000324from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000325
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000326class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000327 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000328 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000329
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000330 def setUp(self):
331 self.__save = dict(os.environ)
Christian Heimes90333392007-11-01 19:08:42 +0000332 for key, value in self._reference().items():
333 os.environ[key] = value
334
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000335 def tearDown(self):
336 os.environ.clear()
337 os.environ.update(self.__save)
338
Christian Heimes90333392007-11-01 19:08:42 +0000339 def _reference(self):
340 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
341
342 def _empty_mapping(self):
343 os.environ.clear()
344 return os.environ
345
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000346 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000347 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000348 os.environ.clear()
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000349 if os.path.exists("/bin/sh"):
350 os.environ.update(HELLO="World")
351 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
352 self.assertEquals(value, "World")
353
Christian Heimes1a13d592007-11-08 14:16:55 +0000354 def test_os_popen_iter(self):
355 if os.path.exists("/bin/sh"):
356 popen = os.popen("/bin/sh -c 'echo \"line1\nline2\nline3\"'")
357 it = iter(popen)
358 self.assertEquals(next(it), "line1\n")
359 self.assertEquals(next(it), "line2\n")
360 self.assertEquals(next(it), "line3\n")
361 self.assertRaises(StopIteration, next, it)
362
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000363 # Verify environ keys and values from the OS are of the
364 # correct str type.
365 def test_keyvalue_types(self):
366 for key, val in os.environ.items():
367 self.assertEquals(type(key), str)
368 self.assertEquals(type(val), str)
369
Christian Heimes90333392007-11-01 19:08:42 +0000370 def test_items(self):
371 for key, value in self._reference().items():
372 self.assertEqual(os.environ.get(key), value)
373
Tim Petersc4e09402003-04-25 07:11:48 +0000374class WalkTests(unittest.TestCase):
375 """Tests for os.walk()."""
376
377 def test_traversal(self):
378 import os
379 from os.path import join
380
381 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000382 # TESTFN/
383 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000384 # tmp1
385 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000386 # tmp2
387 # SUB11/ no kids
388 # SUB2/ a file kid and a dirsymlink kid
389 # tmp3
390 # link/ a symlink to TESTFN.2
391 # TEST2/
392 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000393 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000394 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000395 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000396 sub2_path = join(walk_path, "SUB2")
397 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000398 tmp2_path = join(sub1_path, "tmp2")
399 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000400 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000401 t2_path = join(support.TESTFN, "TEST2")
402 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000403
404 # Create stuff.
405 os.makedirs(sub11_path)
406 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000407 os.makedirs(t2_path)
408 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000409 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000410 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
411 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000412 if hasattr(os, "symlink"):
413 os.symlink(os.path.abspath(t2_path), link_path)
414 sub2_tree = (sub2_path, ["link"], ["tmp3"])
415 else:
416 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000417
418 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000419 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000420 self.assertEqual(len(all), 4)
421 # We can't know which order SUB1 and SUB2 will appear in.
422 # Not flipped: TESTFN, SUB1, SUB11, SUB2
423 # flipped: TESTFN, SUB2, SUB1, SUB11
424 flipped = all[0][1][0] != "SUB1"
425 all[0][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000426 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000427 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
428 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000429 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000430
431 # Prune the search.
432 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000433 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000434 all.append((root, dirs, files))
435 # Don't descend into SUB1.
436 if 'SUB1' in dirs:
437 # Note that this also mutates the dirs we appended to all!
438 dirs.remove('SUB1')
439 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000440 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
441 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000442
443 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000444 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000445 self.assertEqual(len(all), 4)
446 # We can't know which order SUB1 and SUB2 will appear in.
447 # Not flipped: SUB11, SUB1, SUB2, TESTFN
448 # flipped: SUB2, SUB11, SUB1, TESTFN
449 flipped = all[3][1][0] != "SUB1"
450 all[3][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000451 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000452 self.assertEqual(all[flipped], (sub11_path, [], []))
453 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000454 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000455
Guido van Rossumd8faa362007-04-27 19:54:29 +0000456 if hasattr(os, "symlink"):
457 # Walk, following symlinks.
458 for root, dirs, files in os.walk(walk_path, followlinks=True):
459 if root == link_path:
460 self.assertEqual(dirs, [])
461 self.assertEqual(files, ["tmp4"])
462 break
463 else:
464 self.fail("Didn't follow symlink with followlinks=True")
465
466 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000467 # Tear everything down. This is a decent use for bottom-up on
468 # Windows, which doesn't have a recursive delete command. The
469 # (not so) subtlety is that rmdir will fail unless the dir's
470 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000471 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000472 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000473 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000474 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000475 dirname = os.path.join(root, name)
476 if not os.path.islink(dirname):
477 os.rmdir(dirname)
478 else:
479 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000480 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000481
Guido van Rossume7ba4952007-06-06 23:52:48 +0000482class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000483 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000484 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000485
486 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000487 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000488 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
489 os.makedirs(path) # Should work
490 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
491 os.makedirs(path)
492
493 # Try paths with a '.' in them
494 self.failUnlessRaises(OSError, os.makedirs, os.curdir)
495 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
496 os.makedirs(path)
497 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
498 'dir5', 'dir6')
499 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000500
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000501 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000502 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000503 'dir4', 'dir5', 'dir6')
504 # If the tests failed, the bottom-most directory ('../dir6')
505 # may not have been created, so we look for the outermost directory
506 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000507 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000508 path = os.path.dirname(path)
509
510 os.removedirs(path)
511
Guido van Rossume7ba4952007-06-06 23:52:48 +0000512class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000513 def test_devnull(self):
Alex Martelli01c77c62006-08-24 02:58:11 +0000514 f = open(os.devnull, 'w')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000515 f.write('hello')
516 f.close()
Alex Martelli01c77c62006-08-24 02:58:11 +0000517 f = open(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000518 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000519 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000520
Guido van Rossume7ba4952007-06-06 23:52:48 +0000521class URandomTests(unittest.TestCase):
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000522 def test_urandom(self):
523 try:
524 self.assertEqual(len(os.urandom(1)), 1)
525 self.assertEqual(len(os.urandom(10)), 10)
526 self.assertEqual(len(os.urandom(100)), 100)
527 self.assertEqual(len(os.urandom(1000)), 1000)
528 except NotImplementedError:
529 pass
530
Guido van Rossume7ba4952007-06-06 23:52:48 +0000531class ExecTests(unittest.TestCase):
532 def test_execvpe_with_bad_program(self):
Thomas Hellerbd315c52007-08-30 17:57:21 +0000533 self.assertRaises(OSError, os.execvpe, 'no such app-', ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000534
Thomas Heller6790d602007-08-30 17:15:14 +0000535 def test_execvpe_with_bad_arglist(self):
536 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
537
Thomas Wouters477c8d52006-05-27 19:21:47 +0000538class Win32ErrorTests(unittest.TestCase):
539 def test_rename(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000540 self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000541
542 def test_remove(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000543 self.assertRaises(WindowsError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000544
545 def test_chdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000546 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000547
548 def test_mkdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000549 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000550
551 def test_utime(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000552 self.assertRaises(WindowsError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000553
554 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000555 self.assertRaises(WindowsError, os.utime, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000556
557 def test_chmod(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000558 self.assertRaises(WindowsError, os.utime, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000559
560if sys.platform != 'win32':
561 class Win32ErrorTests(unittest.TestCase):
562 pass
563
Fred Drake2e2be372001-09-20 21:33:42 +0000564def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000565 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000566 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000567 StatAttributeTests,
568 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000569 WalkTests,
570 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000571 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000572 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000573 ExecTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000574 Win32ErrorTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000575 )
Fred Drake2e2be372001-09-20 21:33:42 +0000576
577if __name__ == "__main__":
578 test_main()