blob: 49f9cbd10d2fa3c0fb7cf0299f46c004e635dade [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
Victor Stinnerc2d095f2010-05-17 00:14:53 +000015import contextlib
Fred Drake38c2ef02001-07-17 20:52:51 +000016
Mark Dickinson7cf03892010-04-16 13:45:35 +000017# Detect whether we're on a Linux system that uses the (now outdated
18# and unmaintained) linuxthreads threading library. There's an issue
19# when combining linuxthreads with a failed execv call: see
20# http://bugs.python.org/issue4970.
Mark Dickinson89589c92010-04-16 13:51:27 +000021if (hasattr(os, "confstr_names") and
22 "CS_GNU_LIBPTHREAD_VERSION" in os.confstr_names):
Mark Dickinson7cf03892010-04-16 13:45:35 +000023 libpthread = os.confstr("CS_GNU_LIBPTHREAD_VERSION")
24 USING_LINUXTHREADS= libpthread.startswith("linuxthreads")
25else:
26 USING_LINUXTHREADS= False
Brian Curtineb24d742010-04-12 17:16:38 +000027
Thomas Wouters0e3f5912006-08-11 14:57:12 +000028# Tests creating TESTFN
29class FileTests(unittest.TestCase):
30 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000031 if os.path.exists(support.TESTFN):
32 os.unlink(support.TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000033 tearDown = setUp
34
35 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000036 f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000037 os.close(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000038 self.assertTrue(os.access(support.TESTFN, os.W_OK))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000039
Christian Heimesfdab48e2008-01-20 09:06:41 +000040 def test_closerange(self):
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000041 first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
42 # We must allocate two consecutive file descriptors, otherwise
43 # it will mess up other file descriptors (perhaps even the three
44 # standard ones).
45 second = os.dup(first)
46 try:
47 retries = 0
48 while second != first + 1:
49 os.close(first)
50 retries += 1
51 if retries > 10:
52 # XXX test skipped
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000053 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000054 first, second = second, os.dup(second)
55 finally:
56 os.close(second)
Christian Heimesfdab48e2008-01-20 09:06:41 +000057 # close a fd that is open, and one that isn't
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000058 os.closerange(first, first + 2)
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000059 self.assertRaises(OSError, os.write, first, b"a")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000060
Hirokazu Yamamoto4c19e6e2008-09-08 23:41:21 +000061 def test_rename(self):
62 path = support.TESTFN
63 old = sys.getrefcount(path)
64 self.assertRaises(TypeError, os.rename, path, 0)
65 new = sys.getrefcount(path)
66 self.assertEqual(old, new)
67
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000068 def test_read(self):
69 with open(support.TESTFN, "w+b") as fobj:
70 fobj.write(b"spam")
71 fobj.flush()
72 fd = fobj.fileno()
73 os.lseek(fd, 0, 0)
74 s = os.read(fd, 4)
75 self.assertEqual(type(s), bytes)
76 self.assertEqual(s, b"spam")
77
78 def test_write(self):
79 # os.write() accepts bytes- and buffer-like objects but not strings
80 fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY)
81 self.assertRaises(TypeError, os.write, fd, "beans")
82 os.write(fd, b"bacon\n")
83 os.write(fd, bytearray(b"eggs\n"))
84 os.write(fd, memoryview(b"spam\n"))
85 os.close(fd)
86 with open(support.TESTFN, "rb") as fobj:
Antoine Pitroud62269f2008-09-15 23:54:52 +000087 self.assertEqual(fobj.read().splitlines(),
88 [b"bacon", b"eggs", b"spam"])
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000089
90
Christian Heimesdd15f6c2008-03-16 00:07:10 +000091class TemporaryFileTests(unittest.TestCase):
92 def setUp(self):
93 self.files = []
Benjamin Petersonee8712c2008-05-20 21:35:26 +000094 os.mkdir(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000095
96 def tearDown(self):
97 for name in self.files:
98 os.unlink(name)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000099 os.rmdir(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000100
101 def check_tempfile(self, name):
102 # make sure it doesn't already exist:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000103 self.assertFalse(os.path.exists(name),
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000104 "file already exists for temporary file")
105 # make sure we can create the file
106 open(name, "w")
107 self.files.append(name)
108
109 def test_tempnam(self):
110 if not hasattr(os, "tempnam"):
111 return
112 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
113 r"test_os$")
114 self.check_tempfile(os.tempnam())
115
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000116 name = os.tempnam(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000117 self.check_tempfile(name)
118
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000119 name = os.tempnam(support.TESTFN, "pfx")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000120 self.assertTrue(os.path.basename(name)[:3] == "pfx")
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000121 self.check_tempfile(name)
122
123 def test_tmpfile(self):
124 if not hasattr(os, "tmpfile"):
125 return
126 # As with test_tmpnam() below, the Windows implementation of tmpfile()
127 # attempts to create a file in the root directory of the current drive.
128 # On Vista and Server 2008, this test will always fail for normal users
129 # as writing to the root directory requires elevated privileges. With
130 # XP and below, the semantics of tmpfile() are the same, but the user
131 # running the test is more likely to have administrative privileges on
132 # their account already. If that's the case, then os.tmpfile() should
133 # work. In order to make this test as useful as possible, rather than
134 # trying to detect Windows versions or whether or not the user has the
135 # right permissions, just try and create a file in the root directory
136 # and see if it raises a 'Permission denied' OSError. If it does, then
137 # test that a subsequent call to os.tmpfile() raises the same error. If
138 # it doesn't, assume we're on XP or below and the user running the test
139 # has administrative privileges, and proceed with the test as normal.
140 if sys.platform == 'win32':
141 name = '\\python_test_os_test_tmpfile.txt'
142 if os.path.exists(name):
143 os.remove(name)
144 try:
145 fp = open(name, 'w')
146 except IOError as first:
147 # open() failed, assert tmpfile() fails in the same way.
148 # Although open() raises an IOError and os.tmpfile() raises an
149 # OSError(), 'args' will be (13, 'Permission denied') in both
150 # cases.
151 try:
152 fp = os.tmpfile()
153 except OSError as second:
154 self.assertEqual(first.args, second.args)
155 else:
156 self.fail("expected os.tmpfile() to raise OSError")
157 return
158 else:
159 # open() worked, therefore, tmpfile() should work. Close our
160 # dummy file and proceed with the test as normal.
161 fp.close()
162 os.remove(name)
163
164 fp = os.tmpfile()
165 fp.write("foobar")
166 fp.seek(0,0)
167 s = fp.read()
168 fp.close()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000169 self.assertTrue(s == "foobar")
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000170
171 def test_tmpnam(self):
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000172 if not hasattr(os, "tmpnam"):
173 return
174 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
175 r"test_os$")
176 name = os.tmpnam()
177 if sys.platform in ("win32",):
178 # The Windows tmpnam() seems useless. From the MS docs:
179 #
180 # The character string that tmpnam creates consists of
181 # the path prefix, defined by the entry P_tmpdir in the
182 # file STDIO.H, followed by a sequence consisting of the
183 # digit characters '0' through '9'; the numerical value
184 # of this string is in the range 1 - 65,535. Changing the
185 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
186 # change the operation of tmpnam.
187 #
188 # The really bizarre part is that, at least under MSVC6,
189 # P_tmpdir is "\\". That is, the path returned refers to
190 # the root of the current drive. That's a terrible place to
191 # put temp files, and, depending on privileges, the user
192 # may not even be able to open a file in the root directory.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000193 self.assertFalse(os.path.exists(name),
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000194 "file already exists for temporary file")
195 else:
196 self.check_tempfile(name)
197
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000198 def fdopen_helper(self, *args):
199 fd = os.open(support.TESTFN, os.O_RDONLY)
200 fp2 = os.fdopen(fd, *args)
201 fp2.close()
202
203 def test_fdopen(self):
204 self.fdopen_helper()
205 self.fdopen_helper('r')
206 self.fdopen_helper('r', 100)
207
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000208# Test attributes on return values from os.*stat* family.
209class StatAttributeTests(unittest.TestCase):
210 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000211 os.mkdir(support.TESTFN)
212 self.fname = os.path.join(support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000213 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +0000214 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000215 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000216
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000217 def tearDown(self):
218 os.unlink(self.fname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000219 os.rmdir(support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000220
221 def test_stat_attributes(self):
222 if not hasattr(os, "stat"):
223 return
224
225 import stat
226 result = os.stat(self.fname)
227
228 # Make sure direct access works
229 self.assertEquals(result[stat.ST_SIZE], 3)
230 self.assertEquals(result.st_size, 3)
231
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000232 # Make sure all the attributes are there
233 members = dir(result)
234 for name in dir(stat):
235 if name[:3] == 'ST_':
236 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000237 if name.endswith("TIME"):
238 def trunc(x): return int(x)
239 else:
240 def trunc(x): return x
241 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000242 result[getattr(stat, name)])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000243 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000244
245 try:
246 result[200]
247 self.fail("No exception thrown")
248 except IndexError:
249 pass
250
251 # Make sure that assignment fails
252 try:
253 result.st_mode = 1
254 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000255 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000256 pass
257
258 try:
259 result.st_rdev = 1
260 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000261 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000262 pass
263
264 try:
265 result.parrot = 1
266 self.fail("No exception thrown")
267 except AttributeError:
268 pass
269
270 # Use the stat_result constructor with a too-short tuple.
271 try:
272 result2 = os.stat_result((10,))
273 self.fail("No exception thrown")
274 except TypeError:
275 pass
276
277 # Use the constructr with a too-long tuple.
278 try:
279 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
280 except TypeError:
281 pass
282
Tim Peterse0c446b2001-10-18 21:57:37 +0000283
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000284 def test_statvfs_attributes(self):
285 if not hasattr(os, "statvfs"):
286 return
287
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000288 try:
289 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000290 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000291 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000292 if e.errno == errno.ENOSYS:
293 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000294
295 # Make sure direct access works
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000296 self.assertEquals(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000297
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000298 # Make sure all the attributes are there.
299 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
300 'ffree', 'favail', 'flag', 'namemax')
301 for value, member in enumerate(members):
302 self.assertEquals(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000303
304 # Make sure that assignment really fails
305 try:
306 result.f_bfree = 1
307 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000308 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000309 pass
310
311 try:
312 result.parrot = 1
313 self.fail("No exception thrown")
314 except AttributeError:
315 pass
316
317 # Use the constructor with a too-short tuple.
318 try:
319 result2 = os.statvfs_result((10,))
320 self.fail("No exception thrown")
321 except TypeError:
322 pass
323
324 # Use the constructr with a too-long tuple.
325 try:
326 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
327 except TypeError:
328 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000329
Thomas Wouters89f507f2006-12-13 04:49:30 +0000330 def test_utime_dir(self):
331 delta = 1000000
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000332 st = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000333 # round to int, because some systems may support sub-second
334 # time stamps in stat, but not in utime.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000335 os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
336 st2 = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000337 self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
338
339 # Restrict test to Win32, since there is no guarantee other
340 # systems support centiseconds
341 if sys.platform == 'win32':
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000342 def get_file_system(path):
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000343 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000344 import ctypes
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000345 kernel32 = ctypes.windll.kernel32
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000346 buf = ctypes.create_unicode_buffer("", 100)
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000347 if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000348 return buf.value
349
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000350 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000351 def test_1565150(self):
352 t1 = 1159195039.25
353 os.utime(self.fname, (t1, t1))
354 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000355
Guido van Rossumd8faa362007-04-27 19:54:29 +0000356 def test_1686475(self):
357 # Verify that an open file can be stat'ed
358 try:
359 os.stat(r"c:\pagefile.sys")
360 except WindowsError as e:
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000361 if e.errno == 2: # file does not exist; cannot run test
Guido van Rossumd8faa362007-04-27 19:54:29 +0000362 return
363 self.fail("Could not stat pagefile.sys")
364
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000365from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000366
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000367class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000368 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000369 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000370
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000371 def setUp(self):
372 self.__save = dict(os.environ)
Victor Stinner208d28c2010-05-07 00:54:14 +0000373 if os.name not in ('os2', 'nt'):
374 self.__saveb = dict(os.environb)
Christian Heimes90333392007-11-01 19:08:42 +0000375 for key, value in self._reference().items():
376 os.environ[key] = value
377
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000378 def tearDown(self):
379 os.environ.clear()
380 os.environ.update(self.__save)
Victor Stinner208d28c2010-05-07 00:54:14 +0000381 if os.name not in ('os2', 'nt'):
382 os.environb.clear()
383 os.environb.update(self.__saveb)
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000384
Christian Heimes90333392007-11-01 19:08:42 +0000385 def _reference(self):
386 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
387
388 def _empty_mapping(self):
389 os.environ.clear()
390 return os.environ
391
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000392 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000393 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000394 os.environ.clear()
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000395 if os.path.exists("/bin/sh"):
396 os.environ.update(HELLO="World")
397 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
398 self.assertEquals(value, "World")
399
Christian Heimes1a13d592007-11-08 14:16:55 +0000400 def test_os_popen_iter(self):
401 if os.path.exists("/bin/sh"):
402 popen = os.popen("/bin/sh -c 'echo \"line1\nline2\nline3\"'")
403 it = iter(popen)
404 self.assertEquals(next(it), "line1\n")
405 self.assertEquals(next(it), "line2\n")
406 self.assertEquals(next(it), "line3\n")
407 self.assertRaises(StopIteration, next, it)
408
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000409 # Verify environ keys and values from the OS are of the
410 # correct str type.
411 def test_keyvalue_types(self):
412 for key, val in os.environ.items():
413 self.assertEquals(type(key), str)
414 self.assertEquals(type(val), str)
415
Christian Heimes90333392007-11-01 19:08:42 +0000416 def test_items(self):
417 for key, value in self._reference().items():
418 self.assertEqual(os.environ.get(key), value)
419
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000420 # Issue 7310
421 def test___repr__(self):
422 """Check that the repr() of os.environ looks like environ({...})."""
423 env = os.environ
424 self.assertTrue(isinstance(env.data, dict))
425 self.assertEqual(repr(env), 'environ({!r})'.format(env.data))
426
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000427 def test_get_exec_path(self):
428 defpath_list = os.defpath.split(os.pathsep)
429 test_path = ['/monty', '/python', '', '/flying/circus']
430 test_env = {'PATH': os.pathsep.join(test_path)}
431
432 saved_environ = os.environ
433 try:
434 os.environ = dict(test_env)
435 # Test that defaulting to os.environ works.
436 self.assertSequenceEqual(test_path, os.get_exec_path())
437 self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
438 finally:
439 os.environ = saved_environ
440
441 # No PATH environment variable
442 self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
443 # Empty PATH environment variable
444 self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
445 # Supplied PATH environment variable
446 self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
447
Victor Stinner84ae1182010-05-06 22:05:07 +0000448 @unittest.skipIf(sys.platform == "win32", "POSIX specific test")
449 def test_environb(self):
450 # os.environ -> os.environb
451 value = 'euro\u20ac'
452 try:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000453 value_bytes = value.encode(sys.getfilesystemencoding(),
454 'surrogateescape')
Victor Stinner84ae1182010-05-06 22:05:07 +0000455 except UnicodeEncodeError:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000456 msg = "U+20AC character is not encodable to %s" % (
457 sys.getfilesystemencoding(),)
Benjamin Peterson932d3f42010-05-06 22:26:31 +0000458 self.skipTest(msg)
Victor Stinner84ae1182010-05-06 22:05:07 +0000459 os.environ['unicode'] = value
460 self.assertEquals(os.environ['unicode'], value)
461 self.assertEquals(os.environb[b'unicode'], value_bytes)
462
463 # os.environb -> os.environ
464 value = b'\xff'
465 os.environb[b'bytes'] = value
466 self.assertEquals(os.environb[b'bytes'], value)
467 value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape')
468 self.assertEquals(os.environ['bytes'], value_str)
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000469
Tim Petersc4e09402003-04-25 07:11:48 +0000470class WalkTests(unittest.TestCase):
471 """Tests for os.walk()."""
472
473 def test_traversal(self):
474 import os
475 from os.path import join
476
477 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000478 # TESTFN/
479 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000480 # tmp1
481 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000482 # tmp2
483 # SUB11/ no kids
484 # SUB2/ a file kid and a dirsymlink kid
485 # tmp3
486 # link/ a symlink to TESTFN.2
487 # TEST2/
488 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000489 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000490 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000491 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000492 sub2_path = join(walk_path, "SUB2")
493 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000494 tmp2_path = join(sub1_path, "tmp2")
495 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000496 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000497 t2_path = join(support.TESTFN, "TEST2")
498 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000499
500 # Create stuff.
501 os.makedirs(sub11_path)
502 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000503 os.makedirs(t2_path)
504 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000505 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000506 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
507 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000508 if hasattr(os, "symlink"):
509 os.symlink(os.path.abspath(t2_path), link_path)
510 sub2_tree = (sub2_path, ["link"], ["tmp3"])
511 else:
512 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000513
514 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000515 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000516 self.assertEqual(len(all), 4)
517 # We can't know which order SUB1 and SUB2 will appear in.
518 # Not flipped: TESTFN, SUB1, SUB11, SUB2
519 # flipped: TESTFN, SUB2, SUB1, SUB11
520 flipped = all[0][1][0] != "SUB1"
521 all[0][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000522 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000523 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
524 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000525 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000526
527 # Prune the search.
528 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000529 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000530 all.append((root, dirs, files))
531 # Don't descend into SUB1.
532 if 'SUB1' in dirs:
533 # Note that this also mutates the dirs we appended to all!
534 dirs.remove('SUB1')
535 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000536 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
537 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000538
539 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000540 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000541 self.assertEqual(len(all), 4)
542 # We can't know which order SUB1 and SUB2 will appear in.
543 # Not flipped: SUB11, SUB1, SUB2, TESTFN
544 # flipped: SUB2, SUB11, SUB1, TESTFN
545 flipped = all[3][1][0] != "SUB1"
546 all[3][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000547 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000548 self.assertEqual(all[flipped], (sub11_path, [], []))
549 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000550 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000551
Guido van Rossumd8faa362007-04-27 19:54:29 +0000552 if hasattr(os, "symlink"):
553 # Walk, following symlinks.
554 for root, dirs, files in os.walk(walk_path, followlinks=True):
555 if root == link_path:
556 self.assertEqual(dirs, [])
557 self.assertEqual(files, ["tmp4"])
558 break
559 else:
560 self.fail("Didn't follow symlink with followlinks=True")
561
562 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000563 # Tear everything down. This is a decent use for bottom-up on
564 # Windows, which doesn't have a recursive delete command. The
565 # (not so) subtlety is that rmdir will fail unless the dir's
566 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000567 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000568 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000569 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000570 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000571 dirname = os.path.join(root, name)
572 if not os.path.islink(dirname):
573 os.rmdir(dirname)
574 else:
575 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000576 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000577
Guido van Rossume7ba4952007-06-06 23:52:48 +0000578class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000579 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000580 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000581
582 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000583 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000584 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
585 os.makedirs(path) # Should work
586 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
587 os.makedirs(path)
588
589 # Try paths with a '.' in them
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000590 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000591 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
592 os.makedirs(path)
593 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
594 'dir5', 'dir6')
595 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000596
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000597 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000598 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000599 'dir4', 'dir5', 'dir6')
600 # If the tests failed, the bottom-most directory ('../dir6')
601 # may not have been created, so we look for the outermost directory
602 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000603 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000604 path = os.path.dirname(path)
605
606 os.removedirs(path)
607
Guido van Rossume7ba4952007-06-06 23:52:48 +0000608class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000609 def test_devnull(self):
Alex Martelli01c77c62006-08-24 02:58:11 +0000610 f = open(os.devnull, 'w')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000611 f.write('hello')
612 f.close()
Alex Martelli01c77c62006-08-24 02:58:11 +0000613 f = open(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000614 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000615 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000616
Guido van Rossume7ba4952007-06-06 23:52:48 +0000617class URandomTests(unittest.TestCase):
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000618 def test_urandom(self):
619 try:
620 self.assertEqual(len(os.urandom(1)), 1)
621 self.assertEqual(len(os.urandom(10)), 10)
622 self.assertEqual(len(os.urandom(100)), 100)
623 self.assertEqual(len(os.urandom(1000)), 1000)
624 except NotImplementedError:
625 pass
626
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000627@contextlib.contextmanager
628def _execvpe_mockup(defpath=None):
629 """
630 Stubs out execv and execve functions when used as context manager.
631 Records exec calls. The mock execv and execve functions always raise an
632 exception as they would normally never return.
633 """
634 # A list of tuples containing (function name, first arg, args)
635 # of calls to execv or execve that have been made.
636 calls = []
637
638 def mock_execv(name, *args):
639 calls.append(('execv', name, args))
640 raise RuntimeError("execv called")
641
642 def mock_execve(name, *args):
643 calls.append(('execve', name, args))
644 raise OSError(errno.ENOTDIR, "execve called")
645
646 try:
647 orig_execv = os.execv
648 orig_execve = os.execve
649 orig_defpath = os.defpath
650 os.execv = mock_execv
651 os.execve = mock_execve
652 if defpath is not None:
653 os.defpath = defpath
654 yield calls
655 finally:
656 os.execv = orig_execv
657 os.execve = orig_execve
658 os.defpath = orig_defpath
659
Guido van Rossume7ba4952007-06-06 23:52:48 +0000660class ExecTests(unittest.TestCase):
Mark Dickinson7cf03892010-04-16 13:45:35 +0000661 @unittest.skipIf(USING_LINUXTHREADS,
662 "avoid triggering a linuxthreads bug: see issue #4970")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000663 def test_execvpe_with_bad_program(self):
Mark Dickinson7cf03892010-04-16 13:45:35 +0000664 self.assertRaises(OSError, os.execvpe, 'no such app-',
665 ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000666
Thomas Heller6790d602007-08-30 17:15:14 +0000667 def test_execvpe_with_bad_arglist(self):
668 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
669
Gregory P. Smith4ae37772010-05-08 18:05:46 +0000670 @unittest.skipUnless(hasattr(os, '_execvpe'),
671 "No internal os._execvpe function to test.")
672 def test_internal_execvpe(self):
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000673 program_path = os.sep+'absolutepath'
674 program = 'executable'
675 fullpath = os.path.join(program_path, program)
676 arguments = ['progname', 'arg1', 'arg2']
677 env = {'spam': 'beans'}
678
679 with _execvpe_mockup() as calls:
680 self.assertRaises(RuntimeError, os._execvpe, fullpath, arguments)
681 self.assertEqual(len(calls), 1)
682 self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))
683
684 with _execvpe_mockup(defpath=program_path) as calls:
685 self.assertRaises(OSError, os._execvpe, program, arguments, env=env)
686 self.assertEqual(len(calls), 1)
687 if os.name != "nt":
688 self.assertEqual(calls[0], ('execve', os.fsencode(fullpath), (arguments, env)))
689 else:
690 self.assertEqual(calls[0], ('execve', fullpath, (arguments, env)))
691
Gregory P. Smith4ae37772010-05-08 18:05:46 +0000692
Thomas Wouters477c8d52006-05-27 19:21:47 +0000693class Win32ErrorTests(unittest.TestCase):
694 def test_rename(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000695 self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000696
697 def test_remove(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000698 self.assertRaises(WindowsError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000699
700 def test_chdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000701 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000702
703 def test_mkdir(self):
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +0000704 f = open(support.TESTFN, "w")
Benjamin Petersonf91df042009-02-13 02:50:59 +0000705 try:
706 self.assertRaises(WindowsError, os.mkdir, support.TESTFN)
707 finally:
708 f.close()
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +0000709 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000710
711 def test_utime(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000712 self.assertRaises(WindowsError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000713
Thomas Wouters477c8d52006-05-27 19:21:47 +0000714 def test_chmod(self):
Benjamin Petersonf91df042009-02-13 02:50:59 +0000715 self.assertRaises(WindowsError, os.chmod, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000716
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000717class TestInvalidFD(unittest.TestCase):
Benjamin Peterson05e782f2009-01-19 15:15:02 +0000718 singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000719 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
720 #singles.append("close")
721 #We omit close because it doesn'r raise an exception on some platforms
722 def get_single(f):
723 def helper(self):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000724 if hasattr(os, f):
725 self.check(getattr(os, f))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000726 return helper
727 for f in singles:
728 locals()["test_"+f] = get_single(f)
729
Benjamin Peterson7522c742009-01-19 21:00:09 +0000730 def check(self, f, *args):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000731 try:
732 f(support.make_bad_fd(), *args)
733 except OSError as e:
734 self.assertEqual(e.errno, errno.EBADF)
735 else:
736 self.fail("%r didn't raise a OSError with a bad file descriptor"
737 % f)
Benjamin Peterson7522c742009-01-19 21:00:09 +0000738
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000739 def test_isatty(self):
740 if hasattr(os, "isatty"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000741 self.assertEqual(os.isatty(support.make_bad_fd()), False)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000742
743 def test_closerange(self):
744 if hasattr(os, "closerange"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000745 fd = support.make_bad_fd()
R. David Murray630cc482009-07-22 15:20:27 +0000746 # Make sure none of the descriptors we are about to close are
747 # currently valid (issue 6542).
748 for i in range(10):
749 try: os.fstat(fd+i)
750 except OSError:
751 pass
752 else:
753 break
754 if i < 2:
755 raise unittest.SkipTest(
756 "Unable to acquire a range of invalid file descriptors")
757 self.assertEqual(os.closerange(fd, fd + i-1), None)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000758
759 def test_dup2(self):
760 if hasattr(os, "dup2"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000761 self.check(os.dup2, 20)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000762
763 def test_fchmod(self):
764 if hasattr(os, "fchmod"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000765 self.check(os.fchmod, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000766
767 def test_fchown(self):
768 if hasattr(os, "fchown"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000769 self.check(os.fchown, -1, -1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000770
771 def test_fpathconf(self):
772 if hasattr(os, "fpathconf"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000773 self.check(os.fpathconf, "PC_NAME_MAX")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000774
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000775 def test_ftruncate(self):
776 if hasattr(os, "ftruncate"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000777 self.check(os.ftruncate, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000778
779 def test_lseek(self):
780 if hasattr(os, "lseek"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000781 self.check(os.lseek, 0, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000782
783 def test_read(self):
784 if hasattr(os, "read"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000785 self.check(os.read, 1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000786
787 def test_tcsetpgrpt(self):
788 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000789 self.check(os.tcsetpgrp, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000790
791 def test_write(self):
792 if hasattr(os, "write"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000793 self.check(os.write, b" ")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000794
Thomas Wouters477c8d52006-05-27 19:21:47 +0000795if sys.platform != 'win32':
796 class Win32ErrorTests(unittest.TestCase):
797 pass
798
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000799 class PosixUidGidTests(unittest.TestCase):
800 if hasattr(os, 'setuid'):
801 def test_setuid(self):
802 if os.getuid() != 0:
803 self.assertRaises(os.error, os.setuid, 0)
804 self.assertRaises(OverflowError, os.setuid, 1<<32)
805
806 if hasattr(os, 'setgid'):
807 def test_setgid(self):
808 if os.getuid() != 0:
809 self.assertRaises(os.error, os.setgid, 0)
810 self.assertRaises(OverflowError, os.setgid, 1<<32)
811
812 if hasattr(os, 'seteuid'):
813 def test_seteuid(self):
814 if os.getuid() != 0:
815 self.assertRaises(os.error, os.seteuid, 0)
816 self.assertRaises(OverflowError, os.seteuid, 1<<32)
817
818 if hasattr(os, 'setegid'):
819 def test_setegid(self):
820 if os.getuid() != 0:
821 self.assertRaises(os.error, os.setegid, 0)
822 self.assertRaises(OverflowError, os.setegid, 1<<32)
823
824 if hasattr(os, 'setreuid'):
825 def test_setreuid(self):
826 if os.getuid() != 0:
827 self.assertRaises(os.error, os.setreuid, 0, 0)
828 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
829 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000830
831 def test_setreuid_neg1(self):
832 # Needs to accept -1. We run this in a subprocess to avoid
833 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000834 subprocess.check_call([
835 sys.executable, '-c',
836 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000837
838 if hasattr(os, 'setregid'):
839 def test_setregid(self):
840 if os.getuid() != 0:
841 self.assertRaises(os.error, os.setregid, 0, 0)
842 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
843 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000844
845 def test_setregid_neg1(self):
846 # Needs to accept -1. We run this in a subprocess to avoid
847 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000848 subprocess.check_call([
849 sys.executable, '-c',
850 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Martin v. Löwis011e8422009-05-05 04:43:17 +0000851
Mark Dickinson70613682009-05-05 21:34:59 +0000852 @unittest.skipIf(sys.platform == 'darwin', "tests don't apply to OS X")
Martin v. Löwis011e8422009-05-05 04:43:17 +0000853 class Pep383Tests(unittest.TestCase):
854 filenames = [b'foo\xf6bar', 'foo\xf6bar'.encode("utf-8")]
855
856 def setUp(self):
857 self.fsencoding = sys.getfilesystemencoding()
858 sys.setfilesystemencoding("utf-8")
859 self.dir = support.TESTFN
Martin v. Löwis43c57782009-05-10 08:15:24 +0000860 self.bdir = self.dir.encode("utf-8", "surrogateescape")
Martin v. Löwis011e8422009-05-05 04:43:17 +0000861 os.mkdir(self.dir)
862 self.unicodefn = []
863 for fn in self.filenames:
864 f = open(os.path.join(self.bdir, fn), "w")
865 f.close()
Martin v. Löwis43c57782009-05-10 08:15:24 +0000866 self.unicodefn.append(fn.decode("utf-8", "surrogateescape"))
Martin v. Löwis011e8422009-05-05 04:43:17 +0000867
868 def tearDown(self):
869 shutil.rmtree(self.dir)
870 sys.setfilesystemencoding(self.fsencoding)
871
872 def test_listdir(self):
873 expected = set(self.unicodefn)
874 found = set(os.listdir(support.TESTFN))
875 self.assertEquals(found, expected)
876
877 def test_open(self):
878 for fn in self.unicodefn:
879 f = open(os.path.join(self.dir, fn))
880 f.close()
881
882 def test_stat(self):
883 for fn in self.unicodefn:
884 os.stat(os.path.join(self.dir, fn))
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000885else:
886 class PosixUidGidTests(unittest.TestCase):
887 pass
Martin v. Löwis011e8422009-05-05 04:43:17 +0000888 class Pep383Tests(unittest.TestCase):
889 pass
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000890
Brian Curtineb24d742010-04-12 17:16:38 +0000891@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
892class Win32KillTests(unittest.TestCase):
893 def _kill(self, sig, *args):
894 # Send a subprocess a signal (or in some cases, just an int to be
895 # the return value)
896 proc = subprocess.Popen(*args)
897 os.kill(proc.pid, sig)
898 self.assertEqual(proc.wait(), sig)
899
900 def test_kill_sigterm(self):
901 # SIGTERM doesn't mean anything special, but make sure it works
902 self._kill(signal.SIGTERM, [sys.executable])
903
904 def test_kill_int(self):
905 # os.kill on Windows can take an int which gets set as the exit code
906 self._kill(100, [sys.executable])
907
908 def _kill_with_event(self, event, name):
909 # Run a script which has console control handling enabled.
910 proc = subprocess.Popen([sys.executable,
911 os.path.join(os.path.dirname(__file__),
912 "win_console_handler.py")],
913 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
914 # Let the interpreter startup before we send signals. See #3137.
915 time.sleep(0.5)
916 os.kill(proc.pid, event)
917 # proc.send_signal(event) could also be done here.
918 # Allow time for the signal to be passed and the process to exit.
919 time.sleep(0.5)
920 if not proc.poll():
921 # Forcefully kill the process if we weren't able to signal it.
922 os.kill(proc.pid, signal.SIGINT)
923 self.fail("subprocess did not stop on {}".format(name))
924
925 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
926 def test_CTRL_C_EVENT(self):
927 from ctypes import wintypes
928 import ctypes
929
930 # Make a NULL value by creating a pointer with no argument.
931 NULL = ctypes.POINTER(ctypes.c_int)()
932 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
933 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
934 wintypes.BOOL)
935 SetConsoleCtrlHandler.restype = wintypes.BOOL
936
937 # Calling this with NULL and FALSE causes the calling process to
938 # handle CTRL+C, rather than ignore it. This property is inherited
939 # by subprocesses.
940 SetConsoleCtrlHandler(NULL, 0)
941
942 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
943
944 def test_CTRL_BREAK_EVENT(self):
945 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
946
947
Victor Stinnerbf9bcab2010-05-09 03:15:33 +0000948class MiscTests(unittest.TestCase):
Benjamin Peterson31191a92010-05-09 03:22:58 +0000949
950 @unittest.skipIf(os.name == "nt", "POSIX specific test")
Victor Stinnerbf9bcab2010-05-09 03:15:33 +0000951 def test_fsencode(self):
952 self.assertEquals(os.fsencode(b'ab\xff'), b'ab\xff')
953 self.assertEquals(os.fsencode('ab\uDCFF'), b'ab\xff')
954
955
Fred Drake2e2be372001-09-20 21:33:42 +0000956def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000957 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000958 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000959 StatAttributeTests,
960 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000961 WalkTests,
962 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000963 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000964 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000965 ExecTests,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000966 Win32ErrorTests,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000967 TestInvalidFD,
Martin v. Löwis011e8422009-05-05 04:43:17 +0000968 PosixUidGidTests,
Brian Curtineb24d742010-04-12 17:16:38 +0000969 Pep383Tests,
Victor Stinnerbf9bcab2010-05-09 03:15:33 +0000970 Win32KillTests,
971 MiscTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000972 )
Fred Drake2e2be372001-09-20 21:33:42 +0000973
974if __name__ == "__main__":
975 test_main()