blob: d82ee58f1b44a389d2b82768f7acde02c4f62d1c [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
Victor Stinnere0a0bd62015-02-24 14:30:43 +010013import textwrap
Brian Curtine5aa8862010-04-02 23:26:06 +000014import time
Antoine Pitrouf48a67b2013-08-16 20:44:38 +020015try:
16 import resource
17except ImportError:
18 resource = None
Barry Warsaw1e13eb02012-02-20 20:42:21 -050019
Walter Dörwald21d3a322003-05-01 17:45:56 +000020from test import test_support
Antoine Pitroue7587152013-08-24 20:52:27 +020021from test.script_helper import assert_python_ok
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +000022import mmap
23import uuid
Fred Drake38c2ef02001-07-17 20:52:51 +000024
Barry Warsaw60f01882001-08-22 19:24:42 +000025warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, __name__)
26warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, __name__)
27
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000028# Tests creating TESTFN
29class FileTests(unittest.TestCase):
30 def setUp(self):
31 if os.path.exists(test_support.TESTFN):
32 os.unlink(test_support.TESTFN)
33 tearDown = setUp
34
35 def test_access(self):
36 f = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
37 os.close(f)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000038 self.assertTrue(os.access(test_support.TESTFN, os.W_OK))
Tim Peters16a39322006-07-03 08:23:19 +000039
Georg Brandl309501a2008-01-19 20:22:13 +000040 def test_closerange(self):
Antoine Pitroubebb18b2008-08-17 14:43:41 +000041 first = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
42 # We must allocate two consecutive file descriptors, otherwise
43 # it will mess up other file descriptors (perhaps even the three
44 # standard ones).
45 second = os.dup(first)
46 try:
47 retries = 0
48 while second != first + 1:
49 os.close(first)
50 retries += 1
51 if retries > 10:
52 # XXX test skipped
Benjamin Peterson757b3c92009-05-16 18:44:34 +000053 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroubebb18b2008-08-17 14:43:41 +000054 first, second = second, os.dup(second)
55 finally:
56 os.close(second)
Georg Brandl309501a2008-01-19 20:22:13 +000057 # close a fd that is open, and one that isn't
Antoine Pitroubebb18b2008-08-17 14:43:41 +000058 os.closerange(first, first + 2)
59 self.assertRaises(OSError, os.write, first, "a")
Georg Brandl309501a2008-01-19 20:22:13 +000060
Benjamin Peterson10947a62010-06-30 17:11:08 +000061 @test_support.cpython_only
Hirokazu Yamamoto74ce88f2008-09-08 23:03:47 +000062 def test_rename(self):
63 path = unicode(test_support.TESTFN)
64 old = sys.getrefcount(path)
65 self.assertRaises(TypeError, os.rename, path, 0)
66 new = sys.getrefcount(path)
67 self.assertEqual(old, new)
68
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000069
Fred Drake38c2ef02001-07-17 20:52:51 +000070class TemporaryFileTests(unittest.TestCase):
71 def setUp(self):
72 self.files = []
Walter Dörwald21d3a322003-05-01 17:45:56 +000073 os.mkdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000074
75 def tearDown(self):
76 for name in self.files:
77 os.unlink(name)
Walter Dörwald21d3a322003-05-01 17:45:56 +000078 os.rmdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000079
80 def check_tempfile(self, name):
81 # make sure it doesn't already exist:
Benjamin Peterson5c8da862009-06-30 22:57:08 +000082 self.assertFalse(os.path.exists(name),
Fred Drake38c2ef02001-07-17 20:52:51 +000083 "file already exists for temporary file")
84 # make sure we can create the file
85 open(name, "w")
86 self.files.append(name)
87
Serhiy Storchaka32e23e72013-11-03 23:15:46 +020088 @unittest.skipUnless(hasattr(os, 'tempnam'), 'test needs os.tempnam()')
Fred Drake38c2ef02001-07-17 20:52:51 +000089 def test_tempnam(self):
Antoine Pitroub0614612011-01-02 20:04:52 +000090 with warnings.catch_warnings():
91 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
92 r"test_os$")
93 warnings.filterwarnings("ignore", "tempnam", DeprecationWarning)
94 self.check_tempfile(os.tempnam())
Fred Drake38c2ef02001-07-17 20:52:51 +000095
Antoine Pitroub0614612011-01-02 20:04:52 +000096 name = os.tempnam(test_support.TESTFN)
97 self.check_tempfile(name)
Fred Drake38c2ef02001-07-17 20:52:51 +000098
Antoine Pitroub0614612011-01-02 20:04:52 +000099 name = os.tempnam(test_support.TESTFN, "pfx")
100 self.assertTrue(os.path.basename(name)[:3] == "pfx")
101 self.check_tempfile(name)
Fred Drake38c2ef02001-07-17 20:52:51 +0000102
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200103 @unittest.skipUnless(hasattr(os, 'tmpfile'), 'test needs os.tmpfile()')
Fred Drake38c2ef02001-07-17 20:52:51 +0000104 def test_tmpfile(self):
Martin v. Löwisd2bbe522008-03-06 06:55:22 +0000105 # As with test_tmpnam() below, the Windows implementation of tmpfile()
106 # attempts to create a file in the root directory of the current drive.
107 # On Vista and Server 2008, this test will always fail for normal users
108 # as writing to the root directory requires elevated privileges. With
109 # XP and below, the semantics of tmpfile() are the same, but the user
110 # running the test is more likely to have administrative privileges on
111 # their account already. If that's the case, then os.tmpfile() should
112 # work. In order to make this test as useful as possible, rather than
113 # trying to detect Windows versions or whether or not the user has the
114 # right permissions, just try and create a file in the root directory
115 # and see if it raises a 'Permission denied' OSError. If it does, then
116 # test that a subsequent call to os.tmpfile() raises the same error. If
117 # it doesn't, assume we're on XP or below and the user running the test
118 # has administrative privileges, and proceed with the test as normal.
Antoine Pitroub0614612011-01-02 20:04:52 +0000119 with warnings.catch_warnings():
120 warnings.filterwarnings("ignore", "tmpfile", DeprecationWarning)
Martin v. Löwisd2bbe522008-03-06 06:55:22 +0000121
Antoine Pitroub0614612011-01-02 20:04:52 +0000122 if sys.platform == 'win32':
123 name = '\\python_test_os_test_tmpfile.txt'
124 if os.path.exists(name):
125 os.remove(name)
126 try:
127 fp = open(name, 'w')
128 except IOError, first:
129 # open() failed, assert tmpfile() fails in the same way.
130 # Although open() raises an IOError and os.tmpfile() raises an
131 # OSError(), 'args' will be (13, 'Permission denied') in both
132 # cases.
133 try:
134 fp = os.tmpfile()
135 except OSError, second:
136 self.assertEqual(first.args, second.args)
137 else:
138 self.fail("expected os.tmpfile() to raise OSError")
Zachary Wareb06231a2013-12-10 16:06:46 -0600139 return
Antoine Pitroub0614612011-01-02 20:04:52 +0000140 else:
141 # open() worked, therefore, tmpfile() should work. Close our
142 # dummy file and proceed with the test as normal.
143 fp.close()
144 os.remove(name)
145
146 fp = os.tmpfile()
147 fp.write("foobar")
148 fp.seek(0,0)
149 s = fp.read()
150 fp.close()
151 self.assertTrue(s == "foobar")
Fred Drake38c2ef02001-07-17 20:52:51 +0000152
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200153 @unittest.skipUnless(hasattr(os, 'tmpnam'), 'test needs os.tmpnam()')
Fred Drake38c2ef02001-07-17 20:52:51 +0000154 def test_tmpnam(self):
Antoine Pitroub0614612011-01-02 20:04:52 +0000155 with warnings.catch_warnings():
156 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
157 r"test_os$")
158 warnings.filterwarnings("ignore", "tmpnam", DeprecationWarning)
159
160 name = os.tmpnam()
161 if sys.platform in ("win32",):
162 # The Windows tmpnam() seems useless. From the MS docs:
163 #
164 # The character string that tmpnam creates consists of
165 # the path prefix, defined by the entry P_tmpdir in the
166 # file STDIO.H, followed by a sequence consisting of the
167 # digit characters '0' through '9'; the numerical value
168 # of this string is in the range 1 - 65,535. Changing the
169 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
170 # change the operation of tmpnam.
171 #
172 # The really bizarre part is that, at least under MSVC6,
173 # P_tmpdir is "\\". That is, the path returned refers to
174 # the root of the current drive. That's a terrible place to
175 # put temp files, and, depending on privileges, the user
176 # may not even be able to open a file in the root directory.
177 self.assertFalse(os.path.exists(name),
178 "file already exists for temporary file")
179 else:
180 self.check_tempfile(name)
Tim Peters87cc0c32001-07-21 01:41:30 +0000181
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000182# Test attributes on return values from os.*stat* family.
183class StatAttributeTests(unittest.TestCase):
184 def setUp(self):
Walter Dörwald21d3a322003-05-01 17:45:56 +0000185 os.mkdir(test_support.TESTFN)
186 self.fname = os.path.join(test_support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000187 f = open(self.fname, 'wb')
188 f.write("ABC")
189 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000190
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000191 def tearDown(self):
192 os.unlink(self.fname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000193 os.rmdir(test_support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000194
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200195 @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000196 def test_stat_attributes(self):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000197 import stat
198 result = os.stat(self.fname)
199
200 # Make sure direct access works
Ezio Melotti2623a372010-11-21 13:34:58 +0000201 self.assertEqual(result[stat.ST_SIZE], 3)
202 self.assertEqual(result.st_size, 3)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000203
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000204 # Make sure all the attributes are there
205 members = dir(result)
206 for name in dir(stat):
207 if name[:3] == 'ST_':
208 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000209 if name.endswith("TIME"):
210 def trunc(x): return int(x)
211 else:
212 def trunc(x): return x
Ezio Melotti2623a372010-11-21 13:34:58 +0000213 self.assertEqual(trunc(getattr(result, attr)),
214 result[getattr(stat, name)])
Ezio Melottiaa980582010-01-23 23:04:36 +0000215 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000216
217 try:
218 result[200]
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200219 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000220 except IndexError:
221 pass
222
223 # Make sure that assignment fails
224 try:
225 result.st_mode = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200226 self.fail("No exception raised")
Benjamin Petersonc262a692010-06-30 18:41:08 +0000227 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000228 pass
229
230 try:
231 result.st_rdev = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200232 self.fail("No exception raised")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000233 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000234 pass
235
236 try:
237 result.parrot = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200238 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000239 except AttributeError:
240 pass
241
242 # Use the stat_result constructor with a too-short tuple.
243 try:
244 result2 = os.stat_result((10,))
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200245 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000246 except TypeError:
247 pass
248
Ezio Melotti24b07bc2011-03-15 18:55:01 +0200249 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000250 try:
251 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
252 except TypeError:
253 pass
254
Tim Peterse0c446b2001-10-18 21:57:37 +0000255
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200256 @unittest.skipUnless(hasattr(os, 'statvfs'), 'test needs os.statvfs()')
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000257 def test_statvfs_attributes(self):
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000258 try:
259 result = os.statvfs(self.fname)
260 except OSError, e:
261 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000262 if e.errno == errno.ENOSYS:
Zachary Ware1f702212013-12-10 14:09:20 -0600263 self.skipTest('glibc always returns ENOSYS on AtheOS')
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000264
265 # Make sure direct access works
Ezio Melotti2623a372010-11-21 13:34:58 +0000266 self.assertEqual(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000267
Brett Cannon90f2cb42008-05-16 00:37:42 +0000268 # Make sure all the attributes are there.
269 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
270 'ffree', 'favail', 'flag', 'namemax')
271 for value, member in enumerate(members):
Ezio Melotti2623a372010-11-21 13:34:58 +0000272 self.assertEqual(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000273
274 # Make sure that assignment really fails
275 try:
276 result.f_bfree = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200277 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000278 except TypeError:
279 pass
280
281 try:
282 result.parrot = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200283 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000284 except AttributeError:
285 pass
286
287 # Use the constructor with a too-short tuple.
288 try:
289 result2 = os.statvfs_result((10,))
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200290 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000291 except TypeError:
292 pass
293
Ezio Melotti24b07bc2011-03-15 18:55:01 +0200294 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000295 try:
296 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
297 except TypeError:
298 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000299
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000300 def test_utime_dir(self):
301 delta = 1000000
302 st = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000303 # round to int, because some systems may support sub-second
304 # time stamps in stat, but not in utime.
305 os.utime(test_support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000306 st2 = os.stat(test_support.TESTFN)
Ezio Melotti2623a372010-11-21 13:34:58 +0000307 self.assertEqual(st2.st_mtime, int(st.st_mtime-delta))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000308
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200309 # Restrict tests to Win32, since there is no guarantee other
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000310 # systems support centiseconds
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200311 def get_file_system(path):
312 if sys.platform == 'win32':
Hirokazu Yamamotoccfdcd02008-08-20 04:13:28 +0000313 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000314 import ctypes
Hirokazu Yamamotocd3b74d2008-08-20 16:15:28 +0000315 kernel32 = ctypes.windll.kernel32
316 buf = ctypes.create_string_buffer("", 100)
317 if kernel32.GetVolumeInformationA(root, None, 0, None, None, None, buf, len(buf)):
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000318 return buf.value
319
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200320 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Serhiy Storchakad412b492013-11-03 23:25:42 +0200321 @unittest.skipUnless(get_file_system(test_support.TESTFN) == "NTFS",
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200322 "requires NTFS")
323 def test_1565150(self):
324 t1 = 1159195039.25
325 os.utime(self.fname, (t1, t1))
326 self.assertEqual(os.stat(self.fname).st_mtime, t1)
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000327
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200328 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Serhiy Storchakad412b492013-11-03 23:25:42 +0200329 @unittest.skipUnless(get_file_system(test_support.TESTFN) == "NTFS",
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200330 "requires NTFS")
331 def test_large_time(self):
332 t1 = 5000000000 # some day in 2128
333 os.utime(self.fname, (t1, t1))
334 self.assertEqual(os.stat(self.fname).st_mtime, t1)
Amaury Forgeot d'Arcac514c82011-01-03 00:50:57 +0000335
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200336 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
337 def test_1686475(self):
338 # Verify that an open file can be stat'ed
339 try:
340 os.stat(r"c:\pagefile.sys")
341 except WindowsError, e:
342 if e.errno == 2: # file does not exist; cannot run test
Zachary Ware1f702212013-12-10 14:09:20 -0600343 self.skipTest(r'c:\pagefile.sys does not exist')
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200344 self.fail("Could not stat pagefile.sys")
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000345
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000346from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000347
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000348class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000349 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000350 type2test = None
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000351 def _reference(self):
352 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
353 def _empty_mapping(self):
354 os.environ.clear()
355 return os.environ
356 def setUp(self):
357 self.__save = dict(os.environ)
358 os.environ.clear()
359 def tearDown(self):
360 os.environ.clear()
361 os.environ.update(self.__save)
362
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000363 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000364 def test_update2(self):
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000365 if os.path.exists("/bin/sh"):
366 os.environ.update(HELLO="World")
Brian Curtinfcbf5d02010-10-30 21:29:52 +0000367 with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
368 value = popen.read().strip()
Ezio Melotti2623a372010-11-21 13:34:58 +0000369 self.assertEqual(value, "World")
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000370
Charles-François Natali27bc4d02011-11-27 13:05:14 +0100371 # On FreeBSD < 7 and OS X < 10.6, unsetenv() doesn't return a value (issue
372 # #13415).
373 @unittest.skipIf(sys.platform.startswith(('freebsd', 'darwin')),
374 "due to known OS bug: see issue #13415")
Victor Stinner53853c32011-11-22 22:20:13 +0100375 def test_unset_error(self):
376 if sys.platform == "win32":
377 # an environment variable is limited to 32,767 characters
378 key = 'x' * 50000
Victor Stinner091b6ef2011-11-22 22:30:19 +0100379 self.assertRaises(ValueError, os.environ.__delitem__, key)
Victor Stinner53853c32011-11-22 22:20:13 +0100380 else:
381 # "=" is not allowed in a variable name
382 key = 'key='
Victor Stinner091b6ef2011-11-22 22:30:19 +0100383 self.assertRaises(OSError, os.environ.__delitem__, key)
Victor Stinner53853c32011-11-22 22:20:13 +0100384
Tim Petersc4e09402003-04-25 07:11:48 +0000385class WalkTests(unittest.TestCase):
386 """Tests for os.walk()."""
387
388 def test_traversal(self):
389 import os
390 from os.path import join
391
392 # Build:
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000393 # TESTFN/
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000394 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000395 # tmp1
396 # SUB1/ a file kid and a directory kid
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000397 # tmp2
398 # SUB11/ no kids
399 # SUB2/ a file kid and a dirsymlink kid
400 # tmp3
401 # link/ a symlink to TESTFN.2
402 # TEST2/
403 # tmp4 a lone file
404 walk_path = join(test_support.TESTFN, "TEST1")
405 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000406 sub11_path = join(sub1_path, "SUB11")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000407 sub2_path = join(walk_path, "SUB2")
408 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000409 tmp2_path = join(sub1_path, "tmp2")
410 tmp3_path = join(sub2_path, "tmp3")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000411 link_path = join(sub2_path, "link")
412 t2_path = join(test_support.TESTFN, "TEST2")
413 tmp4_path = join(test_support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000414
415 # Create stuff.
416 os.makedirs(sub11_path)
417 os.makedirs(sub2_path)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000418 os.makedirs(t2_path)
419 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Tim Petersc4e09402003-04-25 07:11:48 +0000420 f = file(path, "w")
421 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
422 f.close()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000423 if hasattr(os, "symlink"):
424 os.symlink(os.path.abspath(t2_path), link_path)
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000425 sub2_tree = (sub2_path, ["link"], ["tmp3"])
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000426 else:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000427 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000428
429 # Walk top-down.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000430 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000431 self.assertEqual(len(all), 4)
432 # We can't know which order SUB1 and SUB2 will appear in.
433 # Not flipped: TESTFN, SUB1, SUB11, SUB2
434 # flipped: TESTFN, SUB2, SUB1, SUB11
435 flipped = all[0][1][0] != "SUB1"
436 all[0][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000437 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000438 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
439 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000440 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000441
442 # Prune the search.
443 all = []
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000444 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000445 all.append((root, dirs, files))
446 # Don't descend into SUB1.
447 if 'SUB1' in dirs:
448 # Note that this also mutates the dirs we appended to all!
449 dirs.remove('SUB1')
450 self.assertEqual(len(all), 2)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000451 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000452 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000453
454 # Walk bottom-up.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000455 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000456 self.assertEqual(len(all), 4)
457 # We can't know which order SUB1 and SUB2 will appear in.
458 # Not flipped: SUB11, SUB1, SUB2, TESTFN
459 # flipped: SUB2, SUB11, SUB1, TESTFN
460 flipped = all[3][1][0] != "SUB1"
461 all[3][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000462 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000463 self.assertEqual(all[flipped], (sub11_path, [], []))
464 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000465 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000466
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000467 if hasattr(os, "symlink"):
468 # Walk, following symlinks.
469 for root, dirs, files in os.walk(walk_path, followlinks=True):
470 if root == link_path:
471 self.assertEqual(dirs, [])
472 self.assertEqual(files, ["tmp4"])
473 break
474 else:
475 self.fail("Didn't follow symlink with followlinks=True")
Tim Petersc4e09402003-04-25 07:11:48 +0000476
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000477 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000478 # Tear everything down. This is a decent use for bottom-up on
479 # Windows, which doesn't have a recursive delete command. The
480 # (not so) subtlety is that rmdir will fail unless the dir's
481 # kids are removed first, so bottom up is essential.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000482 for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000483 for name in files:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000484 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000485 for name in dirs:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000486 dirname = os.path.join(root, name)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000487 if not os.path.islink(dirname):
488 os.rmdir(dirname)
489 else:
490 os.remove(dirname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000491 os.rmdir(test_support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000492
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000493class MakedirTests (unittest.TestCase):
494 def setUp(self):
495 os.mkdir(test_support.TESTFN)
496
497 def test_makedir(self):
498 base = test_support.TESTFN
499 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
500 os.makedirs(path) # Should work
501 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
502 os.makedirs(path)
503
504 # Try paths with a '.' in them
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000505 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000506 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
507 os.makedirs(path)
508 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
509 'dir5', 'dir6')
510 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000511
Tim Peters58eb11c2004-01-18 20:29:55 +0000512
513
514
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000515 def tearDown(self):
516 path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
517 'dir4', 'dir5', 'dir6')
518 # If the tests failed, the bottom-most directory ('../dir6')
519 # may not have been created, so we look for the outermost directory
520 # that exists.
521 while not os.path.exists(path) and path != test_support.TESTFN:
522 path = os.path.dirname(path)
523
524 os.removedirs(path)
525
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000526class DevNullTests (unittest.TestCase):
527 def test_devnull(self):
528 f = file(os.devnull, 'w')
529 f.write('hello')
530 f.close()
531 f = file(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000532 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000533 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000534
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000535class URandomTests (unittest.TestCase):
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500536
537 def test_urandom_length(self):
538 self.assertEqual(len(os.urandom(0)), 0)
539 self.assertEqual(len(os.urandom(1)), 1)
540 self.assertEqual(len(os.urandom(10)), 10)
541 self.assertEqual(len(os.urandom(100)), 100)
542 self.assertEqual(len(os.urandom(1000)), 1000)
543
544 def test_urandom_value(self):
545 data1 = os.urandom(16)
546 data2 = os.urandom(16)
547 self.assertNotEqual(data1, data2)
548
549 def get_urandom_subprocess(self, count):
Antoine Pitrou341016e2012-02-22 22:16:25 +0100550 # We need to use repr() and eval() to avoid line ending conversions
551 # under Windows.
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500552 code = '\n'.join((
553 'import os, sys',
554 'data = os.urandom(%s)' % count,
Antoine Pitrou341016e2012-02-22 22:16:25 +0100555 'sys.stdout.write(repr(data))',
Antoine Pitrou0607f732012-02-21 22:02:04 +0100556 'sys.stdout.flush()',
557 'print >> sys.stderr, (len(data), data)'))
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500558 cmd_line = [sys.executable, '-c', code]
559 p = subprocess.Popen(cmd_line, stdin=subprocess.PIPE,
Antoine Pitrou0607f732012-02-21 22:02:04 +0100560 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500561 out, err = p.communicate()
Antoine Pitrou0607f732012-02-21 22:02:04 +0100562 self.assertEqual(p.wait(), 0, (p.wait(), err))
Antoine Pitrou341016e2012-02-22 22:16:25 +0100563 out = eval(out)
564 self.assertEqual(len(out), count, err)
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500565 return out
566
567 def test_urandom_subprocess(self):
568 data1 = self.get_urandom_subprocess(16)
569 data2 = self.get_urandom_subprocess(16)
570 self.assertNotEqual(data1, data2)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000571
Victor Stinnerebcbbfb2015-02-24 15:12:57 +0100572 # os.urandom() doesn't use a file descriptor on Windows
573 @unittest.skipIf(sys.platform == "win32", "POSIX specific tests")
Ned Deily9e527352015-03-17 15:18:07 -0700574 # FD_CLOEXEC is first supported on OS X 10.5
575 @test_support.requires_mac_ver(10, 5)
Victor Stinnere0a0bd62015-02-24 14:30:43 +0100576 def test_urandom_fd_non_inheritable(self):
577 # Issue #23458: os.urandom() keeps a file descriptor open, but it
578 # must be non inheritable
579 fd_status = test_support.findfile("fd_status.py", subdir="subprocessdata")
580
581 # Need a two subprocesses because the Python test suite opens other
582 # inheritable file descriptors, whereas the test is specific to
583 # os.urandom() file descriptor
584 code = textwrap.dedent("""
585 import os
586 import subprocess
587 import sys
588
589 # Ensure that the /dev/urandom file descriptor is open
590 os.urandom(1)
591
592 exitcode = subprocess.call([sys.executable, %r],
593 close_fds=False)
594 sys.exit(exitcode)
595 """ % fd_status)
596
597 proc = subprocess.Popen([sys.executable, "-c", code],
598 stdout=subprocess.PIPE, close_fds=True)
599 output, error = proc.communicate()
600 open_fds = set(map(int, output.rstrip().split(',')))
601 self.assertEqual(open_fds - set(range(3)), set())
602
Benjamin Peterson27c269a2014-12-26 11:09:00 -0600603
604HAVE_GETENTROPY = (sysconfig.get_config_var('HAVE_GETENTROPY') == 1)
605
606@unittest.skipIf(HAVE_GETENTROPY,
607 "getentropy() does not use a file descriptor")
608class URandomFDTests(unittest.TestCase):
Antoine Pitrouf48a67b2013-08-16 20:44:38 +0200609 @unittest.skipUnless(resource, "test requires the resource module")
610 def test_urandom_failure(self):
Antoine Pitroue7587152013-08-24 20:52:27 +0200611 # Check urandom() failing when it is not able to open /dev/random.
612 # We spawn a new process to make the test more robust (if getrlimit()
613 # failed to restore the file descriptor limit after this, the whole
614 # test suite would crash; this actually happened on the OS X Tiger
615 # buildbot).
616 code = """if 1:
617 import errno
618 import os
619 import resource
620
621 soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
622 resource.setrlimit(resource.RLIMIT_NOFILE, (1, hard_limit))
623 try:
Antoine Pitrouf48a67b2013-08-16 20:44:38 +0200624 os.urandom(16)
Antoine Pitroue7587152013-08-24 20:52:27 +0200625 except OSError as e:
626 assert e.errno == errno.EMFILE, e.errno
627 else:
628 raise AssertionError("OSError not raised")
629 """
630 assert_python_ok('-c', code)
Antoine Pitrouf48a67b2013-08-16 20:44:38 +0200631
Antoine Pitrou326ec042013-08-16 20:56:12 +0200632
633class ExecvpeTests(unittest.TestCase):
634
Matthias Klosee9fbf2b2010-03-19 14:45:06 +0000635 def test_execvpe_with_bad_arglist(self):
636 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
637
Antoine Pitrou326ec042013-08-16 20:56:12 +0200638
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200639@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000640class Win32ErrorTests(unittest.TestCase):
641 def test_rename(self):
642 self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak")
643
644 def test_remove(self):
645 self.assertRaises(WindowsError, os.remove, test_support.TESTFN)
646
647 def test_chdir(self):
648 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
649
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000650 def test_mkdir(self):
Kristján Valur Jónssone20f54f2009-02-06 10:17:34 +0000651 f = open(test_support.TESTFN, "w")
652 try:
653 self.assertRaises(WindowsError, os.mkdir, test_support.TESTFN)
654 finally:
655 f.close()
656 os.unlink(test_support.TESTFN)
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000657
658 def test_utime(self):
659 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, None)
660
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000661 def test_chmod(self):
Kristján Valur Jónssone20f54f2009-02-06 10:17:34 +0000662 self.assertRaises(WindowsError, os.chmod, test_support.TESTFN, 0)
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000663
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000664class TestInvalidFD(unittest.TestCase):
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000665 singles = ["fchdir", "fdopen", "dup", "fdatasync", "fstat",
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000666 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000667 #singles.append("close")
668 #We omit close because it doesn'r raise an exception on some platforms
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000669 def get_single(f):
670 def helper(self):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000671 if hasattr(os, f):
672 self.check(getattr(os, f))
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000673 return helper
674 for f in singles:
675 locals()["test_"+f] = get_single(f)
676
Benjamin Peterson5539c782009-01-19 17:37:42 +0000677 def check(self, f, *args):
Benjamin Peterson1de05e92009-01-31 01:42:55 +0000678 try:
679 f(test_support.make_bad_fd(), *args)
680 except OSError as e:
681 self.assertEqual(e.errno, errno.EBADF)
682 else:
683 self.fail("%r didn't raise a OSError with a bad file descriptor"
684 % f)
Benjamin Peterson5539c782009-01-19 17:37:42 +0000685
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200686 @unittest.skipUnless(hasattr(os, 'isatty'), 'test needs os.isatty()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000687 def test_isatty(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200688 self.assertEqual(os.isatty(test_support.make_bad_fd()), False)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000689
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200690 @unittest.skipUnless(hasattr(os, 'closerange'), 'test needs os.closerange()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000691 def test_closerange(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200692 fd = test_support.make_bad_fd()
693 # Make sure none of the descriptors we are about to close are
694 # currently valid (issue 6542).
695 for i in range(10):
696 try: os.fstat(fd+i)
697 except OSError:
698 pass
699 else:
700 break
701 if i < 2:
702 raise unittest.SkipTest(
703 "Unable to acquire a range of invalid file descriptors")
704 self.assertEqual(os.closerange(fd, fd + i-1), None)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000705
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200706 @unittest.skipUnless(hasattr(os, 'dup2'), 'test needs os.dup2()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000707 def test_dup2(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200708 self.check(os.dup2, 20)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000709
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200710 @unittest.skipUnless(hasattr(os, 'fchmod'), 'test needs os.fchmod()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000711 def test_fchmod(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200712 self.check(os.fchmod, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000713
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200714 @unittest.skipUnless(hasattr(os, 'fchown'), 'test needs os.fchown()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000715 def test_fchown(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200716 self.check(os.fchown, -1, -1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000717
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200718 @unittest.skipUnless(hasattr(os, 'fpathconf'), 'test needs os.fpathconf()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000719 def test_fpathconf(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200720 self.check(os.fpathconf, "PC_NAME_MAX")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000721
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200722 @unittest.skipUnless(hasattr(os, 'ftruncate'), 'test needs os.ftruncate()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000723 def test_ftruncate(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200724 self.check(os.ftruncate, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000725
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200726 @unittest.skipUnless(hasattr(os, 'lseek'), 'test needs os.lseek()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000727 def test_lseek(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200728 self.check(os.lseek, 0, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000729
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200730 @unittest.skipUnless(hasattr(os, 'read'), 'test needs os.read()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000731 def test_read(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200732 self.check(os.read, 1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000733
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200734 @unittest.skipUnless(hasattr(os, 'tcsetpgrp'), 'test needs os.tcsetpgrp()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000735 def test_tcsetpgrpt(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200736 self.check(os.tcsetpgrp, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000737
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200738 @unittest.skipUnless(hasattr(os, 'write'), 'test needs os.write()')
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000739 def test_write(self):
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200740 self.check(os.write, " ")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000741
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200742@unittest.skipIf(sys.platform == "win32", "Posix specific tests")
743class PosixUidGidTests(unittest.TestCase):
744 @unittest.skipUnless(hasattr(os, 'setuid'), 'test needs os.setuid()')
745 def test_setuid(self):
746 if os.getuid() != 0:
747 self.assertRaises(os.error, os.setuid, 0)
748 self.assertRaises(OverflowError, os.setuid, 1<<32)
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000749
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200750 @unittest.skipUnless(hasattr(os, 'setgid'), 'test needs os.setgid()')
751 def test_setgid(self):
752 if os.getuid() != 0:
753 self.assertRaises(os.error, os.setgid, 0)
754 self.assertRaises(OverflowError, os.setgid, 1<<32)
Gregory P. Smith6d307932009-04-05 23:43:58 +0000755
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200756 @unittest.skipUnless(hasattr(os, 'seteuid'), 'test needs os.seteuid()')
757 def test_seteuid(self):
758 if os.getuid() != 0:
759 self.assertRaises(os.error, os.seteuid, 0)
760 self.assertRaises(OverflowError, os.seteuid, 1<<32)
Gregory P. Smith6d307932009-04-05 23:43:58 +0000761
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200762 @unittest.skipUnless(hasattr(os, 'setegid'), 'test needs os.setegid()')
763 def test_setegid(self):
764 if os.getuid() != 0:
765 self.assertRaises(os.error, os.setegid, 0)
766 self.assertRaises(OverflowError, os.setegid, 1<<32)
Gregory P. Smith6d307932009-04-05 23:43:58 +0000767
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200768 @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
769 def test_setreuid(self):
770 if os.getuid() != 0:
771 self.assertRaises(os.error, os.setreuid, 0, 0)
772 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
773 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Gregory P. Smith6d307932009-04-05 23:43:58 +0000774
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200775 @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
776 def test_setreuid_neg1(self):
777 # Needs to accept -1. We run this in a subprocess to avoid
778 # altering the test runner's process state (issue8045).
779 subprocess.check_call([
780 sys.executable, '-c',
781 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Gregory P. Smith467298c2010-03-06 07:35:19 +0000782
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200783 @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
784 def test_setregid(self):
785 if os.getuid() != 0:
786 self.assertRaises(os.error, os.setregid, 0, 0)
787 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
788 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Gregory P. Smith6d307932009-04-05 23:43:58 +0000789
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200790 @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
791 def test_setregid_neg1(self):
792 # Needs to accept -1. We run this in a subprocess to avoid
793 # altering the test runner's process state (issue8045).
794 subprocess.check_call([
795 sys.executable, '-c',
796 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Gregory P. Smith467298c2010-03-06 07:35:19 +0000797
Gregory P. Smith6d307932009-04-05 23:43:58 +0000798
Brian Curtine5aa8862010-04-02 23:26:06 +0000799@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
800class Win32KillTests(unittest.TestCase):
Brian Curtinb3dde132010-04-15 00:40:40 +0000801 def _kill(self, sig):
802 # Start sys.executable as a subprocess and communicate from the
803 # subprocess to the parent that the interpreter is ready. When it
804 # becomes ready, send *sig* via os.kill to the subprocess and check
805 # that the return code is equal to *sig*.
806 import ctypes
807 from ctypes import wintypes
808 import msvcrt
809
810 # Since we can't access the contents of the process' stdout until the
811 # process has exited, use PeekNamedPipe to see what's inside stdout
812 # without waiting. This is done so we can tell that the interpreter
813 # is started and running at a point where it could handle a signal.
814 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
815 PeekNamedPipe.restype = wintypes.BOOL
816 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
817 ctypes.POINTER(ctypes.c_char), # stdout buf
818 wintypes.DWORD, # Buffer size
819 ctypes.POINTER(wintypes.DWORD), # bytes read
820 ctypes.POINTER(wintypes.DWORD), # bytes avail
821 ctypes.POINTER(wintypes.DWORD)) # bytes left
822 msg = "running"
823 proc = subprocess.Popen([sys.executable, "-c",
824 "import sys;"
825 "sys.stdout.write('{}');"
826 "sys.stdout.flush();"
827 "input()".format(msg)],
828 stdout=subprocess.PIPE,
829 stderr=subprocess.PIPE,
830 stdin=subprocess.PIPE)
Brian Curtinf4f0c8b2010-11-05 15:31:20 +0000831 self.addCleanup(proc.stdout.close)
832 self.addCleanup(proc.stderr.close)
833 self.addCleanup(proc.stdin.close)
Brian Curtinb3dde132010-04-15 00:40:40 +0000834
Brian Curtin83cba052010-05-28 15:49:21 +0000835 count, max = 0, 100
836 while count < max and proc.poll() is None:
837 # Create a string buffer to store the result of stdout from the pipe
838 buf = ctypes.create_string_buffer(len(msg))
839 # Obtain the text currently in proc.stdout
840 # Bytes read/avail/left are left as NULL and unused
841 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
842 buf, ctypes.sizeof(buf), None, None, None)
843 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
844 if buf.value:
845 self.assertEqual(msg, buf.value)
846 break
847 time.sleep(0.1)
848 count += 1
849 else:
850 self.fail("Did not receive communication from the subprocess")
Brian Curtinb3dde132010-04-15 00:40:40 +0000851
Brian Curtine5aa8862010-04-02 23:26:06 +0000852 os.kill(proc.pid, sig)
853 self.assertEqual(proc.wait(), sig)
854
855 def test_kill_sigterm(self):
856 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinb3dde132010-04-15 00:40:40 +0000857 self._kill(signal.SIGTERM)
Brian Curtine5aa8862010-04-02 23:26:06 +0000858
859 def test_kill_int(self):
860 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinb3dde132010-04-15 00:40:40 +0000861 self._kill(100)
Brian Curtine5aa8862010-04-02 23:26:06 +0000862
863 def _kill_with_event(self, event, name):
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000864 tagname = "test_os_%s" % uuid.uuid1()
865 m = mmap.mmap(-1, 1, tagname)
866 m[0] = '0'
Brian Curtine5aa8862010-04-02 23:26:06 +0000867 # Run a script which has console control handling enabled.
868 proc = subprocess.Popen([sys.executable,
869 os.path.join(os.path.dirname(__file__),
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000870 "win_console_handler.py"), tagname],
Brian Curtine5aa8862010-04-02 23:26:06 +0000871 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
872 # Let the interpreter startup before we send signals. See #3137.
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000873 count, max = 0, 20
874 while count < max and proc.poll() is None:
Brian Curtindbf8e832010-11-05 15:28:19 +0000875 if m[0] == '1':
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000876 break
877 time.sleep(0.5)
878 count += 1
879 else:
880 self.fail("Subprocess didn't finish initialization")
Brian Curtine5aa8862010-04-02 23:26:06 +0000881 os.kill(proc.pid, event)
882 # proc.send_signal(event) could also be done here.
883 # Allow time for the signal to be passed and the process to exit.
Brian Curtinfce1d312010-04-05 19:04:23 +0000884 time.sleep(0.5)
Brian Curtine5aa8862010-04-02 23:26:06 +0000885 if not proc.poll():
886 # Forcefully kill the process if we weren't able to signal it.
887 os.kill(proc.pid, signal.SIGINT)
888 self.fail("subprocess did not stop on {}".format(name))
889
890 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
891 def test_CTRL_C_EVENT(self):
892 from ctypes import wintypes
893 import ctypes
894
895 # Make a NULL value by creating a pointer with no argument.
896 NULL = ctypes.POINTER(ctypes.c_int)()
897 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
898 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
899 wintypes.BOOL)
900 SetConsoleCtrlHandler.restype = wintypes.BOOL
901
902 # Calling this with NULL and FALSE causes the calling process to
903 # handle CTRL+C, rather than ignore it. This property is inherited
904 # by subprocesses.
905 SetConsoleCtrlHandler(NULL, 0)
906
907 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
908
909 def test_CTRL_BREAK_EVENT(self):
910 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
911
912
Fred Drake2e2be372001-09-20 21:33:42 +0000913def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000914 test_support.run_unittest(
Martin v. Löwisee1e06d2006-07-02 18:44:00 +0000915 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000916 TemporaryFileTests,
917 StatAttributeTests,
918 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000919 WalkTests,
920 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000921 DevNullTests,
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000922 URandomTests,
Ned Deily596b7512015-03-17 04:34:46 -0700923 URandomFDTests,
Antoine Pitrou326ec042013-08-16 20:56:12 +0200924 ExecvpeTests,
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000925 Win32ErrorTests,
Gregory P. Smith6d307932009-04-05 23:43:58 +0000926 TestInvalidFD,
Brian Curtine5aa8862010-04-02 23:26:06 +0000927 PosixUidGidTests,
928 Win32KillTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000929 )
Fred Drake2e2be372001-09-20 21:33:42 +0000930
931if __name__ == "__main__":
932 test_main()