blob: 50b583162ed2c95507cfbe50a690cdcd9c086cc4 [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
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
Christian Heimesdd15f6c2008-03-16 00:07:10 +000053class TemporaryFileTests(unittest.TestCase):
54 def setUp(self):
55 self.files = []
Benjamin Petersonee8712c2008-05-20 21:35:26 +000056 os.mkdir(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000057
58 def tearDown(self):
59 for name in self.files:
60 os.unlink(name)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000061 os.rmdir(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000062
63 def check_tempfile(self, name):
64 # make sure it doesn't already exist:
65 self.failIf(os.path.exists(name),
66 "file already exists for temporary file")
67 # make sure we can create the file
68 open(name, "w")
69 self.files.append(name)
70
71 def test_tempnam(self):
72 if not hasattr(os, "tempnam"):
73 return
74 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
75 r"test_os$")
76 self.check_tempfile(os.tempnam())
77
Benjamin Petersonee8712c2008-05-20 21:35:26 +000078 name = os.tempnam(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000079 self.check_tempfile(name)
80
Benjamin Petersonee8712c2008-05-20 21:35:26 +000081 name = os.tempnam(support.TESTFN, "pfx")
Christian Heimesdd15f6c2008-03-16 00:07:10 +000082 self.assert_(os.path.basename(name)[:3] == "pfx")
83 self.check_tempfile(name)
84
85 def test_tmpfile(self):
86 if not hasattr(os, "tmpfile"):
87 return
88 # As with test_tmpnam() below, the Windows implementation of tmpfile()
89 # attempts to create a file in the root directory of the current drive.
90 # On Vista and Server 2008, this test will always fail for normal users
91 # as writing to the root directory requires elevated privileges. With
92 # XP and below, the semantics of tmpfile() are the same, but the user
93 # running the test is more likely to have administrative privileges on
94 # their account already. If that's the case, then os.tmpfile() should
95 # work. In order to make this test as useful as possible, rather than
96 # trying to detect Windows versions or whether or not the user has the
97 # right permissions, just try and create a file in the root directory
98 # and see if it raises a 'Permission denied' OSError. If it does, then
99 # test that a subsequent call to os.tmpfile() raises the same error. If
100 # it doesn't, assume we're on XP or below and the user running the test
101 # has administrative privileges, and proceed with the test as normal.
102 if sys.platform == 'win32':
103 name = '\\python_test_os_test_tmpfile.txt'
104 if os.path.exists(name):
105 os.remove(name)
106 try:
107 fp = open(name, 'w')
108 except IOError as first:
109 # open() failed, assert tmpfile() fails in the same way.
110 # Although open() raises an IOError and os.tmpfile() raises an
111 # OSError(), 'args' will be (13, 'Permission denied') in both
112 # cases.
113 try:
114 fp = os.tmpfile()
115 except OSError as second:
116 self.assertEqual(first.args, second.args)
117 else:
118 self.fail("expected os.tmpfile() to raise OSError")
119 return
120 else:
121 # open() worked, therefore, tmpfile() should work. Close our
122 # dummy file and proceed with the test as normal.
123 fp.close()
124 os.remove(name)
125
126 fp = os.tmpfile()
127 fp.write("foobar")
128 fp.seek(0,0)
129 s = fp.read()
130 fp.close()
131 self.assert_(s == "foobar")
132
133 def test_tmpnam(self):
134 import sys
135 if not hasattr(os, "tmpnam"):
136 return
137 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
138 r"test_os$")
139 name = os.tmpnam()
140 if sys.platform in ("win32",):
141 # The Windows tmpnam() seems useless. From the MS docs:
142 #
143 # The character string that tmpnam creates consists of
144 # the path prefix, defined by the entry P_tmpdir in the
145 # file STDIO.H, followed by a sequence consisting of the
146 # digit characters '0' through '9'; the numerical value
147 # of this string is in the range 1 - 65,535. Changing the
148 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
149 # change the operation of tmpnam.
150 #
151 # The really bizarre part is that, at least under MSVC6,
152 # P_tmpdir is "\\". That is, the path returned refers to
153 # the root of the current drive. That's a terrible place to
154 # put temp files, and, depending on privileges, the user
155 # may not even be able to open a file in the root directory.
156 self.failIf(os.path.exists(name),
157 "file already exists for temporary file")
158 else:
159 self.check_tempfile(name)
160
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000161 def fdopen_helper(self, *args):
162 fd = os.open(support.TESTFN, os.O_RDONLY)
163 fp2 = os.fdopen(fd, *args)
164 fp2.close()
165
166 def test_fdopen(self):
167 self.fdopen_helper()
168 self.fdopen_helper('r')
169 self.fdopen_helper('r', 100)
170
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000171# Test attributes on return values from os.*stat* family.
172class StatAttributeTests(unittest.TestCase):
173 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000174 os.mkdir(support.TESTFN)
175 self.fname = os.path.join(support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000176 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +0000177 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000178 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000179
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000180 def tearDown(self):
181 os.unlink(self.fname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000182 os.rmdir(support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000183
184 def test_stat_attributes(self):
185 if not hasattr(os, "stat"):
186 return
187
188 import stat
189 result = os.stat(self.fname)
190
191 # Make sure direct access works
192 self.assertEquals(result[stat.ST_SIZE], 3)
193 self.assertEquals(result.st_size, 3)
194
195 import sys
196
197 # Make sure all the attributes are there
198 members = dir(result)
199 for name in dir(stat):
200 if name[:3] == 'ST_':
201 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000202 if name.endswith("TIME"):
203 def trunc(x): return int(x)
204 else:
205 def trunc(x): return x
206 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000207 result[getattr(stat, name)])
208 self.assert_(attr in members)
209
210 try:
211 result[200]
212 self.fail("No exception thrown")
213 except IndexError:
214 pass
215
216 # Make sure that assignment fails
217 try:
218 result.st_mode = 1
219 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000220 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000221 pass
222
223 try:
224 result.st_rdev = 1
225 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000226 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000227 pass
228
229 try:
230 result.parrot = 1
231 self.fail("No exception thrown")
232 except AttributeError:
233 pass
234
235 # Use the stat_result constructor with a too-short tuple.
236 try:
237 result2 = os.stat_result((10,))
238 self.fail("No exception thrown")
239 except TypeError:
240 pass
241
242 # Use the constructr with a too-long tuple.
243 try:
244 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
245 except TypeError:
246 pass
247
Tim Peterse0c446b2001-10-18 21:57:37 +0000248
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000249 def test_statvfs_attributes(self):
250 if not hasattr(os, "statvfs"):
251 return
252
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000253 try:
254 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000255 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000256 # On AtheOS, glibc always returns ENOSYS
257 import errno
258 if e.errno == errno.ENOSYS:
259 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000260
261 # Make sure direct access works
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000262 self.assertEquals(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000263
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000264 # Make sure all the attributes are there.
265 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
266 'ffree', 'favail', 'flag', 'namemax')
267 for value, member in enumerate(members):
268 self.assertEquals(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000269
270 # Make sure that assignment really fails
271 try:
272 result.f_bfree = 1
273 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000274 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000275 pass
276
277 try:
278 result.parrot = 1
279 self.fail("No exception thrown")
280 except AttributeError:
281 pass
282
283 # Use the constructor with a too-short tuple.
284 try:
285 result2 = os.statvfs_result((10,))
286 self.fail("No exception thrown")
287 except TypeError:
288 pass
289
290 # Use the constructr with a too-long tuple.
291 try:
292 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
293 except TypeError:
294 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000295
Thomas Wouters89f507f2006-12-13 04:49:30 +0000296 def test_utime_dir(self):
297 delta = 1000000
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000298 st = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000299 # round to int, because some systems may support sub-second
300 # time stamps in stat, but not in utime.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000301 os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
302 st2 = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000303 self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
304
305 # Restrict test to Win32, since there is no guarantee other
306 # systems support centiseconds
307 if sys.platform == 'win32':
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000308 def get_file_system(path):
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000309 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000310 import ctypes
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000311 kernel32 = ctypes.windll.kernel32
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000312 buf = ctypes.create_unicode_buffer("", 100)
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000313 if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000314 return buf.value
315
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000316 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000317 def test_1565150(self):
318 t1 = 1159195039.25
319 os.utime(self.fname, (t1, t1))
320 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000321
Guido van Rossumd8faa362007-04-27 19:54:29 +0000322 def test_1686475(self):
323 # Verify that an open file can be stat'ed
324 try:
325 os.stat(r"c:\pagefile.sys")
326 except WindowsError as e:
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000327 if e.errno == 2: # file does not exist; cannot run test
Guido van Rossumd8faa362007-04-27 19:54:29 +0000328 return
329 self.fail("Could not stat pagefile.sys")
330
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000331from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000332
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000333class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000334 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000335 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000336
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000337 def setUp(self):
338 self.__save = dict(os.environ)
Christian Heimes90333392007-11-01 19:08:42 +0000339 for key, value in self._reference().items():
340 os.environ[key] = value
341
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000342 def tearDown(self):
343 os.environ.clear()
344 os.environ.update(self.__save)
345
Christian Heimes90333392007-11-01 19:08:42 +0000346 def _reference(self):
347 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
348
349 def _empty_mapping(self):
350 os.environ.clear()
351 return os.environ
352
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000353 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000354 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000355 os.environ.clear()
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000356 if os.path.exists("/bin/sh"):
357 os.environ.update(HELLO="World")
358 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
359 self.assertEquals(value, "World")
360
Christian Heimes1a13d592007-11-08 14:16:55 +0000361 def test_os_popen_iter(self):
362 if os.path.exists("/bin/sh"):
363 popen = os.popen("/bin/sh -c 'echo \"line1\nline2\nline3\"'")
364 it = iter(popen)
365 self.assertEquals(next(it), "line1\n")
366 self.assertEquals(next(it), "line2\n")
367 self.assertEquals(next(it), "line3\n")
368 self.assertRaises(StopIteration, next, it)
369
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000370 # Verify environ keys and values from the OS are of the
371 # correct str type.
372 def test_keyvalue_types(self):
373 for key, val in os.environ.items():
374 self.assertEquals(type(key), str)
375 self.assertEquals(type(val), str)
376
Christian Heimes90333392007-11-01 19:08:42 +0000377 def test_items(self):
378 for key, value in self._reference().items():
379 self.assertEqual(os.environ.get(key), value)
380
Tim Petersc4e09402003-04-25 07:11:48 +0000381class WalkTests(unittest.TestCase):
382 """Tests for os.walk()."""
383
384 def test_traversal(self):
385 import os
386 from os.path import join
387
388 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000389 # TESTFN/
390 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000391 # tmp1
392 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000393 # tmp2
394 # SUB11/ no kids
395 # SUB2/ a file kid and a dirsymlink kid
396 # tmp3
397 # link/ a symlink to TESTFN.2
398 # TEST2/
399 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000400 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000401 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000402 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000403 sub2_path = join(walk_path, "SUB2")
404 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000405 tmp2_path = join(sub1_path, "tmp2")
406 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000407 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000408 t2_path = join(support.TESTFN, "TEST2")
409 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000410
411 # Create stuff.
412 os.makedirs(sub11_path)
413 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000414 os.makedirs(t2_path)
415 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000416 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000417 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
418 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000419 if hasattr(os, "symlink"):
420 os.symlink(os.path.abspath(t2_path), link_path)
421 sub2_tree = (sub2_path, ["link"], ["tmp3"])
422 else:
423 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000424
425 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000426 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000427 self.assertEqual(len(all), 4)
428 # We can't know which order SUB1 and SUB2 will appear in.
429 # Not flipped: TESTFN, SUB1, SUB11, SUB2
430 # flipped: TESTFN, SUB2, SUB1, SUB11
431 flipped = all[0][1][0] != "SUB1"
432 all[0][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000433 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000434 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
435 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000436 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000437
438 # Prune the search.
439 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000440 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000441 all.append((root, dirs, files))
442 # Don't descend into SUB1.
443 if 'SUB1' in dirs:
444 # Note that this also mutates the dirs we appended to all!
445 dirs.remove('SUB1')
446 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000447 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
448 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000449
450 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000451 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000452 self.assertEqual(len(all), 4)
453 # We can't know which order SUB1 and SUB2 will appear in.
454 # Not flipped: SUB11, SUB1, SUB2, TESTFN
455 # flipped: SUB2, SUB11, SUB1, TESTFN
456 flipped = all[3][1][0] != "SUB1"
457 all[3][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000458 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000459 self.assertEqual(all[flipped], (sub11_path, [], []))
460 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000461 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000462
Guido van Rossumd8faa362007-04-27 19:54:29 +0000463 if hasattr(os, "symlink"):
464 # Walk, following symlinks.
465 for root, dirs, files in os.walk(walk_path, followlinks=True):
466 if root == link_path:
467 self.assertEqual(dirs, [])
468 self.assertEqual(files, ["tmp4"])
469 break
470 else:
471 self.fail("Didn't follow symlink with followlinks=True")
472
473 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000474 # Tear everything down. This is a decent use for bottom-up on
475 # Windows, which doesn't have a recursive delete command. The
476 # (not so) subtlety is that rmdir will fail unless the dir's
477 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000478 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000479 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000480 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000481 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000482 dirname = os.path.join(root, name)
483 if not os.path.islink(dirname):
484 os.rmdir(dirname)
485 else:
486 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000487 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000488
Guido van Rossume7ba4952007-06-06 23:52:48 +0000489class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000490 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000491 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000492
493 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000494 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000495 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
496 os.makedirs(path) # Should work
497 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
498 os.makedirs(path)
499
500 # Try paths with a '.' in them
501 self.failUnlessRaises(OSError, os.makedirs, os.curdir)
502 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
503 os.makedirs(path)
504 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
505 'dir5', 'dir6')
506 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000507
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000508 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000509 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000510 'dir4', 'dir5', 'dir6')
511 # If the tests failed, the bottom-most directory ('../dir6')
512 # may not have been created, so we look for the outermost directory
513 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000514 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000515 path = os.path.dirname(path)
516
517 os.removedirs(path)
518
Guido van Rossume7ba4952007-06-06 23:52:48 +0000519class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000520 def test_devnull(self):
Alex Martelli01c77c62006-08-24 02:58:11 +0000521 f = open(os.devnull, 'w')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000522 f.write('hello')
523 f.close()
Alex Martelli01c77c62006-08-24 02:58:11 +0000524 f = open(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000525 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000526 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000527
Guido van Rossume7ba4952007-06-06 23:52:48 +0000528class URandomTests(unittest.TestCase):
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000529 def test_urandom(self):
530 try:
531 self.assertEqual(len(os.urandom(1)), 1)
532 self.assertEqual(len(os.urandom(10)), 10)
533 self.assertEqual(len(os.urandom(100)), 100)
534 self.assertEqual(len(os.urandom(1000)), 1000)
535 except NotImplementedError:
536 pass
537
Guido van Rossume7ba4952007-06-06 23:52:48 +0000538class ExecTests(unittest.TestCase):
539 def test_execvpe_with_bad_program(self):
Thomas Hellerbd315c52007-08-30 17:57:21 +0000540 self.assertRaises(OSError, os.execvpe, 'no such app-', ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000541
Thomas Heller6790d602007-08-30 17:15:14 +0000542 def test_execvpe_with_bad_arglist(self):
543 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
544
Thomas Wouters477c8d52006-05-27 19:21:47 +0000545class Win32ErrorTests(unittest.TestCase):
546 def test_rename(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000547 self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000548
549 def test_remove(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000550 self.assertRaises(WindowsError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000551
552 def test_chdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000553 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000554
555 def test_mkdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000556 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000557
558 def test_utime(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000559 self.assertRaises(WindowsError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000560
561 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000562 self.assertRaises(WindowsError, os.utime, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000563
564 def test_chmod(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000565 self.assertRaises(WindowsError, os.utime, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000566
567if sys.platform != 'win32':
568 class Win32ErrorTests(unittest.TestCase):
569 pass
570
Fred Drake2e2be372001-09-20 21:33:42 +0000571def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000572 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000573 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000574 StatAttributeTests,
575 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000576 WalkTests,
577 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000578 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000579 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000580 ExecTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000581 Win32ErrorTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000582 )
Fred Drake2e2be372001-09-20 21:33:42 +0000583
584if __name__ == "__main__":
585 test_main()