blob: de1d06ea136d9edf76010176ad1a3db5d448136e [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
Brian Curtine5aa8862010-04-02 23:26:06 +000010import signal
11import subprocess
12import time
Walter Dörwald21d3a322003-05-01 17:45:56 +000013from test import test_support
Fred Drake38c2ef02001-07-17 20:52:51 +000014
Barry Warsaw60f01882001-08-22 19:24:42 +000015warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, __name__)
16warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, __name__)
17
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000018# Tests creating TESTFN
19class FileTests(unittest.TestCase):
20 def setUp(self):
21 if os.path.exists(test_support.TESTFN):
22 os.unlink(test_support.TESTFN)
23 tearDown = setUp
24
25 def test_access(self):
26 f = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
27 os.close(f)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000028 self.assertTrue(os.access(test_support.TESTFN, os.W_OK))
Tim Peters16a39322006-07-03 08:23:19 +000029
Georg Brandl309501a2008-01-19 20:22:13 +000030 def test_closerange(self):
Antoine Pitroubebb18b2008-08-17 14:43:41 +000031 first = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
32 # We must allocate two consecutive file descriptors, otherwise
33 # it will mess up other file descriptors (perhaps even the three
34 # standard ones).
35 second = os.dup(first)
36 try:
37 retries = 0
38 while second != first + 1:
39 os.close(first)
40 retries += 1
41 if retries > 10:
42 # XXX test skipped
Benjamin Peterson757b3c92009-05-16 18:44:34 +000043 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroubebb18b2008-08-17 14:43:41 +000044 first, second = second, os.dup(second)
45 finally:
46 os.close(second)
Georg Brandl309501a2008-01-19 20:22:13 +000047 # close a fd that is open, and one that isn't
Antoine Pitroubebb18b2008-08-17 14:43:41 +000048 os.closerange(first, first + 2)
49 self.assertRaises(OSError, os.write, first, "a")
Georg Brandl309501a2008-01-19 20:22:13 +000050
Benjamin Peterson10947a62010-06-30 17:11:08 +000051 @test_support.cpython_only
Hirokazu Yamamoto74ce88f2008-09-08 23:03:47 +000052 def test_rename(self):
53 path = unicode(test_support.TESTFN)
54 old = sys.getrefcount(path)
55 self.assertRaises(TypeError, os.rename, path, 0)
56 new = sys.getrefcount(path)
57 self.assertEqual(old, new)
58
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000059
Fred Drake38c2ef02001-07-17 20:52:51 +000060class TemporaryFileTests(unittest.TestCase):
61 def setUp(self):
62 self.files = []
Walter Dörwald21d3a322003-05-01 17:45:56 +000063 os.mkdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000064
65 def tearDown(self):
66 for name in self.files:
67 os.unlink(name)
Walter Dörwald21d3a322003-05-01 17:45:56 +000068 os.rmdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000069
70 def check_tempfile(self, name):
71 # make sure it doesn't already exist:
Benjamin Peterson5c8da862009-06-30 22:57:08 +000072 self.assertFalse(os.path.exists(name),
Fred Drake38c2ef02001-07-17 20:52:51 +000073 "file already exists for temporary file")
74 # make sure we can create the file
75 open(name, "w")
76 self.files.append(name)
77
78 def test_tempnam(self):
79 if not hasattr(os, "tempnam"):
80 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +000081 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +000082 r"test_os$")
Fred Drake38c2ef02001-07-17 20:52:51 +000083 self.check_tempfile(os.tempnam())
84
Walter Dörwald21d3a322003-05-01 17:45:56 +000085 name = os.tempnam(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000086 self.check_tempfile(name)
87
Walter Dörwald21d3a322003-05-01 17:45:56 +000088 name = os.tempnam(test_support.TESTFN, "pfx")
Benjamin Peterson5c8da862009-06-30 22:57:08 +000089 self.assertTrue(os.path.basename(name)[:3] == "pfx")
Fred Drake38c2ef02001-07-17 20:52:51 +000090 self.check_tempfile(name)
91
92 def test_tmpfile(self):
93 if not hasattr(os, "tmpfile"):
94 return
Martin v. Löwisd2bbe522008-03-06 06:55:22 +000095 # As with test_tmpnam() below, the Windows implementation of tmpfile()
96 # attempts to create a file in the root directory of the current drive.
97 # On Vista and Server 2008, this test will always fail for normal users
98 # as writing to the root directory requires elevated privileges. With
99 # XP and below, the semantics of tmpfile() are the same, but the user
100 # running the test is more likely to have administrative privileges on
101 # their account already. If that's the case, then os.tmpfile() should
102 # work. In order to make this test as useful as possible, rather than
103 # trying to detect Windows versions or whether or not the user has the
104 # right permissions, just try and create a file in the root directory
105 # and see if it raises a 'Permission denied' OSError. If it does, then
106 # test that a subsequent call to os.tmpfile() raises the same error. If
107 # it doesn't, assume we're on XP or below and the user running the test
108 # has administrative privileges, and proceed with the test as normal.
109 if sys.platform == 'win32':
110 name = '\\python_test_os_test_tmpfile.txt'
111 if os.path.exists(name):
112 os.remove(name)
113 try:
114 fp = open(name, 'w')
115 except IOError, first:
116 # open() failed, assert tmpfile() fails in the same way.
117 # Although open() raises an IOError and os.tmpfile() raises an
118 # OSError(), 'args' will be (13, 'Permission denied') in both
119 # cases.
120 try:
121 fp = os.tmpfile()
122 except OSError, second:
123 self.assertEqual(first.args, second.args)
124 else:
125 self.fail("expected os.tmpfile() to raise OSError")
126 return
127 else:
128 # open() worked, therefore, tmpfile() should work. Close our
129 # dummy file and proceed with the test as normal.
130 fp.close()
131 os.remove(name)
132
Fred Drake38c2ef02001-07-17 20:52:51 +0000133 fp = os.tmpfile()
134 fp.write("foobar")
135 fp.seek(0,0)
136 s = fp.read()
137 fp.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000138 self.assertTrue(s == "foobar")
Fred Drake38c2ef02001-07-17 20:52:51 +0000139
140 def test_tmpnam(self):
141 if not hasattr(os, "tmpnam"):
142 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +0000143 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +0000144 r"test_os$")
Tim Peters5501b5e2003-04-28 03:13:03 +0000145 name = os.tmpnam()
146 if sys.platform in ("win32",):
147 # The Windows tmpnam() seems useless. From the MS docs:
148 #
149 # The character string that tmpnam creates consists of
150 # the path prefix, defined by the entry P_tmpdir in the
151 # file STDIO.H, followed by a sequence consisting of the
152 # digit characters '0' through '9'; the numerical value
153 # of this string is in the range 1 - 65,535. Changing the
154 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
155 # change the operation of tmpnam.
156 #
157 # The really bizarre part is that, at least under MSVC6,
158 # P_tmpdir is "\\". That is, the path returned refers to
159 # the root of the current drive. That's a terrible place to
160 # put temp files, and, depending on privileges, the user
161 # may not even be able to open a file in the root directory.
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000162 self.assertFalse(os.path.exists(name),
Tim Peters5501b5e2003-04-28 03:13:03 +0000163 "file already exists for temporary file")
164 else:
165 self.check_tempfile(name)
Tim Peters87cc0c32001-07-21 01:41:30 +0000166
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000167# Test attributes on return values from os.*stat* family.
168class StatAttributeTests(unittest.TestCase):
169 def setUp(self):
Walter Dörwald21d3a322003-05-01 17:45:56 +0000170 os.mkdir(test_support.TESTFN)
171 self.fname = os.path.join(test_support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000172 f = open(self.fname, 'wb')
173 f.write("ABC")
174 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000175
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000176 def tearDown(self):
177 os.unlink(self.fname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000178 os.rmdir(test_support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000179
180 def test_stat_attributes(self):
181 if not hasattr(os, "stat"):
182 return
183
184 import stat
185 result = os.stat(self.fname)
186
187 # Make sure direct access works
188 self.assertEquals(result[stat.ST_SIZE], 3)
189 self.assertEquals(result.st_size, 3)
190
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000191 # Make sure all the attributes are there
192 members = dir(result)
193 for name in dir(stat):
194 if name[:3] == 'ST_':
195 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000196 if name.endswith("TIME"):
197 def trunc(x): return int(x)
198 else:
199 def trunc(x): return x
200 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000201 result[getattr(stat, name)])
Ezio Melottiaa980582010-01-23 23:04:36 +0000202 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000203
204 try:
205 result[200]
206 self.fail("No exception thrown")
207 except IndexError:
208 pass
209
210 # Make sure that assignment fails
211 try:
212 result.st_mode = 1
213 self.fail("No exception thrown")
Benjamin Petersonc262a692010-06-30 18:41:08 +0000214 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000215 pass
216
217 try:
218 result.st_rdev = 1
219 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000220 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000221 pass
222
223 try:
224 result.parrot = 1
225 self.fail("No exception thrown")
226 except AttributeError:
227 pass
228
229 # Use the stat_result constructor with a too-short tuple.
230 try:
231 result2 = os.stat_result((10,))
232 self.fail("No exception thrown")
233 except TypeError:
234 pass
235
236 # Use the constructr with a too-long tuple.
237 try:
238 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
239 except TypeError:
240 pass
241
Tim Peterse0c446b2001-10-18 21:57:37 +0000242
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000243 def test_statvfs_attributes(self):
244 if not hasattr(os, "statvfs"):
245 return
246
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000247 try:
248 result = os.statvfs(self.fname)
249 except OSError, e:
250 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000251 if e.errno == errno.ENOSYS:
252 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000253
254 # Make sure direct access works
Brett Cannon90f2cb42008-05-16 00:37:42 +0000255 self.assertEquals(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000256
Brett Cannon90f2cb42008-05-16 00:37:42 +0000257 # Make sure all the attributes are there.
258 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
259 'ffree', 'favail', 'flag', 'namemax')
260 for value, member in enumerate(members):
261 self.assertEquals(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000262
263 # Make sure that assignment really fails
264 try:
265 result.f_bfree = 1
266 self.fail("No exception thrown")
267 except TypeError:
268 pass
269
270 try:
271 result.parrot = 1
272 self.fail("No exception thrown")
273 except AttributeError:
274 pass
275
276 # Use the constructor with a too-short tuple.
277 try:
278 result2 = os.statvfs_result((10,))
279 self.fail("No exception thrown")
280 except TypeError:
281 pass
282
283 # Use the constructr with a too-long tuple.
284 try:
285 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
286 except TypeError:
287 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000288
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000289 def test_utime_dir(self):
290 delta = 1000000
291 st = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000292 # round to int, because some systems may support sub-second
293 # time stamps in stat, but not in utime.
294 os.utime(test_support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000295 st2 = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000296 self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000297
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000298 # Restrict test to Win32, since there is no guarantee other
299 # systems support centiseconds
300 if sys.platform == 'win32':
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000301 def get_file_system(path):
Hirokazu Yamamotoccfdcd02008-08-20 04:13:28 +0000302 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000303 import ctypes
Hirokazu Yamamotocd3b74d2008-08-20 16:15:28 +0000304 kernel32 = ctypes.windll.kernel32
305 buf = ctypes.create_string_buffer("", 100)
306 if kernel32.GetVolumeInformationA(root, None, 0, None, None, None, buf, len(buf)):
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000307 return buf.value
308
309 if get_file_system(test_support.TESTFN) == "NTFS":
310 def test_1565150(self):
311 t1 = 1159195039.25
312 os.utime(self.fname, (t1, t1))
313 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000314
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000315 def test_1686475(self):
316 # Verify that an open file can be stat'ed
317 try:
318 os.stat(r"c:\pagefile.sys")
319 except WindowsError, e:
Antoine Pitrou954ea642008-08-17 20:15:07 +0000320 if e.errno == 2: # file does not exist; cannot run test
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000321 return
322 self.fail("Could not stat pagefile.sys")
323
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000324from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000325
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000326class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000327 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000328 type2test = None
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000329 def _reference(self):
330 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
331 def _empty_mapping(self):
332 os.environ.clear()
333 return os.environ
334 def setUp(self):
335 self.__save = dict(os.environ)
336 os.environ.clear()
337 def tearDown(self):
338 os.environ.clear()
339 os.environ.update(self.__save)
340
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000341 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000342 def test_update2(self):
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000343 if os.path.exists("/bin/sh"):
344 os.environ.update(HELLO="World")
345 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
346 self.assertEquals(value, "World")
347
Tim Petersc4e09402003-04-25 07:11:48 +0000348class WalkTests(unittest.TestCase):
349 """Tests for os.walk()."""
350
351 def test_traversal(self):
352 import os
353 from os.path import join
354
355 # Build:
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000356 # TESTFN/
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000357 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000358 # tmp1
359 # SUB1/ a file kid and a directory kid
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000360 # tmp2
361 # SUB11/ no kids
362 # SUB2/ a file kid and a dirsymlink kid
363 # tmp3
364 # link/ a symlink to TESTFN.2
365 # TEST2/
366 # tmp4 a lone file
367 walk_path = join(test_support.TESTFN, "TEST1")
368 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000369 sub11_path = join(sub1_path, "SUB11")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000370 sub2_path = join(walk_path, "SUB2")
371 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000372 tmp2_path = join(sub1_path, "tmp2")
373 tmp3_path = join(sub2_path, "tmp3")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000374 link_path = join(sub2_path, "link")
375 t2_path = join(test_support.TESTFN, "TEST2")
376 tmp4_path = join(test_support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000377
378 # Create stuff.
379 os.makedirs(sub11_path)
380 os.makedirs(sub2_path)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000381 os.makedirs(t2_path)
382 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Tim Petersc4e09402003-04-25 07:11:48 +0000383 f = file(path, "w")
384 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
385 f.close()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000386 if hasattr(os, "symlink"):
387 os.symlink(os.path.abspath(t2_path), link_path)
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000388 sub2_tree = (sub2_path, ["link"], ["tmp3"])
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000389 else:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000390 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000391
392 # Walk top-down.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000393 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000394 self.assertEqual(len(all), 4)
395 # We can't know which order SUB1 and SUB2 will appear in.
396 # Not flipped: TESTFN, SUB1, SUB11, SUB2
397 # flipped: TESTFN, SUB2, SUB1, SUB11
398 flipped = all[0][1][0] != "SUB1"
399 all[0][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000400 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000401 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
402 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000403 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000404
405 # Prune the search.
406 all = []
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000407 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000408 all.append((root, dirs, files))
409 # Don't descend into SUB1.
410 if 'SUB1' in dirs:
411 # Note that this also mutates the dirs we appended to all!
412 dirs.remove('SUB1')
413 self.assertEqual(len(all), 2)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000414 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000415 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000416
417 # Walk bottom-up.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000418 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000419 self.assertEqual(len(all), 4)
420 # We can't know which order SUB1 and SUB2 will appear in.
421 # Not flipped: SUB11, SUB1, SUB2, TESTFN
422 # flipped: SUB2, SUB11, SUB1, TESTFN
423 flipped = all[3][1][0] != "SUB1"
424 all[3][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000425 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000426 self.assertEqual(all[flipped], (sub11_path, [], []))
427 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000428 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000429
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000430 if hasattr(os, "symlink"):
431 # Walk, following symlinks.
432 for root, dirs, files in os.walk(walk_path, followlinks=True):
433 if root == link_path:
434 self.assertEqual(dirs, [])
435 self.assertEqual(files, ["tmp4"])
436 break
437 else:
438 self.fail("Didn't follow symlink with followlinks=True")
Tim Petersc4e09402003-04-25 07:11:48 +0000439
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000440 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000441 # Tear everything down. This is a decent use for bottom-up on
442 # Windows, which doesn't have a recursive delete command. The
443 # (not so) subtlety is that rmdir will fail unless the dir's
444 # kids are removed first, so bottom up is essential.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000445 for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000446 for name in files:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000447 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000448 for name in dirs:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000449 dirname = os.path.join(root, name)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000450 if not os.path.islink(dirname):
451 os.rmdir(dirname)
452 else:
453 os.remove(dirname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000454 os.rmdir(test_support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000455
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000456class MakedirTests (unittest.TestCase):
457 def setUp(self):
458 os.mkdir(test_support.TESTFN)
459
460 def test_makedir(self):
461 base = test_support.TESTFN
462 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
463 os.makedirs(path) # Should work
464 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
465 os.makedirs(path)
466
467 # Try paths with a '.' in them
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000468 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000469 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
470 os.makedirs(path)
471 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
472 'dir5', 'dir6')
473 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000474
Tim Peters58eb11c2004-01-18 20:29:55 +0000475
476
477
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000478 def tearDown(self):
479 path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
480 'dir4', 'dir5', 'dir6')
481 # If the tests failed, the bottom-most directory ('../dir6')
482 # may not have been created, so we look for the outermost directory
483 # that exists.
484 while not os.path.exists(path) and path != test_support.TESTFN:
485 path = os.path.dirname(path)
486
487 os.removedirs(path)
488
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000489class DevNullTests (unittest.TestCase):
490 def test_devnull(self):
491 f = file(os.devnull, 'w')
492 f.write('hello')
493 f.close()
494 f = file(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000495 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000496 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000497
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000498class URandomTests (unittest.TestCase):
499 def test_urandom(self):
500 try:
501 self.assertEqual(len(os.urandom(1)), 1)
502 self.assertEqual(len(os.urandom(10)), 10)
503 self.assertEqual(len(os.urandom(100)), 100)
504 self.assertEqual(len(os.urandom(1000)), 1000)
Gregory P. Smithd7122032008-09-02 05:36:11 +0000505 # see http://bugs.python.org/issue3708
Mark Dickinson1b34d252010-01-01 17:27:30 +0000506 self.assertRaises(TypeError, os.urandom, 0.9)
507 self.assertRaises(TypeError, os.urandom, 1.1)
508 self.assertRaises(TypeError, os.urandom, 2.0)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000509 except NotImplementedError:
510 pass
511
Matthias Klosee9fbf2b2010-03-19 14:45:06 +0000512 def test_execvpe_with_bad_arglist(self):
513 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
514
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000515class Win32ErrorTests(unittest.TestCase):
516 def test_rename(self):
517 self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak")
518
519 def test_remove(self):
520 self.assertRaises(WindowsError, os.remove, test_support.TESTFN)
521
522 def test_chdir(self):
523 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
524
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000525 def test_mkdir(self):
Kristján Valur Jónssone20f54f2009-02-06 10:17:34 +0000526 f = open(test_support.TESTFN, "w")
527 try:
528 self.assertRaises(WindowsError, os.mkdir, test_support.TESTFN)
529 finally:
530 f.close()
531 os.unlink(test_support.TESTFN)
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000532
533 def test_utime(self):
534 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, None)
535
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000536 def test_chmod(self):
Kristján Valur Jónssone20f54f2009-02-06 10:17:34 +0000537 self.assertRaises(WindowsError, os.chmod, test_support.TESTFN, 0)
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000538
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000539class TestInvalidFD(unittest.TestCase):
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000540 singles = ["fchdir", "fdopen", "dup", "fdatasync", "fstat",
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000541 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000542 #singles.append("close")
543 #We omit close because it doesn'r raise an exception on some platforms
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000544 def get_single(f):
545 def helper(self):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000546 if hasattr(os, f):
547 self.check(getattr(os, f))
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000548 return helper
549 for f in singles:
550 locals()["test_"+f] = get_single(f)
551
Benjamin Peterson5539c782009-01-19 17:37:42 +0000552 def check(self, f, *args):
Benjamin Peterson1de05e92009-01-31 01:42:55 +0000553 try:
554 f(test_support.make_bad_fd(), *args)
555 except OSError as e:
556 self.assertEqual(e.errno, errno.EBADF)
557 else:
558 self.fail("%r didn't raise a OSError with a bad file descriptor"
559 % f)
Benjamin Peterson5539c782009-01-19 17:37:42 +0000560
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000561 def test_isatty(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000562 if hasattr(os, "isatty"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000563 self.assertEqual(os.isatty(test_support.make_bad_fd()), False)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000564
565 def test_closerange(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000566 if hasattr(os, "closerange"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000567 fd = test_support.make_bad_fd()
R. David Murray46ca2f22009-07-22 17:22:58 +0000568 # Make sure none of the descriptors we are about to close are
569 # currently valid (issue 6542).
570 for i in range(10):
571 try: os.fstat(fd+i)
572 except OSError:
573 pass
574 else:
575 break
576 if i < 2:
577 raise unittest.SkipTest(
578 "Unable to acquire a range of invalid file descriptors")
579 self.assertEqual(os.closerange(fd, fd + i-1), None)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000580
581 def test_dup2(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000582 if hasattr(os, "dup2"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000583 self.check(os.dup2, 20)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000584
585 def test_fchmod(self):
586 if hasattr(os, "fchmod"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000587 self.check(os.fchmod, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000588
589 def test_fchown(self):
590 if hasattr(os, "fchown"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000591 self.check(os.fchown, -1, -1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000592
593 def test_fpathconf(self):
594 if hasattr(os, "fpathconf"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000595 self.check(os.fpathconf, "PC_NAME_MAX")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000596
597 def test_ftruncate(self):
598 if hasattr(os, "ftruncate"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000599 self.check(os.ftruncate, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000600
601 def test_lseek(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000602 if hasattr(os, "lseek"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000603 self.check(os.lseek, 0, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000604
605 def test_read(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000606 if hasattr(os, "read"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000607 self.check(os.read, 1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000608
609 def test_tcsetpgrpt(self):
610 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000611 self.check(os.tcsetpgrp, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000612
613 def test_write(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000614 if hasattr(os, "write"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000615 self.check(os.write, " ")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000616
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000617if sys.platform != 'win32':
618 class Win32ErrorTests(unittest.TestCase):
619 pass
620
Gregory P. Smith6d307932009-04-05 23:43:58 +0000621 class PosixUidGidTests(unittest.TestCase):
622 if hasattr(os, 'setuid'):
623 def test_setuid(self):
624 if os.getuid() != 0:
625 self.assertRaises(os.error, os.setuid, 0)
626 self.assertRaises(OverflowError, os.setuid, 1<<32)
627
628 if hasattr(os, 'setgid'):
629 def test_setgid(self):
630 if os.getuid() != 0:
631 self.assertRaises(os.error, os.setgid, 0)
632 self.assertRaises(OverflowError, os.setgid, 1<<32)
633
634 if hasattr(os, 'seteuid'):
635 def test_seteuid(self):
636 if os.getuid() != 0:
637 self.assertRaises(os.error, os.seteuid, 0)
638 self.assertRaises(OverflowError, os.seteuid, 1<<32)
639
640 if hasattr(os, 'setegid'):
641 def test_setegid(self):
642 if os.getuid() != 0:
643 self.assertRaises(os.error, os.setegid, 0)
644 self.assertRaises(OverflowError, os.setegid, 1<<32)
645
646 if hasattr(os, 'setreuid'):
647 def test_setreuid(self):
648 if os.getuid() != 0:
649 self.assertRaises(os.error, os.setreuid, 0, 0)
650 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
651 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Gregory P. Smith467298c2010-03-06 07:35:19 +0000652
653 def test_setreuid_neg1(self):
654 # Needs to accept -1. We run this in a subprocess to avoid
655 # altering the test runner's process state (issue8045).
Gregory P. Smith467298c2010-03-06 07:35:19 +0000656 subprocess.check_call([
657 sys.executable, '-c',
658 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Gregory P. Smith6d307932009-04-05 23:43:58 +0000659
660 if hasattr(os, 'setregid'):
661 def test_setregid(self):
662 if os.getuid() != 0:
663 self.assertRaises(os.error, os.setregid, 0, 0)
664 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
665 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Gregory P. Smith467298c2010-03-06 07:35:19 +0000666
667 def test_setregid_neg1(self):
668 # Needs to accept -1. We run this in a subprocess to avoid
669 # altering the test runner's process state (issue8045).
Gregory P. Smith467298c2010-03-06 07:35:19 +0000670 subprocess.check_call([
671 sys.executable, '-c',
672 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Gregory P. Smith6d307932009-04-05 23:43:58 +0000673else:
674 class PosixUidGidTests(unittest.TestCase):
675 pass
676
Brian Curtine5aa8862010-04-02 23:26:06 +0000677@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
678class Win32KillTests(unittest.TestCase):
Brian Curtinb3dde132010-04-15 00:40:40 +0000679 def _kill(self, sig):
680 # Start sys.executable as a subprocess and communicate from the
681 # subprocess to the parent that the interpreter is ready. When it
682 # becomes ready, send *sig* via os.kill to the subprocess and check
683 # that the return code is equal to *sig*.
684 import ctypes
685 from ctypes import wintypes
686 import msvcrt
687
688 # Since we can't access the contents of the process' stdout until the
689 # process has exited, use PeekNamedPipe to see what's inside stdout
690 # without waiting. This is done so we can tell that the interpreter
691 # is started and running at a point where it could handle a signal.
692 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
693 PeekNamedPipe.restype = wintypes.BOOL
694 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
695 ctypes.POINTER(ctypes.c_char), # stdout buf
696 wintypes.DWORD, # Buffer size
697 ctypes.POINTER(wintypes.DWORD), # bytes read
698 ctypes.POINTER(wintypes.DWORD), # bytes avail
699 ctypes.POINTER(wintypes.DWORD)) # bytes left
700 msg = "running"
701 proc = subprocess.Popen([sys.executable, "-c",
702 "import sys;"
703 "sys.stdout.write('{}');"
704 "sys.stdout.flush();"
705 "input()".format(msg)],
706 stdout=subprocess.PIPE,
707 stderr=subprocess.PIPE,
708 stdin=subprocess.PIPE)
709
Brian Curtin83cba052010-05-28 15:49:21 +0000710 count, max = 0, 100
711 while count < max and proc.poll() is None:
712 # Create a string buffer to store the result of stdout from the pipe
713 buf = ctypes.create_string_buffer(len(msg))
714 # Obtain the text currently in proc.stdout
715 # Bytes read/avail/left are left as NULL and unused
716 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
717 buf, ctypes.sizeof(buf), None, None, None)
718 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
719 if buf.value:
720 self.assertEqual(msg, buf.value)
721 break
722 time.sleep(0.1)
723 count += 1
724 else:
725 self.fail("Did not receive communication from the subprocess")
Brian Curtinb3dde132010-04-15 00:40:40 +0000726
Brian Curtine5aa8862010-04-02 23:26:06 +0000727 os.kill(proc.pid, sig)
728 self.assertEqual(proc.wait(), sig)
729
730 def test_kill_sigterm(self):
731 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinb3dde132010-04-15 00:40:40 +0000732 self._kill(signal.SIGTERM)
Brian Curtine5aa8862010-04-02 23:26:06 +0000733
734 def test_kill_int(self):
735 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinb3dde132010-04-15 00:40:40 +0000736 self._kill(100)
Brian Curtine5aa8862010-04-02 23:26:06 +0000737
738 def _kill_with_event(self, event, name):
739 # Run a script which has console control handling enabled.
740 proc = subprocess.Popen([sys.executable,
741 os.path.join(os.path.dirname(__file__),
742 "win_console_handler.py")],
743 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
744 # Let the interpreter startup before we send signals. See #3137.
Brian Curtinfce1d312010-04-05 19:04:23 +0000745 time.sleep(0.5)
Brian Curtine5aa8862010-04-02 23:26:06 +0000746 os.kill(proc.pid, event)
747 # proc.send_signal(event) could also be done here.
748 # Allow time for the signal to be passed and the process to exit.
Brian Curtinfce1d312010-04-05 19:04:23 +0000749 time.sleep(0.5)
Brian Curtine5aa8862010-04-02 23:26:06 +0000750 if not proc.poll():
751 # Forcefully kill the process if we weren't able to signal it.
752 os.kill(proc.pid, signal.SIGINT)
753 self.fail("subprocess did not stop on {}".format(name))
754
755 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
756 def test_CTRL_C_EVENT(self):
757 from ctypes import wintypes
758 import ctypes
759
760 # Make a NULL value by creating a pointer with no argument.
761 NULL = ctypes.POINTER(ctypes.c_int)()
762 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
763 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
764 wintypes.BOOL)
765 SetConsoleCtrlHandler.restype = wintypes.BOOL
766
767 # Calling this with NULL and FALSE causes the calling process to
768 # handle CTRL+C, rather than ignore it. This property is inherited
769 # by subprocesses.
770 SetConsoleCtrlHandler(NULL, 0)
771
772 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
773
774 def test_CTRL_BREAK_EVENT(self):
775 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
776
777
Fred Drake2e2be372001-09-20 21:33:42 +0000778def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000779 test_support.run_unittest(
Martin v. Löwisee1e06d2006-07-02 18:44:00 +0000780 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000781 TemporaryFileTests,
782 StatAttributeTests,
783 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000784 WalkTests,
785 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000786 DevNullTests,
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000787 URandomTests,
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000788 Win32ErrorTests,
Gregory P. Smith6d307932009-04-05 23:43:58 +0000789 TestInvalidFD,
Brian Curtine5aa8862010-04-02 23:26:06 +0000790 PosixUidGidTests,
791 Win32KillTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000792 )
Fred Drake2e2be372001-09-20 21:33:42 +0000793
794if __name__ == "__main__":
795 test_main()