blob: c5667054046599b0f8eadf8ed842c2bf463caffb [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 Yamamoto5ef6d182008-08-20 04:17:24 +0000304 from ctypes.wintypes import LPCWSTR, LPWSTR, DWORD
305 LPDWORD = ctypes.POINTER(DWORD)
306 f = ctypes.windll.kernel32.GetVolumeInformationW
307 f.argtypes = (LPCWSTR, LPWSTR, DWORD,
308 LPDWORD, LPDWORD, LPDWORD, LPWSTR, DWORD)
309 buf = ctypes.create_unicode_buffer("", 100)
310 if f(root, None, 0, None, None, None, buf, len(buf)):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000311 return buf.value
312
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000313 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000314 def test_1565150(self):
315 t1 = 1159195039.25
316 os.utime(self.fname, (t1, t1))
317 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000318
Guido van Rossumd8faa362007-04-27 19:54:29 +0000319 def test_1686475(self):
320 # Verify that an open file can be stat'ed
321 try:
322 os.stat(r"c:\pagefile.sys")
323 except WindowsError as e:
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000324 if e.errno == 2: # file does not exist; cannot run test
Guido van Rossumd8faa362007-04-27 19:54:29 +0000325 return
326 self.fail("Could not stat pagefile.sys")
327
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000328from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000329
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000330class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000331 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000332 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000333
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000334 def setUp(self):
335 self.__save = dict(os.environ)
Christian Heimes90333392007-11-01 19:08:42 +0000336 for key, value in self._reference().items():
337 os.environ[key] = value
338
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000339 def tearDown(self):
340 os.environ.clear()
341 os.environ.update(self.__save)
342
Christian Heimes90333392007-11-01 19:08:42 +0000343 def _reference(self):
344 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
345
346 def _empty_mapping(self):
347 os.environ.clear()
348 return os.environ
349
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000350 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000351 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000352 os.environ.clear()
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000353 if os.path.exists("/bin/sh"):
354 os.environ.update(HELLO="World")
355 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
356 self.assertEquals(value, "World")
357
Christian Heimes1a13d592007-11-08 14:16:55 +0000358 def test_os_popen_iter(self):
359 if os.path.exists("/bin/sh"):
360 popen = os.popen("/bin/sh -c 'echo \"line1\nline2\nline3\"'")
361 it = iter(popen)
362 self.assertEquals(next(it), "line1\n")
363 self.assertEquals(next(it), "line2\n")
364 self.assertEquals(next(it), "line3\n")
365 self.assertRaises(StopIteration, next, it)
366
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000367 # Verify environ keys and values from the OS are of the
368 # correct str type.
369 def test_keyvalue_types(self):
370 for key, val in os.environ.items():
371 self.assertEquals(type(key), str)
372 self.assertEquals(type(val), str)
373
Christian Heimes90333392007-11-01 19:08:42 +0000374 def test_items(self):
375 for key, value in self._reference().items():
376 self.assertEqual(os.environ.get(key), value)
377
Tim Petersc4e09402003-04-25 07:11:48 +0000378class WalkTests(unittest.TestCase):
379 """Tests for os.walk()."""
380
381 def test_traversal(self):
382 import os
383 from os.path import join
384
385 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000386 # TESTFN/
387 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000388 # tmp1
389 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000390 # tmp2
391 # SUB11/ no kids
392 # SUB2/ a file kid and a dirsymlink kid
393 # tmp3
394 # link/ a symlink to TESTFN.2
395 # TEST2/
396 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000397 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000398 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000399 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000400 sub2_path = join(walk_path, "SUB2")
401 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000402 tmp2_path = join(sub1_path, "tmp2")
403 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000404 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000405 t2_path = join(support.TESTFN, "TEST2")
406 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000407
408 # Create stuff.
409 os.makedirs(sub11_path)
410 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000411 os.makedirs(t2_path)
412 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000413 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000414 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
415 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000416 if hasattr(os, "symlink"):
417 os.symlink(os.path.abspath(t2_path), link_path)
418 sub2_tree = (sub2_path, ["link"], ["tmp3"])
419 else:
420 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000421
422 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000423 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000424 self.assertEqual(len(all), 4)
425 # We can't know which order SUB1 and SUB2 will appear in.
426 # Not flipped: TESTFN, SUB1, SUB11, SUB2
427 # flipped: TESTFN, SUB2, SUB1, SUB11
428 flipped = all[0][1][0] != "SUB1"
429 all[0][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000430 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000431 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
432 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000433 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000434
435 # Prune the search.
436 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000437 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000438 all.append((root, dirs, files))
439 # Don't descend into SUB1.
440 if 'SUB1' in dirs:
441 # Note that this also mutates the dirs we appended to all!
442 dirs.remove('SUB1')
443 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000444 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
445 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000446
447 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000448 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000449 self.assertEqual(len(all), 4)
450 # We can't know which order SUB1 and SUB2 will appear in.
451 # Not flipped: SUB11, SUB1, SUB2, TESTFN
452 # flipped: SUB2, SUB11, SUB1, TESTFN
453 flipped = all[3][1][0] != "SUB1"
454 all[3][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000455 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000456 self.assertEqual(all[flipped], (sub11_path, [], []))
457 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000458 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000459
Guido van Rossumd8faa362007-04-27 19:54:29 +0000460 if hasattr(os, "symlink"):
461 # Walk, following symlinks.
462 for root, dirs, files in os.walk(walk_path, followlinks=True):
463 if root == link_path:
464 self.assertEqual(dirs, [])
465 self.assertEqual(files, ["tmp4"])
466 break
467 else:
468 self.fail("Didn't follow symlink with followlinks=True")
469
470 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000471 # Tear everything down. This is a decent use for bottom-up on
472 # Windows, which doesn't have a recursive delete command. The
473 # (not so) subtlety is that rmdir will fail unless the dir's
474 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000475 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000476 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000477 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000478 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000479 dirname = os.path.join(root, name)
480 if not os.path.islink(dirname):
481 os.rmdir(dirname)
482 else:
483 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000484 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000485
Guido van Rossume7ba4952007-06-06 23:52:48 +0000486class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000487 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000488 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000489
490 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000491 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000492 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
493 os.makedirs(path) # Should work
494 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
495 os.makedirs(path)
496
497 # Try paths with a '.' in them
498 self.failUnlessRaises(OSError, os.makedirs, os.curdir)
499 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
500 os.makedirs(path)
501 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
502 'dir5', 'dir6')
503 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000504
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000505 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000506 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000507 'dir4', 'dir5', 'dir6')
508 # If the tests failed, the bottom-most directory ('../dir6')
509 # may not have been created, so we look for the outermost directory
510 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000511 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000512 path = os.path.dirname(path)
513
514 os.removedirs(path)
515
Guido van Rossume7ba4952007-06-06 23:52:48 +0000516class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000517 def test_devnull(self):
Alex Martelli01c77c62006-08-24 02:58:11 +0000518 f = open(os.devnull, 'w')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000519 f.write('hello')
520 f.close()
Alex Martelli01c77c62006-08-24 02:58:11 +0000521 f = open(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000522 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000523 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000524
Guido van Rossume7ba4952007-06-06 23:52:48 +0000525class URandomTests(unittest.TestCase):
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000526 def test_urandom(self):
527 try:
528 self.assertEqual(len(os.urandom(1)), 1)
529 self.assertEqual(len(os.urandom(10)), 10)
530 self.assertEqual(len(os.urandom(100)), 100)
531 self.assertEqual(len(os.urandom(1000)), 1000)
532 except NotImplementedError:
533 pass
534
Guido van Rossume7ba4952007-06-06 23:52:48 +0000535class ExecTests(unittest.TestCase):
536 def test_execvpe_with_bad_program(self):
Thomas Hellerbd315c52007-08-30 17:57:21 +0000537 self.assertRaises(OSError, os.execvpe, 'no such app-', ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000538
Thomas Heller6790d602007-08-30 17:15:14 +0000539 def test_execvpe_with_bad_arglist(self):
540 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
541
Thomas Wouters477c8d52006-05-27 19:21:47 +0000542class Win32ErrorTests(unittest.TestCase):
543 def test_rename(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000544 self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000545
546 def test_remove(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000547 self.assertRaises(WindowsError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000548
549 def test_chdir(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_mkdir(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_utime(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000556 self.assertRaises(WindowsError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000557
558 def test_access(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
561 def test_chmod(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
564if sys.platform != 'win32':
565 class Win32ErrorTests(unittest.TestCase):
566 pass
567
Fred Drake2e2be372001-09-20 21:33:42 +0000568def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000569 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000570 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000571 StatAttributeTests,
572 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000573 WalkTests,
574 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000575 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000576 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000577 ExecTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000578 Win32ErrorTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000579 )
Fred Drake2e2be372001-09-20 21:33:42 +0000580
581if __name__ == "__main__":
582 test_main()