blob: 09270e10f8ab7aac46a3bed9ed426e9c1cfd2cf8 [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):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000024 f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
Christian Heimesfdab48e2008-01-20 09:06:41 +000025 # close a fd that is open, and one that isn't
26 os.closerange(f, f+2)
27 self.assertRaises(OSError, os.write, f, "a")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000028
Christian Heimesdd15f6c2008-03-16 00:07:10 +000029class TemporaryFileTests(unittest.TestCase):
30 def setUp(self):
31 self.files = []
Benjamin Petersonee8712c2008-05-20 21:35:26 +000032 os.mkdir(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000033
34 def tearDown(self):
35 for name in self.files:
36 os.unlink(name)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000037 os.rmdir(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000038
39 def check_tempfile(self, name):
40 # make sure it doesn't already exist:
41 self.failIf(os.path.exists(name),
42 "file already exists for temporary file")
43 # make sure we can create the file
44 open(name, "w")
45 self.files.append(name)
46
47 def test_tempnam(self):
48 if not hasattr(os, "tempnam"):
49 return
50 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
51 r"test_os$")
52 self.check_tempfile(os.tempnam())
53
Benjamin Petersonee8712c2008-05-20 21:35:26 +000054 name = os.tempnam(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000055 self.check_tempfile(name)
56
Benjamin Petersonee8712c2008-05-20 21:35:26 +000057 name = os.tempnam(support.TESTFN, "pfx")
Christian Heimesdd15f6c2008-03-16 00:07:10 +000058 self.assert_(os.path.basename(name)[:3] == "pfx")
59 self.check_tempfile(name)
60
61 def test_tmpfile(self):
62 if not hasattr(os, "tmpfile"):
63 return
64 # As with test_tmpnam() below, the Windows implementation of tmpfile()
65 # attempts to create a file in the root directory of the current drive.
66 # On Vista and Server 2008, this test will always fail for normal users
67 # as writing to the root directory requires elevated privileges. With
68 # XP and below, the semantics of tmpfile() are the same, but the user
69 # running the test is more likely to have administrative privileges on
70 # their account already. If that's the case, then os.tmpfile() should
71 # work. In order to make this test as useful as possible, rather than
72 # trying to detect Windows versions or whether or not the user has the
73 # right permissions, just try and create a file in the root directory
74 # and see if it raises a 'Permission denied' OSError. If it does, then
75 # test that a subsequent call to os.tmpfile() raises the same error. If
76 # it doesn't, assume we're on XP or below and the user running the test
77 # has administrative privileges, and proceed with the test as normal.
78 if sys.platform == 'win32':
79 name = '\\python_test_os_test_tmpfile.txt'
80 if os.path.exists(name):
81 os.remove(name)
82 try:
83 fp = open(name, 'w')
84 except IOError as first:
85 # open() failed, assert tmpfile() fails in the same way.
86 # Although open() raises an IOError and os.tmpfile() raises an
87 # OSError(), 'args' will be (13, 'Permission denied') in both
88 # cases.
89 try:
90 fp = os.tmpfile()
91 except OSError as second:
92 self.assertEqual(first.args, second.args)
93 else:
94 self.fail("expected os.tmpfile() to raise OSError")
95 return
96 else:
97 # open() worked, therefore, tmpfile() should work. Close our
98 # dummy file and proceed with the test as normal.
99 fp.close()
100 os.remove(name)
101
102 fp = os.tmpfile()
103 fp.write("foobar")
104 fp.seek(0,0)
105 s = fp.read()
106 fp.close()
107 self.assert_(s == "foobar")
108
109 def test_tmpnam(self):
110 import sys
111 if not hasattr(os, "tmpnam"):
112 return
113 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
114 r"test_os$")
115 name = os.tmpnam()
116 if sys.platform in ("win32",):
117 # The Windows tmpnam() seems useless. From the MS docs:
118 #
119 # The character string that tmpnam creates consists of
120 # the path prefix, defined by the entry P_tmpdir in the
121 # file STDIO.H, followed by a sequence consisting of the
122 # digit characters '0' through '9'; the numerical value
123 # of this string is in the range 1 - 65,535. Changing the
124 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
125 # change the operation of tmpnam.
126 #
127 # The really bizarre part is that, at least under MSVC6,
128 # P_tmpdir is "\\". That is, the path returned refers to
129 # the root of the current drive. That's a terrible place to
130 # put temp files, and, depending on privileges, the user
131 # may not even be able to open a file in the root directory.
132 self.failIf(os.path.exists(name),
133 "file already exists for temporary file")
134 else:
135 self.check_tempfile(name)
136
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000137 def fdopen_helper(self, *args):
138 fd = os.open(support.TESTFN, os.O_RDONLY)
139 fp2 = os.fdopen(fd, *args)
140 fp2.close()
141
142 def test_fdopen(self):
143 self.fdopen_helper()
144 self.fdopen_helper('r')
145 self.fdopen_helper('r', 100)
146
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000147# Test attributes on return values from os.*stat* family.
148class StatAttributeTests(unittest.TestCase):
149 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000150 os.mkdir(support.TESTFN)
151 self.fname = os.path.join(support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000152 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +0000153 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000154 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000155
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000156 def tearDown(self):
157 os.unlink(self.fname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000158 os.rmdir(support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000159
160 def test_stat_attributes(self):
161 if not hasattr(os, "stat"):
162 return
163
164 import stat
165 result = os.stat(self.fname)
166
167 # Make sure direct access works
168 self.assertEquals(result[stat.ST_SIZE], 3)
169 self.assertEquals(result.st_size, 3)
170
171 import sys
172
173 # Make sure all the attributes are there
174 members = dir(result)
175 for name in dir(stat):
176 if name[:3] == 'ST_':
177 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000178 if name.endswith("TIME"):
179 def trunc(x): return int(x)
180 else:
181 def trunc(x): return x
182 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000183 result[getattr(stat, name)])
184 self.assert_(attr in members)
185
186 try:
187 result[200]
188 self.fail("No exception thrown")
189 except IndexError:
190 pass
191
192 # Make sure that assignment fails
193 try:
194 result.st_mode = 1
195 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000196 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000197 pass
198
199 try:
200 result.st_rdev = 1
201 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000202 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000203 pass
204
205 try:
206 result.parrot = 1
207 self.fail("No exception thrown")
208 except AttributeError:
209 pass
210
211 # Use the stat_result constructor with a too-short tuple.
212 try:
213 result2 = os.stat_result((10,))
214 self.fail("No exception thrown")
215 except TypeError:
216 pass
217
218 # Use the constructr with a too-long tuple.
219 try:
220 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
221 except TypeError:
222 pass
223
Tim Peterse0c446b2001-10-18 21:57:37 +0000224
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000225 def test_statvfs_attributes(self):
226 if not hasattr(os, "statvfs"):
227 return
228
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000229 try:
230 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000231 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000232 # On AtheOS, glibc always returns ENOSYS
233 import errno
234 if e.errno == errno.ENOSYS:
235 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000236
237 # Make sure direct access works
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000238 self.assertEquals(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000239
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000240 # Make sure all the attributes are there.
241 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
242 'ffree', 'favail', 'flag', 'namemax')
243 for value, member in enumerate(members):
244 self.assertEquals(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000245
246 # Make sure that assignment really fails
247 try:
248 result.f_bfree = 1
249 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000250 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000251 pass
252
253 try:
254 result.parrot = 1
255 self.fail("No exception thrown")
256 except AttributeError:
257 pass
258
259 # Use the constructor with a too-short tuple.
260 try:
261 result2 = os.statvfs_result((10,))
262 self.fail("No exception thrown")
263 except TypeError:
264 pass
265
266 # Use the constructr with a too-long tuple.
267 try:
268 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
269 except TypeError:
270 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000271
Thomas Wouters89f507f2006-12-13 04:49:30 +0000272 def test_utime_dir(self):
273 delta = 1000000
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000274 st = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000275 # round to int, because some systems may support sub-second
276 # time stamps in stat, but not in utime.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000277 os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
278 st2 = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000279 self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
280
281 # Restrict test to Win32, since there is no guarantee other
282 # systems support centiseconds
283 if sys.platform == 'win32':
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000284 def get_file_system(path):
285 import os
286 root = os.path.splitdrive(os.path.realpath("."))[0] + '\\'
287 import ctypes
288 kernel32 = ctypes.windll.kernel32
289 buf = ctypes.create_string_buffer("", 100)
290 if kernel32.GetVolumeInformationA(root, None, 0, None, None, None, buf, len(buf)):
291 return buf.value
292
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000293 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000294 def test_1565150(self):
295 t1 = 1159195039.25
296 os.utime(self.fname, (t1, t1))
297 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000298
Guido van Rossumd8faa362007-04-27 19:54:29 +0000299 def test_1686475(self):
300 # Verify that an open file can be stat'ed
301 try:
302 os.stat(r"c:\pagefile.sys")
303 except WindowsError as e:
304 if e == 2: # file does not exist; cannot run test
305 return
306 self.fail("Could not stat pagefile.sys")
307
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000308from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000309
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000310class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000311 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000312 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000313
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000314 def setUp(self):
315 self.__save = dict(os.environ)
Christian Heimes90333392007-11-01 19:08:42 +0000316 for key, value in self._reference().items():
317 os.environ[key] = value
318
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000319 def tearDown(self):
320 os.environ.clear()
321 os.environ.update(self.__save)
322
Christian Heimes90333392007-11-01 19:08:42 +0000323 def _reference(self):
324 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
325
326 def _empty_mapping(self):
327 os.environ.clear()
328 return os.environ
329
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000330 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000331 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000332 os.environ.clear()
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000333 if os.path.exists("/bin/sh"):
334 os.environ.update(HELLO="World")
335 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
336 self.assertEquals(value, "World")
337
Christian Heimes1a13d592007-11-08 14:16:55 +0000338 def test_os_popen_iter(self):
339 if os.path.exists("/bin/sh"):
340 popen = os.popen("/bin/sh -c 'echo \"line1\nline2\nline3\"'")
341 it = iter(popen)
342 self.assertEquals(next(it), "line1\n")
343 self.assertEquals(next(it), "line2\n")
344 self.assertEquals(next(it), "line3\n")
345 self.assertRaises(StopIteration, next, it)
346
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000347 # Verify environ keys and values from the OS are of the
348 # correct str type.
349 def test_keyvalue_types(self):
350 for key, val in os.environ.items():
351 self.assertEquals(type(key), str)
352 self.assertEquals(type(val), str)
353
Christian Heimes90333392007-11-01 19:08:42 +0000354 def test_items(self):
355 for key, value in self._reference().items():
356 self.assertEqual(os.environ.get(key), value)
357
Tim Petersc4e09402003-04-25 07:11:48 +0000358class WalkTests(unittest.TestCase):
359 """Tests for os.walk()."""
360
361 def test_traversal(self):
362 import os
363 from os.path import join
364
365 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000366 # TESTFN/
367 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000368 # tmp1
369 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000370 # tmp2
371 # SUB11/ no kids
372 # SUB2/ a file kid and a dirsymlink kid
373 # tmp3
374 # link/ a symlink to TESTFN.2
375 # TEST2/
376 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000377 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000378 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000379 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000380 sub2_path = join(walk_path, "SUB2")
381 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000382 tmp2_path = join(sub1_path, "tmp2")
383 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000384 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000385 t2_path = join(support.TESTFN, "TEST2")
386 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000387
388 # Create stuff.
389 os.makedirs(sub11_path)
390 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000391 os.makedirs(t2_path)
392 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000393 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000394 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
395 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000396 if hasattr(os, "symlink"):
397 os.symlink(os.path.abspath(t2_path), link_path)
398 sub2_tree = (sub2_path, ["link"], ["tmp3"])
399 else:
400 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000401
402 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000403 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000404 self.assertEqual(len(all), 4)
405 # We can't know which order SUB1 and SUB2 will appear in.
406 # Not flipped: TESTFN, SUB1, SUB11, SUB2
407 # flipped: TESTFN, SUB2, SUB1, SUB11
408 flipped = all[0][1][0] != "SUB1"
409 all[0][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000410 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000411 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
412 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000413 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000414
415 # Prune the search.
416 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000417 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000418 all.append((root, dirs, files))
419 # Don't descend into SUB1.
420 if 'SUB1' in dirs:
421 # Note that this also mutates the dirs we appended to all!
422 dirs.remove('SUB1')
423 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000424 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
425 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000426
427 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000428 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000429 self.assertEqual(len(all), 4)
430 # We can't know which order SUB1 and SUB2 will appear in.
431 # Not flipped: SUB11, SUB1, SUB2, TESTFN
432 # flipped: SUB2, SUB11, SUB1, TESTFN
433 flipped = all[3][1][0] != "SUB1"
434 all[3][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000435 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000436 self.assertEqual(all[flipped], (sub11_path, [], []))
437 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000438 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000439
Guido van Rossumd8faa362007-04-27 19:54:29 +0000440 if hasattr(os, "symlink"):
441 # Walk, following symlinks.
442 for root, dirs, files in os.walk(walk_path, followlinks=True):
443 if root == link_path:
444 self.assertEqual(dirs, [])
445 self.assertEqual(files, ["tmp4"])
446 break
447 else:
448 self.fail("Didn't follow symlink with followlinks=True")
449
450 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000451 # Tear everything down. This is a decent use for bottom-up on
452 # Windows, which doesn't have a recursive delete command. The
453 # (not so) subtlety is that rmdir will fail unless the dir's
454 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000455 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000456 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000457 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000458 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000459 dirname = os.path.join(root, name)
460 if not os.path.islink(dirname):
461 os.rmdir(dirname)
462 else:
463 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000464 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000465
Guido van Rossume7ba4952007-06-06 23:52:48 +0000466class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000467 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000468 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000469
470 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000471 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000472 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
473 os.makedirs(path) # Should work
474 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
475 os.makedirs(path)
476
477 # Try paths with a '.' in them
478 self.failUnlessRaises(OSError, os.makedirs, os.curdir)
479 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
480 os.makedirs(path)
481 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
482 'dir5', 'dir6')
483 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000484
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000485 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000486 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000487 'dir4', 'dir5', 'dir6')
488 # If the tests failed, the bottom-most directory ('../dir6')
489 # may not have been created, so we look for the outermost directory
490 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000491 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000492 path = os.path.dirname(path)
493
494 os.removedirs(path)
495
Guido van Rossume7ba4952007-06-06 23:52:48 +0000496class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000497 def test_devnull(self):
Alex Martelli01c77c62006-08-24 02:58:11 +0000498 f = open(os.devnull, 'w')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000499 f.write('hello')
500 f.close()
Alex Martelli01c77c62006-08-24 02:58:11 +0000501 f = open(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000502 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000503 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000504
Guido van Rossume7ba4952007-06-06 23:52:48 +0000505class URandomTests(unittest.TestCase):
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000506 def test_urandom(self):
507 try:
508 self.assertEqual(len(os.urandom(1)), 1)
509 self.assertEqual(len(os.urandom(10)), 10)
510 self.assertEqual(len(os.urandom(100)), 100)
511 self.assertEqual(len(os.urandom(1000)), 1000)
512 except NotImplementedError:
513 pass
514
Guido van Rossume7ba4952007-06-06 23:52:48 +0000515class ExecTests(unittest.TestCase):
516 def test_execvpe_with_bad_program(self):
Thomas Hellerbd315c52007-08-30 17:57:21 +0000517 self.assertRaises(OSError, os.execvpe, 'no such app-', ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000518
Thomas Heller6790d602007-08-30 17:15:14 +0000519 def test_execvpe_with_bad_arglist(self):
520 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
521
Thomas Wouters477c8d52006-05-27 19:21:47 +0000522class Win32ErrorTests(unittest.TestCase):
523 def test_rename(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000524 self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000525
526 def test_remove(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000527 self.assertRaises(WindowsError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000528
529 def test_chdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000530 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000531
532 def test_mkdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000533 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000534
535 def test_utime(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000536 self.assertRaises(WindowsError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000537
538 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000539 self.assertRaises(WindowsError, os.utime, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000540
541 def test_chmod(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000542 self.assertRaises(WindowsError, os.utime, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000543
544if sys.platform != 'win32':
545 class Win32ErrorTests(unittest.TestCase):
546 pass
547
Fred Drake2e2be372001-09-20 21:33:42 +0000548def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000549 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000550 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000551 StatAttributeTests,
552 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000553 WalkTests,
554 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000555 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000556 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000557 ExecTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000558 Win32ErrorTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000559 )
Fred Drake2e2be372001-09-20 21:33:42 +0000560
561if __name__ == "__main__":
562 test_main()