blob: cec023d308d2569e5c49ec807719c5e33fb5b89f [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):
Antoine Pitroubebb18b2008-08-17 14:43:41 +000027 first = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
28 # We must allocate two consecutive file descriptors, otherwise
29 # it will mess up other file descriptors (perhaps even the three
30 # standard ones).
31 second = os.dup(first)
32 try:
33 retries = 0
34 while second != first + 1:
35 os.close(first)
36 retries += 1
37 if retries > 10:
38 # XXX test skipped
39 print >> sys.stderr, (
40 "couldn't allocate two consecutive fds, "
41 "skipping test_closerange")
42 return
43 first, second = second, os.dup(second)
44 finally:
45 os.close(second)
Georg Brandl309501a2008-01-19 20:22:13 +000046 # close a fd that is open, and one that isn't
Antoine Pitroubebb18b2008-08-17 14:43:41 +000047 os.closerange(first, first + 2)
48 self.assertRaises(OSError, os.write, first, "a")
Georg Brandl309501a2008-01-19 20:22:13 +000049
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000050
Fred Drake38c2ef02001-07-17 20:52:51 +000051class TemporaryFileTests(unittest.TestCase):
52 def setUp(self):
53 self.files = []
Walter Dörwald21d3a322003-05-01 17:45:56 +000054 os.mkdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000055
56 def tearDown(self):
57 for name in self.files:
58 os.unlink(name)
Walter Dörwald21d3a322003-05-01 17:45:56 +000059 os.rmdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000060
61 def check_tempfile(self, name):
62 # make sure it doesn't already exist:
63 self.failIf(os.path.exists(name),
64 "file already exists for temporary file")
65 # make sure we can create the file
66 open(name, "w")
67 self.files.append(name)
68
69 def test_tempnam(self):
70 if not hasattr(os, "tempnam"):
71 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +000072 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +000073 r"test_os$")
Fred Drake38c2ef02001-07-17 20:52:51 +000074 self.check_tempfile(os.tempnam())
75
Walter Dörwald21d3a322003-05-01 17:45:56 +000076 name = os.tempnam(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000077 self.check_tempfile(name)
78
Walter Dörwald21d3a322003-05-01 17:45:56 +000079 name = os.tempnam(test_support.TESTFN, "pfx")
Fred Drake38c2ef02001-07-17 20:52:51 +000080 self.assert_(os.path.basename(name)[:3] == "pfx")
81 self.check_tempfile(name)
82
83 def test_tmpfile(self):
84 if not hasattr(os, "tmpfile"):
85 return
Martin v. Löwisd2bbe522008-03-06 06:55:22 +000086 # As with test_tmpnam() below, the Windows implementation of tmpfile()
87 # attempts to create a file in the root directory of the current drive.
88 # On Vista and Server 2008, this test will always fail for normal users
89 # as writing to the root directory requires elevated privileges. With
90 # XP and below, the semantics of tmpfile() are the same, but the user
91 # running the test is more likely to have administrative privileges on
92 # their account already. If that's the case, then os.tmpfile() should
93 # work. In order to make this test as useful as possible, rather than
94 # trying to detect Windows versions or whether or not the user has the
95 # right permissions, just try and create a file in the root directory
96 # and see if it raises a 'Permission denied' OSError. If it does, then
97 # test that a subsequent call to os.tmpfile() raises the same error. If
98 # it doesn't, assume we're on XP or below and the user running the test
99 # has administrative privileges, and proceed with the test as normal.
100 if sys.platform == 'win32':
101 name = '\\python_test_os_test_tmpfile.txt'
102 if os.path.exists(name):
103 os.remove(name)
104 try:
105 fp = open(name, 'w')
106 except IOError, first:
107 # open() failed, assert tmpfile() fails in the same way.
108 # Although open() raises an IOError and os.tmpfile() raises an
109 # OSError(), 'args' will be (13, 'Permission denied') in both
110 # cases.
111 try:
112 fp = os.tmpfile()
113 except OSError, second:
114 self.assertEqual(first.args, second.args)
115 else:
116 self.fail("expected os.tmpfile() to raise OSError")
117 return
118 else:
119 # open() worked, therefore, tmpfile() should work. Close our
120 # dummy file and proceed with the test as normal.
121 fp.close()
122 os.remove(name)
123
Fred Drake38c2ef02001-07-17 20:52:51 +0000124 fp = os.tmpfile()
125 fp.write("foobar")
126 fp.seek(0,0)
127 s = fp.read()
128 fp.close()
129 self.assert_(s == "foobar")
130
131 def test_tmpnam(self):
Tim Peters5501b5e2003-04-28 03:13:03 +0000132 import sys
Fred Drake38c2ef02001-07-17 20:52:51 +0000133 if not hasattr(os, "tmpnam"):
134 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +0000135 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +0000136 r"test_os$")
Tim Peters5501b5e2003-04-28 03:13:03 +0000137 name = os.tmpnam()
138 if sys.platform in ("win32",):
139 # The Windows tmpnam() seems useless. From the MS docs:
140 #
141 # The character string that tmpnam creates consists of
142 # the path prefix, defined by the entry P_tmpdir in the
143 # file STDIO.H, followed by a sequence consisting of the
144 # digit characters '0' through '9'; the numerical value
145 # of this string is in the range 1 - 65,535. Changing the
146 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
147 # change the operation of tmpnam.
148 #
149 # The really bizarre part is that, at least under MSVC6,
150 # P_tmpdir is "\\". That is, the path returned refers to
151 # the root of the current drive. That's a terrible place to
152 # put temp files, and, depending on privileges, the user
153 # may not even be able to open a file in the root directory.
154 self.failIf(os.path.exists(name),
155 "file already exists for temporary file")
156 else:
157 self.check_tempfile(name)
Tim Peters87cc0c32001-07-21 01:41:30 +0000158
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000159# Test attributes on return values from os.*stat* family.
160class StatAttributeTests(unittest.TestCase):
161 def setUp(self):
Walter Dörwald21d3a322003-05-01 17:45:56 +0000162 os.mkdir(test_support.TESTFN)
163 self.fname = os.path.join(test_support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000164 f = open(self.fname, 'wb')
165 f.write("ABC")
166 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000167
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000168 def tearDown(self):
169 os.unlink(self.fname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000170 os.rmdir(test_support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000171
172 def test_stat_attributes(self):
173 if not hasattr(os, "stat"):
174 return
175
176 import stat
177 result = os.stat(self.fname)
178
179 # Make sure direct access works
180 self.assertEquals(result[stat.ST_SIZE], 3)
181 self.assertEquals(result.st_size, 3)
182
183 import sys
184
185 # Make sure all the attributes are there
186 members = dir(result)
187 for name in dir(stat):
188 if name[:3] == 'ST_':
189 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000190 if name.endswith("TIME"):
191 def trunc(x): return int(x)
192 else:
193 def trunc(x): return x
194 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000195 result[getattr(stat, name)])
196 self.assert_(attr in members)
197
198 try:
199 result[200]
200 self.fail("No exception thrown")
201 except IndexError:
202 pass
203
204 # Make sure that assignment fails
205 try:
206 result.st_mode = 1
207 self.fail("No exception thrown")
208 except TypeError:
209 pass
210
211 try:
212 result.st_rdev = 1
213 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000214 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000215 pass
216
217 try:
218 result.parrot = 1
219 self.fail("No exception thrown")
220 except AttributeError:
221 pass
222
223 # Use the stat_result constructor with a too-short tuple.
224 try:
225 result2 = os.stat_result((10,))
226 self.fail("No exception thrown")
227 except TypeError:
228 pass
229
230 # Use the constructr with a too-long tuple.
231 try:
232 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
233 except TypeError:
234 pass
235
Tim Peterse0c446b2001-10-18 21:57:37 +0000236
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000237 def test_statvfs_attributes(self):
238 if not hasattr(os, "statvfs"):
239 return
240
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000241 try:
242 result = os.statvfs(self.fname)
243 except OSError, e:
244 # On AtheOS, glibc always returns ENOSYS
245 import errno
246 if e.errno == errno.ENOSYS:
247 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000248
249 # Make sure direct access works
Brett Cannon90f2cb42008-05-16 00:37:42 +0000250 self.assertEquals(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000251
Brett Cannon90f2cb42008-05-16 00:37:42 +0000252 # Make sure all the attributes are there.
253 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
254 'ffree', 'favail', 'flag', 'namemax')
255 for value, member in enumerate(members):
256 self.assertEquals(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000257
258 # Make sure that assignment really fails
259 try:
260 result.f_bfree = 1
261 self.fail("No exception thrown")
262 except TypeError:
263 pass
264
265 try:
266 result.parrot = 1
267 self.fail("No exception thrown")
268 except AttributeError:
269 pass
270
271 # Use the constructor with a too-short tuple.
272 try:
273 result2 = os.statvfs_result((10,))
274 self.fail("No exception thrown")
275 except TypeError:
276 pass
277
278 # Use the constructr with a too-long tuple.
279 try:
280 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
281 except TypeError:
282 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000283
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000284 def test_utime_dir(self):
285 delta = 1000000
286 st = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000287 # round to int, because some systems may support sub-second
288 # time stamps in stat, but not in utime.
289 os.utime(test_support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000290 st2 = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000291 self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000292
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000293 # Restrict test to Win32, since there is no guarantee other
294 # systems support centiseconds
295 if sys.platform == 'win32':
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000296 def get_file_system(path):
Hirokazu Yamamotoccfdcd02008-08-20 04:13:28 +0000297 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000298 import ctypes
Hirokazu Yamamotocd3b74d2008-08-20 16:15:28 +0000299 kernel32 = ctypes.windll.kernel32
300 buf = ctypes.create_string_buffer("", 100)
301 if kernel32.GetVolumeInformationA(root, None, 0, None, None, None, buf, len(buf)):
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000302 return buf.value
303
304 if get_file_system(test_support.TESTFN) == "NTFS":
305 def test_1565150(self):
306 t1 = 1159195039.25
307 os.utime(self.fname, (t1, t1))
308 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000309
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000310 def test_1686475(self):
311 # Verify that an open file can be stat'ed
312 try:
313 os.stat(r"c:\pagefile.sys")
314 except WindowsError, e:
Antoine Pitrou954ea642008-08-17 20:15:07 +0000315 if e.errno == 2: # file does not exist; cannot run test
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000316 return
317 self.fail("Could not stat pagefile.sys")
318
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000319from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000320
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000321class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000322 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000323 type2test = None
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000324 def _reference(self):
325 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
326 def _empty_mapping(self):
327 os.environ.clear()
328 return os.environ
329 def setUp(self):
330 self.__save = dict(os.environ)
331 os.environ.clear()
332 def tearDown(self):
333 os.environ.clear()
334 os.environ.update(self.__save)
335
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000336 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000337 def test_update2(self):
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000338 if os.path.exists("/bin/sh"):
339 os.environ.update(HELLO="World")
340 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
341 self.assertEquals(value, "World")
342
Tim Petersc4e09402003-04-25 07:11:48 +0000343class WalkTests(unittest.TestCase):
344 """Tests for os.walk()."""
345
346 def test_traversal(self):
347 import os
348 from os.path import join
349
350 # Build:
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000351 # TESTFN/
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000352 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000353 # tmp1
354 # SUB1/ a file kid and a directory kid
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000355 # tmp2
356 # SUB11/ no kids
357 # SUB2/ a file kid and a dirsymlink kid
358 # tmp3
359 # link/ a symlink to TESTFN.2
360 # TEST2/
361 # tmp4 a lone file
362 walk_path = join(test_support.TESTFN, "TEST1")
363 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000364 sub11_path = join(sub1_path, "SUB11")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000365 sub2_path = join(walk_path, "SUB2")
366 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000367 tmp2_path = join(sub1_path, "tmp2")
368 tmp3_path = join(sub2_path, "tmp3")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000369 link_path = join(sub2_path, "link")
370 t2_path = join(test_support.TESTFN, "TEST2")
371 tmp4_path = join(test_support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000372
373 # Create stuff.
374 os.makedirs(sub11_path)
375 os.makedirs(sub2_path)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000376 os.makedirs(t2_path)
377 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Tim Petersc4e09402003-04-25 07:11:48 +0000378 f = file(path, "w")
379 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
380 f.close()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000381 if hasattr(os, "symlink"):
382 os.symlink(os.path.abspath(t2_path), link_path)
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000383 sub2_tree = (sub2_path, ["link"], ["tmp3"])
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000384 else:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000385 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000386
387 # Walk top-down.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000388 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000389 self.assertEqual(len(all), 4)
390 # We can't know which order SUB1 and SUB2 will appear in.
391 # Not flipped: TESTFN, SUB1, SUB11, SUB2
392 # flipped: TESTFN, SUB2, SUB1, SUB11
393 flipped = all[0][1][0] != "SUB1"
394 all[0][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000395 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000396 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
397 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000398 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000399
400 # Prune the search.
401 all = []
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000402 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000403 all.append((root, dirs, files))
404 # Don't descend into SUB1.
405 if 'SUB1' in dirs:
406 # Note that this also mutates the dirs we appended to all!
407 dirs.remove('SUB1')
408 self.assertEqual(len(all), 2)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000409 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000410 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000411
412 # Walk bottom-up.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000413 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000414 self.assertEqual(len(all), 4)
415 # We can't know which order SUB1 and SUB2 will appear in.
416 # Not flipped: SUB11, SUB1, SUB2, TESTFN
417 # flipped: SUB2, SUB11, SUB1, TESTFN
418 flipped = all[3][1][0] != "SUB1"
419 all[3][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000420 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000421 self.assertEqual(all[flipped], (sub11_path, [], []))
422 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000423 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000424
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000425 if hasattr(os, "symlink"):
426 # Walk, following symlinks.
427 for root, dirs, files in os.walk(walk_path, followlinks=True):
428 if root == link_path:
429 self.assertEqual(dirs, [])
430 self.assertEqual(files, ["tmp4"])
431 break
432 else:
433 self.fail("Didn't follow symlink with followlinks=True")
Tim Petersc4e09402003-04-25 07:11:48 +0000434
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000435 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000436 # Tear everything down. This is a decent use for bottom-up on
437 # Windows, which doesn't have a recursive delete command. The
438 # (not so) subtlety is that rmdir will fail unless the dir's
439 # kids are removed first, so bottom up is essential.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000440 for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000441 for name in files:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000442 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000443 for name in dirs:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000444 dirname = os.path.join(root, name)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000445 if not os.path.islink(dirname):
446 os.rmdir(dirname)
447 else:
448 os.remove(dirname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000449 os.rmdir(test_support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000450
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000451class MakedirTests (unittest.TestCase):
452 def setUp(self):
453 os.mkdir(test_support.TESTFN)
454
455 def test_makedir(self):
456 base = test_support.TESTFN
457 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
458 os.makedirs(path) # Should work
459 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
460 os.makedirs(path)
461
462 # Try paths with a '.' in them
463 self.failUnlessRaises(OSError, os.makedirs, os.curdir)
464 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
465 os.makedirs(path)
466 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
467 'dir5', 'dir6')
468 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000469
Tim Peters58eb11c2004-01-18 20:29:55 +0000470
471
472
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000473 def tearDown(self):
474 path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
475 'dir4', 'dir5', 'dir6')
476 # If the tests failed, the bottom-most directory ('../dir6')
477 # may not have been created, so we look for the outermost directory
478 # that exists.
479 while not os.path.exists(path) and path != test_support.TESTFN:
480 path = os.path.dirname(path)
481
482 os.removedirs(path)
483
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000484class DevNullTests (unittest.TestCase):
485 def test_devnull(self):
486 f = file(os.devnull, 'w')
487 f.write('hello')
488 f.close()
489 f = file(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000490 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000491 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000492
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000493class URandomTests (unittest.TestCase):
494 def test_urandom(self):
495 try:
496 self.assertEqual(len(os.urandom(1)), 1)
497 self.assertEqual(len(os.urandom(10)), 10)
498 self.assertEqual(len(os.urandom(100)), 100)
499 self.assertEqual(len(os.urandom(1000)), 1000)
500 except NotImplementedError:
501 pass
502
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000503class Win32ErrorTests(unittest.TestCase):
504 def test_rename(self):
505 self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak")
506
507 def test_remove(self):
508 self.assertRaises(WindowsError, os.remove, test_support.TESTFN)
509
510 def test_chdir(self):
511 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
512
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000513 def test_mkdir(self):
514 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
515
516 def test_utime(self):
517 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, None)
518
519 def test_access(self):
520 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, 0)
521
522 def test_chmod(self):
523 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, 0)
524
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000525if sys.platform != 'win32':
526 class Win32ErrorTests(unittest.TestCase):
527 pass
528
Fred Drake2e2be372001-09-20 21:33:42 +0000529def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000530 test_support.run_unittest(
Martin v. Löwisee1e06d2006-07-02 18:44:00 +0000531 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000532 TemporaryFileTests,
533 StatAttributeTests,
534 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000535 WalkTests,
536 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000537 DevNullTests,
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000538 URandomTests,
539 Win32ErrorTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000540 )
Fred Drake2e2be372001-09-20 21:33:42 +0000541
542if __name__ == "__main__":
543 test_main()