blob: 44cc4cb7134ab0dcb6e19544b99e90ef4c5238de [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
Benjamin Peterson1de05e92009-01-31 01:42:55 +00006import errno
Fred Drake38c2ef02001-07-17 20:52:51 +00007import unittest
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +00008import warnings
Martin v. Löwis8e0d4942006-05-04 10:08:42 +00009import sys
Walter Dörwald21d3a322003-05-01 17:45:56 +000010from test import test_support
Fred Drake38c2ef02001-07-17 20:52:51 +000011
Barry Warsaw60f01882001-08-22 19:24:42 +000012warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, __name__)
13warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, __name__)
14
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000015# Tests creating TESTFN
16class FileTests(unittest.TestCase):
17 def setUp(self):
18 if os.path.exists(test_support.TESTFN):
19 os.unlink(test_support.TESTFN)
20 tearDown = setUp
21
22 def test_access(self):
23 f = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
24 os.close(f)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000025 self.assertTrue(os.access(test_support.TESTFN, os.W_OK))
Tim Peters16a39322006-07-03 08:23:19 +000026
Georg Brandl309501a2008-01-19 20:22:13 +000027 def test_closerange(self):
Antoine Pitroubebb18b2008-08-17 14:43:41 +000028 first = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
29 # We must allocate two consecutive file descriptors, otherwise
30 # it will mess up other file descriptors (perhaps even the three
31 # standard ones).
32 second = os.dup(first)
33 try:
34 retries = 0
35 while second != first + 1:
36 os.close(first)
37 retries += 1
38 if retries > 10:
39 # XXX test skipped
Benjamin Peterson757b3c92009-05-16 18:44:34 +000040 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroubebb18b2008-08-17 14:43:41 +000041 first, second = second, os.dup(second)
42 finally:
43 os.close(second)
Georg Brandl309501a2008-01-19 20:22:13 +000044 # close a fd that is open, and one that isn't
Antoine Pitroubebb18b2008-08-17 14:43:41 +000045 os.closerange(first, first + 2)
46 self.assertRaises(OSError, os.write, first, "a")
Georg Brandl309501a2008-01-19 20:22:13 +000047
Hirokazu Yamamoto74ce88f2008-09-08 23:03:47 +000048 def test_rename(self):
49 path = unicode(test_support.TESTFN)
50 old = sys.getrefcount(path)
51 self.assertRaises(TypeError, os.rename, path, 0)
52 new = sys.getrefcount(path)
53 self.assertEqual(old, new)
54
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000055
Fred Drake38c2ef02001-07-17 20:52:51 +000056class TemporaryFileTests(unittest.TestCase):
57 def setUp(self):
58 self.files = []
Walter Dörwald21d3a322003-05-01 17:45:56 +000059 os.mkdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000060
61 def tearDown(self):
62 for name in self.files:
63 os.unlink(name)
Walter Dörwald21d3a322003-05-01 17:45:56 +000064 os.rmdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000065
66 def check_tempfile(self, name):
67 # make sure it doesn't already exist:
Benjamin Peterson5c8da862009-06-30 22:57:08 +000068 self.assertFalse(os.path.exists(name),
Fred Drake38c2ef02001-07-17 20:52:51 +000069 "file already exists for temporary file")
70 # make sure we can create the file
71 open(name, "w")
72 self.files.append(name)
73
74 def test_tempnam(self):
75 if not hasattr(os, "tempnam"):
76 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +000077 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +000078 r"test_os$")
Fred Drake38c2ef02001-07-17 20:52:51 +000079 self.check_tempfile(os.tempnam())
80
Walter Dörwald21d3a322003-05-01 17:45:56 +000081 name = os.tempnam(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000082 self.check_tempfile(name)
83
Walter Dörwald21d3a322003-05-01 17:45:56 +000084 name = os.tempnam(test_support.TESTFN, "pfx")
Benjamin Peterson5c8da862009-06-30 22:57:08 +000085 self.assertTrue(os.path.basename(name)[:3] == "pfx")
Fred Drake38c2ef02001-07-17 20:52:51 +000086 self.check_tempfile(name)
87
88 def test_tmpfile(self):
89 if not hasattr(os, "tmpfile"):
90 return
Martin v. Löwisd2bbe522008-03-06 06:55:22 +000091 # As with test_tmpnam() below, the Windows implementation of tmpfile()
92 # attempts to create a file in the root directory of the current drive.
93 # On Vista and Server 2008, this test will always fail for normal users
94 # as writing to the root directory requires elevated privileges. With
95 # XP and below, the semantics of tmpfile() are the same, but the user
96 # running the test is more likely to have administrative privileges on
97 # their account already. If that's the case, then os.tmpfile() should
98 # work. In order to make this test as useful as possible, rather than
99 # trying to detect Windows versions or whether or not the user has the
100 # right permissions, just try and create a file in the root directory
101 # and see if it raises a 'Permission denied' OSError. If it does, then
102 # test that a subsequent call to os.tmpfile() raises the same error. If
103 # it doesn't, assume we're on XP or below and the user running the test
104 # has administrative privileges, and proceed with the test as normal.
105 if sys.platform == 'win32':
106 name = '\\python_test_os_test_tmpfile.txt'
107 if os.path.exists(name):
108 os.remove(name)
109 try:
110 fp = open(name, 'w')
111 except IOError, first:
112 # open() failed, assert tmpfile() fails in the same way.
113 # Although open() raises an IOError and os.tmpfile() raises an
114 # OSError(), 'args' will be (13, 'Permission denied') in both
115 # cases.
116 try:
117 fp = os.tmpfile()
118 except OSError, second:
119 self.assertEqual(first.args, second.args)
120 else:
121 self.fail("expected os.tmpfile() to raise OSError")
122 return
123 else:
124 # open() worked, therefore, tmpfile() should work. Close our
125 # dummy file and proceed with the test as normal.
126 fp.close()
127 os.remove(name)
128
Fred Drake38c2ef02001-07-17 20:52:51 +0000129 fp = os.tmpfile()
130 fp.write("foobar")
131 fp.seek(0,0)
132 s = fp.read()
133 fp.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000134 self.assertTrue(s == "foobar")
Fred Drake38c2ef02001-07-17 20:52:51 +0000135
136 def test_tmpnam(self):
137 if not hasattr(os, "tmpnam"):
138 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +0000139 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +0000140 r"test_os$")
Tim Peters5501b5e2003-04-28 03:13:03 +0000141 name = os.tmpnam()
142 if sys.platform in ("win32",):
143 # The Windows tmpnam() seems useless. From the MS docs:
144 #
145 # The character string that tmpnam creates consists of
146 # the path prefix, defined by the entry P_tmpdir in the
147 # file STDIO.H, followed by a sequence consisting of the
148 # digit characters '0' through '9'; the numerical value
149 # of this string is in the range 1 - 65,535. Changing the
150 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
151 # change the operation of tmpnam.
152 #
153 # The really bizarre part is that, at least under MSVC6,
154 # P_tmpdir is "\\". That is, the path returned refers to
155 # the root of the current drive. That's a terrible place to
156 # put temp files, and, depending on privileges, the user
157 # may not even be able to open a file in the root directory.
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000158 self.assertFalse(os.path.exists(name),
Tim Peters5501b5e2003-04-28 03:13:03 +0000159 "file already exists for temporary file")
160 else:
161 self.check_tempfile(name)
Tim Peters87cc0c32001-07-21 01:41:30 +0000162
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000163# Test attributes on return values from os.*stat* family.
164class StatAttributeTests(unittest.TestCase):
165 def setUp(self):
Walter Dörwald21d3a322003-05-01 17:45:56 +0000166 os.mkdir(test_support.TESTFN)
167 self.fname = os.path.join(test_support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000168 f = open(self.fname, 'wb')
169 f.write("ABC")
170 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000171
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000172 def tearDown(self):
173 os.unlink(self.fname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000174 os.rmdir(test_support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000175
176 def test_stat_attributes(self):
177 if not hasattr(os, "stat"):
178 return
179
180 import stat
181 result = os.stat(self.fname)
182
183 # Make sure direct access works
184 self.assertEquals(result[stat.ST_SIZE], 3)
185 self.assertEquals(result.st_size, 3)
186
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000187 # Make sure all the attributes are there
188 members = dir(result)
189 for name in dir(stat):
190 if name[:3] == 'ST_':
191 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000192 if name.endswith("TIME"):
193 def trunc(x): return int(x)
194 else:
195 def trunc(x): return x
196 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000197 result[getattr(stat, name)])
Ezio Melottiaa980582010-01-23 23:04:36 +0000198 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000199
200 try:
201 result[200]
202 self.fail("No exception thrown")
203 except IndexError:
204 pass
205
206 # Make sure that assignment fails
207 try:
208 result.st_mode = 1
209 self.fail("No exception thrown")
210 except TypeError:
211 pass
212
213 try:
214 result.st_rdev = 1
215 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000216 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000217 pass
218
219 try:
220 result.parrot = 1
221 self.fail("No exception thrown")
222 except AttributeError:
223 pass
224
225 # Use the stat_result constructor with a too-short tuple.
226 try:
227 result2 = os.stat_result((10,))
228 self.fail("No exception thrown")
229 except TypeError:
230 pass
231
232 # Use the constructr with a too-long tuple.
233 try:
234 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
235 except TypeError:
236 pass
237
Tim Peterse0c446b2001-10-18 21:57:37 +0000238
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000239 def test_statvfs_attributes(self):
240 if not hasattr(os, "statvfs"):
241 return
242
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000243 try:
244 result = os.statvfs(self.fname)
245 except OSError, e:
246 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000247 if e.errno == errno.ENOSYS:
248 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000249
250 # Make sure direct access works
Brett Cannon90f2cb42008-05-16 00:37:42 +0000251 self.assertEquals(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000252
Brett Cannon90f2cb42008-05-16 00:37:42 +0000253 # Make sure all the attributes are there.
254 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
255 'ffree', 'favail', 'flag', 'namemax')
256 for value, member in enumerate(members):
257 self.assertEquals(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000258
259 # Make sure that assignment really fails
260 try:
261 result.f_bfree = 1
262 self.fail("No exception thrown")
263 except TypeError:
264 pass
265
266 try:
267 result.parrot = 1
268 self.fail("No exception thrown")
269 except AttributeError:
270 pass
271
272 # Use the constructor with a too-short tuple.
273 try:
274 result2 = os.statvfs_result((10,))
275 self.fail("No exception thrown")
276 except TypeError:
277 pass
278
279 # Use the constructr with a too-long tuple.
280 try:
281 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
282 except TypeError:
283 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000284
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000285 def test_utime_dir(self):
286 delta = 1000000
287 st = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000288 # round to int, because some systems may support sub-second
289 # time stamps in stat, but not in utime.
290 os.utime(test_support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000291 st2 = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000292 self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000293
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000294 # Restrict test to Win32, since there is no guarantee other
295 # systems support centiseconds
296 if sys.platform == 'win32':
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000297 def get_file_system(path):
Hirokazu Yamamotoccfdcd02008-08-20 04:13:28 +0000298 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000299 import ctypes
Hirokazu Yamamotocd3b74d2008-08-20 16:15:28 +0000300 kernel32 = ctypes.windll.kernel32
301 buf = ctypes.create_string_buffer("", 100)
302 if kernel32.GetVolumeInformationA(root, None, 0, None, None, None, buf, len(buf)):
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000303 return buf.value
304
305 if get_file_system(test_support.TESTFN) == "NTFS":
306 def test_1565150(self):
307 t1 = 1159195039.25
308 os.utime(self.fname, (t1, t1))
309 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000310
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000311 def test_1686475(self):
312 # Verify that an open file can be stat'ed
313 try:
314 os.stat(r"c:\pagefile.sys")
315 except WindowsError, e:
Antoine Pitrou954ea642008-08-17 20:15:07 +0000316 if e.errno == 2: # file does not exist; cannot run test
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000317 return
318 self.fail("Could not stat pagefile.sys")
319
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000320from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000321
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000322class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000323 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000324 type2test = None
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000325 def _reference(self):
326 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
327 def _empty_mapping(self):
328 os.environ.clear()
329 return os.environ
330 def setUp(self):
331 self.__save = dict(os.environ)
332 os.environ.clear()
333 def tearDown(self):
334 os.environ.clear()
335 os.environ.update(self.__save)
336
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000337 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000338 def test_update2(self):
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000339 if os.path.exists("/bin/sh"):
340 os.environ.update(HELLO="World")
341 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
342 self.assertEquals(value, "World")
343
Tim Petersc4e09402003-04-25 07:11:48 +0000344class WalkTests(unittest.TestCase):
345 """Tests for os.walk()."""
346
347 def test_traversal(self):
348 import os
349 from os.path import join
350
351 # Build:
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000352 # TESTFN/
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000353 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000354 # tmp1
355 # SUB1/ a file kid and a directory kid
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000356 # tmp2
357 # SUB11/ no kids
358 # SUB2/ a file kid and a dirsymlink kid
359 # tmp3
360 # link/ a symlink to TESTFN.2
361 # TEST2/
362 # tmp4 a lone file
363 walk_path = join(test_support.TESTFN, "TEST1")
364 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000365 sub11_path = join(sub1_path, "SUB11")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000366 sub2_path = join(walk_path, "SUB2")
367 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000368 tmp2_path = join(sub1_path, "tmp2")
369 tmp3_path = join(sub2_path, "tmp3")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000370 link_path = join(sub2_path, "link")
371 t2_path = join(test_support.TESTFN, "TEST2")
372 tmp4_path = join(test_support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000373
374 # Create stuff.
375 os.makedirs(sub11_path)
376 os.makedirs(sub2_path)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000377 os.makedirs(t2_path)
378 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Tim Petersc4e09402003-04-25 07:11:48 +0000379 f = file(path, "w")
380 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
381 f.close()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000382 if hasattr(os, "symlink"):
383 os.symlink(os.path.abspath(t2_path), link_path)
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000384 sub2_tree = (sub2_path, ["link"], ["tmp3"])
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000385 else:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000386 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000387
388 # Walk top-down.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000389 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000390 self.assertEqual(len(all), 4)
391 # We can't know which order SUB1 and SUB2 will appear in.
392 # Not flipped: TESTFN, SUB1, SUB11, SUB2
393 # flipped: TESTFN, SUB2, SUB1, SUB11
394 flipped = all[0][1][0] != "SUB1"
395 all[0][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000396 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000397 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
398 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000399 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000400
401 # Prune the search.
402 all = []
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000403 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000404 all.append((root, dirs, files))
405 # Don't descend into SUB1.
406 if 'SUB1' in dirs:
407 # Note that this also mutates the dirs we appended to all!
408 dirs.remove('SUB1')
409 self.assertEqual(len(all), 2)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000410 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000411 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000412
413 # Walk bottom-up.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000414 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000415 self.assertEqual(len(all), 4)
416 # We can't know which order SUB1 and SUB2 will appear in.
417 # Not flipped: SUB11, SUB1, SUB2, TESTFN
418 # flipped: SUB2, SUB11, SUB1, TESTFN
419 flipped = all[3][1][0] != "SUB1"
420 all[3][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000421 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000422 self.assertEqual(all[flipped], (sub11_path, [], []))
423 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000424 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000425
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000426 if hasattr(os, "symlink"):
427 # Walk, following symlinks.
428 for root, dirs, files in os.walk(walk_path, followlinks=True):
429 if root == link_path:
430 self.assertEqual(dirs, [])
431 self.assertEqual(files, ["tmp4"])
432 break
433 else:
434 self.fail("Didn't follow symlink with followlinks=True")
Tim Petersc4e09402003-04-25 07:11:48 +0000435
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000436 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000437 # Tear everything down. This is a decent use for bottom-up on
438 # Windows, which doesn't have a recursive delete command. The
439 # (not so) subtlety is that rmdir will fail unless the dir's
440 # kids are removed first, so bottom up is essential.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000441 for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000442 for name in files:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000443 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000444 for name in dirs:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000445 dirname = os.path.join(root, name)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000446 if not os.path.islink(dirname):
447 os.rmdir(dirname)
448 else:
449 os.remove(dirname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000450 os.rmdir(test_support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000451
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000452class MakedirTests (unittest.TestCase):
453 def setUp(self):
454 os.mkdir(test_support.TESTFN)
455
456 def test_makedir(self):
457 base = test_support.TESTFN
458 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
459 os.makedirs(path) # Should work
460 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
461 os.makedirs(path)
462
463 # Try paths with a '.' in them
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000464 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000465 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
466 os.makedirs(path)
467 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
468 'dir5', 'dir6')
469 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000470
Tim Peters58eb11c2004-01-18 20:29:55 +0000471
472
473
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000474 def tearDown(self):
475 path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
476 'dir4', 'dir5', 'dir6')
477 # If the tests failed, the bottom-most directory ('../dir6')
478 # may not have been created, so we look for the outermost directory
479 # that exists.
480 while not os.path.exists(path) and path != test_support.TESTFN:
481 path = os.path.dirname(path)
482
483 os.removedirs(path)
484
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000485class DevNullTests (unittest.TestCase):
486 def test_devnull(self):
487 f = file(os.devnull, 'w')
488 f.write('hello')
489 f.close()
490 f = file(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000491 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000492 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000493
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000494class URandomTests (unittest.TestCase):
495 def test_urandom(self):
496 try:
497 self.assertEqual(len(os.urandom(1)), 1)
498 self.assertEqual(len(os.urandom(10)), 10)
499 self.assertEqual(len(os.urandom(100)), 100)
500 self.assertEqual(len(os.urandom(1000)), 1000)
Gregory P. Smithd7122032008-09-02 05:36:11 +0000501 # see http://bugs.python.org/issue3708
Mark Dickinson1b34d252010-01-01 17:27:30 +0000502 self.assertRaises(TypeError, os.urandom, 0.9)
503 self.assertRaises(TypeError, os.urandom, 1.1)
504 self.assertRaises(TypeError, os.urandom, 2.0)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000505 except NotImplementedError:
506 pass
507
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000508class Win32ErrorTests(unittest.TestCase):
509 def test_rename(self):
510 self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak")
511
512 def test_remove(self):
513 self.assertRaises(WindowsError, os.remove, test_support.TESTFN)
514
515 def test_chdir(self):
516 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
517
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000518 def test_mkdir(self):
Kristján Valur Jónssone20f54f2009-02-06 10:17:34 +0000519 f = open(test_support.TESTFN, "w")
520 try:
521 self.assertRaises(WindowsError, os.mkdir, test_support.TESTFN)
522 finally:
523 f.close()
524 os.unlink(test_support.TESTFN)
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000525
526 def test_utime(self):
527 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, None)
528
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000529 def test_chmod(self):
Kristján Valur Jónssone20f54f2009-02-06 10:17:34 +0000530 self.assertRaises(WindowsError, os.chmod, test_support.TESTFN, 0)
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000531
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000532class TestInvalidFD(unittest.TestCase):
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000533 singles = ["fchdir", "fdopen", "dup", "fdatasync", "fstat",
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000534 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000535 #singles.append("close")
536 #We omit close because it doesn'r raise an exception on some platforms
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000537 def get_single(f):
538 def helper(self):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000539 if hasattr(os, f):
540 self.check(getattr(os, f))
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000541 return helper
542 for f in singles:
543 locals()["test_"+f] = get_single(f)
544
Benjamin Peterson5539c782009-01-19 17:37:42 +0000545 def check(self, f, *args):
Benjamin Peterson1de05e92009-01-31 01:42:55 +0000546 try:
547 f(test_support.make_bad_fd(), *args)
548 except OSError as e:
549 self.assertEqual(e.errno, errno.EBADF)
550 else:
551 self.fail("%r didn't raise a OSError with a bad file descriptor"
552 % f)
Benjamin Peterson5539c782009-01-19 17:37:42 +0000553
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000554 def test_isatty(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000555 if hasattr(os, "isatty"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000556 self.assertEqual(os.isatty(test_support.make_bad_fd()), False)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000557
558 def test_closerange(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000559 if hasattr(os, "closerange"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000560 fd = test_support.make_bad_fd()
R. David Murray46ca2f22009-07-22 17:22:58 +0000561 # Make sure none of the descriptors we are about to close are
562 # currently valid (issue 6542).
563 for i in range(10):
564 try: os.fstat(fd+i)
565 except OSError:
566 pass
567 else:
568 break
569 if i < 2:
570 raise unittest.SkipTest(
571 "Unable to acquire a range of invalid file descriptors")
572 self.assertEqual(os.closerange(fd, fd + i-1), None)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000573
574 def test_dup2(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000575 if hasattr(os, "dup2"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000576 self.check(os.dup2, 20)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000577
578 def test_fchmod(self):
579 if hasattr(os, "fchmod"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000580 self.check(os.fchmod, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000581
582 def test_fchown(self):
583 if hasattr(os, "fchown"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000584 self.check(os.fchown, -1, -1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000585
586 def test_fpathconf(self):
587 if hasattr(os, "fpathconf"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000588 self.check(os.fpathconf, "PC_NAME_MAX")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000589
590 def test_ftruncate(self):
591 if hasattr(os, "ftruncate"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000592 self.check(os.ftruncate, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000593
594 def test_lseek(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000595 if hasattr(os, "lseek"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000596 self.check(os.lseek, 0, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000597
598 def test_read(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000599 if hasattr(os, "read"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000600 self.check(os.read, 1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000601
602 def test_tcsetpgrpt(self):
603 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000604 self.check(os.tcsetpgrp, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000605
606 def test_write(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000607 if hasattr(os, "write"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000608 self.check(os.write, " ")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000609
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000610if sys.platform != 'win32':
611 class Win32ErrorTests(unittest.TestCase):
612 pass
613
Gregory P. Smith6d307932009-04-05 23:43:58 +0000614 class PosixUidGidTests(unittest.TestCase):
615 if hasattr(os, 'setuid'):
616 def test_setuid(self):
617 if os.getuid() != 0:
618 self.assertRaises(os.error, os.setuid, 0)
619 self.assertRaises(OverflowError, os.setuid, 1<<32)
620
621 if hasattr(os, 'setgid'):
622 def test_setgid(self):
623 if os.getuid() != 0:
624 self.assertRaises(os.error, os.setgid, 0)
625 self.assertRaises(OverflowError, os.setgid, 1<<32)
626
627 if hasattr(os, 'seteuid'):
628 def test_seteuid(self):
629 if os.getuid() != 0:
630 self.assertRaises(os.error, os.seteuid, 0)
631 self.assertRaises(OverflowError, os.seteuid, 1<<32)
632
633 if hasattr(os, 'setegid'):
634 def test_setegid(self):
635 if os.getuid() != 0:
636 self.assertRaises(os.error, os.setegid, 0)
637 self.assertRaises(OverflowError, os.setegid, 1<<32)
638
639 if hasattr(os, 'setreuid'):
640 def test_setreuid(self):
641 if os.getuid() != 0:
642 self.assertRaises(os.error, os.setreuid, 0, 0)
643 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
644 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Gregory P. Smith6a65f852010-03-01 05:43:43 +0000645 os.setreuid(-1, -1) # Does nothing, but it needs to accept -1
Gregory P. Smith6d307932009-04-05 23:43:58 +0000646
647 if hasattr(os, 'setregid'):
648 def test_setregid(self):
649 if os.getuid() != 0:
650 self.assertRaises(os.error, os.setregid, 0, 0)
651 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
652 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Gregory P. Smith6a65f852010-03-01 05:43:43 +0000653 os.setregid(-1, -1) # Does nothing, but it needs to accept -1
Gregory P. Smith6d307932009-04-05 23:43:58 +0000654else:
655 class PosixUidGidTests(unittest.TestCase):
656 pass
657
Fred Drake2e2be372001-09-20 21:33:42 +0000658def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000659 test_support.run_unittest(
Martin v. Löwisee1e06d2006-07-02 18:44:00 +0000660 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000661 TemporaryFileTests,
662 StatAttributeTests,
663 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000664 WalkTests,
665 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000666 DevNullTests,
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000667 URandomTests,
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000668 Win32ErrorTests,
Gregory P. Smith6d307932009-04-05 23:43:58 +0000669 TestInvalidFD,
670 PosixUidGidTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000671 )
Fred Drake2e2be372001-09-20 21:33:42 +0000672
673if __name__ == "__main__":
674 test_main()