blob: fe2a228f6b937e5a49e00381ef6d72aa18245348 [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.
20if "CS_GNU_LIBPTHREAD_VERSION" in os.confstr_names:
21 libpthread = os.confstr("CS_GNU_LIBPTHREAD_VERSION")
22 USING_LINUXTHREADS= libpthread.startswith("linuxthreads")
23else:
24 USING_LINUXTHREADS= False
Brian Curtineb24d742010-04-12 17:16:38 +000025
Thomas Wouters0e3f5912006-08-11 14:57:12 +000026# Tests creating TESTFN
27class FileTests(unittest.TestCase):
28 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000029 if os.path.exists(support.TESTFN):
30 os.unlink(support.TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000031 tearDown = setUp
32
33 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000034 f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000035 os.close(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000036 self.assertTrue(os.access(support.TESTFN, os.W_OK))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000037
Christian Heimesfdab48e2008-01-20 09:06:41 +000038 def test_closerange(self):
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000039 first = os.open(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 Petersonfa0d7032009-06-01 22:42:33 +000051 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000052 first, second = second, os.dup(second)
53 finally:
54 os.close(second)
Christian Heimesfdab48e2008-01-20 09:06:41 +000055 # close a fd that is open, and one that isn't
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000056 os.closerange(first, first + 2)
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000057 self.assertRaises(OSError, os.write, first, b"a")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000058
Hirokazu Yamamoto4c19e6e2008-09-08 23:41:21 +000059 def test_rename(self):
60 path = 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
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000066 def test_read(self):
67 with open(support.TESTFN, "w+b") as fobj:
68 fobj.write(b"spam")
69 fobj.flush()
70 fd = fobj.fileno()
71 os.lseek(fd, 0, 0)
72 s = os.read(fd, 4)
73 self.assertEqual(type(s), bytes)
74 self.assertEqual(s, b"spam")
75
76 def test_write(self):
77 # os.write() accepts bytes- and buffer-like objects but not strings
78 fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY)
79 self.assertRaises(TypeError, os.write, fd, "beans")
80 os.write(fd, b"bacon\n")
81 os.write(fd, bytearray(b"eggs\n"))
82 os.write(fd, memoryview(b"spam\n"))
83 os.close(fd)
84 with open(support.TESTFN, "rb") as fobj:
Antoine Pitroud62269f2008-09-15 23:54:52 +000085 self.assertEqual(fobj.read().splitlines(),
86 [b"bacon", b"eggs", b"spam"])
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000087
88
Christian Heimesdd15f6c2008-03-16 00:07:10 +000089class TemporaryFileTests(unittest.TestCase):
90 def setUp(self):
91 self.files = []
Benjamin Petersonee8712c2008-05-20 21:35:26 +000092 os.mkdir(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000093
94 def tearDown(self):
95 for name in self.files:
96 os.unlink(name)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000097 os.rmdir(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000098
99 def check_tempfile(self, name):
100 # make sure it doesn't already exist:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000101 self.assertFalse(os.path.exists(name),
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000102 "file already exists for temporary file")
103 # make sure we can create the file
104 open(name, "w")
105 self.files.append(name)
106
107 def test_tempnam(self):
108 if not hasattr(os, "tempnam"):
109 return
110 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
111 r"test_os$")
112 self.check_tempfile(os.tempnam())
113
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000114 name = os.tempnam(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000115 self.check_tempfile(name)
116
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000117 name = os.tempnam(support.TESTFN, "pfx")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000118 self.assertTrue(os.path.basename(name)[:3] == "pfx")
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000119 self.check_tempfile(name)
120
121 def test_tmpfile(self):
122 if not hasattr(os, "tmpfile"):
123 return
124 # As with test_tmpnam() below, the Windows implementation of tmpfile()
125 # attempts to create a file in the root directory of the current drive.
126 # On Vista and Server 2008, this test will always fail for normal users
127 # as writing to the root directory requires elevated privileges. With
128 # XP and below, the semantics of tmpfile() are the same, but the user
129 # running the test is more likely to have administrative privileges on
130 # their account already. If that's the case, then os.tmpfile() should
131 # work. In order to make this test as useful as possible, rather than
132 # trying to detect Windows versions or whether or not the user has the
133 # right permissions, just try and create a file in the root directory
134 # and see if it raises a 'Permission denied' OSError. If it does, then
135 # test that a subsequent call to os.tmpfile() raises the same error. If
136 # it doesn't, assume we're on XP or below and the user running the test
137 # has administrative privileges, and proceed with the test as normal.
138 if sys.platform == 'win32':
139 name = '\\python_test_os_test_tmpfile.txt'
140 if os.path.exists(name):
141 os.remove(name)
142 try:
143 fp = open(name, 'w')
144 except IOError as first:
145 # open() failed, assert tmpfile() fails in the same way.
146 # Although open() raises an IOError and os.tmpfile() raises an
147 # OSError(), 'args' will be (13, 'Permission denied') in both
148 # cases.
149 try:
150 fp = os.tmpfile()
151 except OSError as second:
152 self.assertEqual(first.args, second.args)
153 else:
154 self.fail("expected os.tmpfile() to raise OSError")
155 return
156 else:
157 # open() worked, therefore, tmpfile() should work. Close our
158 # dummy file and proceed with the test as normal.
159 fp.close()
160 os.remove(name)
161
162 fp = os.tmpfile()
163 fp.write("foobar")
164 fp.seek(0,0)
165 s = fp.read()
166 fp.close()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000167 self.assertTrue(s == "foobar")
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000168
169 def test_tmpnam(self):
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000170 if not hasattr(os, "tmpnam"):
171 return
172 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
173 r"test_os$")
174 name = os.tmpnam()
175 if sys.platform in ("win32",):
176 # The Windows tmpnam() seems useless. From the MS docs:
177 #
178 # The character string that tmpnam creates consists of
179 # the path prefix, defined by the entry P_tmpdir in the
180 # file STDIO.H, followed by a sequence consisting of the
181 # digit characters '0' through '9'; the numerical value
182 # of this string is in the range 1 - 65,535. Changing the
183 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
184 # change the operation of tmpnam.
185 #
186 # The really bizarre part is that, at least under MSVC6,
187 # P_tmpdir is "\\". That is, the path returned refers to
188 # the root of the current drive. That's a terrible place to
189 # put temp files, and, depending on privileges, the user
190 # may not even be able to open a file in the root directory.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000191 self.assertFalse(os.path.exists(name),
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000192 "file already exists for temporary file")
193 else:
194 self.check_tempfile(name)
195
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000196 def fdopen_helper(self, *args):
197 fd = os.open(support.TESTFN, os.O_RDONLY)
198 fp2 = os.fdopen(fd, *args)
199 fp2.close()
200
201 def test_fdopen(self):
202 self.fdopen_helper()
203 self.fdopen_helper('r')
204 self.fdopen_helper('r', 100)
205
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000206# Test attributes on return values from os.*stat* family.
207class StatAttributeTests(unittest.TestCase):
208 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000209 os.mkdir(support.TESTFN)
210 self.fname = os.path.join(support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000211 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +0000212 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000213 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000214
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000215 def tearDown(self):
216 os.unlink(self.fname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000217 os.rmdir(support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000218
219 def test_stat_attributes(self):
220 if not hasattr(os, "stat"):
221 return
222
223 import stat
224 result = os.stat(self.fname)
225
226 # Make sure direct access works
227 self.assertEquals(result[stat.ST_SIZE], 3)
228 self.assertEquals(result.st_size, 3)
229
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000230 # Make sure all the attributes are there
231 members = dir(result)
232 for name in dir(stat):
233 if name[:3] == 'ST_':
234 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000235 if name.endswith("TIME"):
236 def trunc(x): return int(x)
237 else:
238 def trunc(x): return x
239 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000240 result[getattr(stat, name)])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000241 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000242
243 try:
244 result[200]
245 self.fail("No exception thrown")
246 except IndexError:
247 pass
248
249 # Make sure that assignment fails
250 try:
251 result.st_mode = 1
252 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000253 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000254 pass
255
256 try:
257 result.st_rdev = 1
258 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000259 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000260 pass
261
262 try:
263 result.parrot = 1
264 self.fail("No exception thrown")
265 except AttributeError:
266 pass
267
268 # Use the stat_result constructor with a too-short tuple.
269 try:
270 result2 = os.stat_result((10,))
271 self.fail("No exception thrown")
272 except TypeError:
273 pass
274
275 # Use the constructr with a too-long tuple.
276 try:
277 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
278 except TypeError:
279 pass
280
Tim Peterse0c446b2001-10-18 21:57:37 +0000281
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000282 def test_statvfs_attributes(self):
283 if not hasattr(os, "statvfs"):
284 return
285
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000286 try:
287 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000288 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000289 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000290 if e.errno == errno.ENOSYS:
291 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000292
293 # Make sure direct access works
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000294 self.assertEquals(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000295
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000296 # Make sure all the attributes are there.
297 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
298 'ffree', 'favail', 'flag', 'namemax')
299 for value, member in enumerate(members):
300 self.assertEquals(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000301
302 # Make sure that assignment really fails
303 try:
304 result.f_bfree = 1
305 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000306 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000307 pass
308
309 try:
310 result.parrot = 1
311 self.fail("No exception thrown")
312 except AttributeError:
313 pass
314
315 # Use the constructor with a too-short tuple.
316 try:
317 result2 = os.statvfs_result((10,))
318 self.fail("No exception thrown")
319 except TypeError:
320 pass
321
322 # Use the constructr with a too-long tuple.
323 try:
324 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
325 except TypeError:
326 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000327
Thomas Wouters89f507f2006-12-13 04:49:30 +0000328 def test_utime_dir(self):
329 delta = 1000000
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000330 st = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000331 # round to int, because some systems may support sub-second
332 # time stamps in stat, but not in utime.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000333 os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
334 st2 = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000335 self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
336
337 # Restrict test to Win32, since there is no guarantee other
338 # systems support centiseconds
339 if sys.platform == 'win32':
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000340 def get_file_system(path):
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000341 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000342 import ctypes
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000343 kernel32 = ctypes.windll.kernel32
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000344 buf = ctypes.create_unicode_buffer("", 100)
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000345 if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000346 return buf.value
347
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000348 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000349 def test_1565150(self):
350 t1 = 1159195039.25
351 os.utime(self.fname, (t1, t1))
352 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000353
Guido van Rossumd8faa362007-04-27 19:54:29 +0000354 def test_1686475(self):
355 # Verify that an open file can be stat'ed
356 try:
357 os.stat(r"c:\pagefile.sys")
358 except WindowsError as e:
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000359 if e.errno == 2: # file does not exist; cannot run test
Guido van Rossumd8faa362007-04-27 19:54:29 +0000360 return
361 self.fail("Could not stat pagefile.sys")
362
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000363from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000364
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000365class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000366 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000367 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000368
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000369 def setUp(self):
370 self.__save = dict(os.environ)
Christian Heimes90333392007-11-01 19:08:42 +0000371 for key, value in self._reference().items():
372 os.environ[key] = value
373
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000374 def tearDown(self):
375 os.environ.clear()
376 os.environ.update(self.__save)
377
Christian Heimes90333392007-11-01 19:08:42 +0000378 def _reference(self):
379 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
380
381 def _empty_mapping(self):
382 os.environ.clear()
383 return os.environ
384
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000385 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000386 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000387 os.environ.clear()
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000388 if os.path.exists("/bin/sh"):
389 os.environ.update(HELLO="World")
390 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
391 self.assertEquals(value, "World")
392
Christian Heimes1a13d592007-11-08 14:16:55 +0000393 def test_os_popen_iter(self):
394 if os.path.exists("/bin/sh"):
395 popen = os.popen("/bin/sh -c 'echo \"line1\nline2\nline3\"'")
396 it = iter(popen)
397 self.assertEquals(next(it), "line1\n")
398 self.assertEquals(next(it), "line2\n")
399 self.assertEquals(next(it), "line3\n")
400 self.assertRaises(StopIteration, next, it)
401
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000402 # Verify environ keys and values from the OS are of the
403 # correct str type.
404 def test_keyvalue_types(self):
405 for key, val in os.environ.items():
406 self.assertEquals(type(key), str)
407 self.assertEquals(type(val), str)
408
Christian Heimes90333392007-11-01 19:08:42 +0000409 def test_items(self):
410 for key, value in self._reference().items():
411 self.assertEqual(os.environ.get(key), value)
412
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000413 # Issue 7310
414 def test___repr__(self):
415 """Check that the repr() of os.environ looks like environ({...})."""
416 env = os.environ
417 self.assertTrue(isinstance(env.data, dict))
418 self.assertEqual(repr(env), 'environ({!r})'.format(env.data))
419
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000420 def test_get_exec_path(self):
421 defpath_list = os.defpath.split(os.pathsep)
422 test_path = ['/monty', '/python', '', '/flying/circus']
423 test_env = {'PATH': os.pathsep.join(test_path)}
424
425 saved_environ = os.environ
426 try:
427 os.environ = dict(test_env)
428 # Test that defaulting to os.environ works.
429 self.assertSequenceEqual(test_path, os.get_exec_path())
430 self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
431 finally:
432 os.environ = saved_environ
433
434 # No PATH environment variable
435 self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
436 # Empty PATH environment variable
437 self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
438 # Supplied PATH environment variable
439 self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
440
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000441
Tim Petersc4e09402003-04-25 07:11:48 +0000442class WalkTests(unittest.TestCase):
443 """Tests for os.walk()."""
444
445 def test_traversal(self):
446 import os
447 from os.path import join
448
449 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000450 # TESTFN/
451 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000452 # tmp1
453 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000454 # tmp2
455 # SUB11/ no kids
456 # SUB2/ a file kid and a dirsymlink kid
457 # tmp3
458 # link/ a symlink to TESTFN.2
459 # TEST2/
460 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000461 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000462 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000463 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000464 sub2_path = join(walk_path, "SUB2")
465 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000466 tmp2_path = join(sub1_path, "tmp2")
467 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000468 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000469 t2_path = join(support.TESTFN, "TEST2")
470 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000471
472 # Create stuff.
473 os.makedirs(sub11_path)
474 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000475 os.makedirs(t2_path)
476 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000477 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000478 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
479 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000480 if hasattr(os, "symlink"):
481 os.symlink(os.path.abspath(t2_path), link_path)
482 sub2_tree = (sub2_path, ["link"], ["tmp3"])
483 else:
484 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000485
486 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000487 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000488 self.assertEqual(len(all), 4)
489 # We can't know which order SUB1 and SUB2 will appear in.
490 # Not flipped: TESTFN, SUB1, SUB11, SUB2
491 # flipped: TESTFN, SUB2, SUB1, SUB11
492 flipped = all[0][1][0] != "SUB1"
493 all[0][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000494 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000495 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
496 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000497 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000498
499 # Prune the search.
500 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000501 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000502 all.append((root, dirs, files))
503 # Don't descend into SUB1.
504 if 'SUB1' in dirs:
505 # Note that this also mutates the dirs we appended to all!
506 dirs.remove('SUB1')
507 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000508 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
509 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000510
511 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000512 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000513 self.assertEqual(len(all), 4)
514 # We can't know which order SUB1 and SUB2 will appear in.
515 # Not flipped: SUB11, SUB1, SUB2, TESTFN
516 # flipped: SUB2, SUB11, SUB1, TESTFN
517 flipped = all[3][1][0] != "SUB1"
518 all[3][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000519 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000520 self.assertEqual(all[flipped], (sub11_path, [], []))
521 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000522 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000523
Guido van Rossumd8faa362007-04-27 19:54:29 +0000524 if hasattr(os, "symlink"):
525 # Walk, following symlinks.
526 for root, dirs, files in os.walk(walk_path, followlinks=True):
527 if root == link_path:
528 self.assertEqual(dirs, [])
529 self.assertEqual(files, ["tmp4"])
530 break
531 else:
532 self.fail("Didn't follow symlink with followlinks=True")
533
534 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000535 # Tear everything down. This is a decent use for bottom-up on
536 # Windows, which doesn't have a recursive delete command. The
537 # (not so) subtlety is that rmdir will fail unless the dir's
538 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000539 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000540 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000541 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000542 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000543 dirname = os.path.join(root, name)
544 if not os.path.islink(dirname):
545 os.rmdir(dirname)
546 else:
547 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000548 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000549
Guido van Rossume7ba4952007-06-06 23:52:48 +0000550class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000551 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000552 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000553
554 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000555 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000556 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
557 os.makedirs(path) # Should work
558 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
559 os.makedirs(path)
560
561 # Try paths with a '.' in them
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000562 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000563 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
564 os.makedirs(path)
565 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
566 'dir5', 'dir6')
567 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000568
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000569 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000570 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000571 'dir4', 'dir5', 'dir6')
572 # If the tests failed, the bottom-most directory ('../dir6')
573 # may not have been created, so we look for the outermost directory
574 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000575 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000576 path = os.path.dirname(path)
577
578 os.removedirs(path)
579
Guido van Rossume7ba4952007-06-06 23:52:48 +0000580class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000581 def test_devnull(self):
Alex Martelli01c77c62006-08-24 02:58:11 +0000582 f = open(os.devnull, 'w')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000583 f.write('hello')
584 f.close()
Alex Martelli01c77c62006-08-24 02:58:11 +0000585 f = open(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000586 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000587 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000588
Guido van Rossume7ba4952007-06-06 23:52:48 +0000589class URandomTests(unittest.TestCase):
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000590 def test_urandom(self):
591 try:
592 self.assertEqual(len(os.urandom(1)), 1)
593 self.assertEqual(len(os.urandom(10)), 10)
594 self.assertEqual(len(os.urandom(100)), 100)
595 self.assertEqual(len(os.urandom(1000)), 1000)
596 except NotImplementedError:
597 pass
598
Guido van Rossume7ba4952007-06-06 23:52:48 +0000599class ExecTests(unittest.TestCase):
Mark Dickinson7cf03892010-04-16 13:45:35 +0000600 @unittest.skipIf(USING_LINUXTHREADS,
601 "avoid triggering a linuxthreads bug: see issue #4970")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000602 def test_execvpe_with_bad_program(self):
Mark Dickinson7cf03892010-04-16 13:45:35 +0000603 self.assertRaises(OSError, os.execvpe, 'no such app-',
604 ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000605
Thomas Heller6790d602007-08-30 17:15:14 +0000606 def test_execvpe_with_bad_arglist(self):
607 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
608
Antoine Pitrou1119a642010-01-17 12:16:23 +0000609class ArgTests(unittest.TestCase):
610 def test_bytearray(self):
611 # Issue #7561: posix module didn't release bytearray exports properly.
612 b = bytearray(os.sep.encode('ascii'))
613 self.assertRaises(OSError, os.mkdir, b)
614 # Check object is still resizable.
615 b[:] = b''
616
Thomas Wouters477c8d52006-05-27 19:21:47 +0000617class Win32ErrorTests(unittest.TestCase):
618 def test_rename(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000619 self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000620
621 def test_remove(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000622 self.assertRaises(WindowsError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000623
624 def test_chdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000625 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000626
627 def test_mkdir(self):
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +0000628 f = open(support.TESTFN, "w")
Benjamin Petersonf91df042009-02-13 02:50:59 +0000629 try:
630 self.assertRaises(WindowsError, os.mkdir, support.TESTFN)
631 finally:
632 f.close()
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +0000633 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000634
635 def test_utime(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000636 self.assertRaises(WindowsError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000637
Thomas Wouters477c8d52006-05-27 19:21:47 +0000638 def test_chmod(self):
Benjamin Petersonf91df042009-02-13 02:50:59 +0000639 self.assertRaises(WindowsError, os.chmod, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000640
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000641class TestInvalidFD(unittest.TestCase):
Benjamin Peterson05e782f2009-01-19 15:15:02 +0000642 singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000643 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
644 #singles.append("close")
645 #We omit close because it doesn'r raise an exception on some platforms
646 def get_single(f):
647 def helper(self):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000648 if hasattr(os, f):
649 self.check(getattr(os, f))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000650 return helper
651 for f in singles:
652 locals()["test_"+f] = get_single(f)
653
Benjamin Peterson7522c742009-01-19 21:00:09 +0000654 def check(self, f, *args):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000655 try:
656 f(support.make_bad_fd(), *args)
657 except OSError as e:
658 self.assertEqual(e.errno, errno.EBADF)
659 else:
660 self.fail("%r didn't raise a OSError with a bad file descriptor"
661 % f)
Benjamin Peterson7522c742009-01-19 21:00:09 +0000662
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000663 def test_isatty(self):
664 if hasattr(os, "isatty"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000665 self.assertEqual(os.isatty(support.make_bad_fd()), False)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000666
667 def test_closerange(self):
668 if hasattr(os, "closerange"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000669 fd = support.make_bad_fd()
R. David Murray630cc482009-07-22 15:20:27 +0000670 # Make sure none of the descriptors we are about to close are
671 # currently valid (issue 6542).
672 for i in range(10):
673 try: os.fstat(fd+i)
674 except OSError:
675 pass
676 else:
677 break
678 if i < 2:
679 raise unittest.SkipTest(
680 "Unable to acquire a range of invalid file descriptors")
681 self.assertEqual(os.closerange(fd, fd + i-1), None)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000682
683 def test_dup2(self):
684 if hasattr(os, "dup2"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000685 self.check(os.dup2, 20)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000686
687 def test_fchmod(self):
688 if hasattr(os, "fchmod"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000689 self.check(os.fchmod, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000690
691 def test_fchown(self):
692 if hasattr(os, "fchown"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000693 self.check(os.fchown, -1, -1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000694
695 def test_fpathconf(self):
696 if hasattr(os, "fpathconf"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000697 self.check(os.fpathconf, "PC_NAME_MAX")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000698
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000699 def test_ftruncate(self):
700 if hasattr(os, "ftruncate"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000701 self.check(os.ftruncate, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000702
703 def test_lseek(self):
704 if hasattr(os, "lseek"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000705 self.check(os.lseek, 0, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000706
707 def test_read(self):
708 if hasattr(os, "read"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000709 self.check(os.read, 1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000710
711 def test_tcsetpgrpt(self):
712 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000713 self.check(os.tcsetpgrp, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000714
715 def test_write(self):
716 if hasattr(os, "write"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000717 self.check(os.write, b" ")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000718
Thomas Wouters477c8d52006-05-27 19:21:47 +0000719if sys.platform != 'win32':
720 class Win32ErrorTests(unittest.TestCase):
721 pass
722
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000723 class PosixUidGidTests(unittest.TestCase):
724 if hasattr(os, 'setuid'):
725 def test_setuid(self):
726 if os.getuid() != 0:
727 self.assertRaises(os.error, os.setuid, 0)
728 self.assertRaises(OverflowError, os.setuid, 1<<32)
729
730 if hasattr(os, 'setgid'):
731 def test_setgid(self):
732 if os.getuid() != 0:
733 self.assertRaises(os.error, os.setgid, 0)
734 self.assertRaises(OverflowError, os.setgid, 1<<32)
735
736 if hasattr(os, 'seteuid'):
737 def test_seteuid(self):
738 if os.getuid() != 0:
739 self.assertRaises(os.error, os.seteuid, 0)
740 self.assertRaises(OverflowError, os.seteuid, 1<<32)
741
742 if hasattr(os, 'setegid'):
743 def test_setegid(self):
744 if os.getuid() != 0:
745 self.assertRaises(os.error, os.setegid, 0)
746 self.assertRaises(OverflowError, os.setegid, 1<<32)
747
748 if hasattr(os, 'setreuid'):
749 def test_setreuid(self):
750 if os.getuid() != 0:
751 self.assertRaises(os.error, os.setreuid, 0, 0)
752 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
753 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000754
755 def test_setreuid_neg1(self):
756 # Needs to accept -1. We run this in a subprocess to avoid
757 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000758 subprocess.check_call([
759 sys.executable, '-c',
760 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000761
762 if hasattr(os, 'setregid'):
763 def test_setregid(self):
764 if os.getuid() != 0:
765 self.assertRaises(os.error, os.setregid, 0, 0)
766 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
767 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000768
769 def test_setregid_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.setregid(-1,-1);sys.exit(0)'])
Martin v. Löwis011e8422009-05-05 04:43:17 +0000775
Mark Dickinson70613682009-05-05 21:34:59 +0000776 @unittest.skipIf(sys.platform == 'darwin', "tests don't apply to OS X")
Martin v. Löwis011e8422009-05-05 04:43:17 +0000777 class Pep383Tests(unittest.TestCase):
778 filenames = [b'foo\xf6bar', 'foo\xf6bar'.encode("utf-8")]
779
780 def setUp(self):
781 self.fsencoding = sys.getfilesystemencoding()
782 sys.setfilesystemencoding("utf-8")
783 self.dir = support.TESTFN
Martin v. Löwis43c57782009-05-10 08:15:24 +0000784 self.bdir = self.dir.encode("utf-8", "surrogateescape")
Martin v. Löwis011e8422009-05-05 04:43:17 +0000785 os.mkdir(self.dir)
786 self.unicodefn = []
787 for fn in self.filenames:
788 f = open(os.path.join(self.bdir, fn), "w")
789 f.close()
Martin v. Löwis43c57782009-05-10 08:15:24 +0000790 self.unicodefn.append(fn.decode("utf-8", "surrogateescape"))
Martin v. Löwis011e8422009-05-05 04:43:17 +0000791
792 def tearDown(self):
793 shutil.rmtree(self.dir)
794 sys.setfilesystemencoding(self.fsencoding)
795
796 def test_listdir(self):
797 expected = set(self.unicodefn)
798 found = set(os.listdir(support.TESTFN))
799 self.assertEquals(found, expected)
800
801 def test_open(self):
802 for fn in self.unicodefn:
803 f = open(os.path.join(self.dir, fn))
804 f.close()
805
806 def test_stat(self):
807 for fn in self.unicodefn:
808 os.stat(os.path.join(self.dir, fn))
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000809else:
810 class PosixUidGidTests(unittest.TestCase):
811 pass
Martin v. Löwis011e8422009-05-05 04:43:17 +0000812 class Pep383Tests(unittest.TestCase):
813 pass
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000814
Brian Curtineb24d742010-04-12 17:16:38 +0000815@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
816class Win32KillTests(unittest.TestCase):
817 def _kill(self, sig, *args):
818 # Send a subprocess a signal (or in some cases, just an int to be
819 # the return value)
820 proc = subprocess.Popen(*args)
821 os.kill(proc.pid, sig)
822 self.assertEqual(proc.wait(), sig)
823
824 def test_kill_sigterm(self):
825 # SIGTERM doesn't mean anything special, but make sure it works
826 self._kill(signal.SIGTERM, [sys.executable])
827
828 def test_kill_int(self):
829 # os.kill on Windows can take an int which gets set as the exit code
830 self._kill(100, [sys.executable])
831
832 def _kill_with_event(self, event, name):
833 # Run a script which has console control handling enabled.
834 proc = subprocess.Popen([sys.executable,
835 os.path.join(os.path.dirname(__file__),
836 "win_console_handler.py")],
837 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
838 # Let the interpreter startup before we send signals. See #3137.
839 time.sleep(0.5)
840 os.kill(proc.pid, event)
841 # proc.send_signal(event) could also be done here.
842 # Allow time for the signal to be passed and the process to exit.
843 time.sleep(0.5)
844 if not proc.poll():
845 # Forcefully kill the process if we weren't able to signal it.
846 os.kill(proc.pid, signal.SIGINT)
847 self.fail("subprocess did not stop on {}".format(name))
848
849 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
850 def test_CTRL_C_EVENT(self):
851 from ctypes import wintypes
852 import ctypes
853
854 # Make a NULL value by creating a pointer with no argument.
855 NULL = ctypes.POINTER(ctypes.c_int)()
856 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
857 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
858 wintypes.BOOL)
859 SetConsoleCtrlHandler.restype = wintypes.BOOL
860
861 # Calling this with NULL and FALSE causes the calling process to
862 # handle CTRL+C, rather than ignore it. This property is inherited
863 # by subprocesses.
864 SetConsoleCtrlHandler(NULL, 0)
865
866 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
867
868 def test_CTRL_BREAK_EVENT(self):
869 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
870
871
Fred Drake2e2be372001-09-20 21:33:42 +0000872def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000873 support.run_unittest(
Antoine Pitrou1119a642010-01-17 12:16:23 +0000874 ArgTests,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000875 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000876 StatAttributeTests,
877 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000878 WalkTests,
879 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000880 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000881 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000882 ExecTests,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000883 Win32ErrorTests,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000884 TestInvalidFD,
Martin v. Löwis011e8422009-05-05 04:43:17 +0000885 PosixUidGidTests,
Brian Curtineb24d742010-04-12 17:16:38 +0000886 Pep383Tests,
887 Win32KillTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000888 )
Fred Drake2e2be372001-09-20 21:33:42 +0000889
890if __name__ == "__main__":
891 test_main()