blob: 49c659127c9594775b106d959ed4ac2f212586b6 [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 Peterson5c6d7872009-02-06 02:40:07 +00006import errno
Fred Drake38c2ef02001-07-17 20:52:51 +00007import unittest
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +00008import warnings
Thomas Wouters477c8d52006-05-27 19:21:47 +00009import sys
Brian Curtineb24d742010-04-12 17:16:38 +000010import signal
11import subprocess
12import time
Martin v. Löwis011e8422009-05-05 04:43:17 +000013import shutil
Benjamin Petersonee8712c2008-05-20 21:35:26 +000014from test import support
Fred Drake38c2ef02001-07-17 20:52:51 +000015
Mark Dickinson7cf03892010-04-16 13:45:35 +000016# Detect whether we're on a Linux system that uses the (now outdated
17# and unmaintained) linuxthreads threading library. There's an issue
18# when combining linuxthreads with a failed execv call: see
19# http://bugs.python.org/issue4970.
Mark Dickinson89589c92010-04-16 13:51:27 +000020if (hasattr(os, "confstr_names") and
21 "CS_GNU_LIBPTHREAD_VERSION" in os.confstr_names):
Mark Dickinson7cf03892010-04-16 13:45:35 +000022 libpthread = os.confstr("CS_GNU_LIBPTHREAD_VERSION")
23 USING_LINUXTHREADS= libpthread.startswith("linuxthreads")
24else:
25 USING_LINUXTHREADS= False
Brian Curtineb24d742010-04-12 17:16:38 +000026
Thomas Wouters0e3f5912006-08-11 14:57:12 +000027# Tests creating TESTFN
28class FileTests(unittest.TestCase):
29 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000030 if os.path.exists(support.TESTFN):
31 os.unlink(support.TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000032 tearDown = setUp
33
34 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000035 f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000036 os.close(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000037 self.assertTrue(os.access(support.TESTFN, os.W_OK))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000038
Christian Heimesfdab48e2008-01-20 09:06:41 +000039 def test_closerange(self):
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000040 first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
41 # We must allocate two consecutive file descriptors, otherwise
42 # it will mess up other file descriptors (perhaps even the three
43 # standard ones).
44 second = os.dup(first)
45 try:
46 retries = 0
47 while second != first + 1:
48 os.close(first)
49 retries += 1
50 if retries > 10:
51 # XXX test skipped
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000052 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000053 first, second = second, os.dup(second)
54 finally:
55 os.close(second)
Christian Heimesfdab48e2008-01-20 09:06:41 +000056 # close a fd that is open, and one that isn't
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000057 os.closerange(first, first + 2)
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000058 self.assertRaises(OSError, os.write, first, b"a")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000059
Hirokazu Yamamoto4c19e6e2008-09-08 23:41:21 +000060 def test_rename(self):
61 path = 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
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000067 def test_read(self):
68 with open(support.TESTFN, "w+b") as fobj:
69 fobj.write(b"spam")
70 fobj.flush()
71 fd = fobj.fileno()
72 os.lseek(fd, 0, 0)
73 s = os.read(fd, 4)
74 self.assertEqual(type(s), bytes)
75 self.assertEqual(s, b"spam")
76
77 def test_write(self):
78 # os.write() accepts bytes- and buffer-like objects but not strings
79 fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY)
80 self.assertRaises(TypeError, os.write, fd, "beans")
81 os.write(fd, b"bacon\n")
82 os.write(fd, bytearray(b"eggs\n"))
83 os.write(fd, memoryview(b"spam\n"))
84 os.close(fd)
85 with open(support.TESTFN, "rb") as fobj:
Antoine Pitroud62269f2008-09-15 23:54:52 +000086 self.assertEqual(fobj.read().splitlines(),
87 [b"bacon", b"eggs", b"spam"])
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000088
89
Christian Heimesdd15f6c2008-03-16 00:07:10 +000090class TemporaryFileTests(unittest.TestCase):
91 def setUp(self):
92 self.files = []
Benjamin Petersonee8712c2008-05-20 21:35:26 +000093 os.mkdir(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000094
95 def tearDown(self):
96 for name in self.files:
97 os.unlink(name)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000098 os.rmdir(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000099
100 def check_tempfile(self, name):
101 # make sure it doesn't already exist:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000102 self.assertFalse(os.path.exists(name),
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000103 "file already exists for temporary file")
104 # make sure we can create the file
105 open(name, "w")
106 self.files.append(name)
107
108 def test_tempnam(self):
109 if not hasattr(os, "tempnam"):
110 return
111 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
112 r"test_os$")
113 self.check_tempfile(os.tempnam())
114
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000115 name = os.tempnam(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000116 self.check_tempfile(name)
117
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000118 name = os.tempnam(support.TESTFN, "pfx")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000119 self.assertTrue(os.path.basename(name)[:3] == "pfx")
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000120 self.check_tempfile(name)
121
122 def test_tmpfile(self):
123 if not hasattr(os, "tmpfile"):
124 return
125 # As with test_tmpnam() below, the Windows implementation of tmpfile()
126 # attempts to create a file in the root directory of the current drive.
127 # On Vista and Server 2008, this test will always fail for normal users
128 # as writing to the root directory requires elevated privileges. With
129 # XP and below, the semantics of tmpfile() are the same, but the user
130 # running the test is more likely to have administrative privileges on
131 # their account already. If that's the case, then os.tmpfile() should
132 # work. In order to make this test as useful as possible, rather than
133 # trying to detect Windows versions or whether or not the user has the
134 # right permissions, just try and create a file in the root directory
135 # and see if it raises a 'Permission denied' OSError. If it does, then
136 # test that a subsequent call to os.tmpfile() raises the same error. If
137 # it doesn't, assume we're on XP or below and the user running the test
138 # has administrative privileges, and proceed with the test as normal.
139 if sys.platform == 'win32':
140 name = '\\python_test_os_test_tmpfile.txt'
141 if os.path.exists(name):
142 os.remove(name)
143 try:
144 fp = open(name, 'w')
145 except IOError as first:
146 # open() failed, assert tmpfile() fails in the same way.
147 # Although open() raises an IOError and os.tmpfile() raises an
148 # OSError(), 'args' will be (13, 'Permission denied') in both
149 # cases.
150 try:
151 fp = os.tmpfile()
152 except OSError as second:
153 self.assertEqual(first.args, second.args)
154 else:
155 self.fail("expected os.tmpfile() to raise OSError")
156 return
157 else:
158 # open() worked, therefore, tmpfile() should work. Close our
159 # dummy file and proceed with the test as normal.
160 fp.close()
161 os.remove(name)
162
163 fp = os.tmpfile()
164 fp.write("foobar")
165 fp.seek(0,0)
166 s = fp.read()
167 fp.close()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000168 self.assertTrue(s == "foobar")
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000169
170 def test_tmpnam(self):
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000171 if not hasattr(os, "tmpnam"):
172 return
173 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
174 r"test_os$")
175 name = os.tmpnam()
176 if sys.platform in ("win32",):
177 # The Windows tmpnam() seems useless. From the MS docs:
178 #
179 # The character string that tmpnam creates consists of
180 # the path prefix, defined by the entry P_tmpdir in the
181 # file STDIO.H, followed by a sequence consisting of the
182 # digit characters '0' through '9'; the numerical value
183 # of this string is in the range 1 - 65,535. Changing the
184 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
185 # change the operation of tmpnam.
186 #
187 # The really bizarre part is that, at least under MSVC6,
188 # P_tmpdir is "\\". That is, the path returned refers to
189 # the root of the current drive. That's a terrible place to
190 # put temp files, and, depending on privileges, the user
191 # may not even be able to open a file in the root directory.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000192 self.assertFalse(os.path.exists(name),
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000193 "file already exists for temporary file")
194 else:
195 self.check_tempfile(name)
196
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000197 def fdopen_helper(self, *args):
198 fd = os.open(support.TESTFN, os.O_RDONLY)
199 fp2 = os.fdopen(fd, *args)
200 fp2.close()
201
202 def test_fdopen(self):
203 self.fdopen_helper()
204 self.fdopen_helper('r')
205 self.fdopen_helper('r', 100)
206
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000207# Test attributes on return values from os.*stat* family.
208class StatAttributeTests(unittest.TestCase):
209 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000210 os.mkdir(support.TESTFN)
211 self.fname = os.path.join(support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000212 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +0000213 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000214 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000215
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000216 def tearDown(self):
217 os.unlink(self.fname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000218 os.rmdir(support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000219
220 def test_stat_attributes(self):
221 if not hasattr(os, "stat"):
222 return
223
224 import stat
225 result = os.stat(self.fname)
226
227 # Make sure direct access works
228 self.assertEquals(result[stat.ST_SIZE], 3)
229 self.assertEquals(result.st_size, 3)
230
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000231 # Make sure all the attributes are there
232 members = dir(result)
233 for name in dir(stat):
234 if name[:3] == 'ST_':
235 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000236 if name.endswith("TIME"):
237 def trunc(x): return int(x)
238 else:
239 def trunc(x): return x
240 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000241 result[getattr(stat, name)])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000242 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000243
244 try:
245 result[200]
246 self.fail("No exception thrown")
247 except IndexError:
248 pass
249
250 # Make sure that assignment fails
251 try:
252 result.st_mode = 1
253 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000254 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000255 pass
256
257 try:
258 result.st_rdev = 1
259 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000260 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000261 pass
262
263 try:
264 result.parrot = 1
265 self.fail("No exception thrown")
266 except AttributeError:
267 pass
268
269 # Use the stat_result constructor with a too-short tuple.
270 try:
271 result2 = os.stat_result((10,))
272 self.fail("No exception thrown")
273 except TypeError:
274 pass
275
276 # Use the constructr with a too-long tuple.
277 try:
278 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
279 except TypeError:
280 pass
281
Tim Peterse0c446b2001-10-18 21:57:37 +0000282
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000283 def test_statvfs_attributes(self):
284 if not hasattr(os, "statvfs"):
285 return
286
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000287 try:
288 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000289 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000290 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000291 if e.errno == errno.ENOSYS:
292 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000293
294 # Make sure direct access works
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000295 self.assertEquals(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000296
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000297 # Make sure all the attributes are there.
298 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
299 'ffree', 'favail', 'flag', 'namemax')
300 for value, member in enumerate(members):
301 self.assertEquals(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000302
303 # Make sure that assignment really fails
304 try:
305 result.f_bfree = 1
306 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000307 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000308 pass
309
310 try:
311 result.parrot = 1
312 self.fail("No exception thrown")
313 except AttributeError:
314 pass
315
316 # Use the constructor with a too-short tuple.
317 try:
318 result2 = os.statvfs_result((10,))
319 self.fail("No exception thrown")
320 except TypeError:
321 pass
322
323 # Use the constructr with a too-long tuple.
324 try:
325 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
326 except TypeError:
327 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000328
Thomas Wouters89f507f2006-12-13 04:49:30 +0000329 def test_utime_dir(self):
330 delta = 1000000
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000331 st = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000332 # round to int, because some systems may support sub-second
333 # time stamps in stat, but not in utime.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000334 os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
335 st2 = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000336 self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
337
338 # Restrict test to Win32, since there is no guarantee other
339 # systems support centiseconds
340 if sys.platform == 'win32':
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000341 def get_file_system(path):
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000342 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000343 import ctypes
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000344 kernel32 = ctypes.windll.kernel32
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000345 buf = ctypes.create_unicode_buffer("", 100)
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000346 if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000347 return buf.value
348
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000349 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000350 def test_1565150(self):
351 t1 = 1159195039.25
352 os.utime(self.fname, (t1, t1))
353 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000354
Guido van Rossumd8faa362007-04-27 19:54:29 +0000355 def test_1686475(self):
356 # Verify that an open file can be stat'ed
357 try:
358 os.stat(r"c:\pagefile.sys")
359 except WindowsError as e:
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000360 if e.errno == 2: # file does not exist; cannot run test
Guido van Rossumd8faa362007-04-27 19:54:29 +0000361 return
362 self.fail("Could not stat pagefile.sys")
363
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000364from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000365
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000366class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000367 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000368 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000369
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000370 def setUp(self):
371 self.__save = dict(os.environ)
Victor Stinner84ae1182010-05-06 22:05:07 +0000372 self.__saveb = dict(os.environb)
Christian Heimes90333392007-11-01 19:08:42 +0000373 for key, value in self._reference().items():
374 os.environ[key] = value
375
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000376 def tearDown(self):
377 os.environ.clear()
378 os.environ.update(self.__save)
Victor Stinner84ae1182010-05-06 22:05:07 +0000379 os.environb.clear()
380 os.environb.update(self.__saveb)
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000381
Christian Heimes90333392007-11-01 19:08:42 +0000382 def _reference(self):
383 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
384
385 def _empty_mapping(self):
386 os.environ.clear()
387 return os.environ
388
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000389 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000390 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000391 os.environ.clear()
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000392 if os.path.exists("/bin/sh"):
393 os.environ.update(HELLO="World")
394 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
395 self.assertEquals(value, "World")
396
Christian Heimes1a13d592007-11-08 14:16:55 +0000397 def test_os_popen_iter(self):
398 if os.path.exists("/bin/sh"):
399 popen = os.popen("/bin/sh -c 'echo \"line1\nline2\nline3\"'")
400 it = iter(popen)
401 self.assertEquals(next(it), "line1\n")
402 self.assertEquals(next(it), "line2\n")
403 self.assertEquals(next(it), "line3\n")
404 self.assertRaises(StopIteration, next, it)
405
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000406 # Verify environ keys and values from the OS are of the
407 # correct str type.
408 def test_keyvalue_types(self):
409 for key, val in os.environ.items():
410 self.assertEquals(type(key), str)
411 self.assertEquals(type(val), str)
412
Christian Heimes90333392007-11-01 19:08:42 +0000413 def test_items(self):
414 for key, value in self._reference().items():
415 self.assertEqual(os.environ.get(key), value)
416
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000417 # Issue 7310
418 def test___repr__(self):
419 """Check that the repr() of os.environ looks like environ({...})."""
420 env = os.environ
421 self.assertTrue(isinstance(env.data, dict))
422 self.assertEqual(repr(env), 'environ({!r})'.format(env.data))
423
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000424 def test_get_exec_path(self):
425 defpath_list = os.defpath.split(os.pathsep)
426 test_path = ['/monty', '/python', '', '/flying/circus']
427 test_env = {'PATH': os.pathsep.join(test_path)}
428
429 saved_environ = os.environ
430 try:
431 os.environ = dict(test_env)
432 # Test that defaulting to os.environ works.
433 self.assertSequenceEqual(test_path, os.get_exec_path())
434 self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
435 finally:
436 os.environ = saved_environ
437
438 # No PATH environment variable
439 self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
440 # Empty PATH environment variable
441 self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
442 # Supplied PATH environment variable
443 self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
444
Victor Stinner84ae1182010-05-06 22:05:07 +0000445 @unittest.skipIf(sys.platform == "win32", "POSIX specific test")
446 def test_environb(self):
447 # os.environ -> os.environb
448 value = 'euro\u20ac'
449 try:
450 value_bytes = value.encode(sys.getfilesystemencoding(), 'surrogateescape')
451 except UnicodeEncodeError:
452 raise unittest.SkipTest("U+20AC character is not encodable to %s" % sys.getfilesystemencoding())
453 os.environ['unicode'] = value
454 self.assertEquals(os.environ['unicode'], value)
455 self.assertEquals(os.environb[b'unicode'], value_bytes)
456
457 # os.environb -> os.environ
458 value = b'\xff'
459 os.environb[b'bytes'] = value
460 self.assertEquals(os.environb[b'bytes'], value)
461 value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape')
462 self.assertEquals(os.environ['bytes'], value_str)
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000463
Tim Petersc4e09402003-04-25 07:11:48 +0000464class WalkTests(unittest.TestCase):
465 """Tests for os.walk()."""
466
467 def test_traversal(self):
468 import os
469 from os.path import join
470
471 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000472 # TESTFN/
473 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000474 # tmp1
475 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000476 # tmp2
477 # SUB11/ no kids
478 # SUB2/ a file kid and a dirsymlink kid
479 # tmp3
480 # link/ a symlink to TESTFN.2
481 # TEST2/
482 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000483 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000484 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000485 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000486 sub2_path = join(walk_path, "SUB2")
487 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000488 tmp2_path = join(sub1_path, "tmp2")
489 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000490 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000491 t2_path = join(support.TESTFN, "TEST2")
492 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000493
494 # Create stuff.
495 os.makedirs(sub11_path)
496 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000497 os.makedirs(t2_path)
498 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000499 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000500 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
501 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000502 if hasattr(os, "symlink"):
503 os.symlink(os.path.abspath(t2_path), link_path)
504 sub2_tree = (sub2_path, ["link"], ["tmp3"])
505 else:
506 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000507
508 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000509 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000510 self.assertEqual(len(all), 4)
511 # We can't know which order SUB1 and SUB2 will appear in.
512 # Not flipped: TESTFN, SUB1, SUB11, SUB2
513 # flipped: TESTFN, SUB2, SUB1, SUB11
514 flipped = all[0][1][0] != "SUB1"
515 all[0][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000516 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000517 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
518 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000519 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000520
521 # Prune the search.
522 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000523 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000524 all.append((root, dirs, files))
525 # Don't descend into SUB1.
526 if 'SUB1' in dirs:
527 # Note that this also mutates the dirs we appended to all!
528 dirs.remove('SUB1')
529 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000530 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
531 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000532
533 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000534 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000535 self.assertEqual(len(all), 4)
536 # We can't know which order SUB1 and SUB2 will appear in.
537 # Not flipped: SUB11, SUB1, SUB2, TESTFN
538 # flipped: SUB2, SUB11, SUB1, TESTFN
539 flipped = all[3][1][0] != "SUB1"
540 all[3][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000541 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000542 self.assertEqual(all[flipped], (sub11_path, [], []))
543 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000544 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000545
Guido van Rossumd8faa362007-04-27 19:54:29 +0000546 if hasattr(os, "symlink"):
547 # Walk, following symlinks.
548 for root, dirs, files in os.walk(walk_path, followlinks=True):
549 if root == link_path:
550 self.assertEqual(dirs, [])
551 self.assertEqual(files, ["tmp4"])
552 break
553 else:
554 self.fail("Didn't follow symlink with followlinks=True")
555
556 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000557 # Tear everything down. This is a decent use for bottom-up on
558 # Windows, which doesn't have a recursive delete command. The
559 # (not so) subtlety is that rmdir will fail unless the dir's
560 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000561 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000562 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000563 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000564 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000565 dirname = os.path.join(root, name)
566 if not os.path.islink(dirname):
567 os.rmdir(dirname)
568 else:
569 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000570 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000571
Guido van Rossume7ba4952007-06-06 23:52:48 +0000572class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000573 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000574 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000575
576 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000577 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000578 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
579 os.makedirs(path) # Should work
580 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
581 os.makedirs(path)
582
583 # Try paths with a '.' in them
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000584 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000585 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
586 os.makedirs(path)
587 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
588 'dir5', 'dir6')
589 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000590
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000591 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000592 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000593 'dir4', 'dir5', 'dir6')
594 # If the tests failed, the bottom-most directory ('../dir6')
595 # may not have been created, so we look for the outermost directory
596 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000597 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000598 path = os.path.dirname(path)
599
600 os.removedirs(path)
601
Guido van Rossume7ba4952007-06-06 23:52:48 +0000602class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000603 def test_devnull(self):
Alex Martelli01c77c62006-08-24 02:58:11 +0000604 f = open(os.devnull, 'w')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000605 f.write('hello')
606 f.close()
Alex Martelli01c77c62006-08-24 02:58:11 +0000607 f = open(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000608 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000609 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000610
Guido van Rossume7ba4952007-06-06 23:52:48 +0000611class URandomTests(unittest.TestCase):
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000612 def test_urandom(self):
613 try:
614 self.assertEqual(len(os.urandom(1)), 1)
615 self.assertEqual(len(os.urandom(10)), 10)
616 self.assertEqual(len(os.urandom(100)), 100)
617 self.assertEqual(len(os.urandom(1000)), 1000)
618 except NotImplementedError:
619 pass
620
Guido van Rossume7ba4952007-06-06 23:52:48 +0000621class ExecTests(unittest.TestCase):
Mark Dickinson7cf03892010-04-16 13:45:35 +0000622 @unittest.skipIf(USING_LINUXTHREADS,
623 "avoid triggering a linuxthreads bug: see issue #4970")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000624 def test_execvpe_with_bad_program(self):
Mark Dickinson7cf03892010-04-16 13:45:35 +0000625 self.assertRaises(OSError, os.execvpe, 'no such app-',
626 ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000627
Thomas Heller6790d602007-08-30 17:15:14 +0000628 def test_execvpe_with_bad_arglist(self):
629 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
630
Thomas Wouters477c8d52006-05-27 19:21:47 +0000631class Win32ErrorTests(unittest.TestCase):
632 def test_rename(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000633 self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000634
635 def test_remove(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000636 self.assertRaises(WindowsError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000637
638 def test_chdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000639 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000640
641 def test_mkdir(self):
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +0000642 f = open(support.TESTFN, "w")
Benjamin Petersonf91df042009-02-13 02:50:59 +0000643 try:
644 self.assertRaises(WindowsError, os.mkdir, support.TESTFN)
645 finally:
646 f.close()
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +0000647 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000648
649 def test_utime(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000650 self.assertRaises(WindowsError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000651
Thomas Wouters477c8d52006-05-27 19:21:47 +0000652 def test_chmod(self):
Benjamin Petersonf91df042009-02-13 02:50:59 +0000653 self.assertRaises(WindowsError, os.chmod, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000654
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000655class TestInvalidFD(unittest.TestCase):
Benjamin Peterson05e782f2009-01-19 15:15:02 +0000656 singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000657 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
658 #singles.append("close")
659 #We omit close because it doesn'r raise an exception on some platforms
660 def get_single(f):
661 def helper(self):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000662 if hasattr(os, f):
663 self.check(getattr(os, f))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000664 return helper
665 for f in singles:
666 locals()["test_"+f] = get_single(f)
667
Benjamin Peterson7522c742009-01-19 21:00:09 +0000668 def check(self, f, *args):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000669 try:
670 f(support.make_bad_fd(), *args)
671 except OSError as e:
672 self.assertEqual(e.errno, errno.EBADF)
673 else:
674 self.fail("%r didn't raise a OSError with a bad file descriptor"
675 % f)
Benjamin Peterson7522c742009-01-19 21:00:09 +0000676
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000677 def test_isatty(self):
678 if hasattr(os, "isatty"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000679 self.assertEqual(os.isatty(support.make_bad_fd()), False)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000680
681 def test_closerange(self):
682 if hasattr(os, "closerange"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000683 fd = support.make_bad_fd()
R. David Murray630cc482009-07-22 15:20:27 +0000684 # Make sure none of the descriptors we are about to close are
685 # currently valid (issue 6542).
686 for i in range(10):
687 try: os.fstat(fd+i)
688 except OSError:
689 pass
690 else:
691 break
692 if i < 2:
693 raise unittest.SkipTest(
694 "Unable to acquire a range of invalid file descriptors")
695 self.assertEqual(os.closerange(fd, fd + i-1), None)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000696
697 def test_dup2(self):
698 if hasattr(os, "dup2"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000699 self.check(os.dup2, 20)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000700
701 def test_fchmod(self):
702 if hasattr(os, "fchmod"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000703 self.check(os.fchmod, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000704
705 def test_fchown(self):
706 if hasattr(os, "fchown"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000707 self.check(os.fchown, -1, -1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000708
709 def test_fpathconf(self):
710 if hasattr(os, "fpathconf"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000711 self.check(os.fpathconf, "PC_NAME_MAX")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000712
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000713 def test_ftruncate(self):
714 if hasattr(os, "ftruncate"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000715 self.check(os.ftruncate, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000716
717 def test_lseek(self):
718 if hasattr(os, "lseek"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000719 self.check(os.lseek, 0, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000720
721 def test_read(self):
722 if hasattr(os, "read"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000723 self.check(os.read, 1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000724
725 def test_tcsetpgrpt(self):
726 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000727 self.check(os.tcsetpgrp, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000728
729 def test_write(self):
730 if hasattr(os, "write"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000731 self.check(os.write, b" ")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000732
Thomas Wouters477c8d52006-05-27 19:21:47 +0000733if sys.platform != 'win32':
734 class Win32ErrorTests(unittest.TestCase):
735 pass
736
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000737 class PosixUidGidTests(unittest.TestCase):
738 if hasattr(os, 'setuid'):
739 def test_setuid(self):
740 if os.getuid() != 0:
741 self.assertRaises(os.error, os.setuid, 0)
742 self.assertRaises(OverflowError, os.setuid, 1<<32)
743
744 if hasattr(os, 'setgid'):
745 def test_setgid(self):
746 if os.getuid() != 0:
747 self.assertRaises(os.error, os.setgid, 0)
748 self.assertRaises(OverflowError, os.setgid, 1<<32)
749
750 if hasattr(os, 'seteuid'):
751 def test_seteuid(self):
752 if os.getuid() != 0:
753 self.assertRaises(os.error, os.seteuid, 0)
754 self.assertRaises(OverflowError, os.seteuid, 1<<32)
755
756 if hasattr(os, 'setegid'):
757 def test_setegid(self):
758 if os.getuid() != 0:
759 self.assertRaises(os.error, os.setegid, 0)
760 self.assertRaises(OverflowError, os.setegid, 1<<32)
761
762 if hasattr(os, 'setreuid'):
763 def test_setreuid(self):
764 if os.getuid() != 0:
765 self.assertRaises(os.error, os.setreuid, 0, 0)
766 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
767 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000768
769 def test_setreuid_neg1(self):
770 # Needs to accept -1. We run this in a subprocess to avoid
771 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000772 subprocess.check_call([
773 sys.executable, '-c',
774 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000775
776 if hasattr(os, 'setregid'):
777 def test_setregid(self):
778 if os.getuid() != 0:
779 self.assertRaises(os.error, os.setregid, 0, 0)
780 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
781 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000782
783 def test_setregid_neg1(self):
784 # Needs to accept -1. We run this in a subprocess to avoid
785 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000786 subprocess.check_call([
787 sys.executable, '-c',
788 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Martin v. Löwis011e8422009-05-05 04:43:17 +0000789
Mark Dickinson70613682009-05-05 21:34:59 +0000790 @unittest.skipIf(sys.platform == 'darwin', "tests don't apply to OS X")
Martin v. Löwis011e8422009-05-05 04:43:17 +0000791 class Pep383Tests(unittest.TestCase):
792 filenames = [b'foo\xf6bar', 'foo\xf6bar'.encode("utf-8")]
793
794 def setUp(self):
795 self.fsencoding = sys.getfilesystemencoding()
796 sys.setfilesystemencoding("utf-8")
797 self.dir = support.TESTFN
Martin v. Löwis43c57782009-05-10 08:15:24 +0000798 self.bdir = self.dir.encode("utf-8", "surrogateescape")
Martin v. Löwis011e8422009-05-05 04:43:17 +0000799 os.mkdir(self.dir)
800 self.unicodefn = []
801 for fn in self.filenames:
802 f = open(os.path.join(self.bdir, fn), "w")
803 f.close()
Martin v. Löwis43c57782009-05-10 08:15:24 +0000804 self.unicodefn.append(fn.decode("utf-8", "surrogateescape"))
Martin v. Löwis011e8422009-05-05 04:43:17 +0000805
806 def tearDown(self):
807 shutil.rmtree(self.dir)
808 sys.setfilesystemencoding(self.fsencoding)
809
810 def test_listdir(self):
811 expected = set(self.unicodefn)
812 found = set(os.listdir(support.TESTFN))
813 self.assertEquals(found, expected)
814
815 def test_open(self):
816 for fn in self.unicodefn:
817 f = open(os.path.join(self.dir, fn))
818 f.close()
819
820 def test_stat(self):
821 for fn in self.unicodefn:
822 os.stat(os.path.join(self.dir, fn))
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000823else:
824 class PosixUidGidTests(unittest.TestCase):
825 pass
Martin v. Löwis011e8422009-05-05 04:43:17 +0000826 class Pep383Tests(unittest.TestCase):
827 pass
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000828
Brian Curtineb24d742010-04-12 17:16:38 +0000829@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
830class Win32KillTests(unittest.TestCase):
831 def _kill(self, sig, *args):
832 # Send a subprocess a signal (or in some cases, just an int to be
833 # the return value)
834 proc = subprocess.Popen(*args)
835 os.kill(proc.pid, sig)
836 self.assertEqual(proc.wait(), sig)
837
838 def test_kill_sigterm(self):
839 # SIGTERM doesn't mean anything special, but make sure it works
840 self._kill(signal.SIGTERM, [sys.executable])
841
842 def test_kill_int(self):
843 # os.kill on Windows can take an int which gets set as the exit code
844 self._kill(100, [sys.executable])
845
846 def _kill_with_event(self, event, name):
847 # Run a script which has console control handling enabled.
848 proc = subprocess.Popen([sys.executable,
849 os.path.join(os.path.dirname(__file__),
850 "win_console_handler.py")],
851 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
852 # Let the interpreter startup before we send signals. See #3137.
853 time.sleep(0.5)
854 os.kill(proc.pid, event)
855 # proc.send_signal(event) could also be done here.
856 # Allow time for the signal to be passed and the process to exit.
857 time.sleep(0.5)
858 if not proc.poll():
859 # Forcefully kill the process if we weren't able to signal it.
860 os.kill(proc.pid, signal.SIGINT)
861 self.fail("subprocess did not stop on {}".format(name))
862
863 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
864 def test_CTRL_C_EVENT(self):
865 from ctypes import wintypes
866 import ctypes
867
868 # Make a NULL value by creating a pointer with no argument.
869 NULL = ctypes.POINTER(ctypes.c_int)()
870 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
871 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
872 wintypes.BOOL)
873 SetConsoleCtrlHandler.restype = wintypes.BOOL
874
875 # Calling this with NULL and FALSE causes the calling process to
876 # handle CTRL+C, rather than ignore it. This property is inherited
877 # by subprocesses.
878 SetConsoleCtrlHandler(NULL, 0)
879
880 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
881
882 def test_CTRL_BREAK_EVENT(self):
883 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
884
885
Fred Drake2e2be372001-09-20 21:33:42 +0000886def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000887 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000888 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000889 StatAttributeTests,
890 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000891 WalkTests,
892 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000893 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000894 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000895 ExecTests,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000896 Win32ErrorTests,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000897 TestInvalidFD,
Martin v. Löwis011e8422009-05-05 04:43:17 +0000898 PosixUidGidTests,
Brian Curtineb24d742010-04-12 17:16:38 +0000899 Pep383Tests,
900 Win32KillTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000901 )
Fred Drake2e2be372001-09-20 21:33:42 +0000902
903if __name__ == "__main__":
904 test_main()