blob: e84f4571dbfa0fe4d7f1eb15e3203bc3d64b713e [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
Benjamin Peterson27c269a2014-12-26 11:09:00 -060012import sysconfig
Brian Curtine5aa8862010-04-02 23:26:06 +000013import time
Antoine Pitrouf48a67b2013-08-16 20:44:38 +020014try:
15 import resource
16except ImportError:
17 resource = None
Barry Warsaw1e13eb02012-02-20 20:42:21 -050018
Walter Dörwald21d3a322003-05-01 17:45:56 +000019from test import test_support
Antoine Pitroue7587152013-08-24 20:52:27 +020020from test.script_helper import assert_python_ok
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +000021import mmap
22import uuid
Fred Drake38c2ef02001-07-17 20:52:51 +000023
Barry Warsaw60f01882001-08-22 19:24:42 +000024warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, __name__)
25warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, __name__)
26
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000027# Tests creating TESTFN
28class FileTests(unittest.TestCase):
29 def setUp(self):
30 if os.path.exists(test_support.TESTFN):
31 os.unlink(test_support.TESTFN)
32 tearDown = setUp
33
34 def test_access(self):
35 f = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
36 os.close(f)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000037 self.assertTrue(os.access(test_support.TESTFN, os.W_OK))
Tim Peters16a39322006-07-03 08:23:19 +000038
Georg Brandl309501a2008-01-19 20:22:13 +000039 def test_closerange(self):
Antoine Pitroubebb18b2008-08-17 14:43:41 +000040 first = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
41 # We must allocate two consecutive file descriptors, otherwise
42 # it will mess up other file descriptors (perhaps even the three
43 # standard ones).
44 second = os.dup(first)
45 try:
46 retries = 0
47 while second != first + 1:
48 os.close(first)
49 retries += 1
50 if retries > 10:
51 # XXX test skipped
Benjamin Peterson757b3c92009-05-16 18:44:34 +000052 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroubebb18b2008-08-17 14:43:41 +000053 first, second = second, os.dup(second)
54 finally:
55 os.close(second)
Georg Brandl309501a2008-01-19 20:22:13 +000056 # close a fd that is open, and one that isn't
Antoine Pitroubebb18b2008-08-17 14:43:41 +000057 os.closerange(first, first + 2)
58 self.assertRaises(OSError, os.write, first, "a")
Georg Brandl309501a2008-01-19 20:22:13 +000059
Benjamin Peterson10947a62010-06-30 17:11:08 +000060 @test_support.cpython_only
Hirokazu Yamamoto74ce88f2008-09-08 23:03:47 +000061 def test_rename(self):
62 path = unicode(test_support.TESTFN)
63 old = sys.getrefcount(path)
64 self.assertRaises(TypeError, os.rename, path, 0)
65 new = sys.getrefcount(path)
66 self.assertEqual(old, new)
67
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000068
Fred Drake38c2ef02001-07-17 20:52:51 +000069class TemporaryFileTests(unittest.TestCase):
70 def setUp(self):
71 self.files = []
Walter Dörwald21d3a322003-05-01 17:45:56 +000072 os.mkdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000073
74 def tearDown(self):
75 for name in self.files:
76 os.unlink(name)
Walter Dörwald21d3a322003-05-01 17:45:56 +000077 os.rmdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000078
79 def check_tempfile(self, name):
80 # make sure it doesn't already exist:
Benjamin Peterson5c8da862009-06-30 22:57:08 +000081 self.assertFalse(os.path.exists(name),
Fred Drake38c2ef02001-07-17 20:52:51 +000082 "file already exists for temporary file")
83 # make sure we can create the file
84 open(name, "w")
85 self.files.append(name)
86
Serhiy Storchaka32e23e72013-11-03 23:15:46 +020087 @unittest.skipUnless(hasattr(os, 'tempnam'), 'test needs os.tempnam()')
Fred Drake38c2ef02001-07-17 20:52:51 +000088 def test_tempnam(self):
Antoine Pitroub0614612011-01-02 20:04:52 +000089 with warnings.catch_warnings():
90 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
91 r"test_os$")
92 warnings.filterwarnings("ignore", "tempnam", DeprecationWarning)
93 self.check_tempfile(os.tempnam())
Fred Drake38c2ef02001-07-17 20:52:51 +000094
Antoine Pitroub0614612011-01-02 20:04:52 +000095 name = os.tempnam(test_support.TESTFN)
96 self.check_tempfile(name)
Fred Drake38c2ef02001-07-17 20:52:51 +000097
Antoine Pitroub0614612011-01-02 20:04:52 +000098 name = os.tempnam(test_support.TESTFN, "pfx")
99 self.assertTrue(os.path.basename(name)[:3] == "pfx")
100 self.check_tempfile(name)
Fred Drake38c2ef02001-07-17 20:52:51 +0000101
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200102 @unittest.skipUnless(hasattr(os, 'tmpfile'), 'test needs os.tmpfile()')
Fred Drake38c2ef02001-07-17 20:52:51 +0000103 def test_tmpfile(self):
Martin v. Löwisd2bbe522008-03-06 06:55:22 +0000104 # As with test_tmpnam() below, the Windows implementation of tmpfile()
105 # attempts to create a file in the root directory of the current drive.
106 # On Vista and Server 2008, this test will always fail for normal users
107 # as writing to the root directory requires elevated privileges. With
108 # XP and below, the semantics of tmpfile() are the same, but the user
109 # running the test is more likely to have administrative privileges on
110 # their account already. If that's the case, then os.tmpfile() should
111 # work. In order to make this test as useful as possible, rather than
112 # trying to detect Windows versions or whether or not the user has the
113 # right permissions, just try and create a file in the root directory
114 # and see if it raises a 'Permission denied' OSError. If it does, then
115 # test that a subsequent call to os.tmpfile() raises the same error. If
116 # it doesn't, assume we're on XP or below and the user running the test
117 # has administrative privileges, and proceed with the test as normal.
Antoine Pitroub0614612011-01-02 20:04:52 +0000118 with warnings.catch_warnings():
119 warnings.filterwarnings("ignore", "tmpfile", DeprecationWarning)
Martin v. Löwisd2bbe522008-03-06 06:55:22 +0000120
Antoine Pitroub0614612011-01-02 20:04:52 +0000121 if sys.platform == 'win32':
122 name = '\\python_test_os_test_tmpfile.txt'
123 if os.path.exists(name):
124 os.remove(name)
125 try:
126 fp = open(name, 'w')
127 except IOError, first:
128 # open() failed, assert tmpfile() fails in the same way.
129 # Although open() raises an IOError and os.tmpfile() raises an
130 # OSError(), 'args' will be (13, 'Permission denied') in both
131 # cases.
132 try:
133 fp = os.tmpfile()
134 except OSError, second:
135 self.assertEqual(first.args, second.args)
136 else:
137 self.fail("expected os.tmpfile() to raise OSError")
Zachary Wareb06231a2013-12-10 16:06:46 -0600138 return
Antoine Pitroub0614612011-01-02 20:04:52 +0000139 else:
140 # open() worked, therefore, tmpfile() should work. Close our
141 # dummy file and proceed with the test as normal.
142 fp.close()
143 os.remove(name)
144
145 fp = os.tmpfile()
146 fp.write("foobar")
147 fp.seek(0,0)
148 s = fp.read()
149 fp.close()
150 self.assertTrue(s == "foobar")
Fred Drake38c2ef02001-07-17 20:52:51 +0000151
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200152 @unittest.skipUnless(hasattr(os, 'tmpnam'), 'test needs os.tmpnam()')
Fred Drake38c2ef02001-07-17 20:52:51 +0000153 def test_tmpnam(self):
Antoine Pitroub0614612011-01-02 20:04:52 +0000154 with warnings.catch_warnings():
155 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
156 r"test_os$")
157 warnings.filterwarnings("ignore", "tmpnam", DeprecationWarning)
158
159 name = os.tmpnam()
160 if sys.platform in ("win32",):
161 # The Windows tmpnam() seems useless. From the MS docs:
162 #
163 # The character string that tmpnam creates consists of
164 # the path prefix, defined by the entry P_tmpdir in the
165 # file STDIO.H, followed by a sequence consisting of the
166 # digit characters '0' through '9'; the numerical value
167 # of this string is in the range 1 - 65,535. Changing the
168 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
169 # change the operation of tmpnam.
170 #
171 # The really bizarre part is that, at least under MSVC6,
172 # P_tmpdir is "\\". That is, the path returned refers to
173 # the root of the current drive. That's a terrible place to
174 # put temp files, and, depending on privileges, the user
175 # may not even be able to open a file in the root directory.
176 self.assertFalse(os.path.exists(name),
177 "file already exists for temporary file")
178 else:
179 self.check_tempfile(name)
Tim Peters87cc0c32001-07-21 01:41:30 +0000180
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000181# Test attributes on return values from os.*stat* family.
182class StatAttributeTests(unittest.TestCase):
183 def setUp(self):
Walter Dörwald21d3a322003-05-01 17:45:56 +0000184 os.mkdir(test_support.TESTFN)
185 self.fname = os.path.join(test_support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000186 f = open(self.fname, 'wb')
187 f.write("ABC")
188 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000189
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000190 def tearDown(self):
191 os.unlink(self.fname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000192 os.rmdir(test_support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000193
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200194 @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000195 def test_stat_attributes(self):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000196 import stat
197 result = os.stat(self.fname)
198
199 # Make sure direct access works
Ezio Melotti2623a372010-11-21 13:34:58 +0000200 self.assertEqual(result[stat.ST_SIZE], 3)
201 self.assertEqual(result.st_size, 3)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000202
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000203 # Make sure all the attributes are there
204 members = dir(result)
205 for name in dir(stat):
206 if name[:3] == 'ST_':
207 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000208 if name.endswith("TIME"):
209 def trunc(x): return int(x)
210 else:
211 def trunc(x): return x
Ezio Melotti2623a372010-11-21 13:34:58 +0000212 self.assertEqual(trunc(getattr(result, attr)),
213 result[getattr(stat, name)])
Ezio Melottiaa980582010-01-23 23:04:36 +0000214 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000215
216 try:
217 result[200]
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200218 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000219 except IndexError:
220 pass
221
222 # Make sure that assignment fails
223 try:
224 result.st_mode = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200225 self.fail("No exception raised")
Benjamin Petersonc262a692010-06-30 18:41:08 +0000226 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000227 pass
228
229 try:
230 result.st_rdev = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200231 self.fail("No exception raised")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000232 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000233 pass
234
235 try:
236 result.parrot = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200237 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000238 except AttributeError:
239 pass
240
241 # Use the stat_result constructor with a too-short tuple.
242 try:
243 result2 = os.stat_result((10,))
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200244 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000245 except TypeError:
246 pass
247
Ezio Melotti24b07bc2011-03-15 18:55:01 +0200248 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000249 try:
250 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
251 except TypeError:
252 pass
253
Tim Peterse0c446b2001-10-18 21:57:37 +0000254
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200255 @unittest.skipUnless(hasattr(os, 'statvfs'), 'test needs os.statvfs()')
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000256 def test_statvfs_attributes(self):
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000257 try:
258 result = os.statvfs(self.fname)
259 except OSError, e:
260 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000261 if e.errno == errno.ENOSYS:
Zachary Ware1f702212013-12-10 14:09:20 -0600262 self.skipTest('glibc always returns ENOSYS on AtheOS')
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000263
264 # Make sure direct access works
Ezio Melotti2623a372010-11-21 13:34:58 +0000265 self.assertEqual(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000266
Brett Cannon90f2cb42008-05-16 00:37:42 +0000267 # Make sure all the attributes are there.
268 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
269 'ffree', 'favail', 'flag', 'namemax')
270 for value, member in enumerate(members):
Ezio Melotti2623a372010-11-21 13:34:58 +0000271 self.assertEqual(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000272
273 # Make sure that assignment really fails
274 try:
275 result.f_bfree = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200276 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000277 except TypeError:
278 pass
279
280 try:
281 result.parrot = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200282 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000283 except AttributeError:
284 pass
285
286 # Use the constructor with a too-short tuple.
287 try:
288 result2 = os.statvfs_result((10,))
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200289 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000290 except TypeError:
291 pass
292
Ezio Melotti24b07bc2011-03-15 18:55:01 +0200293 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000294 try:
295 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
296 except TypeError:
297 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000298
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000299 def test_utime_dir(self):
300 delta = 1000000
301 st = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000302 # round to int, because some systems may support sub-second
303 # time stamps in stat, but not in utime.
304 os.utime(test_support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000305 st2 = os.stat(test_support.TESTFN)
Ezio Melotti2623a372010-11-21 13:34:58 +0000306 self.assertEqual(st2.st_mtime, int(st.st_mtime-delta))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000307
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200308 # Restrict tests to Win32, since there is no guarantee other
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000309 # systems support centiseconds
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200310 def get_file_system(path):
311 if sys.platform == 'win32':
Hirokazu Yamamotoccfdcd02008-08-20 04:13:28 +0000312 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000313 import ctypes
Hirokazu Yamamotocd3b74d2008-08-20 16:15:28 +0000314 kernel32 = ctypes.windll.kernel32
315 buf = ctypes.create_string_buffer("", 100)
316 if kernel32.GetVolumeInformationA(root, None, 0, None, None, None, buf, len(buf)):
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000317 return buf.value
318
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200319 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Serhiy Storchakad412b492013-11-03 23:25:42 +0200320 @unittest.skipUnless(get_file_system(test_support.TESTFN) == "NTFS",
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200321 "requires NTFS")
322 def test_1565150(self):
323 t1 = 1159195039.25
324 os.utime(self.fname, (t1, t1))
325 self.assertEqual(os.stat(self.fname).st_mtime, t1)
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000326
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200327 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Serhiy Storchakad412b492013-11-03 23:25:42 +0200328 @unittest.skipUnless(get_file_system(test_support.TESTFN) == "NTFS",
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200329 "requires NTFS")
330 def test_large_time(self):
331 t1 = 5000000000 # some day in 2128
332 os.utime(self.fname, (t1, t1))
333 self.assertEqual(os.stat(self.fname).st_mtime, t1)
Amaury Forgeot d'Arcac514c82011-01-03 00:50:57 +0000334
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200335 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
336 def test_1686475(self):
337 # Verify that an open file can be stat'ed
338 try:
339 os.stat(r"c:\pagefile.sys")
340 except WindowsError, e:
341 if e.errno == 2: # file does not exist; cannot run test
Zachary Ware1f702212013-12-10 14:09:20 -0600342 self.skipTest(r'c:\pagefile.sys does not exist')
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200343 self.fail("Could not stat pagefile.sys")
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000344
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000345from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000346
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000347class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000348 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000349 type2test = None
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000350 def _reference(self):
351 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
352 def _empty_mapping(self):
353 os.environ.clear()
354 return os.environ
355 def setUp(self):
356 self.__save = dict(os.environ)
357 os.environ.clear()
358 def tearDown(self):
359 os.environ.clear()
360 os.environ.update(self.__save)
361
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000362 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000363 def test_update2(self):
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000364 if os.path.exists("/bin/sh"):
365 os.environ.update(HELLO="World")
Brian Curtinfcbf5d02010-10-30 21:29:52 +0000366 with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
367 value = popen.read().strip()
Ezio Melotti2623a372010-11-21 13:34:58 +0000368 self.assertEqual(value, "World")
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000369
Charles-François Natali27bc4d02011-11-27 13:05:14 +0100370 # On FreeBSD < 7 and OS X < 10.6, unsetenv() doesn't return a value (issue
371 # #13415).
372 @unittest.skipIf(sys.platform.startswith(('freebsd', 'darwin')),
373 "due to known OS bug: see issue #13415")
Victor Stinner53853c32011-11-22 22:20:13 +0100374 def test_unset_error(self):
375 if sys.platform == "win32":
376 # an environment variable is limited to 32,767 characters
377 key = 'x' * 50000
Victor Stinner091b6ef2011-11-22 22:30:19 +0100378 self.assertRaises(ValueError, os.environ.__delitem__, key)
Victor Stinner53853c32011-11-22 22:20:13 +0100379 else:
380 # "=" is not allowed in a variable name
381 key = 'key='
Victor Stinner091b6ef2011-11-22 22:30:19 +0100382 self.assertRaises(OSError, os.environ.__delitem__, key)
Victor Stinner53853c32011-11-22 22:20:13 +0100383
Tim Petersc4e09402003-04-25 07:11:48 +0000384class WalkTests(unittest.TestCase):
385 """Tests for os.walk()."""
386
387 def test_traversal(self):
388 import os
389 from os.path import join
390
391 # Build:
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000392 # TESTFN/
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000393 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000394 # tmp1
395 # SUB1/ a file kid and a directory kid
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000396 # tmp2
397 # SUB11/ no kids
398 # SUB2/ a file kid and a dirsymlink kid
399 # tmp3
400 # link/ a symlink to TESTFN.2
401 # TEST2/
402 # tmp4 a lone file
403 walk_path = join(test_support.TESTFN, "TEST1")
404 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000405 sub11_path = join(sub1_path, "SUB11")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000406 sub2_path = join(walk_path, "SUB2")
407 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000408 tmp2_path = join(sub1_path, "tmp2")
409 tmp3_path = join(sub2_path, "tmp3")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000410 link_path = join(sub2_path, "link")
411 t2_path = join(test_support.TESTFN, "TEST2")
412 tmp4_path = join(test_support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000413
414 # Create stuff.
415 os.makedirs(sub11_path)
416 os.makedirs(sub2_path)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000417 os.makedirs(t2_path)
418 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Tim Petersc4e09402003-04-25 07:11:48 +0000419 f = file(path, "w")
420 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
421 f.close()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000422 if hasattr(os, "symlink"):
423 os.symlink(os.path.abspath(t2_path), link_path)
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000424 sub2_tree = (sub2_path, ["link"], ["tmp3"])
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000425 else:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000426 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000427
428 # Walk top-down.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000429 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000430 self.assertEqual(len(all), 4)
431 # We can't know which order SUB1 and SUB2 will appear in.
432 # Not flipped: TESTFN, SUB1, SUB11, SUB2
433 # flipped: TESTFN, SUB2, SUB1, SUB11
434 flipped = all[0][1][0] != "SUB1"
435 all[0][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000436 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000437 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
438 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000439 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000440
441 # Prune the search.
442 all = []
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000443 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000444 all.append((root, dirs, files))
445 # Don't descend into SUB1.
446 if 'SUB1' in dirs:
447 # Note that this also mutates the dirs we appended to all!
448 dirs.remove('SUB1')
449 self.assertEqual(len(all), 2)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000450 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000451 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000452
453 # Walk bottom-up.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000454 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000455 self.assertEqual(len(all), 4)
456 # We can't know which order SUB1 and SUB2 will appear in.
457 # Not flipped: SUB11, SUB1, SUB2, TESTFN
458 # flipped: SUB2, SUB11, SUB1, TESTFN
459 flipped = all[3][1][0] != "SUB1"
460 all[3][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000461 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000462 self.assertEqual(all[flipped], (sub11_path, [], []))
463 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000464 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000465
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000466 if hasattr(os, "symlink"):
467 # Walk, following symlinks.
468 for root, dirs, files in os.walk(walk_path, followlinks=True):
469 if root == link_path:
470 self.assertEqual(dirs, [])
471 self.assertEqual(files, ["tmp4"])
472 break
473 else:
474 self.fail("Didn't follow symlink with followlinks=True")
Tim Petersc4e09402003-04-25 07:11:48 +0000475
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000476 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000477 # Tear everything down. This is a decent use for bottom-up on
478 # Windows, which doesn't have a recursive delete command. The
479 # (not so) subtlety is that rmdir will fail unless the dir's
480 # kids are removed first, so bottom up is essential.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000481 for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000482 for name in files:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000483 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000484 for name in dirs:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000485 dirname = os.path.join(root, name)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000486 if not os.path.islink(dirname):
487 os.rmdir(dirname)
488 else:
489 os.remove(dirname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000490 os.rmdir(test_support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000491
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000492class MakedirTests (unittest.TestCase):
493 def setUp(self):
494 os.mkdir(test_support.TESTFN)
495
496 def test_makedir(self):
497 base = test_support.TESTFN
498 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
499 os.makedirs(path) # Should work
500 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
501 os.makedirs(path)
502
503 # Try paths with a '.' in them
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000504 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000505 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
506 os.makedirs(path)
507 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
508 'dir5', 'dir6')
509 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000510
Tim Peters58eb11c2004-01-18 20:29:55 +0000511
512
513
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000514 def tearDown(self):
515 path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
516 'dir4', 'dir5', 'dir6')
517 # If the tests failed, the bottom-most directory ('../dir6')
518 # may not have been created, so we look for the outermost directory
519 # that exists.
520 while not os.path.exists(path) and path != test_support.TESTFN:
521 path = os.path.dirname(path)
522
523 os.removedirs(path)
524
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000525class DevNullTests (unittest.TestCase):
526 def test_devnull(self):
527 f = file(os.devnull, 'w')
528 f.write('hello')
529 f.close()
530 f = file(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000531 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000532 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000533
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000534class URandomTests (unittest.TestCase):
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500535
536 def test_urandom_length(self):
537 self.assertEqual(len(os.urandom(0)), 0)
538 self.assertEqual(len(os.urandom(1)), 1)
539 self.assertEqual(len(os.urandom(10)), 10)
540 self.assertEqual(len(os.urandom(100)), 100)
541 self.assertEqual(len(os.urandom(1000)), 1000)
542
543 def test_urandom_value(self):
544 data1 = os.urandom(16)
545 data2 = os.urandom(16)
546 self.assertNotEqual(data1, data2)
547
548 def get_urandom_subprocess(self, count):
Antoine Pitrou341016e2012-02-22 22:16:25 +0100549 # We need to use repr() and eval() to avoid line ending conversions
550 # under Windows.
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500551 code = '\n'.join((
552 'import os, sys',
553 'data = os.urandom(%s)' % count,
Antoine Pitrou341016e2012-02-22 22:16:25 +0100554 'sys.stdout.write(repr(data))',
Antoine Pitrou0607f732012-02-21 22:02:04 +0100555 'sys.stdout.flush()',
556 'print >> sys.stderr, (len(data), data)'))
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500557 cmd_line = [sys.executable, '-c', code]
558 p = subprocess.Popen(cmd_line, stdin=subprocess.PIPE,
Antoine Pitrou0607f732012-02-21 22:02:04 +0100559 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500560 out, err = p.communicate()
Antoine Pitrou0607f732012-02-21 22:02:04 +0100561 self.assertEqual(p.wait(), 0, (p.wait(), err))
Antoine Pitrou341016e2012-02-22 22:16:25 +0100562 out = eval(out)
563 self.assertEqual(len(out), count, err)
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500564 return out
565
566 def test_urandom_subprocess(self):
567 data1 = self.get_urandom_subprocess(16)
568 data2 = self.get_urandom_subprocess(16)
569 self.assertNotEqual(data1, data2)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000570
Benjamin Peterson27c269a2014-12-26 11:09:00 -0600571
572HAVE_GETENTROPY = (sysconfig.get_config_var('HAVE_GETENTROPY') == 1)
573
574@unittest.skipIf(HAVE_GETENTROPY,
575 "getentropy() does not use a file descriptor")
576class URandomFDTests(unittest.TestCase):
Antoine Pitrouf48a67b2013-08-16 20:44:38 +0200577 @unittest.skipUnless(resource, "test requires the resource module")
578 def test_urandom_failure(self):
Antoine Pitroue7587152013-08-24 20:52:27 +0200579 # Check urandom() failing when it is not able to open /dev/random.
580 # We spawn a new process to make the test more robust (if getrlimit()
581 # failed to restore the file descriptor limit after this, the whole
582 # test suite would crash; this actually happened on the OS X Tiger
583 # buildbot).
584 code = """if 1:
585 import errno
586 import os
587 import resource
588
589 soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
590 resource.setrlimit(resource.RLIMIT_NOFILE, (1, hard_limit))
591 try:
Antoine Pitrouf48a67b2013-08-16 20:44:38 +0200592 os.urandom(16)
Antoine Pitroue7587152013-08-24 20:52:27 +0200593 except OSError as e:
594 assert e.errno == errno.EMFILE, e.errno
595 else:
596 raise AssertionError("OSError not raised")
597 """
598 assert_python_ok('-c', code)
Antoine Pitrouf48a67b2013-08-16 20:44:38 +0200599
Antoine Pitrou326ec042013-08-16 20:56:12 +0200600
601class ExecvpeTests(unittest.TestCase):
602
Matthias Klosee9fbf2b2010-03-19 14:45:06 +0000603 def test_execvpe_with_bad_arglist(self):
604 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
605
Antoine Pitrou326ec042013-08-16 20:56:12 +0200606
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200607@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000608class Win32ErrorTests(unittest.TestCase):
609 def test_rename(self):
610 self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak")
611
612 def test_remove(self):
613 self.assertRaises(WindowsError, os.remove, test_support.TESTFN)
614
615 def test_chdir(self):
616 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
617
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000618 def test_mkdir(self):
Kristján Valur Jónssone20f54f2009-02-06 10:17:34 +0000619 f = open(test_support.TESTFN, "w")
620 try:
621 self.assertRaises(WindowsError, os.mkdir, test_support.TESTFN)
622 finally:
623 f.close()
624 os.unlink(test_support.TESTFN)
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000625
626 def test_utime(self):
627 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, None)
628
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000629 def test_chmod(self):
Kristján Valur Jónssone20f54f2009-02-06 10:17:34 +0000630 self.assertRaises(WindowsError, os.chmod, test_support.TESTFN, 0)
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000631
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000632class TestInvalidFD(unittest.TestCase):
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000633 singles = ["fchdir", "fdopen", "dup", "fdatasync", "fstat",
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000634 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000635 #singles.append("close")
636 #We omit close because it doesn'r raise an exception on some platforms
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000637 def get_single(f):
638 def helper(self):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000639 if hasattr(os, f):
640 self.check(getattr(os, f))
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000641 return helper
642 for f in singles:
643 locals()["test_"+f] = get_single(f)
644
Benjamin Peterson5539c782009-01-19 17:37:42 +0000645 def check(self, f, *args):
Benjamin Peterson1de05e92009-01-31 01:42:55 +0000646 try:
647 f(test_support.make_bad_fd(), *args)
648 except OSError as e:
649 self.assertEqual(e.errno, errno.EBADF)
650 else:
651 self.fail("%r didn't raise a OSError with a bad file descriptor"
652 % f)
Benjamin Peterson5539c782009-01-19 17:37:42 +0000653
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200654 @unittest.skipUnless(hasattr(os, 'isatty'), 'test needs os.isatty()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000655 def test_isatty(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200656 self.assertEqual(os.isatty(test_support.make_bad_fd()), False)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000657
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200658 @unittest.skipUnless(hasattr(os, 'closerange'), 'test needs os.closerange()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000659 def test_closerange(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200660 fd = test_support.make_bad_fd()
661 # Make sure none of the descriptors we are about to close are
662 # currently valid (issue 6542).
663 for i in range(10):
664 try: os.fstat(fd+i)
665 except OSError:
666 pass
667 else:
668 break
669 if i < 2:
670 raise unittest.SkipTest(
671 "Unable to acquire a range of invalid file descriptors")
672 self.assertEqual(os.closerange(fd, fd + i-1), None)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000673
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200674 @unittest.skipUnless(hasattr(os, 'dup2'), 'test needs os.dup2()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000675 def test_dup2(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200676 self.check(os.dup2, 20)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000677
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200678 @unittest.skipUnless(hasattr(os, 'fchmod'), 'test needs os.fchmod()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000679 def test_fchmod(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200680 self.check(os.fchmod, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000681
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200682 @unittest.skipUnless(hasattr(os, 'fchown'), 'test needs os.fchown()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000683 def test_fchown(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200684 self.check(os.fchown, -1, -1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000685
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200686 @unittest.skipUnless(hasattr(os, 'fpathconf'), 'test needs os.fpathconf()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000687 def test_fpathconf(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200688 self.check(os.fpathconf, "PC_NAME_MAX")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000689
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200690 @unittest.skipUnless(hasattr(os, 'ftruncate'), 'test needs os.ftruncate()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000691 def test_ftruncate(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200692 self.check(os.ftruncate, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000693
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200694 @unittest.skipUnless(hasattr(os, 'lseek'), 'test needs os.lseek()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000695 def test_lseek(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200696 self.check(os.lseek, 0, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000697
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200698 @unittest.skipUnless(hasattr(os, 'read'), 'test needs os.read()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000699 def test_read(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200700 self.check(os.read, 1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000701
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200702 @unittest.skipUnless(hasattr(os, 'tcsetpgrp'), 'test needs os.tcsetpgrp()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000703 def test_tcsetpgrpt(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200704 self.check(os.tcsetpgrp, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000705
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200706 @unittest.skipUnless(hasattr(os, 'write'), 'test needs os.write()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000707 def test_write(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200708 self.check(os.write, " ")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000709
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200710@unittest.skipIf(sys.platform == "win32", "Posix specific tests")
711class PosixUidGidTests(unittest.TestCase):
712 @unittest.skipUnless(hasattr(os, 'setuid'), 'test needs os.setuid()')
713 def test_setuid(self):
714 if os.getuid() != 0:
715 self.assertRaises(os.error, os.setuid, 0)
716 self.assertRaises(OverflowError, os.setuid, 1<<32)
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000717
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200718 @unittest.skipUnless(hasattr(os, 'setgid'), 'test needs os.setgid()')
719 def test_setgid(self):
720 if os.getuid() != 0:
721 self.assertRaises(os.error, os.setgid, 0)
722 self.assertRaises(OverflowError, os.setgid, 1<<32)
Gregory P. Smith6d307932009-04-05 23:43:58 +0000723
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200724 @unittest.skipUnless(hasattr(os, 'seteuid'), 'test needs os.seteuid()')
725 def test_seteuid(self):
726 if os.getuid() != 0:
727 self.assertRaises(os.error, os.seteuid, 0)
728 self.assertRaises(OverflowError, os.seteuid, 1<<32)
Gregory P. Smith6d307932009-04-05 23:43:58 +0000729
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200730 @unittest.skipUnless(hasattr(os, 'setegid'), 'test needs os.setegid()')
731 def test_setegid(self):
732 if os.getuid() != 0:
733 self.assertRaises(os.error, os.setegid, 0)
734 self.assertRaises(OverflowError, os.setegid, 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(self):
738 if os.getuid() != 0:
739 self.assertRaises(os.error, os.setreuid, 0, 0)
740 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
741 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Gregory P. Smith6d307932009-04-05 23:43:58 +0000742
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200743 @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
744 def test_setreuid_neg1(self):
745 # Needs to accept -1. We run this in a subprocess to avoid
746 # altering the test runner's process state (issue8045).
747 subprocess.check_call([
748 sys.executable, '-c',
749 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Gregory P. Smith467298c2010-03-06 07:35:19 +0000750
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200751 @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
752 def test_setregid(self):
753 if os.getuid() != 0:
754 self.assertRaises(os.error, os.setregid, 0, 0)
755 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
756 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Gregory P. Smith6d307932009-04-05 23:43:58 +0000757
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200758 @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
759 def test_setregid_neg1(self):
760 # Needs to accept -1. We run this in a subprocess to avoid
761 # altering the test runner's process state (issue8045).
762 subprocess.check_call([
763 sys.executable, '-c',
764 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Gregory P. Smith467298c2010-03-06 07:35:19 +0000765
Gregory P. Smith6d307932009-04-05 23:43:58 +0000766
Brian Curtine5aa8862010-04-02 23:26:06 +0000767@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
768class Win32KillTests(unittest.TestCase):
Brian Curtinb3dde132010-04-15 00:40:40 +0000769 def _kill(self, sig):
770 # Start sys.executable as a subprocess and communicate from the
771 # subprocess to the parent that the interpreter is ready. When it
772 # becomes ready, send *sig* via os.kill to the subprocess and check
773 # that the return code is equal to *sig*.
774 import ctypes
775 from ctypes import wintypes
776 import msvcrt
777
778 # Since we can't access the contents of the process' stdout until the
779 # process has exited, use PeekNamedPipe to see what's inside stdout
780 # without waiting. This is done so we can tell that the interpreter
781 # is started and running at a point where it could handle a signal.
782 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
783 PeekNamedPipe.restype = wintypes.BOOL
784 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
785 ctypes.POINTER(ctypes.c_char), # stdout buf
786 wintypes.DWORD, # Buffer size
787 ctypes.POINTER(wintypes.DWORD), # bytes read
788 ctypes.POINTER(wintypes.DWORD), # bytes avail
789 ctypes.POINTER(wintypes.DWORD)) # bytes left
790 msg = "running"
791 proc = subprocess.Popen([sys.executable, "-c",
792 "import sys;"
793 "sys.stdout.write('{}');"
794 "sys.stdout.flush();"
795 "input()".format(msg)],
796 stdout=subprocess.PIPE,
797 stderr=subprocess.PIPE,
798 stdin=subprocess.PIPE)
Brian Curtinf4f0c8b2010-11-05 15:31:20 +0000799 self.addCleanup(proc.stdout.close)
800 self.addCleanup(proc.stderr.close)
801 self.addCleanup(proc.stdin.close)
Brian Curtinb3dde132010-04-15 00:40:40 +0000802
Brian Curtin83cba052010-05-28 15:49:21 +0000803 count, max = 0, 100
804 while count < max and proc.poll() is None:
805 # Create a string buffer to store the result of stdout from the pipe
806 buf = ctypes.create_string_buffer(len(msg))
807 # Obtain the text currently in proc.stdout
808 # Bytes read/avail/left are left as NULL and unused
809 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
810 buf, ctypes.sizeof(buf), None, None, None)
811 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
812 if buf.value:
813 self.assertEqual(msg, buf.value)
814 break
815 time.sleep(0.1)
816 count += 1
817 else:
818 self.fail("Did not receive communication from the subprocess")
Brian Curtinb3dde132010-04-15 00:40:40 +0000819
Brian Curtine5aa8862010-04-02 23:26:06 +0000820 os.kill(proc.pid, sig)
821 self.assertEqual(proc.wait(), sig)
822
823 def test_kill_sigterm(self):
824 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinb3dde132010-04-15 00:40:40 +0000825 self._kill(signal.SIGTERM)
Brian Curtine5aa8862010-04-02 23:26:06 +0000826
827 def test_kill_int(self):
828 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinb3dde132010-04-15 00:40:40 +0000829 self._kill(100)
Brian Curtine5aa8862010-04-02 23:26:06 +0000830
831 def _kill_with_event(self, event, name):
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000832 tagname = "test_os_%s" % uuid.uuid1()
833 m = mmap.mmap(-1, 1, tagname)
834 m[0] = '0'
Brian Curtine5aa8862010-04-02 23:26:06 +0000835 # Run a script which has console control handling enabled.
836 proc = subprocess.Popen([sys.executable,
837 os.path.join(os.path.dirname(__file__),
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000838 "win_console_handler.py"), tagname],
Brian Curtine5aa8862010-04-02 23:26:06 +0000839 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
840 # Let the interpreter startup before we send signals. See #3137.
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000841 count, max = 0, 20
842 while count < max and proc.poll() is None:
Brian Curtindbf8e832010-11-05 15:28:19 +0000843 if m[0] == '1':
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000844 break
845 time.sleep(0.5)
846 count += 1
847 else:
848 self.fail("Subprocess didn't finish initialization")
Brian Curtine5aa8862010-04-02 23:26:06 +0000849 os.kill(proc.pid, event)
850 # proc.send_signal(event) could also be done here.
851 # Allow time for the signal to be passed and the process to exit.
Brian Curtinfce1d312010-04-05 19:04:23 +0000852 time.sleep(0.5)
Brian Curtine5aa8862010-04-02 23:26:06 +0000853 if not proc.poll():
854 # Forcefully kill the process if we weren't able to signal it.
855 os.kill(proc.pid, signal.SIGINT)
856 self.fail("subprocess did not stop on {}".format(name))
857
858 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
859 def test_CTRL_C_EVENT(self):
860 from ctypes import wintypes
861 import ctypes
862
863 # Make a NULL value by creating a pointer with no argument.
864 NULL = ctypes.POINTER(ctypes.c_int)()
865 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
866 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
867 wintypes.BOOL)
868 SetConsoleCtrlHandler.restype = wintypes.BOOL
869
870 # Calling this with NULL and FALSE causes the calling process to
871 # handle CTRL+C, rather than ignore it. This property is inherited
872 # by subprocesses.
873 SetConsoleCtrlHandler(NULL, 0)
874
875 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
876
877 def test_CTRL_BREAK_EVENT(self):
878 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
879
880
Fred Drake2e2be372001-09-20 21:33:42 +0000881def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000882 test_support.run_unittest(
Martin v. Löwisee1e06d2006-07-02 18:44:00 +0000883 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000884 TemporaryFileTests,
885 StatAttributeTests,
886 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000887 WalkTests,
888 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000889 DevNullTests,
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000890 URandomTests,
Antoine Pitrou326ec042013-08-16 20:56:12 +0200891 ExecvpeTests,
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000892 Win32ErrorTests,
Gregory P. Smith6d307932009-04-05 23:43:58 +0000893 TestInvalidFD,
Brian Curtine5aa8862010-04-02 23:26:06 +0000894 PosixUidGidTests,
895 Win32KillTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000896 )
Fred Drake2e2be372001-09-20 21:33:42 +0000897
898if __name__ == "__main__":
899 test_main()