blob: bc7dfbea056c8c12d86933ee432cfb273dbc7079 [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
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +000019import mmap
20import uuid
Fred Drake38c2ef02001-07-17 20:52:51 +000021
Barry Warsaw60f01882001-08-22 19:24:42 +000022warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, __name__)
23warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, __name__)
24
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000025# Tests creating TESTFN
26class FileTests(unittest.TestCase):
27 def setUp(self):
28 if os.path.exists(test_support.TESTFN):
29 os.unlink(test_support.TESTFN)
30 tearDown = setUp
31
32 def test_access(self):
33 f = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
34 os.close(f)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000035 self.assertTrue(os.access(test_support.TESTFN, os.W_OK))
Tim Peters16a39322006-07-03 08:23:19 +000036
Georg Brandl309501a2008-01-19 20:22:13 +000037 def test_closerange(self):
Antoine Pitroubebb18b2008-08-17 14:43:41 +000038 first = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
39 # We must allocate two consecutive file descriptors, otherwise
40 # it will mess up other file descriptors (perhaps even the three
41 # standard ones).
42 second = os.dup(first)
43 try:
44 retries = 0
45 while second != first + 1:
46 os.close(first)
47 retries += 1
48 if retries > 10:
49 # XXX test skipped
Benjamin Peterson757b3c92009-05-16 18:44:34 +000050 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroubebb18b2008-08-17 14:43:41 +000051 first, second = second, os.dup(second)
52 finally:
53 os.close(second)
Georg Brandl309501a2008-01-19 20:22:13 +000054 # close a fd that is open, and one that isn't
Antoine Pitroubebb18b2008-08-17 14:43:41 +000055 os.closerange(first, first + 2)
56 self.assertRaises(OSError, os.write, first, "a")
Georg Brandl309501a2008-01-19 20:22:13 +000057
Benjamin Peterson10947a62010-06-30 17:11:08 +000058 @test_support.cpython_only
Hirokazu Yamamoto74ce88f2008-09-08 23:03:47 +000059 def test_rename(self):
60 path = unicode(test_support.TESTFN)
61 old = sys.getrefcount(path)
62 self.assertRaises(TypeError, os.rename, path, 0)
63 new = sys.getrefcount(path)
64 self.assertEqual(old, new)
65
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000066
Fred Drake38c2ef02001-07-17 20:52:51 +000067class TemporaryFileTests(unittest.TestCase):
68 def setUp(self):
69 self.files = []
Walter Dörwald21d3a322003-05-01 17:45:56 +000070 os.mkdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000071
72 def tearDown(self):
73 for name in self.files:
74 os.unlink(name)
Walter Dörwald21d3a322003-05-01 17:45:56 +000075 os.rmdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000076
77 def check_tempfile(self, name):
78 # make sure it doesn't already exist:
Benjamin Peterson5c8da862009-06-30 22:57:08 +000079 self.assertFalse(os.path.exists(name),
Fred Drake38c2ef02001-07-17 20:52:51 +000080 "file already exists for temporary file")
81 # make sure we can create the file
82 open(name, "w")
83 self.files.append(name)
84
85 def test_tempnam(self):
86 if not hasattr(os, "tempnam"):
87 return
Antoine Pitroub0614612011-01-02 20:04:52 +000088 with warnings.catch_warnings():
89 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
90 r"test_os$")
91 warnings.filterwarnings("ignore", "tempnam", DeprecationWarning)
92 self.check_tempfile(os.tempnam())
Fred Drake38c2ef02001-07-17 20:52:51 +000093
Antoine Pitroub0614612011-01-02 20:04:52 +000094 name = os.tempnam(test_support.TESTFN)
95 self.check_tempfile(name)
Fred Drake38c2ef02001-07-17 20:52:51 +000096
Antoine Pitroub0614612011-01-02 20:04:52 +000097 name = os.tempnam(test_support.TESTFN, "pfx")
98 self.assertTrue(os.path.basename(name)[:3] == "pfx")
99 self.check_tempfile(name)
Fred Drake38c2ef02001-07-17 20:52:51 +0000100
101 def test_tmpfile(self):
102 if not hasattr(os, "tmpfile"):
103 return
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")
138 return
139 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
152 def test_tmpnam(self):
153 if not hasattr(os, "tmpnam"):
154 return
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
195 def test_stat_attributes(self):
196 if not hasattr(os, "stat"):
197 return
198
199 import stat
200 result = os.stat(self.fname)
201
202 # Make sure direct access works
Ezio Melotti2623a372010-11-21 13:34:58 +0000203 self.assertEqual(result[stat.ST_SIZE], 3)
204 self.assertEqual(result.st_size, 3)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000205
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000206 # Make sure all the attributes are there
207 members = dir(result)
208 for name in dir(stat):
209 if name[:3] == 'ST_':
210 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000211 if name.endswith("TIME"):
212 def trunc(x): return int(x)
213 else:
214 def trunc(x): return x
Ezio Melotti2623a372010-11-21 13:34:58 +0000215 self.assertEqual(trunc(getattr(result, attr)),
216 result[getattr(stat, name)])
Ezio Melottiaa980582010-01-23 23:04:36 +0000217 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000218
219 try:
220 result[200]
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200221 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000222 except IndexError:
223 pass
224
225 # Make sure that assignment fails
226 try:
227 result.st_mode = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200228 self.fail("No exception raised")
Benjamin Petersonc262a692010-06-30 18:41:08 +0000229 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000230 pass
231
232 try:
233 result.st_rdev = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200234 self.fail("No exception raised")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000235 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000236 pass
237
238 try:
239 result.parrot = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200240 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000241 except AttributeError:
242 pass
243
244 # Use the stat_result constructor with a too-short tuple.
245 try:
246 result2 = os.stat_result((10,))
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200247 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000248 except TypeError:
249 pass
250
Ezio Melotti24b07bc2011-03-15 18:55:01 +0200251 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000252 try:
253 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
254 except TypeError:
255 pass
256
Tim Peterse0c446b2001-10-18 21:57:37 +0000257
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000258 def test_statvfs_attributes(self):
259 if not hasattr(os, "statvfs"):
260 return
261
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000262 try:
263 result = os.statvfs(self.fname)
264 except OSError, e:
265 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000266 if e.errno == errno.ENOSYS:
267 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000268
269 # Make sure direct access works
Ezio Melotti2623a372010-11-21 13:34:58 +0000270 self.assertEqual(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000271
Brett Cannon90f2cb42008-05-16 00:37:42 +0000272 # Make sure all the attributes are there.
273 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
274 'ffree', 'favail', 'flag', 'namemax')
275 for value, member in enumerate(members):
Ezio Melotti2623a372010-11-21 13:34:58 +0000276 self.assertEqual(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000277
278 # Make sure that assignment really fails
279 try:
280 result.f_bfree = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200281 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000282 except TypeError:
283 pass
284
285 try:
286 result.parrot = 1
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200287 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000288 except AttributeError:
289 pass
290
291 # Use the constructor with a too-short tuple.
292 try:
293 result2 = os.statvfs_result((10,))
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200294 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000295 except TypeError:
296 pass
297
Ezio Melotti24b07bc2011-03-15 18:55:01 +0200298 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000299 try:
300 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
301 except TypeError:
302 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000303
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000304 def test_utime_dir(self):
305 delta = 1000000
306 st = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000307 # round to int, because some systems may support sub-second
308 # time stamps in stat, but not in utime.
309 os.utime(test_support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000310 st2 = os.stat(test_support.TESTFN)
Ezio Melotti2623a372010-11-21 13:34:58 +0000311 self.assertEqual(st2.st_mtime, int(st.st_mtime-delta))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000312
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000313 # Restrict test to Win32, since there is no guarantee other
314 # systems support centiseconds
315 if sys.platform == 'win32':
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000316 def get_file_system(path):
Hirokazu Yamamotoccfdcd02008-08-20 04:13:28 +0000317 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000318 import ctypes
Hirokazu Yamamotocd3b74d2008-08-20 16:15:28 +0000319 kernel32 = ctypes.windll.kernel32
320 buf = ctypes.create_string_buffer("", 100)
321 if kernel32.GetVolumeInformationA(root, None, 0, None, None, None, buf, len(buf)):
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000322 return buf.value
323
324 if get_file_system(test_support.TESTFN) == "NTFS":
325 def test_1565150(self):
326 t1 = 1159195039.25
327 os.utime(self.fname, (t1, t1))
Ezio Melotti2623a372010-11-21 13:34:58 +0000328 self.assertEqual(os.stat(self.fname).st_mtime, t1)
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000329
Amaury Forgeot d'Arcac514c82011-01-03 00:50:57 +0000330 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)
334
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000335 def test_1686475(self):
336 # Verify that an open file can be stat'ed
337 try:
338 os.stat(r"c:\pagefile.sys")
339 except WindowsError, e:
Antoine Pitrou954ea642008-08-17 20:15:07 +0000340 if e.errno == 2: # file does not exist; cannot run test
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000341 return
342 self.fail("Could not stat pagefile.sys")
343
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000344from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000345
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000346class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000347 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000348 type2test = None
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000349 def _reference(self):
350 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
351 def _empty_mapping(self):
352 os.environ.clear()
353 return os.environ
354 def setUp(self):
355 self.__save = dict(os.environ)
356 os.environ.clear()
357 def tearDown(self):
358 os.environ.clear()
359 os.environ.update(self.__save)
360
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000361 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000362 def test_update2(self):
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000363 if os.path.exists("/bin/sh"):
364 os.environ.update(HELLO="World")
Brian Curtinfcbf5d02010-10-30 21:29:52 +0000365 with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
366 value = popen.read().strip()
Ezio Melotti2623a372010-11-21 13:34:58 +0000367 self.assertEqual(value, "World")
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000368
Charles-François Natali27bc4d02011-11-27 13:05:14 +0100369 # On FreeBSD < 7 and OS X < 10.6, unsetenv() doesn't return a value (issue
370 # #13415).
371 @unittest.skipIf(sys.platform.startswith(('freebsd', 'darwin')),
372 "due to known OS bug: see issue #13415")
Victor Stinner53853c32011-11-22 22:20:13 +0100373 def test_unset_error(self):
374 if sys.platform == "win32":
375 # an environment variable is limited to 32,767 characters
376 key = 'x' * 50000
Victor Stinner091b6ef2011-11-22 22:30:19 +0100377 self.assertRaises(ValueError, os.environ.__delitem__, key)
Victor Stinner53853c32011-11-22 22:20:13 +0100378 else:
379 # "=" is not allowed in a variable name
380 key = 'key='
Victor Stinner091b6ef2011-11-22 22:30:19 +0100381 self.assertRaises(OSError, os.environ.__delitem__, key)
Victor Stinner53853c32011-11-22 22:20:13 +0100382
Tim Petersc4e09402003-04-25 07:11:48 +0000383class WalkTests(unittest.TestCase):
384 """Tests for os.walk()."""
385
386 def test_traversal(self):
387 import os
388 from os.path import join
389
390 # Build:
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000391 # TESTFN/
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000392 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000393 # tmp1
394 # SUB1/ a file kid and a directory kid
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000395 # tmp2
396 # SUB11/ no kids
397 # SUB2/ a file kid and a dirsymlink kid
398 # tmp3
399 # link/ a symlink to TESTFN.2
400 # TEST2/
401 # tmp4 a lone file
402 walk_path = join(test_support.TESTFN, "TEST1")
403 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000404 sub11_path = join(sub1_path, "SUB11")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000405 sub2_path = join(walk_path, "SUB2")
406 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000407 tmp2_path = join(sub1_path, "tmp2")
408 tmp3_path = join(sub2_path, "tmp3")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000409 link_path = join(sub2_path, "link")
410 t2_path = join(test_support.TESTFN, "TEST2")
411 tmp4_path = join(test_support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000412
413 # Create stuff.
414 os.makedirs(sub11_path)
415 os.makedirs(sub2_path)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000416 os.makedirs(t2_path)
417 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Tim Petersc4e09402003-04-25 07:11:48 +0000418 f = file(path, "w")
419 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
420 f.close()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000421 if hasattr(os, "symlink"):
422 os.symlink(os.path.abspath(t2_path), link_path)
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000423 sub2_tree = (sub2_path, ["link"], ["tmp3"])
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000424 else:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000425 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000426
427 # Walk top-down.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000428 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000429 self.assertEqual(len(all), 4)
430 # We can't know which order SUB1 and SUB2 will appear in.
431 # Not flipped: TESTFN, SUB1, SUB11, SUB2
432 # flipped: TESTFN, SUB2, SUB1, SUB11
433 flipped = all[0][1][0] != "SUB1"
434 all[0][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000435 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000436 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
437 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000438 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000439
440 # Prune the search.
441 all = []
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000442 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000443 all.append((root, dirs, files))
444 # Don't descend into SUB1.
445 if 'SUB1' in dirs:
446 # Note that this also mutates the dirs we appended to all!
447 dirs.remove('SUB1')
448 self.assertEqual(len(all), 2)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000449 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000450 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000451
452 # Walk bottom-up.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000453 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000454 self.assertEqual(len(all), 4)
455 # We can't know which order SUB1 and SUB2 will appear in.
456 # Not flipped: SUB11, SUB1, SUB2, TESTFN
457 # flipped: SUB2, SUB11, SUB1, TESTFN
458 flipped = all[3][1][0] != "SUB1"
459 all[3][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000460 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000461 self.assertEqual(all[flipped], (sub11_path, [], []))
462 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000463 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000464
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000465 if hasattr(os, "symlink"):
466 # Walk, following symlinks.
467 for root, dirs, files in os.walk(walk_path, followlinks=True):
468 if root == link_path:
469 self.assertEqual(dirs, [])
470 self.assertEqual(files, ["tmp4"])
471 break
472 else:
473 self.fail("Didn't follow symlink with followlinks=True")
Tim Petersc4e09402003-04-25 07:11:48 +0000474
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000475 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000476 # Tear everything down. This is a decent use for bottom-up on
477 # Windows, which doesn't have a recursive delete command. The
478 # (not so) subtlety is that rmdir will fail unless the dir's
479 # kids are removed first, so bottom up is essential.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000480 for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000481 for name in files:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000482 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000483 for name in dirs:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000484 dirname = os.path.join(root, name)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000485 if not os.path.islink(dirname):
486 os.rmdir(dirname)
487 else:
488 os.remove(dirname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000489 os.rmdir(test_support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000490
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000491class MakedirTests (unittest.TestCase):
492 def setUp(self):
493 os.mkdir(test_support.TESTFN)
494
495 def test_makedir(self):
496 base = test_support.TESTFN
497 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
498 os.makedirs(path) # Should work
499 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
500 os.makedirs(path)
501
502 # Try paths with a '.' in them
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000503 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000504 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
505 os.makedirs(path)
506 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
507 'dir5', 'dir6')
508 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000509
Tim Peters58eb11c2004-01-18 20:29:55 +0000510
511
512
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000513 def tearDown(self):
514 path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
515 'dir4', 'dir5', 'dir6')
516 # If the tests failed, the bottom-most directory ('../dir6')
517 # may not have been created, so we look for the outermost directory
518 # that exists.
519 while not os.path.exists(path) and path != test_support.TESTFN:
520 path = os.path.dirname(path)
521
522 os.removedirs(path)
523
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000524class DevNullTests (unittest.TestCase):
525 def test_devnull(self):
526 f = file(os.devnull, 'w')
527 f.write('hello')
528 f.close()
529 f = file(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000530 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000531 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000532
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000533class URandomTests (unittest.TestCase):
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500534
535 def test_urandom_length(self):
536 self.assertEqual(len(os.urandom(0)), 0)
537 self.assertEqual(len(os.urandom(1)), 1)
538 self.assertEqual(len(os.urandom(10)), 10)
539 self.assertEqual(len(os.urandom(100)), 100)
540 self.assertEqual(len(os.urandom(1000)), 1000)
541
542 def test_urandom_value(self):
543 data1 = os.urandom(16)
544 data2 = os.urandom(16)
545 self.assertNotEqual(data1, data2)
546
547 def get_urandom_subprocess(self, count):
Antoine Pitrou341016e2012-02-22 22:16:25 +0100548 # We need to use repr() and eval() to avoid line ending conversions
549 # under Windows.
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500550 code = '\n'.join((
551 'import os, sys',
552 'data = os.urandom(%s)' % count,
Antoine Pitrou341016e2012-02-22 22:16:25 +0100553 'sys.stdout.write(repr(data))',
Antoine Pitrou0607f732012-02-21 22:02:04 +0100554 'sys.stdout.flush()',
555 'print >> sys.stderr, (len(data), data)'))
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500556 cmd_line = [sys.executable, '-c', code]
557 p = subprocess.Popen(cmd_line, stdin=subprocess.PIPE,
Antoine Pitrou0607f732012-02-21 22:02:04 +0100558 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500559 out, err = p.communicate()
Antoine Pitrou0607f732012-02-21 22:02:04 +0100560 self.assertEqual(p.wait(), 0, (p.wait(), err))
Antoine Pitrou341016e2012-02-22 22:16:25 +0100561 out = eval(out)
562 self.assertEqual(len(out), count, err)
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500563 return out
564
565 def test_urandom_subprocess(self):
566 data1 = self.get_urandom_subprocess(16)
567 data2 = self.get_urandom_subprocess(16)
568 self.assertNotEqual(data1, data2)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000569
Antoine Pitrouf48a67b2013-08-16 20:44:38 +0200570 @unittest.skipUnless(resource, "test requires the resource module")
571 def test_urandom_failure(self):
572 soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
573 resource.setrlimit(resource.RLIMIT_NOFILE, (1, hard_limit))
574 try:
575 with self.assertRaises(OSError) as cm:
576 os.urandom(16)
577 self.assertEqual(cm.exception.errno, errno.EMFILE)
578 finally:
579 # We restore the old limit as soon as possible. If doing it
580 # using addCleanup(), code running in between would fail
581 # creating any file descriptor.
582 resource.setrlimit(resource.RLIMIT_NOFILE, (soft_limit, hard_limit))
583
Antoine Pitrou326ec042013-08-16 20:56:12 +0200584
585class ExecvpeTests(unittest.TestCase):
586
Matthias Klosee9fbf2b2010-03-19 14:45:06 +0000587 def test_execvpe_with_bad_arglist(self):
588 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
589
Antoine Pitrou326ec042013-08-16 20:56:12 +0200590
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000591class Win32ErrorTests(unittest.TestCase):
592 def test_rename(self):
593 self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak")
594
595 def test_remove(self):
596 self.assertRaises(WindowsError, os.remove, test_support.TESTFN)
597
598 def test_chdir(self):
599 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
600
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000601 def test_mkdir(self):
Kristján Valur Jónssone20f54f2009-02-06 10:17:34 +0000602 f = open(test_support.TESTFN, "w")
603 try:
604 self.assertRaises(WindowsError, os.mkdir, test_support.TESTFN)
605 finally:
606 f.close()
607 os.unlink(test_support.TESTFN)
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000608
609 def test_utime(self):
610 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, None)
611
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000612 def test_chmod(self):
Kristján Valur Jónssone20f54f2009-02-06 10:17:34 +0000613 self.assertRaises(WindowsError, os.chmod, test_support.TESTFN, 0)
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000614
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000615class TestInvalidFD(unittest.TestCase):
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000616 singles = ["fchdir", "fdopen", "dup", "fdatasync", "fstat",
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000617 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000618 #singles.append("close")
619 #We omit close because it doesn'r raise an exception on some platforms
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000620 def get_single(f):
621 def helper(self):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000622 if hasattr(os, f):
623 self.check(getattr(os, f))
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000624 return helper
625 for f in singles:
626 locals()["test_"+f] = get_single(f)
627
Benjamin Peterson5539c782009-01-19 17:37:42 +0000628 def check(self, f, *args):
Benjamin Peterson1de05e92009-01-31 01:42:55 +0000629 try:
630 f(test_support.make_bad_fd(), *args)
631 except OSError as e:
632 self.assertEqual(e.errno, errno.EBADF)
633 else:
634 self.fail("%r didn't raise a OSError with a bad file descriptor"
635 % f)
Benjamin Peterson5539c782009-01-19 17:37:42 +0000636
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000637 def test_isatty(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000638 if hasattr(os, "isatty"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000639 self.assertEqual(os.isatty(test_support.make_bad_fd()), False)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000640
641 def test_closerange(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000642 if hasattr(os, "closerange"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000643 fd = test_support.make_bad_fd()
R. David Murray46ca2f22009-07-22 17:22:58 +0000644 # Make sure none of the descriptors we are about to close are
645 # currently valid (issue 6542).
646 for i in range(10):
647 try: os.fstat(fd+i)
648 except OSError:
649 pass
650 else:
651 break
652 if i < 2:
653 raise unittest.SkipTest(
654 "Unable to acquire a range of invalid file descriptors")
655 self.assertEqual(os.closerange(fd, fd + i-1), None)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000656
657 def test_dup2(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000658 if hasattr(os, "dup2"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000659 self.check(os.dup2, 20)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000660
661 def test_fchmod(self):
662 if hasattr(os, "fchmod"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000663 self.check(os.fchmod, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000664
665 def test_fchown(self):
666 if hasattr(os, "fchown"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000667 self.check(os.fchown, -1, -1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000668
669 def test_fpathconf(self):
670 if hasattr(os, "fpathconf"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000671 self.check(os.fpathconf, "PC_NAME_MAX")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000672
673 def test_ftruncate(self):
674 if hasattr(os, "ftruncate"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000675 self.check(os.ftruncate, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000676
677 def test_lseek(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000678 if hasattr(os, "lseek"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000679 self.check(os.lseek, 0, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000680
681 def test_read(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000682 if hasattr(os, "read"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000683 self.check(os.read, 1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000684
685 def test_tcsetpgrpt(self):
686 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000687 self.check(os.tcsetpgrp, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000688
689 def test_write(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000690 if hasattr(os, "write"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000691 self.check(os.write, " ")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000692
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000693if sys.platform != 'win32':
694 class Win32ErrorTests(unittest.TestCase):
695 pass
696
Gregory P. Smith6d307932009-04-05 23:43:58 +0000697 class PosixUidGidTests(unittest.TestCase):
698 if hasattr(os, 'setuid'):
699 def test_setuid(self):
700 if os.getuid() != 0:
701 self.assertRaises(os.error, os.setuid, 0)
702 self.assertRaises(OverflowError, os.setuid, 1<<32)
703
704 if hasattr(os, 'setgid'):
705 def test_setgid(self):
706 if os.getuid() != 0:
707 self.assertRaises(os.error, os.setgid, 0)
708 self.assertRaises(OverflowError, os.setgid, 1<<32)
709
710 if hasattr(os, 'seteuid'):
711 def test_seteuid(self):
712 if os.getuid() != 0:
713 self.assertRaises(os.error, os.seteuid, 0)
714 self.assertRaises(OverflowError, os.seteuid, 1<<32)
715
716 if hasattr(os, 'setegid'):
717 def test_setegid(self):
718 if os.getuid() != 0:
719 self.assertRaises(os.error, os.setegid, 0)
720 self.assertRaises(OverflowError, os.setegid, 1<<32)
721
722 if hasattr(os, 'setreuid'):
723 def test_setreuid(self):
724 if os.getuid() != 0:
725 self.assertRaises(os.error, os.setreuid, 0, 0)
726 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
727 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Gregory P. Smith467298c2010-03-06 07:35:19 +0000728
729 def test_setreuid_neg1(self):
730 # Needs to accept -1. We run this in a subprocess to avoid
731 # altering the test runner's process state (issue8045).
Gregory P. Smith467298c2010-03-06 07:35:19 +0000732 subprocess.check_call([
733 sys.executable, '-c',
734 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Gregory P. Smith6d307932009-04-05 23:43:58 +0000735
736 if hasattr(os, 'setregid'):
737 def test_setregid(self):
738 if os.getuid() != 0:
739 self.assertRaises(os.error, os.setregid, 0, 0)
740 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
741 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Gregory P. Smith467298c2010-03-06 07:35:19 +0000742
743 def test_setregid_neg1(self):
744 # Needs to accept -1. We run this in a subprocess to avoid
745 # altering the test runner's process state (issue8045).
Gregory P. Smith467298c2010-03-06 07:35:19 +0000746 subprocess.check_call([
747 sys.executable, '-c',
748 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Gregory P. Smith6d307932009-04-05 23:43:58 +0000749else:
750 class PosixUidGidTests(unittest.TestCase):
751 pass
752
Brian Curtine5aa8862010-04-02 23:26:06 +0000753@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
754class Win32KillTests(unittest.TestCase):
Brian Curtinb3dde132010-04-15 00:40:40 +0000755 def _kill(self, sig):
756 # Start sys.executable as a subprocess and communicate from the
757 # subprocess to the parent that the interpreter is ready. When it
758 # becomes ready, send *sig* via os.kill to the subprocess and check
759 # that the return code is equal to *sig*.
760 import ctypes
761 from ctypes import wintypes
762 import msvcrt
763
764 # Since we can't access the contents of the process' stdout until the
765 # process has exited, use PeekNamedPipe to see what's inside stdout
766 # without waiting. This is done so we can tell that the interpreter
767 # is started and running at a point where it could handle a signal.
768 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
769 PeekNamedPipe.restype = wintypes.BOOL
770 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
771 ctypes.POINTER(ctypes.c_char), # stdout buf
772 wintypes.DWORD, # Buffer size
773 ctypes.POINTER(wintypes.DWORD), # bytes read
774 ctypes.POINTER(wintypes.DWORD), # bytes avail
775 ctypes.POINTER(wintypes.DWORD)) # bytes left
776 msg = "running"
777 proc = subprocess.Popen([sys.executable, "-c",
778 "import sys;"
779 "sys.stdout.write('{}');"
780 "sys.stdout.flush();"
781 "input()".format(msg)],
782 stdout=subprocess.PIPE,
783 stderr=subprocess.PIPE,
784 stdin=subprocess.PIPE)
Brian Curtinf4f0c8b2010-11-05 15:31:20 +0000785 self.addCleanup(proc.stdout.close)
786 self.addCleanup(proc.stderr.close)
787 self.addCleanup(proc.stdin.close)
Brian Curtinb3dde132010-04-15 00:40:40 +0000788
Brian Curtin83cba052010-05-28 15:49:21 +0000789 count, max = 0, 100
790 while count < max and proc.poll() is None:
791 # Create a string buffer to store the result of stdout from the pipe
792 buf = ctypes.create_string_buffer(len(msg))
793 # Obtain the text currently in proc.stdout
794 # Bytes read/avail/left are left as NULL and unused
795 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
796 buf, ctypes.sizeof(buf), None, None, None)
797 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
798 if buf.value:
799 self.assertEqual(msg, buf.value)
800 break
801 time.sleep(0.1)
802 count += 1
803 else:
804 self.fail("Did not receive communication from the subprocess")
Brian Curtinb3dde132010-04-15 00:40:40 +0000805
Brian Curtine5aa8862010-04-02 23:26:06 +0000806 os.kill(proc.pid, sig)
807 self.assertEqual(proc.wait(), sig)
808
809 def test_kill_sigterm(self):
810 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinb3dde132010-04-15 00:40:40 +0000811 self._kill(signal.SIGTERM)
Brian Curtine5aa8862010-04-02 23:26:06 +0000812
813 def test_kill_int(self):
814 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinb3dde132010-04-15 00:40:40 +0000815 self._kill(100)
Brian Curtine5aa8862010-04-02 23:26:06 +0000816
817 def _kill_with_event(self, event, name):
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000818 tagname = "test_os_%s" % uuid.uuid1()
819 m = mmap.mmap(-1, 1, tagname)
820 m[0] = '0'
Brian Curtine5aa8862010-04-02 23:26:06 +0000821 # Run a script which has console control handling enabled.
822 proc = subprocess.Popen([sys.executable,
823 os.path.join(os.path.dirname(__file__),
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000824 "win_console_handler.py"), tagname],
Brian Curtine5aa8862010-04-02 23:26:06 +0000825 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
826 # Let the interpreter startup before we send signals. See #3137.
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000827 count, max = 0, 20
828 while count < max and proc.poll() is None:
Brian Curtindbf8e832010-11-05 15:28:19 +0000829 if m[0] == '1':
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000830 break
831 time.sleep(0.5)
832 count += 1
833 else:
834 self.fail("Subprocess didn't finish initialization")
Brian Curtine5aa8862010-04-02 23:26:06 +0000835 os.kill(proc.pid, event)
836 # proc.send_signal(event) could also be done here.
837 # Allow time for the signal to be passed and the process to exit.
Brian Curtinfce1d312010-04-05 19:04:23 +0000838 time.sleep(0.5)
Brian Curtine5aa8862010-04-02 23:26:06 +0000839 if not proc.poll():
840 # Forcefully kill the process if we weren't able to signal it.
841 os.kill(proc.pid, signal.SIGINT)
842 self.fail("subprocess did not stop on {}".format(name))
843
844 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
845 def test_CTRL_C_EVENT(self):
846 from ctypes import wintypes
847 import ctypes
848
849 # Make a NULL value by creating a pointer with no argument.
850 NULL = ctypes.POINTER(ctypes.c_int)()
851 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
852 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
853 wintypes.BOOL)
854 SetConsoleCtrlHandler.restype = wintypes.BOOL
855
856 # Calling this with NULL and FALSE causes the calling process to
857 # handle CTRL+C, rather than ignore it. This property is inherited
858 # by subprocesses.
859 SetConsoleCtrlHandler(NULL, 0)
860
861 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
862
863 def test_CTRL_BREAK_EVENT(self):
864 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
865
866
Fred Drake2e2be372001-09-20 21:33:42 +0000867def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000868 test_support.run_unittest(
Martin v. Löwisee1e06d2006-07-02 18:44:00 +0000869 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000870 TemporaryFileTests,
871 StatAttributeTests,
872 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000873 WalkTests,
874 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000875 DevNullTests,
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000876 URandomTests,
Antoine Pitrou326ec042013-08-16 20:56:12 +0200877 ExecvpeTests,
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000878 Win32ErrorTests,
Gregory P. Smith6d307932009-04-05 23:43:58 +0000879 TestInvalidFD,
Brian Curtine5aa8862010-04-02 23:26:06 +0000880 PosixUidGidTests,
881 Win32KillTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000882 )
Fred Drake2e2be372001-09-20 21:33:42 +0000883
884if __name__ == "__main__":
885 test_main()