blob: 5c94d7dbf8af7627a94b73a2b3f30d6da7cf6108 [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
Hirokazu Yamamoto74ce88f2008-09-08 23:03:47 +000050 def test_rename(self):
51 path = unicode(test_support.TESTFN)
52 old = sys.getrefcount(path)
53 self.assertRaises(TypeError, os.rename, path, 0)
54 new = sys.getrefcount(path)
55 self.assertEqual(old, new)
56
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000057
Fred Drake38c2ef02001-07-17 20:52:51 +000058class TemporaryFileTests(unittest.TestCase):
59 def setUp(self):
60 self.files = []
Walter Dörwald21d3a322003-05-01 17:45:56 +000061 os.mkdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000062
63 def tearDown(self):
64 for name in self.files:
65 os.unlink(name)
Walter Dörwald21d3a322003-05-01 17:45:56 +000066 os.rmdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000067
68 def check_tempfile(self, name):
69 # make sure it doesn't already exist:
70 self.failIf(os.path.exists(name),
71 "file already exists for temporary file")
72 # make sure we can create the file
73 open(name, "w")
74 self.files.append(name)
75
76 def test_tempnam(self):
77 if not hasattr(os, "tempnam"):
78 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +000079 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +000080 r"test_os$")
Fred Drake38c2ef02001-07-17 20:52:51 +000081 self.check_tempfile(os.tempnam())
82
Walter Dörwald21d3a322003-05-01 17:45:56 +000083 name = os.tempnam(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000084 self.check_tempfile(name)
85
Walter Dörwald21d3a322003-05-01 17:45:56 +000086 name = os.tempnam(test_support.TESTFN, "pfx")
Fred Drake38c2ef02001-07-17 20:52:51 +000087 self.assert_(os.path.basename(name)[:3] == "pfx")
88 self.check_tempfile(name)
89
90 def test_tmpfile(self):
91 if not hasattr(os, "tmpfile"):
92 return
Martin v. Löwisd2bbe522008-03-06 06:55:22 +000093 # As with test_tmpnam() below, the Windows implementation of tmpfile()
94 # attempts to create a file in the root directory of the current drive.
95 # On Vista and Server 2008, this test will always fail for normal users
96 # as writing to the root directory requires elevated privileges. With
97 # XP and below, the semantics of tmpfile() are the same, but the user
98 # running the test is more likely to have administrative privileges on
99 # their account already. If that's the case, then os.tmpfile() should
100 # work. In order to make this test as useful as possible, rather than
101 # trying to detect Windows versions or whether or not the user has the
102 # right permissions, just try and create a file in the root directory
103 # and see if it raises a 'Permission denied' OSError. If it does, then
104 # test that a subsequent call to os.tmpfile() raises the same error. If
105 # it doesn't, assume we're on XP or below and the user running the test
106 # has administrative privileges, and proceed with the test as normal.
107 if sys.platform == 'win32':
108 name = '\\python_test_os_test_tmpfile.txt'
109 if os.path.exists(name):
110 os.remove(name)
111 try:
112 fp = open(name, 'w')
113 except IOError, first:
114 # open() failed, assert tmpfile() fails in the same way.
115 # Although open() raises an IOError and os.tmpfile() raises an
116 # OSError(), 'args' will be (13, 'Permission denied') in both
117 # cases.
118 try:
119 fp = os.tmpfile()
120 except OSError, second:
121 self.assertEqual(first.args, second.args)
122 else:
123 self.fail("expected os.tmpfile() to raise OSError")
124 return
125 else:
126 # open() worked, therefore, tmpfile() should work. Close our
127 # dummy file and proceed with the test as normal.
128 fp.close()
129 os.remove(name)
130
Fred Drake38c2ef02001-07-17 20:52:51 +0000131 fp = os.tmpfile()
132 fp.write("foobar")
133 fp.seek(0,0)
134 s = fp.read()
135 fp.close()
136 self.assert_(s == "foobar")
137
138 def test_tmpnam(self):
Tim Peters5501b5e2003-04-28 03:13:03 +0000139 import sys
Fred Drake38c2ef02001-07-17 20:52:51 +0000140 if not hasattr(os, "tmpnam"):
141 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +0000142 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +0000143 r"test_os$")
Tim Peters5501b5e2003-04-28 03:13:03 +0000144 name = os.tmpnam()
145 if sys.platform in ("win32",):
146 # The Windows tmpnam() seems useless. From the MS docs:
147 #
148 # The character string that tmpnam creates consists of
149 # the path prefix, defined by the entry P_tmpdir in the
150 # file STDIO.H, followed by a sequence consisting of the
151 # digit characters '0' through '9'; the numerical value
152 # of this string is in the range 1 - 65,535. Changing the
153 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
154 # change the operation of tmpnam.
155 #
156 # The really bizarre part is that, at least under MSVC6,
157 # P_tmpdir is "\\". That is, the path returned refers to
158 # the root of the current drive. That's a terrible place to
159 # put temp files, and, depending on privileges, the user
160 # may not even be able to open a file in the root directory.
161 self.failIf(os.path.exists(name),
162 "file already exists for temporary file")
163 else:
164 self.check_tempfile(name)
Tim Peters87cc0c32001-07-21 01:41:30 +0000165
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000166# Test attributes on return values from os.*stat* family.
167class StatAttributeTests(unittest.TestCase):
168 def setUp(self):
Walter Dörwald21d3a322003-05-01 17:45:56 +0000169 os.mkdir(test_support.TESTFN)
170 self.fname = os.path.join(test_support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000171 f = open(self.fname, 'wb')
172 f.write("ABC")
173 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000174
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000175 def tearDown(self):
176 os.unlink(self.fname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000177 os.rmdir(test_support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000178
179 def test_stat_attributes(self):
180 if not hasattr(os, "stat"):
181 return
182
183 import stat
184 result = os.stat(self.fname)
185
186 # Make sure direct access works
187 self.assertEquals(result[stat.ST_SIZE], 3)
188 self.assertEquals(result.st_size, 3)
189
190 import sys
191
192 # Make sure all the attributes are there
193 members = dir(result)
194 for name in dir(stat):
195 if name[:3] == 'ST_':
196 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000197 if name.endswith("TIME"):
198 def trunc(x): return int(x)
199 else:
200 def trunc(x): return x
201 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000202 result[getattr(stat, name)])
203 self.assert_(attr in members)
204
205 try:
206 result[200]
207 self.fail("No exception thrown")
208 except IndexError:
209 pass
210
211 # Make sure that assignment fails
212 try:
213 result.st_mode = 1
214 self.fail("No exception thrown")
215 except TypeError:
216 pass
217
218 try:
219 result.st_rdev = 1
220 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000221 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000222 pass
223
224 try:
225 result.parrot = 1
226 self.fail("No exception thrown")
227 except AttributeError:
228 pass
229
230 # Use the stat_result constructor with a too-short tuple.
231 try:
232 result2 = os.stat_result((10,))
233 self.fail("No exception thrown")
234 except TypeError:
235 pass
236
237 # Use the constructr with a too-long tuple.
238 try:
239 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
240 except TypeError:
241 pass
242
Tim Peterse0c446b2001-10-18 21:57:37 +0000243
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000244 def test_statvfs_attributes(self):
245 if not hasattr(os, "statvfs"):
246 return
247
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000248 try:
249 result = os.statvfs(self.fname)
250 except OSError, e:
251 # On AtheOS, glibc always returns ENOSYS
252 import errno
253 if e.errno == errno.ENOSYS:
254 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000255
256 # Make sure direct access works
Brett Cannon90f2cb42008-05-16 00:37:42 +0000257 self.assertEquals(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000258
Brett Cannon90f2cb42008-05-16 00:37:42 +0000259 # Make sure all the attributes are there.
260 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
261 'ffree', 'favail', 'flag', 'namemax')
262 for value, member in enumerate(members):
263 self.assertEquals(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000264
265 # Make sure that assignment really fails
266 try:
267 result.f_bfree = 1
268 self.fail("No exception thrown")
269 except TypeError:
270 pass
271
272 try:
273 result.parrot = 1
274 self.fail("No exception thrown")
275 except AttributeError:
276 pass
277
278 # Use the constructor with a too-short tuple.
279 try:
280 result2 = os.statvfs_result((10,))
281 self.fail("No exception thrown")
282 except TypeError:
283 pass
284
285 # Use the constructr with a too-long tuple.
286 try:
287 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
288 except TypeError:
289 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000290
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000291 def test_utime_dir(self):
292 delta = 1000000
293 st = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000294 # round to int, because some systems may support sub-second
295 # time stamps in stat, but not in utime.
296 os.utime(test_support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000297 st2 = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000298 self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000299
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000300 # Restrict test to Win32, since there is no guarantee other
301 # systems support centiseconds
302 if sys.platform == 'win32':
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000303 def get_file_system(path):
Hirokazu Yamamotoccfdcd02008-08-20 04:13:28 +0000304 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000305 import ctypes
Hirokazu Yamamotocd3b74d2008-08-20 16:15:28 +0000306 kernel32 = ctypes.windll.kernel32
307 buf = ctypes.create_string_buffer("", 100)
308 if kernel32.GetVolumeInformationA(root, None, 0, None, None, None, buf, len(buf)):
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000309 return buf.value
310
311 if get_file_system(test_support.TESTFN) == "NTFS":
312 def test_1565150(self):
313 t1 = 1159195039.25
314 os.utime(self.fname, (t1, t1))
315 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000316
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000317 def test_1686475(self):
318 # Verify that an open file can be stat'ed
319 try:
320 os.stat(r"c:\pagefile.sys")
321 except WindowsError, e:
Antoine Pitrou954ea642008-08-17 20:15:07 +0000322 if e.errno == 2: # file does not exist; cannot run test
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000323 return
324 self.fail("Could not stat pagefile.sys")
325
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000326from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000327
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000328class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000329 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000330 type2test = None
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000331 def _reference(self):
332 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
333 def _empty_mapping(self):
334 os.environ.clear()
335 return os.environ
336 def setUp(self):
337 self.__save = dict(os.environ)
338 os.environ.clear()
339 def tearDown(self):
340 os.environ.clear()
341 os.environ.update(self.__save)
342
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000343 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000344 def test_update2(self):
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000345 if os.path.exists("/bin/sh"):
346 os.environ.update(HELLO="World")
347 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
348 self.assertEquals(value, "World")
349
Tim Petersc4e09402003-04-25 07:11:48 +0000350class WalkTests(unittest.TestCase):
351 """Tests for os.walk()."""
352
353 def test_traversal(self):
354 import os
355 from os.path import join
356
357 # Build:
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000358 # TESTFN/
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000359 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000360 # tmp1
361 # SUB1/ a file kid and a directory kid
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000362 # tmp2
363 # SUB11/ no kids
364 # SUB2/ a file kid and a dirsymlink kid
365 # tmp3
366 # link/ a symlink to TESTFN.2
367 # TEST2/
368 # tmp4 a lone file
369 walk_path = join(test_support.TESTFN, "TEST1")
370 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000371 sub11_path = join(sub1_path, "SUB11")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000372 sub2_path = join(walk_path, "SUB2")
373 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000374 tmp2_path = join(sub1_path, "tmp2")
375 tmp3_path = join(sub2_path, "tmp3")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000376 link_path = join(sub2_path, "link")
377 t2_path = join(test_support.TESTFN, "TEST2")
378 tmp4_path = join(test_support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000379
380 # Create stuff.
381 os.makedirs(sub11_path)
382 os.makedirs(sub2_path)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000383 os.makedirs(t2_path)
384 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Tim Petersc4e09402003-04-25 07:11:48 +0000385 f = file(path, "w")
386 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
387 f.close()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000388 if hasattr(os, "symlink"):
389 os.symlink(os.path.abspath(t2_path), link_path)
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000390 sub2_tree = (sub2_path, ["link"], ["tmp3"])
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000391 else:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000392 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000393
394 # Walk top-down.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000395 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000396 self.assertEqual(len(all), 4)
397 # We can't know which order SUB1 and SUB2 will appear in.
398 # Not flipped: TESTFN, SUB1, SUB11, SUB2
399 # flipped: TESTFN, SUB2, SUB1, SUB11
400 flipped = all[0][1][0] != "SUB1"
401 all[0][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000402 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000403 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
404 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000405 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000406
407 # Prune the search.
408 all = []
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000409 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000410 all.append((root, dirs, files))
411 # Don't descend into SUB1.
412 if 'SUB1' in dirs:
413 # Note that this also mutates the dirs we appended to all!
414 dirs.remove('SUB1')
415 self.assertEqual(len(all), 2)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000416 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000417 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000418
419 # Walk bottom-up.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000420 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000421 self.assertEqual(len(all), 4)
422 # We can't know which order SUB1 and SUB2 will appear in.
423 # Not flipped: SUB11, SUB1, SUB2, TESTFN
424 # flipped: SUB2, SUB11, SUB1, TESTFN
425 flipped = all[3][1][0] != "SUB1"
426 all[3][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000427 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000428 self.assertEqual(all[flipped], (sub11_path, [], []))
429 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000430 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000431
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000432 if hasattr(os, "symlink"):
433 # Walk, following symlinks.
434 for root, dirs, files in os.walk(walk_path, followlinks=True):
435 if root == link_path:
436 self.assertEqual(dirs, [])
437 self.assertEqual(files, ["tmp4"])
438 break
439 else:
440 self.fail("Didn't follow symlink with followlinks=True")
Tim Petersc4e09402003-04-25 07:11:48 +0000441
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000442 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000443 # Tear everything down. This is a decent use for bottom-up on
444 # Windows, which doesn't have a recursive delete command. The
445 # (not so) subtlety is that rmdir will fail unless the dir's
446 # kids are removed first, so bottom up is essential.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000447 for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000448 for name in files:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000449 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000450 for name in dirs:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000451 dirname = os.path.join(root, name)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000452 if not os.path.islink(dirname):
453 os.rmdir(dirname)
454 else:
455 os.remove(dirname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000456 os.rmdir(test_support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000457
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000458class MakedirTests (unittest.TestCase):
459 def setUp(self):
460 os.mkdir(test_support.TESTFN)
461
462 def test_makedir(self):
463 base = test_support.TESTFN
464 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
465 os.makedirs(path) # Should work
466 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
467 os.makedirs(path)
468
469 # Try paths with a '.' in them
470 self.failUnlessRaises(OSError, os.makedirs, os.curdir)
471 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
472 os.makedirs(path)
473 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
474 'dir5', 'dir6')
475 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000476
Tim Peters58eb11c2004-01-18 20:29:55 +0000477
478
479
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000480 def tearDown(self):
481 path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
482 'dir4', 'dir5', 'dir6')
483 # If the tests failed, the bottom-most directory ('../dir6')
484 # may not have been created, so we look for the outermost directory
485 # that exists.
486 while not os.path.exists(path) and path != test_support.TESTFN:
487 path = os.path.dirname(path)
488
489 os.removedirs(path)
490
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000491class DevNullTests (unittest.TestCase):
492 def test_devnull(self):
493 f = file(os.devnull, 'w')
494 f.write('hello')
495 f.close()
496 f = file(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000497 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000498 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000499
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000500class URandomTests (unittest.TestCase):
501 def test_urandom(self):
502 try:
503 self.assertEqual(len(os.urandom(1)), 1)
504 self.assertEqual(len(os.urandom(10)), 10)
505 self.assertEqual(len(os.urandom(100)), 100)
506 self.assertEqual(len(os.urandom(1000)), 1000)
Gregory P. Smithd7122032008-09-02 05:36:11 +0000507 # see http://bugs.python.org/issue3708
508 self.assertEqual(len(os.urandom(0.9)), 0)
509 self.assertEqual(len(os.urandom(1.1)), 1)
510 self.assertEqual(len(os.urandom(2.0)), 2)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000511 except NotImplementedError:
512 pass
513
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000514class Win32ErrorTests(unittest.TestCase):
515 def test_rename(self):
516 self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak")
517
518 def test_remove(self):
519 self.assertRaises(WindowsError, os.remove, test_support.TESTFN)
520
521 def test_chdir(self):
522 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
523
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000524 def test_mkdir(self):
525 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
526
527 def test_utime(self):
528 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, None)
529
530 def test_access(self):
531 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, 0)
532
533 def test_chmod(self):
534 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, 0)
535
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000536class TestInvalidFD(unittest.TestCase):
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000537 singles = ["fchdir", "fdopen", "dup", "fdatasync", "fstat",
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000538 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000539 #singles.append("close")
540 #We omit close because it doesn'r raise an exception on some platforms
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000541 def get_single(f):
542 def helper(self):
543 if getattr(os, f, None):
544 self.assertRaises(OSError, getattr(os, f), 10)
545 return helper
546 for f in singles:
547 locals()["test_"+f] = get_single(f)
548
549 def test_isatty(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000550 if hasattr(os, "isatty"):
551 self.assertEqual(os.isatty(10), False)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000552
553 def test_closerange(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000554 if hasattr(os, "closerange"):
555 self.assertEqual(os.closerange(10, 20), None)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000556
557 def test_dup2(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000558 if hasattr(os, "dup2"):
559 self.assertRaises(OSError, os.dup2, 10, 20)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000560
561 def test_fchmod(self):
562 if hasattr(os, "fchmod"):
563 self.assertRaises(OSError, os.fchmod, 10, 0)
564
565 def test_fchown(self):
566 if hasattr(os, "fchown"):
Kristján Valur Jónsson8adc0b52009-01-15 09:09:13 +0000567 self.assertRaises(OSError, os.fchown, 10, -1, -1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000568
569 def test_fpathconf(self):
570 if hasattr(os, "fpathconf"):
Benjamin Petersonf320c222009-01-17 04:39:05 +0000571 self.assertRaises(OSError, os.fpathconf, 10, "PC_NAME_MAX")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000572
573 def test_ftruncate(self):
574 if hasattr(os, "ftruncate"):
Kristján Valur Jónsson2e659ce2009-01-19 13:10:27 +0000575 self.assertRaises(OSError, os.ftruncate, 10, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000576
577 def test_lseek(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000578 if hasattr(os, "lseek"):
579 self.assertRaises(OSError, os.lseek, 10, 0, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000580
581 def test_read(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000582 if hasattr(os, "read"):
583 self.assertRaises(OSError, os.read, 10, 1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000584
585 def test_tcsetpgrpt(self):
586 if hasattr(os, "tcsetpgrp"):
587 self.assertRaises(OSError, os.tcsetpgrp, 10, 0)
588
589 def test_write(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000590 if hasattr(os, "write"):
591 self.assertRaises(OSError, os.write, 10, " ")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000592
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000593if sys.platform != 'win32':
594 class Win32ErrorTests(unittest.TestCase):
595 pass
596
Fred Drake2e2be372001-09-20 21:33:42 +0000597def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000598 test_support.run_unittest(
Martin v. Löwisee1e06d2006-07-02 18:44:00 +0000599 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000600 TemporaryFileTests,
601 StatAttributeTests,
602 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000603 WalkTests,
604 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000605 DevNullTests,
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000606 URandomTests,
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000607 Win32ErrorTests,
608 TestInvalidFD
Walter Dörwald21d3a322003-05-01 17:45:56 +0000609 )
Fred Drake2e2be372001-09-20 21:33:42 +0000610
611if __name__ == "__main__":
612 test_main()