blob: 4c00422cf6d35a029c2b81b2ce144592d8be77eb [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
Martin v. Löwis8e0d4942006-05-04 10:08:42 +00008import sys
Walter Dörwald21d3a322003-05-01 17:45:56 +00009from test import test_support
Fred Drake38c2ef02001-07-17 20:52:51 +000010
Barry Warsaw60f01882001-08-22 19:24:42 +000011warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, __name__)
12warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, __name__)
13
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000014# Tests creating TESTFN
15class FileTests(unittest.TestCase):
16 def setUp(self):
17 if os.path.exists(test_support.TESTFN):
18 os.unlink(test_support.TESTFN)
19 tearDown = setUp
20
21 def test_access(self):
22 f = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
23 os.close(f)
24 self.assert_(os.access(test_support.TESTFN, os.W_OK))
Tim Peters16a39322006-07-03 08:23:19 +000025
Georg Brandl309501a2008-01-19 20:22:13 +000026 def test_closerange(self):
27 f = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
28 # close a fd that is open, and one that isn't
29 os.closerange(f, f+2)
30 self.assertRaises(OSError, os.write, f, "a")
31
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000032
Fred Drake38c2ef02001-07-17 20:52:51 +000033class TemporaryFileTests(unittest.TestCase):
34 def setUp(self):
35 self.files = []
Walter Dörwald21d3a322003-05-01 17:45:56 +000036 os.mkdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000037
38 def tearDown(self):
39 for name in self.files:
40 os.unlink(name)
Walter Dörwald21d3a322003-05-01 17:45:56 +000041 os.rmdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000042
43 def check_tempfile(self, name):
44 # make sure it doesn't already exist:
45 self.failIf(os.path.exists(name),
46 "file already exists for temporary file")
47 # make sure we can create the file
48 open(name, "w")
49 self.files.append(name)
50
51 def test_tempnam(self):
52 if not hasattr(os, "tempnam"):
53 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +000054 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +000055 r"test_os$")
Fred Drake38c2ef02001-07-17 20:52:51 +000056 self.check_tempfile(os.tempnam())
57
Walter Dörwald21d3a322003-05-01 17:45:56 +000058 name = os.tempnam(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000059 self.check_tempfile(name)
60
Walter Dörwald21d3a322003-05-01 17:45:56 +000061 name = os.tempnam(test_support.TESTFN, "pfx")
Fred Drake38c2ef02001-07-17 20:52:51 +000062 self.assert_(os.path.basename(name)[:3] == "pfx")
63 self.check_tempfile(name)
64
65 def test_tmpfile(self):
66 if not hasattr(os, "tmpfile"):
67 return
Martin v. Löwisd2bbe522008-03-06 06:55:22 +000068 # As with test_tmpnam() below, the Windows implementation of tmpfile()
69 # attempts to create a file in the root directory of the current drive.
70 # On Vista and Server 2008, this test will always fail for normal users
71 # as writing to the root directory requires elevated privileges. With
72 # XP and below, the semantics of tmpfile() are the same, but the user
73 # running the test is more likely to have administrative privileges on
74 # their account already. If that's the case, then os.tmpfile() should
75 # work. In order to make this test as useful as possible, rather than
76 # trying to detect Windows versions or whether or not the user has the
77 # right permissions, just try and create a file in the root directory
78 # and see if it raises a 'Permission denied' OSError. If it does, then
79 # test that a subsequent call to os.tmpfile() raises the same error. If
80 # it doesn't, assume we're on XP or below and the user running the test
81 # has administrative privileges, and proceed with the test as normal.
82 if sys.platform == 'win32':
83 name = '\\python_test_os_test_tmpfile.txt'
84 if os.path.exists(name):
85 os.remove(name)
86 try:
87 fp = open(name, 'w')
88 except IOError, first:
89 # open() failed, assert tmpfile() fails in the same way.
90 # Although open() raises an IOError and os.tmpfile() raises an
91 # OSError(), 'args' will be (13, 'Permission denied') in both
92 # cases.
93 try:
94 fp = os.tmpfile()
95 except OSError, second:
96 self.assertEqual(first.args, second.args)
97 else:
98 self.fail("expected os.tmpfile() to raise OSError")
99 return
100 else:
101 # open() worked, therefore, tmpfile() should work. Close our
102 # dummy file and proceed with the test as normal.
103 fp.close()
104 os.remove(name)
105
Fred Drake38c2ef02001-07-17 20:52:51 +0000106 fp = os.tmpfile()
107 fp.write("foobar")
108 fp.seek(0,0)
109 s = fp.read()
110 fp.close()
111 self.assert_(s == "foobar")
112
113 def test_tmpnam(self):
Tim Peters5501b5e2003-04-28 03:13:03 +0000114 import sys
Fred Drake38c2ef02001-07-17 20:52:51 +0000115 if not hasattr(os, "tmpnam"):
116 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +0000117 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +0000118 r"test_os$")
Tim Peters5501b5e2003-04-28 03:13:03 +0000119 name = os.tmpnam()
120 if sys.platform in ("win32",):
121 # The Windows tmpnam() seems useless. From the MS docs:
122 #
123 # The character string that tmpnam creates consists of
124 # the path prefix, defined by the entry P_tmpdir in the
125 # file STDIO.H, followed by a sequence consisting of the
126 # digit characters '0' through '9'; the numerical value
127 # of this string is in the range 1 - 65,535. Changing the
128 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
129 # change the operation of tmpnam.
130 #
131 # The really bizarre part is that, at least under MSVC6,
132 # P_tmpdir is "\\". That is, the path returned refers to
133 # the root of the current drive. That's a terrible place to
134 # put temp files, and, depending on privileges, the user
135 # may not even be able to open a file in the root directory.
136 self.failIf(os.path.exists(name),
137 "file already exists for temporary file")
138 else:
139 self.check_tempfile(name)
Tim Peters87cc0c32001-07-21 01:41:30 +0000140
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000141# Test attributes on return values from os.*stat* family.
142class StatAttributeTests(unittest.TestCase):
143 def setUp(self):
Walter Dörwald21d3a322003-05-01 17:45:56 +0000144 os.mkdir(test_support.TESTFN)
145 self.fname = os.path.join(test_support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000146 f = open(self.fname, 'wb')
147 f.write("ABC")
148 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000149
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000150 def tearDown(self):
151 os.unlink(self.fname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000152 os.rmdir(test_support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000153
154 def test_stat_attributes(self):
155 if not hasattr(os, "stat"):
156 return
157
158 import stat
159 result = os.stat(self.fname)
160
161 # Make sure direct access works
162 self.assertEquals(result[stat.ST_SIZE], 3)
163 self.assertEquals(result.st_size, 3)
164
165 import sys
166
167 # Make sure all the attributes are there
168 members = dir(result)
169 for name in dir(stat):
170 if name[:3] == 'ST_':
171 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000172 if name.endswith("TIME"):
173 def trunc(x): return int(x)
174 else:
175 def trunc(x): return x
176 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000177 result[getattr(stat, name)])
178 self.assert_(attr in members)
179
180 try:
181 result[200]
182 self.fail("No exception thrown")
183 except IndexError:
184 pass
185
186 # Make sure that assignment fails
187 try:
188 result.st_mode = 1
189 self.fail("No exception thrown")
190 except TypeError:
191 pass
192
193 try:
194 result.st_rdev = 1
195 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000196 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000197 pass
198
199 try:
200 result.parrot = 1
201 self.fail("No exception thrown")
202 except AttributeError:
203 pass
204
205 # Use the stat_result constructor with a too-short tuple.
206 try:
207 result2 = os.stat_result((10,))
208 self.fail("No exception thrown")
209 except TypeError:
210 pass
211
212 # Use the constructr with a too-long tuple.
213 try:
214 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
215 except TypeError:
216 pass
217
Tim Peterse0c446b2001-10-18 21:57:37 +0000218
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000219 def test_statvfs_attributes(self):
220 if not hasattr(os, "statvfs"):
221 return
222
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000223 try:
224 result = os.statvfs(self.fname)
225 except OSError, e:
226 # On AtheOS, glibc always returns ENOSYS
227 import errno
228 if e.errno == errno.ENOSYS:
229 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000230
231 # Make sure direct access works
Brett Cannon90f2cb42008-05-16 00:37:42 +0000232 self.assertEquals(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000233
Brett Cannon90f2cb42008-05-16 00:37:42 +0000234 # Make sure all the attributes are there.
235 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
236 'ffree', 'favail', 'flag', 'namemax')
237 for value, member in enumerate(members):
238 self.assertEquals(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000239
240 # Make sure that assignment really fails
241 try:
242 result.f_bfree = 1
243 self.fail("No exception thrown")
244 except TypeError:
245 pass
246
247 try:
248 result.parrot = 1
249 self.fail("No exception thrown")
250 except AttributeError:
251 pass
252
253 # Use the constructor with a too-short tuple.
254 try:
255 result2 = os.statvfs_result((10,))
256 self.fail("No exception thrown")
257 except TypeError:
258 pass
259
260 # Use the constructr with a too-long tuple.
261 try:
262 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
263 except TypeError:
264 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000265
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000266 def test_utime_dir(self):
267 delta = 1000000
268 st = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000269 # round to int, because some systems may support sub-second
270 # time stamps in stat, but not in utime.
271 os.utime(test_support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000272 st2 = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000273 self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000274
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000275 # Restrict test to Win32, since there is no guarantee other
276 # systems support centiseconds
277 if sys.platform == 'win32':
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000278 def get_file_system(path):
279 import os
280 root = os.path.splitdrive(os.path.realpath("."))[0] + '\\'
281 import ctypes
282 kernel32 = ctypes.windll.kernel32
283 buf = ctypes.create_string_buffer("", 100)
284 if kernel32.GetVolumeInformationA(root, None, 0, None, None, None, buf, len(buf)):
285 return buf.value
286
287 if get_file_system(test_support.TESTFN) == "NTFS":
288 def test_1565150(self):
289 t1 = 1159195039.25
290 os.utime(self.fname, (t1, t1))
291 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000292
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000293 def test_1686475(self):
294 # Verify that an open file can be stat'ed
295 try:
296 os.stat(r"c:\pagefile.sys")
297 except WindowsError, e:
298 if e == 2: # file does not exist; cannot run test
299 return
300 self.fail("Could not stat pagefile.sys")
301
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000302from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000303
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000304class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000305 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000306 type2test = None
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000307 def _reference(self):
308 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
309 def _empty_mapping(self):
310 os.environ.clear()
311 return os.environ
312 def setUp(self):
313 self.__save = dict(os.environ)
314 os.environ.clear()
315 def tearDown(self):
316 os.environ.clear()
317 os.environ.update(self.__save)
318
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000319 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000320 def test_update2(self):
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000321 if os.path.exists("/bin/sh"):
322 os.environ.update(HELLO="World")
323 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
324 self.assertEquals(value, "World")
325
Tim Petersc4e09402003-04-25 07:11:48 +0000326class WalkTests(unittest.TestCase):
327 """Tests for os.walk()."""
328
329 def test_traversal(self):
330 import os
331 from os.path import join
332
333 # Build:
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000334 # TESTFN/
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000335 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000336 # tmp1
337 # SUB1/ a file kid and a directory kid
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000338 # tmp2
339 # SUB11/ no kids
340 # SUB2/ a file kid and a dirsymlink kid
341 # tmp3
342 # link/ a symlink to TESTFN.2
343 # TEST2/
344 # tmp4 a lone file
345 walk_path = join(test_support.TESTFN, "TEST1")
346 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000347 sub11_path = join(sub1_path, "SUB11")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000348 sub2_path = join(walk_path, "SUB2")
349 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000350 tmp2_path = join(sub1_path, "tmp2")
351 tmp3_path = join(sub2_path, "tmp3")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000352 link_path = join(sub2_path, "link")
353 t2_path = join(test_support.TESTFN, "TEST2")
354 tmp4_path = join(test_support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000355
356 # Create stuff.
357 os.makedirs(sub11_path)
358 os.makedirs(sub2_path)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000359 os.makedirs(t2_path)
360 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Tim Petersc4e09402003-04-25 07:11:48 +0000361 f = file(path, "w")
362 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
363 f.close()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000364 if hasattr(os, "symlink"):
365 os.symlink(os.path.abspath(t2_path), link_path)
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000366 sub2_tree = (sub2_path, ["link"], ["tmp3"])
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000367 else:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000368 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000369
370 # Walk top-down.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000371 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000372 self.assertEqual(len(all), 4)
373 # We can't know which order SUB1 and SUB2 will appear in.
374 # Not flipped: TESTFN, SUB1, SUB11, SUB2
375 # flipped: TESTFN, SUB2, SUB1, SUB11
376 flipped = all[0][1][0] != "SUB1"
377 all[0][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000378 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000379 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
380 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000381 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000382
383 # Prune the search.
384 all = []
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000385 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000386 all.append((root, dirs, files))
387 # Don't descend into SUB1.
388 if 'SUB1' in dirs:
389 # Note that this also mutates the dirs we appended to all!
390 dirs.remove('SUB1')
391 self.assertEqual(len(all), 2)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000392 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000393 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000394
395 # Walk bottom-up.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000396 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000397 self.assertEqual(len(all), 4)
398 # We can't know which order SUB1 and SUB2 will appear in.
399 # Not flipped: SUB11, SUB1, SUB2, TESTFN
400 # flipped: SUB2, SUB11, SUB1, TESTFN
401 flipped = all[3][1][0] != "SUB1"
402 all[3][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000403 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000404 self.assertEqual(all[flipped], (sub11_path, [], []))
405 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000406 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000407
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000408 if hasattr(os, "symlink"):
409 # Walk, following symlinks.
410 for root, dirs, files in os.walk(walk_path, followlinks=True):
411 if root == link_path:
412 self.assertEqual(dirs, [])
413 self.assertEqual(files, ["tmp4"])
414 break
415 else:
416 self.fail("Didn't follow symlink with followlinks=True")
Tim Petersc4e09402003-04-25 07:11:48 +0000417
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000418 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000419 # Tear everything down. This is a decent use for bottom-up on
420 # Windows, which doesn't have a recursive delete command. The
421 # (not so) subtlety is that rmdir will fail unless the dir's
422 # kids are removed first, so bottom up is essential.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000423 for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000424 for name in files:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000425 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000426 for name in dirs:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000427 dirname = os.path.join(root, name)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000428 if not os.path.islink(dirname):
429 os.rmdir(dirname)
430 else:
431 os.remove(dirname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000432 os.rmdir(test_support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000433
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000434class MakedirTests (unittest.TestCase):
435 def setUp(self):
436 os.mkdir(test_support.TESTFN)
437
438 def test_makedir(self):
439 base = test_support.TESTFN
440 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
441 os.makedirs(path) # Should work
442 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
443 os.makedirs(path)
444
445 # Try paths with a '.' in them
446 self.failUnlessRaises(OSError, os.makedirs, os.curdir)
447 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
448 os.makedirs(path)
449 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
450 'dir5', 'dir6')
451 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000452
Tim Peters58eb11c2004-01-18 20:29:55 +0000453
454
455
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000456 def tearDown(self):
457 path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
458 'dir4', 'dir5', 'dir6')
459 # If the tests failed, the bottom-most directory ('../dir6')
460 # may not have been created, so we look for the outermost directory
461 # that exists.
462 while not os.path.exists(path) and path != test_support.TESTFN:
463 path = os.path.dirname(path)
464
465 os.removedirs(path)
466
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000467class DevNullTests (unittest.TestCase):
468 def test_devnull(self):
469 f = file(os.devnull, 'w')
470 f.write('hello')
471 f.close()
472 f = file(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000473 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000474 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000475
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000476class URandomTests (unittest.TestCase):
477 def test_urandom(self):
478 try:
479 self.assertEqual(len(os.urandom(1)), 1)
480 self.assertEqual(len(os.urandom(10)), 10)
481 self.assertEqual(len(os.urandom(100)), 100)
482 self.assertEqual(len(os.urandom(1000)), 1000)
483 except NotImplementedError:
484 pass
485
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000486class Win32ErrorTests(unittest.TestCase):
487 def test_rename(self):
488 self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak")
489
490 def test_remove(self):
491 self.assertRaises(WindowsError, os.remove, test_support.TESTFN)
492
493 def test_chdir(self):
494 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
495
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000496 def test_mkdir(self):
497 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
498
499 def test_utime(self):
500 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, None)
501
502 def test_access(self):
503 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, 0)
504
505 def test_chmod(self):
506 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, 0)
507
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000508if sys.platform != 'win32':
509 class Win32ErrorTests(unittest.TestCase):
510 pass
511
Fred Drake2e2be372001-09-20 21:33:42 +0000512def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000513 test_support.run_unittest(
Martin v. Löwisee1e06d2006-07-02 18:44:00 +0000514 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000515 TemporaryFileTests,
516 StatAttributeTests,
517 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000518 WalkTests,
519 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000520 DevNullTests,
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000521 URandomTests,
522 Win32ErrorTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000523 )
Fred Drake2e2be372001-09-20 21:33:42 +0000524
525if __name__ == "__main__":
526 test_main()