blob: 1d7e836f5c9e373eb48a6d22d59edb35daa71d38 [file] [log] [blame]
Fred Drake38c2ef02001-07-17 20:52:51 +00001# As a test suite for the os module, this is woefully inadequate, but this
2# does add tests for a few functions which have been determined to be more
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00003# portable than they had been thought to be.
Fred Drake38c2ef02001-07-17 20:52:51 +00004
5import os
Benjamin Peterson1de05e92009-01-31 01:42:55 +00006import errno
Fred Drake38c2ef02001-07-17 20:52:51 +00007import unittest
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +00008import warnings
Martin v. Löwis8e0d4942006-05-04 10:08:42 +00009import sys
Brian Curtine5aa8862010-04-02 23:26:06 +000010import signal
11import subprocess
12import time
Antoine Pitrouf48a67b2013-08-16 20:44:38 +020013try:
14 import resource
15except ImportError:
16 resource = None
Barry Warsaw1e13eb02012-02-20 20:42:21 -050017
Walter Dörwald21d3a322003-05-01 17:45:56 +000018from test import test_support
Antoine Pitroue7587152013-08-24 20:52:27 +020019from test.script_helper import assert_python_ok
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +000020import mmap
21import uuid
Fred Drake38c2ef02001-07-17 20:52:51 +000022
Barry Warsaw60f01882001-08-22 19:24:42 +000023warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, __name__)
24warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, __name__)
25
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000026# Tests creating TESTFN
27class FileTests(unittest.TestCase):
28 def setUp(self):
29 if os.path.exists(test_support.TESTFN):
30 os.unlink(test_support.TESTFN)
31 tearDown = setUp
32
33 def test_access(self):
34 f = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
35 os.close(f)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000036 self.assertTrue(os.access(test_support.TESTFN, os.W_OK))
Tim Peters16a39322006-07-03 08:23:19 +000037
Georg Brandl309501a2008-01-19 20:22:13 +000038 def test_closerange(self):
Antoine Pitroubebb18b2008-08-17 14:43:41 +000039 first = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
40 # We must allocate two consecutive file descriptors, otherwise
41 # it will mess up other file descriptors (perhaps even the three
42 # standard ones).
43 second = os.dup(first)
44 try:
45 retries = 0
46 while second != first + 1:
47 os.close(first)
48 retries += 1
49 if retries > 10:
50 # XXX test skipped
Benjamin Peterson757b3c92009-05-16 18:44:34 +000051 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroubebb18b2008-08-17 14:43:41 +000052 first, second = second, os.dup(second)
53 finally:
54 os.close(second)
Georg Brandl309501a2008-01-19 20:22:13 +000055 # close a fd that is open, and one that isn't
Antoine Pitroubebb18b2008-08-17 14:43:41 +000056 os.closerange(first, first + 2)
57 self.assertRaises(OSError, os.write, first, "a")
Georg Brandl309501a2008-01-19 20:22:13 +000058
Benjamin Peterson10947a62010-06-30 17:11:08 +000059 @test_support.cpython_only
Hirokazu Yamamoto74ce88f2008-09-08 23:03:47 +000060 def test_rename(self):
61 path = unicode(test_support.TESTFN)
62 old = sys.getrefcount(path)
63 self.assertRaises(TypeError, os.rename, path, 0)
64 new = sys.getrefcount(path)
65 self.assertEqual(old, new)
66
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000067
Fred Drake38c2ef02001-07-17 20:52:51 +000068class TemporaryFileTests(unittest.TestCase):
69 def setUp(self):
70 self.files = []
Walter Dörwald21d3a322003-05-01 17:45:56 +000071 os.mkdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000072
73 def tearDown(self):
74 for name in self.files:
75 os.unlink(name)
Walter Dörwald21d3a322003-05-01 17:45:56 +000076 os.rmdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000077
78 def check_tempfile(self, name):
79 # make sure it doesn't already exist:
Benjamin Peterson5c8da862009-06-30 22:57:08 +000080 self.assertFalse(os.path.exists(name),
Fred Drake38c2ef02001-07-17 20:52:51 +000081 "file already exists for temporary file")
82 # make sure we can create the file
83 open(name, "w")
84 self.files.append(name)
85
86 def test_tempnam(self):
87 if not hasattr(os, "tempnam"):
88 return
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
102 def test_tmpfile(self):
103 if not hasattr(os, "tmpfile"):
104 return
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")
139 return
140 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
153 def test_tmpnam(self):
154 if not hasattr(os, "tmpnam"):
155 return
Antoine Pitroub0614612011-01-02 20:04:52 +0000156 with warnings.catch_warnings():
157 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
158 r"test_os$")
159 warnings.filterwarnings("ignore", "tmpnam", DeprecationWarning)
160
161 name = os.tmpnam()
162 if sys.platform in ("win32",):
163 # The Windows tmpnam() seems useless. From the MS docs:
164 #
165 # The character string that tmpnam creates consists of
166 # the path prefix, defined by the entry P_tmpdir in the
167 # file STDIO.H, followed by a sequence consisting of the
168 # digit characters '0' through '9'; the numerical value
169 # of this string is in the range 1 - 65,535. Changing the
170 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
171 # change the operation of tmpnam.
172 #
173 # The really bizarre part is that, at least under MSVC6,
174 # P_tmpdir is "\\". That is, the path returned refers to
175 # the root of the current drive. That's a terrible place to
176 # put temp files, and, depending on privileges, the user
177 # may not even be able to open a file in the root directory.
178 self.assertFalse(os.path.exists(name),
179 "file already exists for temporary file")
180 else:
181 self.check_tempfile(name)
Tim Peters87cc0c32001-07-21 01:41:30 +0000182
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000183# Test attributes on return values from os.*stat* family.
184class StatAttributeTests(unittest.TestCase):
185 def setUp(self):
Walter Dörwald21d3a322003-05-01 17:45:56 +0000186 os.mkdir(test_support.TESTFN)
187 self.fname = os.path.join(test_support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000188 f = open(self.fname, 'wb')
189 f.write("ABC")
190 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000191
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000192 def tearDown(self):
193 os.unlink(self.fname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000194 os.rmdir(test_support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000195
196 def test_stat_attributes(self):
197 if not hasattr(os, "stat"):
198 return
199
200 import stat
201 result = os.stat(self.fname)
202
203 # Make sure direct access works
Ezio Melotti2623a372010-11-21 13:34:58 +0000204 self.assertEqual(result[stat.ST_SIZE], 3)
205 self.assertEqual(result.st_size, 3)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000206
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000207 # Make sure all the attributes are there
208 members = dir(result)
209 for name in dir(stat):
210 if name[:3] == 'ST_':
211 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000212 if name.endswith("TIME"):
213 def trunc(x): return int(x)
214 else:
215 def trunc(x): return x
Ezio Melotti2623a372010-11-21 13:34:58 +0000216 self.assertEqual(trunc(getattr(result, attr)),
217 result[getattr(stat, name)])
Ezio Melottiaa980582010-01-23 23:04:36 +0000218 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000219
220 try:
221 result[200]
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200222 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000223 except IndexError:
224 pass
225
226 # Make sure that assignment fails
227 try:
228 result.st_mode = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200229 self.fail("No exception raised")
Benjamin Petersonc262a692010-06-30 18:41:08 +0000230 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000231 pass
232
233 try:
234 result.st_rdev = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200235 self.fail("No exception raised")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000236 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000237 pass
238
239 try:
240 result.parrot = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200241 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000242 except AttributeError:
243 pass
244
245 # Use the stat_result constructor with a too-short tuple.
246 try:
247 result2 = os.stat_result((10,))
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200248 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000249 except TypeError:
250 pass
251
Ezio Melotti24b07bc2011-03-15 18:55:01 +0200252 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000253 try:
254 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
255 except TypeError:
256 pass
257
Tim Peterse0c446b2001-10-18 21:57:37 +0000258
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000259 def test_statvfs_attributes(self):
260 if not hasattr(os, "statvfs"):
261 return
262
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000263 try:
264 result = os.statvfs(self.fname)
265 except OSError, e:
266 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000267 if e.errno == errno.ENOSYS:
268 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000269
270 # Make sure direct access works
Ezio Melotti2623a372010-11-21 13:34:58 +0000271 self.assertEqual(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000272
Brett Cannon90f2cb42008-05-16 00:37:42 +0000273 # Make sure all the attributes are there.
274 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
275 'ffree', 'favail', 'flag', 'namemax')
276 for value, member in enumerate(members):
Ezio Melotti2623a372010-11-21 13:34:58 +0000277 self.assertEqual(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000278
279 # Make sure that assignment really fails
280 try:
281 result.f_bfree = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200282 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000283 except TypeError:
284 pass
285
286 try:
287 result.parrot = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200288 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000289 except AttributeError:
290 pass
291
292 # Use the constructor with a too-short tuple.
293 try:
294 result2 = os.statvfs_result((10,))
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200295 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000296 except TypeError:
297 pass
298
Ezio Melotti24b07bc2011-03-15 18:55:01 +0200299 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000300 try:
301 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
302 except TypeError:
303 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000304
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000305 def test_utime_dir(self):
306 delta = 1000000
307 st = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000308 # round to int, because some systems may support sub-second
309 # time stamps in stat, but not in utime.
310 os.utime(test_support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000311 st2 = os.stat(test_support.TESTFN)
Ezio Melotti2623a372010-11-21 13:34:58 +0000312 self.assertEqual(st2.st_mtime, int(st.st_mtime-delta))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000313
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000314 # Restrict test to Win32, since there is no guarantee other
315 # systems support centiseconds
316 if sys.platform == 'win32':
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000317 def get_file_system(path):
Hirokazu Yamamotoccfdcd02008-08-20 04:13:28 +0000318 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000319 import ctypes
Hirokazu Yamamotocd3b74d2008-08-20 16:15:28 +0000320 kernel32 = ctypes.windll.kernel32
321 buf = ctypes.create_string_buffer("", 100)
322 if kernel32.GetVolumeInformationA(root, None, 0, None, None, None, buf, len(buf)):
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000323 return buf.value
324
325 if get_file_system(test_support.TESTFN) == "NTFS":
326 def test_1565150(self):
327 t1 = 1159195039.25
328 os.utime(self.fname, (t1, t1))
Ezio Melotti2623a372010-11-21 13:34:58 +0000329 self.assertEqual(os.stat(self.fname).st_mtime, t1)
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000330
Amaury Forgeot d'Arcac514c82011-01-03 00:50:57 +0000331 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)
335
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000336 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:
Antoine Pitrou954ea642008-08-17 20:15:07 +0000341 if e.errno == 2: # file does not exist; cannot run test
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000342 return
343 self.fail("Could not stat pagefile.sys")
344
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
Antoine Pitrouf48a67b2013-08-16 20:44:38 +0200571 @unittest.skipUnless(resource, "test requires the resource module")
572 def test_urandom_failure(self):
Antoine Pitroue7587152013-08-24 20:52:27 +0200573 # Check urandom() failing when it is not able to open /dev/random.
574 # We spawn a new process to make the test more robust (if getrlimit()
575 # failed to restore the file descriptor limit after this, the whole
576 # test suite would crash; this actually happened on the OS X Tiger
577 # buildbot).
578 code = """if 1:
579 import errno
580 import os
581 import resource
582
583 soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
584 resource.setrlimit(resource.RLIMIT_NOFILE, (1, hard_limit))
585 try:
Antoine Pitrouf48a67b2013-08-16 20:44:38 +0200586 os.urandom(16)
Antoine Pitroue7587152013-08-24 20:52:27 +0200587 except OSError as e:
588 assert e.errno == errno.EMFILE, e.errno
589 else:
590 raise AssertionError("OSError not raised")
591 """
592 assert_python_ok('-c', code)
Antoine Pitrouf48a67b2013-08-16 20:44:38 +0200593
Antoine Pitrou326ec042013-08-16 20:56:12 +0200594
595class ExecvpeTests(unittest.TestCase):
596
Matthias Klosee9fbf2b2010-03-19 14:45:06 +0000597 def test_execvpe_with_bad_arglist(self):
598 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
599
Antoine Pitrou326ec042013-08-16 20:56:12 +0200600
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000601class Win32ErrorTests(unittest.TestCase):
602 def test_rename(self):
603 self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak")
604
605 def test_remove(self):
606 self.assertRaises(WindowsError, os.remove, test_support.TESTFN)
607
608 def test_chdir(self):
609 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
610
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000611 def test_mkdir(self):
Kristján Valur Jónssone20f54f2009-02-06 10:17:34 +0000612 f = open(test_support.TESTFN, "w")
613 try:
614 self.assertRaises(WindowsError, os.mkdir, test_support.TESTFN)
615 finally:
616 f.close()
617 os.unlink(test_support.TESTFN)
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000618
619 def test_utime(self):
620 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, None)
621
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000622 def test_chmod(self):
Kristján Valur Jónssone20f54f2009-02-06 10:17:34 +0000623 self.assertRaises(WindowsError, os.chmod, test_support.TESTFN, 0)
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000624
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000625class TestInvalidFD(unittest.TestCase):
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000626 singles = ["fchdir", "fdopen", "dup", "fdatasync", "fstat",
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000627 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000628 #singles.append("close")
629 #We omit close because it doesn'r raise an exception on some platforms
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000630 def get_single(f):
631 def helper(self):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000632 if hasattr(os, f):
633 self.check(getattr(os, f))
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000634 return helper
635 for f in singles:
636 locals()["test_"+f] = get_single(f)
637
Benjamin Peterson5539c782009-01-19 17:37:42 +0000638 def check(self, f, *args):
Benjamin Peterson1de05e92009-01-31 01:42:55 +0000639 try:
640 f(test_support.make_bad_fd(), *args)
641 except OSError as e:
642 self.assertEqual(e.errno, errno.EBADF)
643 else:
644 self.fail("%r didn't raise a OSError with a bad file descriptor"
645 % f)
Benjamin Peterson5539c782009-01-19 17:37:42 +0000646
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000647 def test_isatty(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000648 if hasattr(os, "isatty"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000649 self.assertEqual(os.isatty(test_support.make_bad_fd()), False)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000650
651 def test_closerange(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000652 if hasattr(os, "closerange"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000653 fd = test_support.make_bad_fd()
R. David Murray46ca2f22009-07-22 17:22:58 +0000654 # Make sure none of the descriptors we are about to close are
655 # currently valid (issue 6542).
656 for i in range(10):
657 try: os.fstat(fd+i)
658 except OSError:
659 pass
660 else:
661 break
662 if i < 2:
663 raise unittest.SkipTest(
664 "Unable to acquire a range of invalid file descriptors")
665 self.assertEqual(os.closerange(fd, fd + i-1), None)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000666
667 def test_dup2(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000668 if hasattr(os, "dup2"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000669 self.check(os.dup2, 20)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000670
671 def test_fchmod(self):
672 if hasattr(os, "fchmod"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000673 self.check(os.fchmod, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000674
675 def test_fchown(self):
676 if hasattr(os, "fchown"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000677 self.check(os.fchown, -1, -1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000678
679 def test_fpathconf(self):
680 if hasattr(os, "fpathconf"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000681 self.check(os.fpathconf, "PC_NAME_MAX")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000682
683 def test_ftruncate(self):
684 if hasattr(os, "ftruncate"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000685 self.check(os.ftruncate, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000686
687 def test_lseek(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000688 if hasattr(os, "lseek"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000689 self.check(os.lseek, 0, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000690
691 def test_read(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000692 if hasattr(os, "read"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000693 self.check(os.read, 1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000694
695 def test_tcsetpgrpt(self):
696 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000697 self.check(os.tcsetpgrp, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000698
699 def test_write(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000700 if hasattr(os, "write"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000701 self.check(os.write, " ")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000702
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000703if sys.platform != 'win32':
704 class Win32ErrorTests(unittest.TestCase):
705 pass
706
Gregory P. Smith6d307932009-04-05 23:43:58 +0000707 class PosixUidGidTests(unittest.TestCase):
708 if hasattr(os, 'setuid'):
709 def test_setuid(self):
710 if os.getuid() != 0:
711 self.assertRaises(os.error, os.setuid, 0)
712 self.assertRaises(OverflowError, os.setuid, 1<<32)
713
714 if hasattr(os, 'setgid'):
715 def test_setgid(self):
716 if os.getuid() != 0:
717 self.assertRaises(os.error, os.setgid, 0)
718 self.assertRaises(OverflowError, os.setgid, 1<<32)
719
720 if hasattr(os, 'seteuid'):
721 def test_seteuid(self):
722 if os.getuid() != 0:
723 self.assertRaises(os.error, os.seteuid, 0)
724 self.assertRaises(OverflowError, os.seteuid, 1<<32)
725
726 if hasattr(os, 'setegid'):
727 def test_setegid(self):
728 if os.getuid() != 0:
729 self.assertRaises(os.error, os.setegid, 0)
730 self.assertRaises(OverflowError, os.setegid, 1<<32)
731
732 if hasattr(os, 'setreuid'):
733 def test_setreuid(self):
734 if os.getuid() != 0:
735 self.assertRaises(os.error, os.setreuid, 0, 0)
736 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
737 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Gregory P. Smith467298c2010-03-06 07:35:19 +0000738
739 def test_setreuid_neg1(self):
740 # Needs to accept -1. We run this in a subprocess to avoid
741 # altering the test runner's process state (issue8045).
Gregory P. Smith467298c2010-03-06 07:35:19 +0000742 subprocess.check_call([
743 sys.executable, '-c',
744 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Gregory P. Smith6d307932009-04-05 23:43:58 +0000745
746 if hasattr(os, 'setregid'):
747 def test_setregid(self):
748 if os.getuid() != 0:
749 self.assertRaises(os.error, os.setregid, 0, 0)
750 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
751 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Gregory P. Smith467298c2010-03-06 07:35:19 +0000752
753 def test_setregid_neg1(self):
754 # Needs to accept -1. We run this in a subprocess to avoid
755 # altering the test runner's process state (issue8045).
Gregory P. Smith467298c2010-03-06 07:35:19 +0000756 subprocess.check_call([
757 sys.executable, '-c',
758 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Gregory P. Smith6d307932009-04-05 23:43:58 +0000759else:
760 class PosixUidGidTests(unittest.TestCase):
761 pass
762
Brian Curtine5aa8862010-04-02 23:26:06 +0000763@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
764class Win32KillTests(unittest.TestCase):
Brian Curtinb3dde132010-04-15 00:40:40 +0000765 def _kill(self, sig):
766 # Start sys.executable as a subprocess and communicate from the
767 # subprocess to the parent that the interpreter is ready. When it
768 # becomes ready, send *sig* via os.kill to the subprocess and check
769 # that the return code is equal to *sig*.
770 import ctypes
771 from ctypes import wintypes
772 import msvcrt
773
774 # Since we can't access the contents of the process' stdout until the
775 # process has exited, use PeekNamedPipe to see what's inside stdout
776 # without waiting. This is done so we can tell that the interpreter
777 # is started and running at a point where it could handle a signal.
778 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
779 PeekNamedPipe.restype = wintypes.BOOL
780 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
781 ctypes.POINTER(ctypes.c_char), # stdout buf
782 wintypes.DWORD, # Buffer size
783 ctypes.POINTER(wintypes.DWORD), # bytes read
784 ctypes.POINTER(wintypes.DWORD), # bytes avail
785 ctypes.POINTER(wintypes.DWORD)) # bytes left
786 msg = "running"
787 proc = subprocess.Popen([sys.executable, "-c",
788 "import sys;"
789 "sys.stdout.write('{}');"
790 "sys.stdout.flush();"
791 "input()".format(msg)],
792 stdout=subprocess.PIPE,
793 stderr=subprocess.PIPE,
794 stdin=subprocess.PIPE)
Brian Curtinf4f0c8b2010-11-05 15:31:20 +0000795 self.addCleanup(proc.stdout.close)
796 self.addCleanup(proc.stderr.close)
797 self.addCleanup(proc.stdin.close)
Brian Curtinb3dde132010-04-15 00:40:40 +0000798
Brian Curtin83cba052010-05-28 15:49:21 +0000799 count, max = 0, 100
800 while count < max and proc.poll() is None:
801 # Create a string buffer to store the result of stdout from the pipe
802 buf = ctypes.create_string_buffer(len(msg))
803 # Obtain the text currently in proc.stdout
804 # Bytes read/avail/left are left as NULL and unused
805 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
806 buf, ctypes.sizeof(buf), None, None, None)
807 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
808 if buf.value:
809 self.assertEqual(msg, buf.value)
810 break
811 time.sleep(0.1)
812 count += 1
813 else:
814 self.fail("Did not receive communication from the subprocess")
Brian Curtinb3dde132010-04-15 00:40:40 +0000815
Brian Curtine5aa8862010-04-02 23:26:06 +0000816 os.kill(proc.pid, sig)
817 self.assertEqual(proc.wait(), sig)
818
819 def test_kill_sigterm(self):
820 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinb3dde132010-04-15 00:40:40 +0000821 self._kill(signal.SIGTERM)
Brian Curtine5aa8862010-04-02 23:26:06 +0000822
823 def test_kill_int(self):
824 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinb3dde132010-04-15 00:40:40 +0000825 self._kill(100)
Brian Curtine5aa8862010-04-02 23:26:06 +0000826
827 def _kill_with_event(self, event, name):
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000828 tagname = "test_os_%s" % uuid.uuid1()
829 m = mmap.mmap(-1, 1, tagname)
830 m[0] = '0'
Brian Curtine5aa8862010-04-02 23:26:06 +0000831 # Run a script which has console control handling enabled.
832 proc = subprocess.Popen([sys.executable,
833 os.path.join(os.path.dirname(__file__),
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000834 "win_console_handler.py"), tagname],
Brian Curtine5aa8862010-04-02 23:26:06 +0000835 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
836 # Let the interpreter startup before we send signals. See #3137.
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000837 count, max = 0, 20
838 while count < max and proc.poll() is None:
Brian Curtindbf8e832010-11-05 15:28:19 +0000839 if m[0] == '1':
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000840 break
841 time.sleep(0.5)
842 count += 1
843 else:
844 self.fail("Subprocess didn't finish initialization")
Brian Curtine5aa8862010-04-02 23:26:06 +0000845 os.kill(proc.pid, event)
846 # proc.send_signal(event) could also be done here.
847 # Allow time for the signal to be passed and the process to exit.
Brian Curtinfce1d312010-04-05 19:04:23 +0000848 time.sleep(0.5)
Brian Curtine5aa8862010-04-02 23:26:06 +0000849 if not proc.poll():
850 # Forcefully kill the process if we weren't able to signal it.
851 os.kill(proc.pid, signal.SIGINT)
852 self.fail("subprocess did not stop on {}".format(name))
853
854 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
855 def test_CTRL_C_EVENT(self):
856 from ctypes import wintypes
857 import ctypes
858
859 # Make a NULL value by creating a pointer with no argument.
860 NULL = ctypes.POINTER(ctypes.c_int)()
861 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
862 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
863 wintypes.BOOL)
864 SetConsoleCtrlHandler.restype = wintypes.BOOL
865
866 # Calling this with NULL and FALSE causes the calling process to
867 # handle CTRL+C, rather than ignore it. This property is inherited
868 # by subprocesses.
869 SetConsoleCtrlHandler(NULL, 0)
870
871 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
872
873 def test_CTRL_BREAK_EVENT(self):
874 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
875
876
Fred Drake2e2be372001-09-20 21:33:42 +0000877def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000878 test_support.run_unittest(
Martin v. Löwisee1e06d2006-07-02 18:44:00 +0000879 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000880 TemporaryFileTests,
881 StatAttributeTests,
882 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000883 WalkTests,
884 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000885 DevNullTests,
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000886 URandomTests,
Antoine Pitrou326ec042013-08-16 20:56:12 +0200887 ExecvpeTests,
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000888 Win32ErrorTests,
Gregory P. Smith6d307932009-04-05 23:43:58 +0000889 TestInvalidFD,
Brian Curtine5aa8862010-04-02 23:26:06 +0000890 PosixUidGidTests,
891 Win32KillTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000892 )
Fred Drake2e2be372001-09-20 21:33:42 +0000893
894if __name__ == "__main__":
895 test_main()