blob: dd0696e328aa3ec33a9e59edd3b41a8cb7c13d4e [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
Antoine Pitrouf48a67b2013-08-16 20:44:38 +020013try:
14 import resource
15except ImportError:
16 resource = None
Barry Warsaw1e13eb02012-02-20 20:42:21 -050017
Walter Dörwald21d3a322003-05-01 17:45:56 +000018from test import test_support
Antoine Pitroue7587152013-08-24 20:52:27 +020019from test.script_helper import assert_python_ok
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +000020import mmap
21import uuid
Fred Drake38c2ef02001-07-17 20:52:51 +000022
Barry Warsaw60f01882001-08-22 19:24:42 +000023warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, __name__)
24warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, __name__)
25
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000026# Tests creating TESTFN
27class FileTests(unittest.TestCase):
28 def setUp(self):
29 if os.path.exists(test_support.TESTFN):
30 os.unlink(test_support.TESTFN)
31 tearDown = setUp
32
33 def test_access(self):
34 f = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
35 os.close(f)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000036 self.assertTrue(os.access(test_support.TESTFN, os.W_OK))
Tim Peters16a39322006-07-03 08:23:19 +000037
Georg Brandl309501a2008-01-19 20:22:13 +000038 def test_closerange(self):
Antoine Pitroubebb18b2008-08-17 14:43:41 +000039 first = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
40 # We must allocate two consecutive file descriptors, otherwise
41 # it will mess up other file descriptors (perhaps even the three
42 # standard ones).
43 second = os.dup(first)
44 try:
45 retries = 0
46 while second != first + 1:
47 os.close(first)
48 retries += 1
49 if retries > 10:
50 # XXX test skipped
Benjamin Peterson757b3c92009-05-16 18:44:34 +000051 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroubebb18b2008-08-17 14:43:41 +000052 first, second = second, os.dup(second)
53 finally:
54 os.close(second)
Georg Brandl309501a2008-01-19 20:22:13 +000055 # close a fd that is open, and one that isn't
Antoine Pitroubebb18b2008-08-17 14:43:41 +000056 os.closerange(first, first + 2)
57 self.assertRaises(OSError, os.write, first, "a")
Georg Brandl309501a2008-01-19 20:22:13 +000058
Benjamin Peterson10947a62010-06-30 17:11:08 +000059 @test_support.cpython_only
Hirokazu Yamamoto74ce88f2008-09-08 23:03:47 +000060 def test_rename(self):
61 path = unicode(test_support.TESTFN)
62 old = sys.getrefcount(path)
63 self.assertRaises(TypeError, os.rename, path, 0)
64 new = sys.getrefcount(path)
65 self.assertEqual(old, new)
66
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000067
Fred Drake38c2ef02001-07-17 20:52:51 +000068class TemporaryFileTests(unittest.TestCase):
69 def setUp(self):
70 self.files = []
Walter Dörwald21d3a322003-05-01 17:45:56 +000071 os.mkdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000072
73 def tearDown(self):
74 for name in self.files:
75 os.unlink(name)
Walter Dörwald21d3a322003-05-01 17:45:56 +000076 os.rmdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000077
78 def check_tempfile(self, name):
79 # make sure it doesn't already exist:
Benjamin Peterson5c8da862009-06-30 22:57:08 +000080 self.assertFalse(os.path.exists(name),
Fred Drake38c2ef02001-07-17 20:52:51 +000081 "file already exists for temporary file")
82 # make sure we can create the file
83 open(name, "w")
84 self.files.append(name)
85
Serhiy Storchaka32e23e72013-11-03 23:15:46 +020086 @unittest.skipUnless(hasattr(os, 'tempnam'), 'test needs os.tempnam()')
Fred Drake38c2ef02001-07-17 20:52:51 +000087 def test_tempnam(self):
Antoine Pitroub0614612011-01-02 20:04:52 +000088 with warnings.catch_warnings():
89 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
90 r"test_os$")
91 warnings.filterwarnings("ignore", "tempnam", DeprecationWarning)
92 self.check_tempfile(os.tempnam())
Fred Drake38c2ef02001-07-17 20:52:51 +000093
Antoine Pitroub0614612011-01-02 20:04:52 +000094 name = os.tempnam(test_support.TESTFN)
95 self.check_tempfile(name)
Fred Drake38c2ef02001-07-17 20:52:51 +000096
Antoine Pitroub0614612011-01-02 20:04:52 +000097 name = os.tempnam(test_support.TESTFN, "pfx")
98 self.assertTrue(os.path.basename(name)[:3] == "pfx")
99 self.check_tempfile(name)
Fred Drake38c2ef02001-07-17 20:52:51 +0000100
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200101 @unittest.skipUnless(hasattr(os, 'tmpfile'), 'test needs os.tmpfile()')
Fred Drake38c2ef02001-07-17 20:52:51 +0000102 def test_tmpfile(self):
Martin v. Löwisd2bbe522008-03-06 06:55:22 +0000103 # As with test_tmpnam() below, the Windows implementation of tmpfile()
104 # attempts to create a file in the root directory of the current drive.
105 # On Vista and Server 2008, this test will always fail for normal users
106 # as writing to the root directory requires elevated privileges. With
107 # XP and below, the semantics of tmpfile() are the same, but the user
108 # running the test is more likely to have administrative privileges on
109 # their account already. If that's the case, then os.tmpfile() should
110 # work. In order to make this test as useful as possible, rather than
111 # trying to detect Windows versions or whether or not the user has the
112 # right permissions, just try and create a file in the root directory
113 # and see if it raises a 'Permission denied' OSError. If it does, then
114 # test that a subsequent call to os.tmpfile() raises the same error. If
115 # it doesn't, assume we're on XP or below and the user running the test
116 # has administrative privileges, and proceed with the test as normal.
Antoine Pitroub0614612011-01-02 20:04:52 +0000117 with warnings.catch_warnings():
118 warnings.filterwarnings("ignore", "tmpfile", DeprecationWarning)
Martin v. Löwisd2bbe522008-03-06 06:55:22 +0000119
Antoine Pitroub0614612011-01-02 20:04:52 +0000120 if sys.platform == 'win32':
121 name = '\\python_test_os_test_tmpfile.txt'
122 if os.path.exists(name):
123 os.remove(name)
124 try:
125 fp = open(name, 'w')
126 except IOError, first:
127 # open() failed, assert tmpfile() fails in the same way.
128 # Although open() raises an IOError and os.tmpfile() raises an
129 # OSError(), 'args' will be (13, 'Permission denied') in both
130 # cases.
131 try:
132 fp = os.tmpfile()
133 except OSError, second:
134 self.assertEqual(first.args, second.args)
135 else:
136 self.fail("expected os.tmpfile() to raise OSError")
137 return
138 else:
139 # open() worked, therefore, tmpfile() should work. Close our
140 # dummy file and proceed with the test as normal.
141 fp.close()
142 os.remove(name)
143
144 fp = os.tmpfile()
145 fp.write("foobar")
146 fp.seek(0,0)
147 s = fp.read()
148 fp.close()
149 self.assertTrue(s == "foobar")
Fred Drake38c2ef02001-07-17 20:52:51 +0000150
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200151 @unittest.skipUnless(hasattr(os, 'tmpnam'), 'test needs os.tmpnam()')
Fred Drake38c2ef02001-07-17 20:52:51 +0000152 def test_tmpnam(self):
Antoine Pitroub0614612011-01-02 20:04:52 +0000153 with warnings.catch_warnings():
154 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
155 r"test_os$")
156 warnings.filterwarnings("ignore", "tmpnam", DeprecationWarning)
157
158 name = os.tmpnam()
159 if sys.platform in ("win32",):
160 # The Windows tmpnam() seems useless. From the MS docs:
161 #
162 # The character string that tmpnam creates consists of
163 # the path prefix, defined by the entry P_tmpdir in the
164 # file STDIO.H, followed by a sequence consisting of the
165 # digit characters '0' through '9'; the numerical value
166 # of this string is in the range 1 - 65,535. Changing the
167 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
168 # change the operation of tmpnam.
169 #
170 # The really bizarre part is that, at least under MSVC6,
171 # P_tmpdir is "\\". That is, the path returned refers to
172 # the root of the current drive. That's a terrible place to
173 # put temp files, and, depending on privileges, the user
174 # may not even be able to open a file in the root directory.
175 self.assertFalse(os.path.exists(name),
176 "file already exists for temporary file")
177 else:
178 self.check_tempfile(name)
Tim Peters87cc0c32001-07-21 01:41:30 +0000179
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000180# Test attributes on return values from os.*stat* family.
181class StatAttributeTests(unittest.TestCase):
182 def setUp(self):
Walter Dörwald21d3a322003-05-01 17:45:56 +0000183 os.mkdir(test_support.TESTFN)
184 self.fname = os.path.join(test_support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000185 f = open(self.fname, 'wb')
186 f.write("ABC")
187 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000188
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000189 def tearDown(self):
190 os.unlink(self.fname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000191 os.rmdir(test_support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000192
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200193 @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000194 def test_stat_attributes(self):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000195 import stat
196 result = os.stat(self.fname)
197
198 # Make sure direct access works
Ezio Melotti2623a372010-11-21 13:34:58 +0000199 self.assertEqual(result[stat.ST_SIZE], 3)
200 self.assertEqual(result.st_size, 3)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000201
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000202 # Make sure all the attributes are there
203 members = dir(result)
204 for name in dir(stat):
205 if name[:3] == 'ST_':
206 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000207 if name.endswith("TIME"):
208 def trunc(x): return int(x)
209 else:
210 def trunc(x): return x
Ezio Melotti2623a372010-11-21 13:34:58 +0000211 self.assertEqual(trunc(getattr(result, attr)),
212 result[getattr(stat, name)])
Ezio Melottiaa980582010-01-23 23:04:36 +0000213 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000214
215 try:
216 result[200]
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200217 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000218 except IndexError:
219 pass
220
221 # Make sure that assignment fails
222 try:
223 result.st_mode = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200224 self.fail("No exception raised")
Benjamin Petersonc262a692010-06-30 18:41:08 +0000225 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000226 pass
227
228 try:
229 result.st_rdev = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200230 self.fail("No exception raised")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000231 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000232 pass
233
234 try:
235 result.parrot = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200236 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000237 except AttributeError:
238 pass
239
240 # Use the stat_result constructor with a too-short tuple.
241 try:
242 result2 = os.stat_result((10,))
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200243 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000244 except TypeError:
245 pass
246
Ezio Melotti24b07bc2011-03-15 18:55:01 +0200247 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000248 try:
249 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
250 except TypeError:
251 pass
252
Tim Peterse0c446b2001-10-18 21:57:37 +0000253
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200254 @unittest.skipUnless(hasattr(os, 'statvfs'), 'test needs os.statvfs()')
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000255 def test_statvfs_attributes(self):
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000256 try:
257 result = os.statvfs(self.fname)
258 except OSError, e:
259 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000260 if e.errno == errno.ENOSYS:
261 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000262
263 # Make sure direct access works
Ezio Melotti2623a372010-11-21 13:34:58 +0000264 self.assertEqual(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000265
Brett Cannon90f2cb42008-05-16 00:37:42 +0000266 # Make sure all the attributes are there.
267 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
268 'ffree', 'favail', 'flag', 'namemax')
269 for value, member in enumerate(members):
Ezio Melotti2623a372010-11-21 13:34:58 +0000270 self.assertEqual(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000271
272 # Make sure that assignment really fails
273 try:
274 result.f_bfree = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200275 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000276 except TypeError:
277 pass
278
279 try:
280 result.parrot = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200281 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000282 except AttributeError:
283 pass
284
285 # Use the constructor with a too-short tuple.
286 try:
287 result2 = os.statvfs_result((10,))
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200288 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000289 except TypeError:
290 pass
291
Ezio Melotti24b07bc2011-03-15 18:55:01 +0200292 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000293 try:
294 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
295 except TypeError:
296 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000297
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000298 def test_utime_dir(self):
299 delta = 1000000
300 st = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000301 # round to int, because some systems may support sub-second
302 # time stamps in stat, but not in utime.
303 os.utime(test_support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000304 st2 = os.stat(test_support.TESTFN)
Ezio Melotti2623a372010-11-21 13:34:58 +0000305 self.assertEqual(st2.st_mtime, int(st.st_mtime-delta))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000306
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200307 # Restrict tests to Win32, since there is no guarantee other
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000308 # systems support centiseconds
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200309 def get_file_system(path):
310 if sys.platform == 'win32':
Hirokazu Yamamotoccfdcd02008-08-20 04:13:28 +0000311 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000312 import ctypes
Hirokazu Yamamotocd3b74d2008-08-20 16:15:28 +0000313 kernel32 = ctypes.windll.kernel32
314 buf = ctypes.create_string_buffer("", 100)
315 if kernel32.GetVolumeInformationA(root, None, 0, None, None, None, buf, len(buf)):
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000316 return buf.value
317
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200318 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Serhiy Storchakad412b492013-11-03 23:25:42 +0200319 @unittest.skipUnless(get_file_system(test_support.TESTFN) == "NTFS",
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200320 "requires NTFS")
321 def test_1565150(self):
322 t1 = 1159195039.25
323 os.utime(self.fname, (t1, t1))
324 self.assertEqual(os.stat(self.fname).st_mtime, t1)
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000325
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200326 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Serhiy Storchakad412b492013-11-03 23:25:42 +0200327 @unittest.skipUnless(get_file_system(test_support.TESTFN) == "NTFS",
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200328 "requires NTFS")
329 def test_large_time(self):
330 t1 = 5000000000 # some day in 2128
331 os.utime(self.fname, (t1, t1))
332 self.assertEqual(os.stat(self.fname).st_mtime, t1)
Amaury Forgeot d'Arcac514c82011-01-03 00:50:57 +0000333
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200334 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
335 def test_1686475(self):
336 # Verify that an open file can be stat'ed
337 try:
338 os.stat(r"c:\pagefile.sys")
339 except WindowsError, e:
340 if e.errno == 2: # file does not exist; cannot run test
341 return
342 self.fail("Could not stat pagefile.sys")
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000343
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000344from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000345
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000346class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000347 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000348 type2test = None
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000349 def _reference(self):
350 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
351 def _empty_mapping(self):
352 os.environ.clear()
353 return os.environ
354 def setUp(self):
355 self.__save = dict(os.environ)
356 os.environ.clear()
357 def tearDown(self):
358 os.environ.clear()
359 os.environ.update(self.__save)
360
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000361 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000362 def test_update2(self):
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000363 if os.path.exists("/bin/sh"):
364 os.environ.update(HELLO="World")
Brian Curtinfcbf5d02010-10-30 21:29:52 +0000365 with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
366 value = popen.read().strip()
Ezio Melotti2623a372010-11-21 13:34:58 +0000367 self.assertEqual(value, "World")
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000368
Charles-François Natali27bc4d02011-11-27 13:05:14 +0100369 # On FreeBSD < 7 and OS X < 10.6, unsetenv() doesn't return a value (issue
370 # #13415).
371 @unittest.skipIf(sys.platform.startswith(('freebsd', 'darwin')),
372 "due to known OS bug: see issue #13415")
Victor Stinner53853c32011-11-22 22:20:13 +0100373 def test_unset_error(self):
374 if sys.platform == "win32":
375 # an environment variable is limited to 32,767 characters
376 key = 'x' * 50000
Victor Stinner091b6ef2011-11-22 22:30:19 +0100377 self.assertRaises(ValueError, os.environ.__delitem__, key)
Victor Stinner53853c32011-11-22 22:20:13 +0100378 else:
379 # "=" is not allowed in a variable name
380 key = 'key='
Victor Stinner091b6ef2011-11-22 22:30:19 +0100381 self.assertRaises(OSError, os.environ.__delitem__, key)
Victor Stinner53853c32011-11-22 22:20:13 +0100382
Tim Petersc4e09402003-04-25 07:11:48 +0000383class WalkTests(unittest.TestCase):
384 """Tests for os.walk()."""
385
386 def test_traversal(self):
387 import os
388 from os.path import join
389
390 # Build:
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000391 # TESTFN/
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000392 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000393 # tmp1
394 # SUB1/ a file kid and a directory kid
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000395 # tmp2
396 # SUB11/ no kids
397 # SUB2/ a file kid and a dirsymlink kid
398 # tmp3
399 # link/ a symlink to TESTFN.2
400 # TEST2/
401 # tmp4 a lone file
402 walk_path = join(test_support.TESTFN, "TEST1")
403 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000404 sub11_path = join(sub1_path, "SUB11")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000405 sub2_path = join(walk_path, "SUB2")
406 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000407 tmp2_path = join(sub1_path, "tmp2")
408 tmp3_path = join(sub2_path, "tmp3")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000409 link_path = join(sub2_path, "link")
410 t2_path = join(test_support.TESTFN, "TEST2")
411 tmp4_path = join(test_support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000412
413 # Create stuff.
414 os.makedirs(sub11_path)
415 os.makedirs(sub2_path)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000416 os.makedirs(t2_path)
417 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Tim Petersc4e09402003-04-25 07:11:48 +0000418 f = file(path, "w")
419 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
420 f.close()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000421 if hasattr(os, "symlink"):
422 os.symlink(os.path.abspath(t2_path), link_path)
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000423 sub2_tree = (sub2_path, ["link"], ["tmp3"])
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000424 else:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000425 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000426
427 # Walk top-down.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000428 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000429 self.assertEqual(len(all), 4)
430 # We can't know which order SUB1 and SUB2 will appear in.
431 # Not flipped: TESTFN, SUB1, SUB11, SUB2
432 # flipped: TESTFN, SUB2, SUB1, SUB11
433 flipped = all[0][1][0] != "SUB1"
434 all[0][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000435 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000436 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
437 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000438 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000439
440 # Prune the search.
441 all = []
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000442 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000443 all.append((root, dirs, files))
444 # Don't descend into SUB1.
445 if 'SUB1' in dirs:
446 # Note that this also mutates the dirs we appended to all!
447 dirs.remove('SUB1')
448 self.assertEqual(len(all), 2)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000449 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000450 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000451
452 # Walk bottom-up.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000453 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000454 self.assertEqual(len(all), 4)
455 # We can't know which order SUB1 and SUB2 will appear in.
456 # Not flipped: SUB11, SUB1, SUB2, TESTFN
457 # flipped: SUB2, SUB11, SUB1, TESTFN
458 flipped = all[3][1][0] != "SUB1"
459 all[3][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000460 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000461 self.assertEqual(all[flipped], (sub11_path, [], []))
462 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000463 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000464
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000465 if hasattr(os, "symlink"):
466 # Walk, following symlinks.
467 for root, dirs, files in os.walk(walk_path, followlinks=True):
468 if root == link_path:
469 self.assertEqual(dirs, [])
470 self.assertEqual(files, ["tmp4"])
471 break
472 else:
473 self.fail("Didn't follow symlink with followlinks=True")
Tim Petersc4e09402003-04-25 07:11:48 +0000474
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000475 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000476 # Tear everything down. This is a decent use for bottom-up on
477 # Windows, which doesn't have a recursive delete command. The
478 # (not so) subtlety is that rmdir will fail unless the dir's
479 # kids are removed first, so bottom up is essential.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000480 for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000481 for name in files:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000482 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000483 for name in dirs:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000484 dirname = os.path.join(root, name)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000485 if not os.path.islink(dirname):
486 os.rmdir(dirname)
487 else:
488 os.remove(dirname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000489 os.rmdir(test_support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000490
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000491class MakedirTests (unittest.TestCase):
492 def setUp(self):
493 os.mkdir(test_support.TESTFN)
494
495 def test_makedir(self):
496 base = test_support.TESTFN
497 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
498 os.makedirs(path) # Should work
499 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
500 os.makedirs(path)
501
502 # Try paths with a '.' in them
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000503 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000504 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
505 os.makedirs(path)
506 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
507 'dir5', 'dir6')
508 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000509
Tim Peters58eb11c2004-01-18 20:29:55 +0000510
511
512
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000513 def tearDown(self):
514 path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
515 'dir4', 'dir5', 'dir6')
516 # If the tests failed, the bottom-most directory ('../dir6')
517 # may not have been created, so we look for the outermost directory
518 # that exists.
519 while not os.path.exists(path) and path != test_support.TESTFN:
520 path = os.path.dirname(path)
521
522 os.removedirs(path)
523
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000524class DevNullTests (unittest.TestCase):
525 def test_devnull(self):
526 f = file(os.devnull, 'w')
527 f.write('hello')
528 f.close()
529 f = file(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000530 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000531 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000532
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000533class URandomTests (unittest.TestCase):
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500534
535 def test_urandom_length(self):
536 self.assertEqual(len(os.urandom(0)), 0)
537 self.assertEqual(len(os.urandom(1)), 1)
538 self.assertEqual(len(os.urandom(10)), 10)
539 self.assertEqual(len(os.urandom(100)), 100)
540 self.assertEqual(len(os.urandom(1000)), 1000)
541
542 def test_urandom_value(self):
543 data1 = os.urandom(16)
544 data2 = os.urandom(16)
545 self.assertNotEqual(data1, data2)
546
547 def get_urandom_subprocess(self, count):
Antoine Pitrou341016e2012-02-22 22:16:25 +0100548 # We need to use repr() and eval() to avoid line ending conversions
549 # under Windows.
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500550 code = '\n'.join((
551 'import os, sys',
552 'data = os.urandom(%s)' % count,
Antoine Pitrou341016e2012-02-22 22:16:25 +0100553 'sys.stdout.write(repr(data))',
Antoine Pitrou0607f732012-02-21 22:02:04 +0100554 'sys.stdout.flush()',
555 'print >> sys.stderr, (len(data), data)'))
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500556 cmd_line = [sys.executable, '-c', code]
557 p = subprocess.Popen(cmd_line, stdin=subprocess.PIPE,
Antoine Pitrou0607f732012-02-21 22:02:04 +0100558 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500559 out, err = p.communicate()
Antoine Pitrou0607f732012-02-21 22:02:04 +0100560 self.assertEqual(p.wait(), 0, (p.wait(), err))
Antoine Pitrou341016e2012-02-22 22:16:25 +0100561 out = eval(out)
562 self.assertEqual(len(out), count, err)
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500563 return out
564
565 def test_urandom_subprocess(self):
566 data1 = self.get_urandom_subprocess(16)
567 data2 = self.get_urandom_subprocess(16)
568 self.assertNotEqual(data1, data2)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000569
Antoine Pitrouf48a67b2013-08-16 20:44:38 +0200570 @unittest.skipUnless(resource, "test requires the resource module")
571 def test_urandom_failure(self):
Antoine Pitroue7587152013-08-24 20:52:27 +0200572 # Check urandom() failing when it is not able to open /dev/random.
573 # We spawn a new process to make the test more robust (if getrlimit()
574 # failed to restore the file descriptor limit after this, the whole
575 # test suite would crash; this actually happened on the OS X Tiger
576 # buildbot).
577 code = """if 1:
578 import errno
579 import os
580 import resource
581
582 soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
583 resource.setrlimit(resource.RLIMIT_NOFILE, (1, hard_limit))
584 try:
Antoine Pitrouf48a67b2013-08-16 20:44:38 +0200585 os.urandom(16)
Antoine Pitroue7587152013-08-24 20:52:27 +0200586 except OSError as e:
587 assert e.errno == errno.EMFILE, e.errno
588 else:
589 raise AssertionError("OSError not raised")
590 """
591 assert_python_ok('-c', code)
Antoine Pitrouf48a67b2013-08-16 20:44:38 +0200592
Antoine Pitrou326ec042013-08-16 20:56:12 +0200593
594class ExecvpeTests(unittest.TestCase):
595
Matthias Klosee9fbf2b2010-03-19 14:45:06 +0000596 def test_execvpe_with_bad_arglist(self):
597 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
598
Antoine Pitrou326ec042013-08-16 20:56:12 +0200599
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200600@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000601class Win32ErrorTests(unittest.TestCase):
602 def test_rename(self):
603 self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak")
604
605 def test_remove(self):
606 self.assertRaises(WindowsError, os.remove, test_support.TESTFN)
607
608 def test_chdir(self):
609 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
610
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000611 def test_mkdir(self):
Kristján Valur Jónssone20f54f2009-02-06 10:17:34 +0000612 f = open(test_support.TESTFN, "w")
613 try:
614 self.assertRaises(WindowsError, os.mkdir, test_support.TESTFN)
615 finally:
616 f.close()
617 os.unlink(test_support.TESTFN)
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000618
619 def test_utime(self):
620 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, None)
621
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000622 def test_chmod(self):
Kristján Valur Jónssone20f54f2009-02-06 10:17:34 +0000623 self.assertRaises(WindowsError, os.chmod, test_support.TESTFN, 0)
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000624
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000625class TestInvalidFD(unittest.TestCase):
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000626 singles = ["fchdir", "fdopen", "dup", "fdatasync", "fstat",
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000627 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000628 #singles.append("close")
629 #We omit close because it doesn'r raise an exception on some platforms
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000630 def get_single(f):
631 def helper(self):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000632 if hasattr(os, f):
633 self.check(getattr(os, f))
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000634 return helper
635 for f in singles:
636 locals()["test_"+f] = get_single(f)
637
Benjamin Peterson5539c782009-01-19 17:37:42 +0000638 def check(self, f, *args):
Benjamin Peterson1de05e92009-01-31 01:42:55 +0000639 try:
640 f(test_support.make_bad_fd(), *args)
641 except OSError as e:
642 self.assertEqual(e.errno, errno.EBADF)
643 else:
644 self.fail("%r didn't raise a OSError with a bad file descriptor"
645 % f)
Benjamin Peterson5539c782009-01-19 17:37:42 +0000646
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200647 @unittest.skipUnless(hasattr(os, 'isatty'), 'test needs os.isatty()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000648 def test_isatty(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200649 self.assertEqual(os.isatty(test_support.make_bad_fd()), False)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000650
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200651 @unittest.skipUnless(hasattr(os, 'closerange'), 'test needs os.closerange()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000652 def test_closerange(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200653 fd = test_support.make_bad_fd()
654 # Make sure none of the descriptors we are about to close are
655 # currently valid (issue 6542).
656 for i in range(10):
657 try: os.fstat(fd+i)
658 except OSError:
659 pass
660 else:
661 break
662 if i < 2:
663 raise unittest.SkipTest(
664 "Unable to acquire a range of invalid file descriptors")
665 self.assertEqual(os.closerange(fd, fd + i-1), None)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000666
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200667 @unittest.skipUnless(hasattr(os, 'dup2'), 'test needs os.dup2()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000668 def test_dup2(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200669 self.check(os.dup2, 20)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000670
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200671 @unittest.skipUnless(hasattr(os, 'fchmod'), 'test needs os.fchmod()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000672 def test_fchmod(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200673 self.check(os.fchmod, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000674
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200675 @unittest.skipUnless(hasattr(os, 'fchown'), 'test needs os.fchown()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000676 def test_fchown(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200677 self.check(os.fchown, -1, -1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000678
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200679 @unittest.skipUnless(hasattr(os, 'fpathconf'), 'test needs os.fpathconf()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000680 def test_fpathconf(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200681 self.check(os.fpathconf, "PC_NAME_MAX")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000682
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200683 @unittest.skipUnless(hasattr(os, 'ftruncate'), 'test needs os.ftruncate()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000684 def test_ftruncate(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200685 self.check(os.ftruncate, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000686
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200687 @unittest.skipUnless(hasattr(os, 'lseek'), 'test needs os.lseek()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000688 def test_lseek(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200689 self.check(os.lseek, 0, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000690
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200691 @unittest.skipUnless(hasattr(os, 'read'), 'test needs os.read()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000692 def test_read(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200693 self.check(os.read, 1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000694
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200695 @unittest.skipUnless(hasattr(os, 'tcsetpgrp'), 'test needs os.tcsetpgrp()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000696 def test_tcsetpgrpt(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200697 self.check(os.tcsetpgrp, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000698
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200699 @unittest.skipUnless(hasattr(os, 'write'), 'test needs os.write()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000700 def test_write(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200701 self.check(os.write, " ")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000702
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200703@unittest.skipIf(sys.platform == "win32", "Posix specific tests")
704class PosixUidGidTests(unittest.TestCase):
705 @unittest.skipUnless(hasattr(os, 'setuid'), 'test needs os.setuid()')
706 def test_setuid(self):
707 if os.getuid() != 0:
708 self.assertRaises(os.error, os.setuid, 0)
709 self.assertRaises(OverflowError, os.setuid, 1<<32)
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000710
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200711 @unittest.skipUnless(hasattr(os, 'setgid'), 'test needs os.setgid()')
712 def test_setgid(self):
713 if os.getuid() != 0:
714 self.assertRaises(os.error, os.setgid, 0)
715 self.assertRaises(OverflowError, os.setgid, 1<<32)
Gregory P. Smith6d307932009-04-05 23:43:58 +0000716
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200717 @unittest.skipUnless(hasattr(os, 'seteuid'), 'test needs os.seteuid()')
718 def test_seteuid(self):
719 if os.getuid() != 0:
720 self.assertRaises(os.error, os.seteuid, 0)
721 self.assertRaises(OverflowError, os.seteuid, 1<<32)
Gregory P. Smith6d307932009-04-05 23:43:58 +0000722
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200723 @unittest.skipUnless(hasattr(os, 'setegid'), 'test needs os.setegid()')
724 def test_setegid(self):
725 if os.getuid() != 0:
726 self.assertRaises(os.error, os.setegid, 0)
727 self.assertRaises(OverflowError, os.setegid, 1<<32)
Gregory P. Smith6d307932009-04-05 23:43:58 +0000728
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200729 @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
730 def test_setreuid(self):
731 if os.getuid() != 0:
732 self.assertRaises(os.error, os.setreuid, 0, 0)
733 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
734 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Gregory P. Smith6d307932009-04-05 23:43:58 +0000735
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200736 @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
737 def test_setreuid_neg1(self):
738 # Needs to accept -1. We run this in a subprocess to avoid
739 # altering the test runner's process state (issue8045).
740 subprocess.check_call([
741 sys.executable, '-c',
742 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Gregory P. Smith467298c2010-03-06 07:35:19 +0000743
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200744 @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
745 def test_setregid(self):
746 if os.getuid() != 0:
747 self.assertRaises(os.error, os.setregid, 0, 0)
748 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
749 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Gregory P. Smith6d307932009-04-05 23:43:58 +0000750
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200751 @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
752 def test_setregid_neg1(self):
753 # Needs to accept -1. We run this in a subprocess to avoid
754 # altering the test runner's process state (issue8045).
755 subprocess.check_call([
756 sys.executable, '-c',
757 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Gregory P. Smith467298c2010-03-06 07:35:19 +0000758
Gregory P. Smith6d307932009-04-05 23:43:58 +0000759
Brian Curtine5aa8862010-04-02 23:26:06 +0000760@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
761class Win32KillTests(unittest.TestCase):
Brian Curtinb3dde132010-04-15 00:40:40 +0000762 def _kill(self, sig):
763 # Start sys.executable as a subprocess and communicate from the
764 # subprocess to the parent that the interpreter is ready. When it
765 # becomes ready, send *sig* via os.kill to the subprocess and check
766 # that the return code is equal to *sig*.
767 import ctypes
768 from ctypes import wintypes
769 import msvcrt
770
771 # Since we can't access the contents of the process' stdout until the
772 # process has exited, use PeekNamedPipe to see what's inside stdout
773 # without waiting. This is done so we can tell that the interpreter
774 # is started and running at a point where it could handle a signal.
775 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
776 PeekNamedPipe.restype = wintypes.BOOL
777 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
778 ctypes.POINTER(ctypes.c_char), # stdout buf
779 wintypes.DWORD, # Buffer size
780 ctypes.POINTER(wintypes.DWORD), # bytes read
781 ctypes.POINTER(wintypes.DWORD), # bytes avail
782 ctypes.POINTER(wintypes.DWORD)) # bytes left
783 msg = "running"
784 proc = subprocess.Popen([sys.executable, "-c",
785 "import sys;"
786 "sys.stdout.write('{}');"
787 "sys.stdout.flush();"
788 "input()".format(msg)],
789 stdout=subprocess.PIPE,
790 stderr=subprocess.PIPE,
791 stdin=subprocess.PIPE)
Brian Curtinf4f0c8b2010-11-05 15:31:20 +0000792 self.addCleanup(proc.stdout.close)
793 self.addCleanup(proc.stderr.close)
794 self.addCleanup(proc.stdin.close)
Brian Curtinb3dde132010-04-15 00:40:40 +0000795
Brian Curtin83cba052010-05-28 15:49:21 +0000796 count, max = 0, 100
797 while count < max and proc.poll() is None:
798 # Create a string buffer to store the result of stdout from the pipe
799 buf = ctypes.create_string_buffer(len(msg))
800 # Obtain the text currently in proc.stdout
801 # Bytes read/avail/left are left as NULL and unused
802 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
803 buf, ctypes.sizeof(buf), None, None, None)
804 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
805 if buf.value:
806 self.assertEqual(msg, buf.value)
807 break
808 time.sleep(0.1)
809 count += 1
810 else:
811 self.fail("Did not receive communication from the subprocess")
Brian Curtinb3dde132010-04-15 00:40:40 +0000812
Brian Curtine5aa8862010-04-02 23:26:06 +0000813 os.kill(proc.pid, sig)
814 self.assertEqual(proc.wait(), sig)
815
816 def test_kill_sigterm(self):
817 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinb3dde132010-04-15 00:40:40 +0000818 self._kill(signal.SIGTERM)
Brian Curtine5aa8862010-04-02 23:26:06 +0000819
820 def test_kill_int(self):
821 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinb3dde132010-04-15 00:40:40 +0000822 self._kill(100)
Brian Curtine5aa8862010-04-02 23:26:06 +0000823
824 def _kill_with_event(self, event, name):
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000825 tagname = "test_os_%s" % uuid.uuid1()
826 m = mmap.mmap(-1, 1, tagname)
827 m[0] = '0'
Brian Curtine5aa8862010-04-02 23:26:06 +0000828 # Run a script which has console control handling enabled.
829 proc = subprocess.Popen([sys.executable,
830 os.path.join(os.path.dirname(__file__),
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000831 "win_console_handler.py"), tagname],
Brian Curtine5aa8862010-04-02 23:26:06 +0000832 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
833 # Let the interpreter startup before we send signals. See #3137.
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000834 count, max = 0, 20
835 while count < max and proc.poll() is None:
Brian Curtindbf8e832010-11-05 15:28:19 +0000836 if m[0] == '1':
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000837 break
838 time.sleep(0.5)
839 count += 1
840 else:
841 self.fail("Subprocess didn't finish initialization")
Brian Curtine5aa8862010-04-02 23:26:06 +0000842 os.kill(proc.pid, event)
843 # proc.send_signal(event) could also be done here.
844 # Allow time for the signal to be passed and the process to exit.
Brian Curtinfce1d312010-04-05 19:04:23 +0000845 time.sleep(0.5)
Brian Curtine5aa8862010-04-02 23:26:06 +0000846 if not proc.poll():
847 # Forcefully kill the process if we weren't able to signal it.
848 os.kill(proc.pid, signal.SIGINT)
849 self.fail("subprocess did not stop on {}".format(name))
850
851 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
852 def test_CTRL_C_EVENT(self):
853 from ctypes import wintypes
854 import ctypes
855
856 # Make a NULL value by creating a pointer with no argument.
857 NULL = ctypes.POINTER(ctypes.c_int)()
858 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
859 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
860 wintypes.BOOL)
861 SetConsoleCtrlHandler.restype = wintypes.BOOL
862
863 # Calling this with NULL and FALSE causes the calling process to
864 # handle CTRL+C, rather than ignore it. This property is inherited
865 # by subprocesses.
866 SetConsoleCtrlHandler(NULL, 0)
867
868 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
869
870 def test_CTRL_BREAK_EVENT(self):
871 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
872
873
Fred Drake2e2be372001-09-20 21:33:42 +0000874def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000875 test_support.run_unittest(
Martin v. Löwisee1e06d2006-07-02 18:44:00 +0000876 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000877 TemporaryFileTests,
878 StatAttributeTests,
879 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000880 WalkTests,
881 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000882 DevNullTests,
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000883 URandomTests,
Antoine Pitrou326ec042013-08-16 20:56:12 +0200884 ExecvpeTests,
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000885 Win32ErrorTests,
Gregory P. Smith6d307932009-04-05 23:43:58 +0000886 TestInvalidFD,
Brian Curtine5aa8862010-04-02 23:26:06 +0000887 PosixUidGidTests,
888 Win32KillTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000889 )
Fred Drake2e2be372001-09-20 21:33:42 +0000890
891if __name__ == "__main__":
892 test_main()