blob: ca23dbac85efd777dec8734999566063e2ecf3c3 [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):
302 import os
303 root = os.path.splitdrive(os.path.realpath("."))[0] + '\\'
304 import ctypes
305 kernel32 = ctypes.windll.kernel32
306 buf = ctypes.create_string_buffer("", 100)
307 if kernel32.GetVolumeInformationA(root, None, 0, None, None, None, buf, len(buf)):
308 return buf.value
309
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000310 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000311 def test_1565150(self):
312 t1 = 1159195039.25
313 os.utime(self.fname, (t1, t1))
314 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000315
Guido van Rossumd8faa362007-04-27 19:54:29 +0000316 def test_1686475(self):
317 # Verify that an open file can be stat'ed
318 try:
319 os.stat(r"c:\pagefile.sys")
320 except WindowsError as e:
321 if e == 2: # file does not exist; cannot run test
322 return
323 self.fail("Could not stat pagefile.sys")
324
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000325from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000326
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000327class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000328 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000329 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000330
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000331 def setUp(self):
332 self.__save = dict(os.environ)
Christian Heimes90333392007-11-01 19:08:42 +0000333 for key, value in self._reference().items():
334 os.environ[key] = value
335
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000336 def tearDown(self):
337 os.environ.clear()
338 os.environ.update(self.__save)
339
Christian Heimes90333392007-11-01 19:08:42 +0000340 def _reference(self):
341 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
342
343 def _empty_mapping(self):
344 os.environ.clear()
345 return os.environ
346
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000347 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000348 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000349 os.environ.clear()
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000350 if os.path.exists("/bin/sh"):
351 os.environ.update(HELLO="World")
352 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
353 self.assertEquals(value, "World")
354
Christian Heimes1a13d592007-11-08 14:16:55 +0000355 def test_os_popen_iter(self):
356 if os.path.exists("/bin/sh"):
357 popen = os.popen("/bin/sh -c 'echo \"line1\nline2\nline3\"'")
358 it = iter(popen)
359 self.assertEquals(next(it), "line1\n")
360 self.assertEquals(next(it), "line2\n")
361 self.assertEquals(next(it), "line3\n")
362 self.assertRaises(StopIteration, next, it)
363
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000364 # Verify environ keys and values from the OS are of the
365 # correct str type.
366 def test_keyvalue_types(self):
367 for key, val in os.environ.items():
368 self.assertEquals(type(key), str)
369 self.assertEquals(type(val), str)
370
Christian Heimes90333392007-11-01 19:08:42 +0000371 def test_items(self):
372 for key, value in self._reference().items():
373 self.assertEqual(os.environ.get(key), value)
374
Tim Petersc4e09402003-04-25 07:11:48 +0000375class WalkTests(unittest.TestCase):
376 """Tests for os.walk()."""
377
378 def test_traversal(self):
379 import os
380 from os.path import join
381
382 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000383 # TESTFN/
384 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000385 # tmp1
386 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000387 # tmp2
388 # SUB11/ no kids
389 # SUB2/ a file kid and a dirsymlink kid
390 # tmp3
391 # link/ a symlink to TESTFN.2
392 # TEST2/
393 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000394 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000395 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000396 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000397 sub2_path = join(walk_path, "SUB2")
398 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000399 tmp2_path = join(sub1_path, "tmp2")
400 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000401 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000402 t2_path = join(support.TESTFN, "TEST2")
403 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000404
405 # Create stuff.
406 os.makedirs(sub11_path)
407 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000408 os.makedirs(t2_path)
409 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000410 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000411 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
412 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000413 if hasattr(os, "symlink"):
414 os.symlink(os.path.abspath(t2_path), link_path)
415 sub2_tree = (sub2_path, ["link"], ["tmp3"])
416 else:
417 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000418
419 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000420 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000421 self.assertEqual(len(all), 4)
422 # We can't know which order SUB1 and SUB2 will appear in.
423 # Not flipped: TESTFN, SUB1, SUB11, SUB2
424 # flipped: TESTFN, SUB2, SUB1, SUB11
425 flipped = all[0][1][0] != "SUB1"
426 all[0][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000427 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000428 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
429 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000430 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000431
432 # Prune the search.
433 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000434 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000435 all.append((root, dirs, files))
436 # Don't descend into SUB1.
437 if 'SUB1' in dirs:
438 # Note that this also mutates the dirs we appended to all!
439 dirs.remove('SUB1')
440 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000441 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
442 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000443
444 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000445 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000446 self.assertEqual(len(all), 4)
447 # We can't know which order SUB1 and SUB2 will appear in.
448 # Not flipped: SUB11, SUB1, SUB2, TESTFN
449 # flipped: SUB2, SUB11, SUB1, TESTFN
450 flipped = all[3][1][0] != "SUB1"
451 all[3][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000452 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000453 self.assertEqual(all[flipped], (sub11_path, [], []))
454 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000455 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000456
Guido van Rossumd8faa362007-04-27 19:54:29 +0000457 if hasattr(os, "symlink"):
458 # Walk, following symlinks.
459 for root, dirs, files in os.walk(walk_path, followlinks=True):
460 if root == link_path:
461 self.assertEqual(dirs, [])
462 self.assertEqual(files, ["tmp4"])
463 break
464 else:
465 self.fail("Didn't follow symlink with followlinks=True")
466
467 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000468 # Tear everything down. This is a decent use for bottom-up on
469 # Windows, which doesn't have a recursive delete command. The
470 # (not so) subtlety is that rmdir will fail unless the dir's
471 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000472 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000473 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000474 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000475 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000476 dirname = os.path.join(root, name)
477 if not os.path.islink(dirname):
478 os.rmdir(dirname)
479 else:
480 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000481 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000482
Guido van Rossume7ba4952007-06-06 23:52:48 +0000483class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000484 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000485 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000486
487 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000488 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000489 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
490 os.makedirs(path) # Should work
491 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
492 os.makedirs(path)
493
494 # Try paths with a '.' in them
495 self.failUnlessRaises(OSError, os.makedirs, os.curdir)
496 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
497 os.makedirs(path)
498 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
499 'dir5', 'dir6')
500 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000501
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000502 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000503 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000504 'dir4', 'dir5', 'dir6')
505 # If the tests failed, the bottom-most directory ('../dir6')
506 # may not have been created, so we look for the outermost directory
507 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000508 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000509 path = os.path.dirname(path)
510
511 os.removedirs(path)
512
Guido van Rossume7ba4952007-06-06 23:52:48 +0000513class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000514 def test_devnull(self):
Alex Martelli01c77c62006-08-24 02:58:11 +0000515 f = open(os.devnull, 'w')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000516 f.write('hello')
517 f.close()
Alex Martelli01c77c62006-08-24 02:58:11 +0000518 f = open(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000519 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000520 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000521
Guido van Rossume7ba4952007-06-06 23:52:48 +0000522class URandomTests(unittest.TestCase):
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000523 def test_urandom(self):
524 try:
525 self.assertEqual(len(os.urandom(1)), 1)
526 self.assertEqual(len(os.urandom(10)), 10)
527 self.assertEqual(len(os.urandom(100)), 100)
528 self.assertEqual(len(os.urandom(1000)), 1000)
529 except NotImplementedError:
530 pass
531
Guido van Rossume7ba4952007-06-06 23:52:48 +0000532class ExecTests(unittest.TestCase):
533 def test_execvpe_with_bad_program(self):
Thomas Hellerbd315c52007-08-30 17:57:21 +0000534 self.assertRaises(OSError, os.execvpe, 'no such app-', ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000535
Thomas Heller6790d602007-08-30 17:15:14 +0000536 def test_execvpe_with_bad_arglist(self):
537 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
538
Thomas Wouters477c8d52006-05-27 19:21:47 +0000539class Win32ErrorTests(unittest.TestCase):
540 def test_rename(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000541 self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000542
543 def test_remove(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000544 self.assertRaises(WindowsError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000545
546 def test_chdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000547 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000548
549 def test_mkdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000550 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000551
552 def test_utime(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000553 self.assertRaises(WindowsError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000554
555 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000556 self.assertRaises(WindowsError, os.utime, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000557
558 def test_chmod(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000559 self.assertRaises(WindowsError, os.utime, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000560
561if sys.platform != 'win32':
562 class Win32ErrorTests(unittest.TestCase):
563 pass
564
Fred Drake2e2be372001-09-20 21:33:42 +0000565def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000566 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000567 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000568 StatAttributeTests,
569 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000570 WalkTests,
571 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000572 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000573 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000574 ExecTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000575 Win32ErrorTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000576 )
Fred Drake2e2be372001-09-20 21:33:42 +0000577
578if __name__ == "__main__":
579 test_main()