blob: 1ffa7dafeb65edb72445ed5862714141a37d7871 [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
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +000016import mmap
Benjamin Peterson799bd802011-08-31 22:15:17 -040017import platform
18import re
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +000019import uuid
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000020import asyncore
21import asynchat
22import socket
Charles-François Natali7372b062012-02-05 15:15:38 +010023import itertools
24import stat
Brett Cannonefb00c02012-02-29 18:31:31 -050025import locale
26import codecs
Larry Hastingsa27b83a2013-08-08 00:19:50 -070027import decimal
28import fractions
Christian Heimes25827622013-10-12 01:27:08 +020029import pickle
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000030try:
31 import threading
32except ImportError:
33 threading = None
Antoine Pitrouec34ab52013-08-16 20:44:38 +020034try:
35 import resource
36except ImportError:
37 resource = None
Victor Stinner7ba6b0f2013-09-08 11:47:54 +020038try:
39 import fcntl
40except ImportError:
41 fcntl = None
Antoine Pitrouec34ab52013-08-16 20:44:38 +020042
Georg Brandl2daf6ae2012-02-20 19:54:16 +010043from test.script_helper import assert_python_ok
Fred Drake38c2ef02001-07-17 20:52:51 +000044
Victor Stinner034d0aa2012-06-05 01:22:15 +020045with warnings.catch_warnings():
46 warnings.simplefilter("ignore", DeprecationWarning)
47 os.stat_float_times(True)
Victor Stinner1aa54a42012-02-08 04:09:37 +010048st = os.stat(__file__)
49stat_supports_subsecond = (
50 # check if float and int timestamps are different
51 (st.st_atime != st[7])
52 or (st.st_mtime != st[8])
53 or (st.st_ctime != st[9]))
54
Mark Dickinson7cf03892010-04-16 13:45:35 +000055# Detect whether we're on a Linux system that uses the (now outdated
56# and unmaintained) linuxthreads threading library. There's an issue
57# when combining linuxthreads with a failed execv call: see
58# http://bugs.python.org/issue4970.
Victor Stinnerd5c355c2011-04-30 14:53:09 +020059if hasattr(sys, 'thread_info') and sys.thread_info.version:
60 USING_LINUXTHREADS = sys.thread_info.version.startswith("linuxthreads")
61else:
62 USING_LINUXTHREADS = False
Brian Curtineb24d742010-04-12 17:16:38 +000063
Stefan Krahebee49a2013-01-17 15:31:00 +010064# Issue #14110: Some tests fail on FreeBSD if the user is in the wheel group.
65HAVE_WHEEL_GROUP = sys.platform.startswith('freebsd') and os.getgid() == 0
66
Thomas Wouters0e3f5912006-08-11 14:57:12 +000067# Tests creating TESTFN
68class FileTests(unittest.TestCase):
69 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000070 if os.path.exists(support.TESTFN):
71 os.unlink(support.TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000072 tearDown = setUp
73
74 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000075 f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000076 os.close(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000077 self.assertTrue(os.access(support.TESTFN, os.W_OK))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000078
Christian Heimesfdab48e2008-01-20 09:06:41 +000079 def test_closerange(self):
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000080 first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
81 # We must allocate two consecutive file descriptors, otherwise
82 # it will mess up other file descriptors (perhaps even the three
83 # standard ones).
84 second = os.dup(first)
85 try:
86 retries = 0
87 while second != first + 1:
88 os.close(first)
89 retries += 1
90 if retries > 10:
91 # XXX test skipped
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000092 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000093 first, second = second, os.dup(second)
94 finally:
95 os.close(second)
Christian Heimesfdab48e2008-01-20 09:06:41 +000096 # close a fd that is open, and one that isn't
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000097 os.closerange(first, first + 2)
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000098 self.assertRaises(OSError, os.write, first, b"a")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000099
Benjamin Peterson1cc6df92010-06-30 17:39:45 +0000100 @support.cpython_only
Hirokazu Yamamoto4c19e6e2008-09-08 23:41:21 +0000101 def test_rename(self):
102 path = support.TESTFN
103 old = sys.getrefcount(path)
104 self.assertRaises(TypeError, os.rename, path, 0)
105 new = sys.getrefcount(path)
106 self.assertEqual(old, new)
107
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000108 def test_read(self):
109 with open(support.TESTFN, "w+b") as fobj:
110 fobj.write(b"spam")
111 fobj.flush()
112 fd = fobj.fileno()
113 os.lseek(fd, 0, 0)
114 s = os.read(fd, 4)
115 self.assertEqual(type(s), bytes)
116 self.assertEqual(s, b"spam")
117
118 def test_write(self):
119 # os.write() accepts bytes- and buffer-like objects but not strings
120 fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY)
121 self.assertRaises(TypeError, os.write, fd, "beans")
122 os.write(fd, b"bacon\n")
123 os.write(fd, bytearray(b"eggs\n"))
124 os.write(fd, memoryview(b"spam\n"))
125 os.close(fd)
126 with open(support.TESTFN, "rb") as fobj:
Antoine Pitroud62269f2008-09-15 23:54:52 +0000127 self.assertEqual(fobj.read().splitlines(),
128 [b"bacon", b"eggs", b"spam"])
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000129
Victor Stinnere0daff12011-03-20 23:36:35 +0100130 def write_windows_console(self, *args):
131 retcode = subprocess.call(args,
132 # use a new console to not flood the test output
133 creationflags=subprocess.CREATE_NEW_CONSOLE,
134 # use a shell to hide the console window (SW_HIDE)
135 shell=True)
136 self.assertEqual(retcode, 0)
137
138 @unittest.skipUnless(sys.platform == 'win32',
139 'test specific to the Windows console')
140 def test_write_windows_console(self):
141 # Issue #11395: the Windows console returns an error (12: not enough
142 # space error) on writing into stdout if stdout mode is binary and the
143 # length is greater than 66,000 bytes (or less, depending on heap
144 # usage).
145 code = "print('x' * 100000)"
146 self.write_windows_console(sys.executable, "-c", code)
147 self.write_windows_console(sys.executable, "-u", "-c", code)
148
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000149 def fdopen_helper(self, *args):
150 fd = os.open(support.TESTFN, os.O_RDONLY)
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200151 f = os.fdopen(fd, *args)
152 f.close()
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000153
154 def test_fdopen(self):
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200155 fd = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
156 os.close(fd)
157
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000158 self.fdopen_helper()
159 self.fdopen_helper('r')
160 self.fdopen_helper('r', 100)
161
Antoine Pitrouf3b2d882012-01-30 22:08:52 +0100162 def test_replace(self):
163 TESTFN2 = support.TESTFN + ".2"
164 with open(support.TESTFN, 'w') as f:
165 f.write("1")
166 with open(TESTFN2, 'w') as f:
167 f.write("2")
168 self.addCleanup(os.unlink, TESTFN2)
169 os.replace(support.TESTFN, TESTFN2)
170 self.assertRaises(FileNotFoundError, os.stat, support.TESTFN)
171 with open(TESTFN2, 'r') as f:
172 self.assertEqual(f.read(), "1")
173
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200174
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000175# Test attributes on return values from os.*stat* family.
176class StatAttributeTests(unittest.TestCase):
177 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000178 os.mkdir(support.TESTFN)
179 self.fname = os.path.join(support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000180 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +0000181 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000182 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000183
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000184 def tearDown(self):
185 os.unlink(self.fname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000186 os.rmdir(support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000187
Serhiy Storchaka43767632013-11-03 21:31:38 +0200188 @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
Antoine Pitrou38425292010-09-21 18:19:07 +0000189 def check_stat_attributes(self, fname):
Antoine Pitrou38425292010-09-21 18:19:07 +0000190 result = os.stat(fname)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000191
192 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000193 self.assertEqual(result[stat.ST_SIZE], 3)
194 self.assertEqual(result.st_size, 3)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000195
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000196 # Make sure all the attributes are there
197 members = dir(result)
198 for name in dir(stat):
199 if name[:3] == 'ST_':
200 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000201 if name.endswith("TIME"):
202 def trunc(x): return int(x)
203 else:
204 def trunc(x): return x
Ezio Melottib3aedd42010-11-20 19:04:17 +0000205 self.assertEqual(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000206 result[getattr(stat, name)])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000207 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000208
Larry Hastings6fe20b32012-04-19 15:07:49 -0700209 # Make sure that the st_?time and st_?time_ns fields roughly agree
Larry Hastings76ad59b2012-05-03 00:30:07 -0700210 # (they should always agree up to around tens-of-microseconds)
Larry Hastings6fe20b32012-04-19 15:07:49 -0700211 for name in 'st_atime st_mtime st_ctime'.split():
212 floaty = int(getattr(result, name) * 100000)
213 nanosecondy = getattr(result, name + "_ns") // 10000
Larry Hastings76ad59b2012-05-03 00:30:07 -0700214 self.assertAlmostEqual(floaty, nanosecondy, delta=2)
Larry Hastings6fe20b32012-04-19 15:07:49 -0700215
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000216 try:
217 result[200]
Andrew Svetlov737fb892012-12-18 21:14:22 +0200218 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000219 except IndexError:
220 pass
221
222 # Make sure that assignment fails
223 try:
224 result.st_mode = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200225 self.fail("No exception raised")
Collin Winter42dae6a2007-03-28 21:44:53 +0000226 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000227 pass
228
229 try:
230 result.st_rdev = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200231 self.fail("No exception raised")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000232 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000233 pass
234
235 try:
236 result.parrot = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200237 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000238 except AttributeError:
239 pass
240
241 # Use the stat_result constructor with a too-short tuple.
242 try:
243 result2 = os.stat_result((10,))
Andrew Svetlov737fb892012-12-18 21:14:22 +0200244 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000245 except TypeError:
246 pass
247
Ezio Melotti42da6632011-03-15 05:18:48 +0200248 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000249 try:
250 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
251 except TypeError:
252 pass
253
Antoine Pitrou38425292010-09-21 18:19:07 +0000254 def test_stat_attributes(self):
255 self.check_stat_attributes(self.fname)
256
257 def test_stat_attributes_bytes(self):
258 try:
259 fname = self.fname.encode(sys.getfilesystemencoding())
260 except UnicodeEncodeError:
261 self.skipTest("cannot encode %a for the filesystem" % self.fname)
Victor Stinner1ab6c2d2011-11-15 22:27:41 +0100262 with warnings.catch_warnings():
263 warnings.simplefilter("ignore", DeprecationWarning)
264 self.check_stat_attributes(fname)
Tim Peterse0c446b2001-10-18 21:57:37 +0000265
Christian Heimes25827622013-10-12 01:27:08 +0200266 def test_stat_result_pickle(self):
267 result = os.stat(self.fname)
268 p = pickle.dumps(result)
269 self.assertIn(b'\x03cos\nstat_result\n', p)
270 unpickled = pickle.loads(p)
271 self.assertEqual(result, unpickled)
272
Serhiy Storchaka43767632013-11-03 21:31:38 +0200273 @unittest.skipUnless(hasattr(os, 'statvfs'), 'test needs os.statvfs()')
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000274 def test_statvfs_attributes(self):
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000275 try:
276 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000277 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000278 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000279 if e.errno == errno.ENOSYS:
Victor Stinner370cb252013-10-12 01:33:54 +0200280 self.skipTest('os.statvfs() failed with ENOSYS')
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000281
282 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000283 self.assertEqual(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000284
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000285 # Make sure all the attributes are there.
286 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
287 'ffree', 'favail', 'flag', 'namemax')
288 for value, member in enumerate(members):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000289 self.assertEqual(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000290
291 # Make sure that assignment really fails
292 try:
293 result.f_bfree = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200294 self.fail("No exception raised")
Collin Winter42dae6a2007-03-28 21:44:53 +0000295 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000296 pass
297
298 try:
299 result.parrot = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200300 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000301 except AttributeError:
302 pass
303
304 # Use the constructor with a too-short tuple.
305 try:
306 result2 = os.statvfs_result((10,))
Andrew Svetlov737fb892012-12-18 21:14:22 +0200307 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000308 except TypeError:
309 pass
310
Ezio Melotti42da6632011-03-15 05:18:48 +0200311 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000312 try:
313 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
314 except TypeError:
315 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000316
Christian Heimes25827622013-10-12 01:27:08 +0200317 @unittest.skipUnless(hasattr(os, 'statvfs'),
318 "need os.statvfs()")
319 def test_statvfs_result_pickle(self):
320 try:
321 result = os.statvfs(self.fname)
322 except OSError as e:
323 # On AtheOS, glibc always returns ENOSYS
324 if e.errno == errno.ENOSYS:
Victor Stinner370cb252013-10-12 01:33:54 +0200325 self.skipTest('os.statvfs() failed with ENOSYS')
326
Christian Heimes25827622013-10-12 01:27:08 +0200327 p = pickle.dumps(result)
328 self.assertIn(b'\x03cos\nstatvfs_result\n', p)
329 unpickled = pickle.loads(p)
330 self.assertEqual(result, unpickled)
331
Thomas Wouters89f507f2006-12-13 04:49:30 +0000332 def test_utime_dir(self):
333 delta = 1000000
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000334 st = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000335 # round to int, because some systems may support sub-second
336 # time stamps in stat, but not in utime.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000337 os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
338 st2 = os.stat(support.TESTFN)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000339 self.assertEqual(st2.st_mtime, int(st.st_mtime-delta))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000340
Larry Hastings76ad59b2012-05-03 00:30:07 -0700341 def _test_utime(self, filename, attr, utime, delta):
Brian Curtin0277aa32011-11-06 13:50:15 -0600342 # Issue #13327 removed the requirement to pass None as the
Brian Curtin52fbea12011-11-06 13:41:17 -0600343 # second argument. Check that the previous methods of passing
344 # a time tuple or None work in addition to no argument.
Larry Hastings76ad59b2012-05-03 00:30:07 -0700345 st0 = os.stat(filename)
Brian Curtin52fbea12011-11-06 13:41:17 -0600346 # Doesn't set anything new, but sets the time tuple way
Larry Hastings76ad59b2012-05-03 00:30:07 -0700347 utime(filename, (attr(st0, "st_atime"), attr(st0, "st_mtime")))
348 # Setting the time to the time you just read, then reading again,
349 # should always return exactly the same times.
350 st1 = os.stat(filename)
351 self.assertEqual(attr(st0, "st_mtime"), attr(st1, "st_mtime"))
352 self.assertEqual(attr(st0, "st_atime"), attr(st1, "st_atime"))
Brian Curtin52fbea12011-11-06 13:41:17 -0600353 # Set to the current time in the old explicit way.
Larry Hastings76ad59b2012-05-03 00:30:07 -0700354 os.utime(filename, None)
Brian Curtin52fbea12011-11-06 13:41:17 -0600355 st2 = os.stat(support.TESTFN)
Larry Hastings76ad59b2012-05-03 00:30:07 -0700356 # Set to the current time in the new way
357 os.utime(filename)
358 st3 = os.stat(filename)
359 self.assertAlmostEqual(attr(st2, "st_mtime"), attr(st3, "st_mtime"), delta=delta)
360
361 def test_utime(self):
362 def utime(file, times):
363 return os.utime(file, times)
364 self._test_utime(self.fname, getattr, utime, 10)
365 self._test_utime(support.TESTFN, getattr, utime, 10)
366
367
368 def _test_utime_ns(self, set_times_ns, test_dir=True):
369 def getattr_ns(o, attr):
370 return getattr(o, attr + "_ns")
371 ten_s = 10 * 1000 * 1000 * 1000
372 self._test_utime(self.fname, getattr_ns, set_times_ns, ten_s)
373 if test_dir:
374 self._test_utime(support.TESTFN, getattr_ns, set_times_ns, ten_s)
375
376 def test_utime_ns(self):
377 def utime_ns(file, times):
378 return os.utime(file, ns=times)
379 self._test_utime_ns(utime_ns)
380
Larry Hastings9cf065c2012-06-22 16:30:09 -0700381 requires_utime_dir_fd = unittest.skipUnless(
382 os.utime in os.supports_dir_fd,
383 "dir_fd support for utime required for this test.")
384 requires_utime_fd = unittest.skipUnless(
385 os.utime in os.supports_fd,
386 "fd support for utime required for this test.")
387 requires_utime_nofollow_symlinks = unittest.skipUnless(
388 os.utime in os.supports_follow_symlinks,
389 "follow_symlinks support for utime required for this test.")
Larry Hastings76ad59b2012-05-03 00:30:07 -0700390
Larry Hastings9cf065c2012-06-22 16:30:09 -0700391 @requires_utime_nofollow_symlinks
Larry Hastings76ad59b2012-05-03 00:30:07 -0700392 def test_lutimes_ns(self):
393 def lutimes_ns(file, times):
Larry Hastings9cf065c2012-06-22 16:30:09 -0700394 return os.utime(file, ns=times, follow_symlinks=False)
Larry Hastings76ad59b2012-05-03 00:30:07 -0700395 self._test_utime_ns(lutimes_ns)
396
Larry Hastings9cf065c2012-06-22 16:30:09 -0700397 @requires_utime_fd
Larry Hastings76ad59b2012-05-03 00:30:07 -0700398 def test_futimes_ns(self):
399 def futimes_ns(file, times):
400 with open(file, "wb") as f:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700401 os.utime(f.fileno(), ns=times)
Larry Hastings76ad59b2012-05-03 00:30:07 -0700402 self._test_utime_ns(futimes_ns, test_dir=False)
403
404 def _utime_invalid_arguments(self, name, arg):
Larry Hastings9cf065c2012-06-22 16:30:09 -0700405 with self.assertRaises(ValueError):
Larry Hastings76ad59b2012-05-03 00:30:07 -0700406 getattr(os, name)(arg, (5, 5), ns=(5, 5))
407
408 def test_utime_invalid_arguments(self):
409 self._utime_invalid_arguments('utime', self.fname)
410
Brian Curtin52fbea12011-11-06 13:41:17 -0600411
Victor Stinner1aa54a42012-02-08 04:09:37 +0100412 @unittest.skipUnless(stat_supports_subsecond,
413 "os.stat() doesn't has a subsecond resolution")
Victor Stinnera2f7c002012-02-08 03:36:25 +0100414 def _test_utime_subsecond(self, set_time_func):
Victor Stinnerbe557de2012-02-08 03:01:11 +0100415 asec, amsec = 1, 901
416 atime = asec + amsec * 1e-3
Victor Stinnera2f7c002012-02-08 03:36:25 +0100417 msec, mmsec = 2, 901
Victor Stinnerbe557de2012-02-08 03:01:11 +0100418 mtime = msec + mmsec * 1e-3
419 filename = self.fname
Victor Stinnera2f7c002012-02-08 03:36:25 +0100420 os.utime(filename, (0, 0))
421 set_time_func(filename, atime, mtime)
Victor Stinner034d0aa2012-06-05 01:22:15 +0200422 with warnings.catch_warnings():
423 warnings.simplefilter("ignore", DeprecationWarning)
424 os.stat_float_times(True)
Victor Stinnera2f7c002012-02-08 03:36:25 +0100425 st = os.stat(filename)
426 self.assertAlmostEqual(st.st_atime, atime, places=3)
427 self.assertAlmostEqual(st.st_mtime, mtime, places=3)
Victor Stinnerbe557de2012-02-08 03:01:11 +0100428
Victor Stinnera2f7c002012-02-08 03:36:25 +0100429 def test_utime_subsecond(self):
430 def set_time(filename, atime, mtime):
431 os.utime(filename, (atime, mtime))
432 self._test_utime_subsecond(set_time)
433
Larry Hastings9cf065c2012-06-22 16:30:09 -0700434 @requires_utime_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100435 def test_futimes_subsecond(self):
436 def set_time(filename, atime, mtime):
437 with open(filename, "wb") as f:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700438 os.utime(f.fileno(), times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100439 self._test_utime_subsecond(set_time)
440
Larry Hastings9cf065c2012-06-22 16:30:09 -0700441 @requires_utime_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100442 def test_futimens_subsecond(self):
443 def set_time(filename, atime, mtime):
444 with open(filename, "wb") as f:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700445 os.utime(f.fileno(), times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100446 self._test_utime_subsecond(set_time)
447
Larry Hastings9cf065c2012-06-22 16:30:09 -0700448 @requires_utime_dir_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100449 def test_futimesat_subsecond(self):
450 def set_time(filename, atime, mtime):
451 dirname = os.path.dirname(filename)
452 dirfd = os.open(dirname, os.O_RDONLY)
453 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700454 os.utime(os.path.basename(filename), dir_fd=dirfd,
455 times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100456 finally:
457 os.close(dirfd)
458 self._test_utime_subsecond(set_time)
459
Larry Hastings9cf065c2012-06-22 16:30:09 -0700460 @requires_utime_nofollow_symlinks
Victor Stinnera2f7c002012-02-08 03:36:25 +0100461 def test_lutimes_subsecond(self):
462 def set_time(filename, atime, mtime):
Larry Hastings9cf065c2012-06-22 16:30:09 -0700463 os.utime(filename, (atime, mtime), follow_symlinks=False)
Victor Stinnera2f7c002012-02-08 03:36:25 +0100464 self._test_utime_subsecond(set_time)
465
Larry Hastings9cf065c2012-06-22 16:30:09 -0700466 @requires_utime_dir_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100467 def test_utimensat_subsecond(self):
468 def set_time(filename, atime, mtime):
469 dirname = os.path.dirname(filename)
470 dirfd = os.open(dirname, os.O_RDONLY)
471 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700472 os.utime(os.path.basename(filename), dir_fd=dirfd,
473 times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100474 finally:
475 os.close(dirfd)
476 self._test_utime_subsecond(set_time)
Victor Stinnerbe557de2012-02-08 03:01:11 +0100477
Serhiy Storchaka43767632013-11-03 21:31:38 +0200478 # Restrict tests to Win32, since there is no guarantee other
Thomas Wouters89f507f2006-12-13 04:49:30 +0000479 # systems support centiseconds
Serhiy Storchaka43767632013-11-03 21:31:38 +0200480 def get_file_system(path):
481 if sys.platform == 'win32':
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000482 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000483 import ctypes
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000484 kernel32 = ctypes.windll.kernel32
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000485 buf = ctypes.create_unicode_buffer("", 100)
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000486 if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000487 return buf.value
488
Serhiy Storchaka43767632013-11-03 21:31:38 +0200489 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
490 @unittest.skipUnless(get_file_system(support.TESTFN) == "NTFS",
491 "requires NTFS")
492 def test_1565150(self):
493 t1 = 1159195039.25
494 os.utime(self.fname, (t1, t1))
495 self.assertEqual(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000496
Serhiy Storchaka43767632013-11-03 21:31:38 +0200497 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
498 @unittest.skipUnless(get_file_system(support.TESTFN) == "NTFS",
499 "requires NTFS")
500 def test_large_time(self):
501 t1 = 5000000000 # some day in 2128
502 os.utime(self.fname, (t1, t1))
503 self.assertEqual(os.stat(self.fname).st_mtime, t1)
Amaury Forgeot d'Arca251a852011-01-03 00:19:11 +0000504
Serhiy Storchaka43767632013-11-03 21:31:38 +0200505 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
506 def test_1686475(self):
507 # Verify that an open file can be stat'ed
508 try:
509 os.stat(r"c:\pagefile.sys")
510 except FileNotFoundError:
511 pass # file does not exist; cannot run test
512 except OSError as e:
513 self.fail("Could not stat pagefile.sys")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000514
Serhiy Storchaka43767632013-11-03 21:31:38 +0200515 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
516 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
517 def test_15261(self):
518 # Verify that stat'ing a closed fd does not cause crash
519 r, w = os.pipe()
520 try:
521 os.stat(r) # should not raise error
522 finally:
523 os.close(r)
524 os.close(w)
525 with self.assertRaises(OSError) as ctx:
526 os.stat(r)
527 self.assertEqual(ctx.exception.errno, errno.EBADF)
Richard Oudkerk2240ac12012-07-06 12:05:32 +0100528
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000529from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000530
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000531class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000532 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000533 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000534
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000535 def setUp(self):
536 self.__save = dict(os.environ)
Victor Stinnerb745a742010-05-18 17:17:23 +0000537 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000538 self.__saveb = dict(os.environb)
Christian Heimes90333392007-11-01 19:08:42 +0000539 for key, value in self._reference().items():
540 os.environ[key] = value
541
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000542 def tearDown(self):
543 os.environ.clear()
544 os.environ.update(self.__save)
Victor Stinnerb745a742010-05-18 17:17:23 +0000545 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000546 os.environb.clear()
547 os.environb.update(self.__saveb)
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000548
Christian Heimes90333392007-11-01 19:08:42 +0000549 def _reference(self):
550 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
551
552 def _empty_mapping(self):
553 os.environ.clear()
554 return os.environ
555
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000556 # Bug 1110478
Ezio Melottic7e139b2012-09-26 20:01:34 +0300557 @unittest.skipUnless(os.path.exists('/bin/sh'), 'requires /bin/sh')
Martin v. Löwis5510f652005-02-17 21:23:20 +0000558 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000559 os.environ.clear()
Ezio Melottic7e139b2012-09-26 20:01:34 +0300560 os.environ.update(HELLO="World")
561 with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
562 value = popen.read().strip()
563 self.assertEqual(value, "World")
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000564
Ezio Melottic7e139b2012-09-26 20:01:34 +0300565 @unittest.skipUnless(os.path.exists('/bin/sh'), 'requires /bin/sh')
Christian Heimes1a13d592007-11-08 14:16:55 +0000566 def test_os_popen_iter(self):
Ezio Melottic7e139b2012-09-26 20:01:34 +0300567 with os.popen(
568 "/bin/sh -c 'echo \"line1\nline2\nline3\"'") as popen:
569 it = iter(popen)
570 self.assertEqual(next(it), "line1\n")
571 self.assertEqual(next(it), "line2\n")
572 self.assertEqual(next(it), "line3\n")
573 self.assertRaises(StopIteration, next, it)
Christian Heimes1a13d592007-11-08 14:16:55 +0000574
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000575 # Verify environ keys and values from the OS are of the
576 # correct str type.
577 def test_keyvalue_types(self):
578 for key, val in os.environ.items():
Ezio Melottib3aedd42010-11-20 19:04:17 +0000579 self.assertEqual(type(key), str)
580 self.assertEqual(type(val), str)
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000581
Christian Heimes90333392007-11-01 19:08:42 +0000582 def test_items(self):
583 for key, value in self._reference().items():
584 self.assertEqual(os.environ.get(key), value)
585
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000586 # Issue 7310
587 def test___repr__(self):
588 """Check that the repr() of os.environ looks like environ({...})."""
589 env = os.environ
Victor Stinner96f0de92010-07-29 00:29:00 +0000590 self.assertEqual(repr(env), 'environ({{{}}})'.format(', '.join(
591 '{!r}: {!r}'.format(key, value)
592 for key, value in env.items())))
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000593
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000594 def test_get_exec_path(self):
595 defpath_list = os.defpath.split(os.pathsep)
596 test_path = ['/monty', '/python', '', '/flying/circus']
597 test_env = {'PATH': os.pathsep.join(test_path)}
598
599 saved_environ = os.environ
600 try:
601 os.environ = dict(test_env)
602 # Test that defaulting to os.environ works.
603 self.assertSequenceEqual(test_path, os.get_exec_path())
604 self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
605 finally:
606 os.environ = saved_environ
607
608 # No PATH environment variable
609 self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
610 # Empty PATH environment variable
611 self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
612 # Supplied PATH environment variable
613 self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
614
Victor Stinnerb745a742010-05-18 17:17:23 +0000615 if os.supports_bytes_environ:
616 # env cannot contain 'PATH' and b'PATH' keys
Victor Stinner38430e22010-08-19 17:10:18 +0000617 try:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000618 # ignore BytesWarning warning
619 with warnings.catch_warnings(record=True):
620 mixed_env = {'PATH': '1', b'PATH': b'2'}
Victor Stinner38430e22010-08-19 17:10:18 +0000621 except BytesWarning:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000622 # mixed_env cannot be created with python -bb
Victor Stinner38430e22010-08-19 17:10:18 +0000623 pass
624 else:
625 self.assertRaises(ValueError, os.get_exec_path, mixed_env)
Victor Stinnerb745a742010-05-18 17:17:23 +0000626
627 # bytes key and/or value
628 self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}),
629 ['abc'])
630 self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}),
631 ['abc'])
632 self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}),
633 ['abc'])
634
635 @unittest.skipUnless(os.supports_bytes_environ,
636 "os.environb required for this test.")
Victor Stinner84ae1182010-05-06 22:05:07 +0000637 def test_environb(self):
638 # os.environ -> os.environb
639 value = 'euro\u20ac'
640 try:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000641 value_bytes = value.encode(sys.getfilesystemencoding(),
642 'surrogateescape')
Victor Stinner84ae1182010-05-06 22:05:07 +0000643 except UnicodeEncodeError:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000644 msg = "U+20AC character is not encodable to %s" % (
645 sys.getfilesystemencoding(),)
Benjamin Peterson932d3f42010-05-06 22:26:31 +0000646 self.skipTest(msg)
Victor Stinner84ae1182010-05-06 22:05:07 +0000647 os.environ['unicode'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000648 self.assertEqual(os.environ['unicode'], value)
649 self.assertEqual(os.environb[b'unicode'], value_bytes)
Victor Stinner84ae1182010-05-06 22:05:07 +0000650
651 # os.environb -> os.environ
652 value = b'\xff'
653 os.environb[b'bytes'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000654 self.assertEqual(os.environb[b'bytes'], value)
Victor Stinner84ae1182010-05-06 22:05:07 +0000655 value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000656 self.assertEqual(os.environ['bytes'], value_str)
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000657
Charles-François Natali2966f102011-11-26 11:32:46 +0100658 # On FreeBSD < 7 and OS X < 10.6, unsetenv() doesn't return a value (issue
659 # #13415).
660 @support.requires_freebsd_version(7)
661 @support.requires_mac_ver(10, 6)
Victor Stinner60b385e2011-11-22 22:01:28 +0100662 def test_unset_error(self):
663 if sys.platform == "win32":
664 # an environment variable is limited to 32,767 characters
665 key = 'x' * 50000
Victor Stinnerb3f82682011-11-22 22:30:19 +0100666 self.assertRaises(ValueError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100667 else:
668 # "=" is not allowed in a variable name
669 key = 'key='
Victor Stinnerb3f82682011-11-22 22:30:19 +0100670 self.assertRaises(OSError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100671
Victor Stinner6d101392013-04-14 16:35:04 +0200672 def test_key_type(self):
673 missing = 'missingkey'
674 self.assertNotIn(missing, os.environ)
675
Victor Stinner839e5ea2013-04-14 16:43:03 +0200676 with self.assertRaises(KeyError) as cm:
Victor Stinner6d101392013-04-14 16:35:04 +0200677 os.environ[missing]
Victor Stinner839e5ea2013-04-14 16:43:03 +0200678 self.assertIs(cm.exception.args[0], missing)
Victor Stinner0c2dd0c2013-08-23 19:19:15 +0200679 self.assertTrue(cm.exception.__suppress_context__)
Victor Stinner6d101392013-04-14 16:35:04 +0200680
Victor Stinner839e5ea2013-04-14 16:43:03 +0200681 with self.assertRaises(KeyError) as cm:
Victor Stinner6d101392013-04-14 16:35:04 +0200682 del os.environ[missing]
Victor Stinner839e5ea2013-04-14 16:43:03 +0200683 self.assertIs(cm.exception.args[0], missing)
Victor Stinner0c2dd0c2013-08-23 19:19:15 +0200684 self.assertTrue(cm.exception.__suppress_context__)
685
Victor Stinner6d101392013-04-14 16:35:04 +0200686
Tim Petersc4e09402003-04-25 07:11:48 +0000687class WalkTests(unittest.TestCase):
688 """Tests for os.walk()."""
689
Charles-François Natali7372b062012-02-05 15:15:38 +0100690 def setUp(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000691 import os
692 from os.path import join
693
694 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000695 # TESTFN/
696 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000697 # tmp1
698 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000699 # tmp2
700 # SUB11/ no kids
701 # SUB2/ a file kid and a dirsymlink kid
702 # tmp3
703 # link/ a symlink to TESTFN.2
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200704 # broken_link
Guido van Rossumd8faa362007-04-27 19:54:29 +0000705 # TEST2/
706 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000707 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000708 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000709 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000710 sub2_path = join(walk_path, "SUB2")
711 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000712 tmp2_path = join(sub1_path, "tmp2")
713 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000714 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000715 t2_path = join(support.TESTFN, "TEST2")
716 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200717 link_path = join(sub2_path, "link")
718 broken_link_path = join(sub2_path, "broken_link")
Tim Petersc4e09402003-04-25 07:11:48 +0000719
720 # Create stuff.
721 os.makedirs(sub11_path)
722 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000723 os.makedirs(t2_path)
724 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000725 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000726 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
727 f.close()
Brian Curtin3b4499c2010-12-28 14:31:47 +0000728 if support.can_symlink():
Jason R. Coombs3a092862013-05-27 23:21:28 -0400729 os.symlink(os.path.abspath(t2_path), link_path)
Jason R. Coombsb501b562013-05-27 23:52:43 -0400730 os.symlink('broken', broken_link_path, True)
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200731 sub2_tree = (sub2_path, ["link"], ["broken_link", "tmp3"])
Guido van Rossumd8faa362007-04-27 19:54:29 +0000732 else:
733 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000734
735 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000736 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000737 self.assertEqual(len(all), 4)
738 # We can't know which order SUB1 and SUB2 will appear in.
739 # Not flipped: TESTFN, SUB1, SUB11, SUB2
740 # flipped: TESTFN, SUB2, SUB1, SUB11
741 flipped = all[0][1][0] != "SUB1"
742 all[0][1].sort()
Hynek Schlawackc96f5a02012-05-15 17:55:38 +0200743 all[3 - 2 * flipped][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000744 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000745 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
746 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000747 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000748
749 # Prune the search.
750 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000751 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000752 all.append((root, dirs, files))
753 # Don't descend into SUB1.
754 if 'SUB1' in dirs:
755 # Note that this also mutates the dirs we appended to all!
756 dirs.remove('SUB1')
757 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000758 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Hynek Schlawack39bf90d2012-05-15 18:40:17 +0200759 all[1][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000760 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000761
762 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000763 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000764 self.assertEqual(len(all), 4)
765 # We can't know which order SUB1 and SUB2 will appear in.
766 # Not flipped: SUB11, SUB1, SUB2, TESTFN
767 # flipped: SUB2, SUB11, SUB1, TESTFN
768 flipped = all[3][1][0] != "SUB1"
769 all[3][1].sort()
Hynek Schlawack39bf90d2012-05-15 18:40:17 +0200770 all[2 - 2 * flipped][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000771 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000772 self.assertEqual(all[flipped], (sub11_path, [], []))
773 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000774 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000775
Brian Curtin3b4499c2010-12-28 14:31:47 +0000776 if support.can_symlink():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000777 # Walk, following symlinks.
778 for root, dirs, files in os.walk(walk_path, followlinks=True):
779 if root == link_path:
780 self.assertEqual(dirs, [])
781 self.assertEqual(files, ["tmp4"])
782 break
783 else:
784 self.fail("Didn't follow symlink with followlinks=True")
785
786 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000787 # Tear everything down. This is a decent use for bottom-up on
788 # Windows, which doesn't have a recursive delete command. The
789 # (not so) subtlety is that rmdir will fail unless the dir's
790 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000791 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000792 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000793 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000794 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000795 dirname = os.path.join(root, name)
796 if not os.path.islink(dirname):
797 os.rmdir(dirname)
798 else:
799 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000800 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000801
Charles-François Natali7372b062012-02-05 15:15:38 +0100802
803@unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
804class FwalkTests(WalkTests):
805 """Tests for os.fwalk()."""
806
Larry Hastingsc48fe982012-06-25 04:49:05 -0700807 def _compare_to_walk(self, walk_kwargs, fwalk_kwargs):
808 """
809 compare with walk() results.
810 """
Larry Hastingsb4038062012-07-15 10:57:38 -0700811 walk_kwargs = walk_kwargs.copy()
812 fwalk_kwargs = fwalk_kwargs.copy()
813 for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
814 walk_kwargs.update(topdown=topdown, followlinks=follow_symlinks)
815 fwalk_kwargs.update(topdown=topdown, follow_symlinks=follow_symlinks)
Larry Hastingsc48fe982012-06-25 04:49:05 -0700816
Charles-François Natali7372b062012-02-05 15:15:38 +0100817 expected = {}
Larry Hastingsc48fe982012-06-25 04:49:05 -0700818 for root, dirs, files in os.walk(**walk_kwargs):
Charles-François Natali7372b062012-02-05 15:15:38 +0100819 expected[root] = (set(dirs), set(files))
820
Larry Hastingsc48fe982012-06-25 04:49:05 -0700821 for root, dirs, files, rootfd in os.fwalk(**fwalk_kwargs):
Charles-François Natali7372b062012-02-05 15:15:38 +0100822 self.assertIn(root, expected)
823 self.assertEqual(expected[root], (set(dirs), set(files)))
824
Larry Hastingsc48fe982012-06-25 04:49:05 -0700825 def test_compare_to_walk(self):
826 kwargs = {'top': support.TESTFN}
827 self._compare_to_walk(kwargs, kwargs)
828
Charles-François Natali7372b062012-02-05 15:15:38 +0100829 def test_dir_fd(self):
Larry Hastingsc48fe982012-06-25 04:49:05 -0700830 try:
831 fd = os.open(".", os.O_RDONLY)
832 walk_kwargs = {'top': support.TESTFN}
833 fwalk_kwargs = walk_kwargs.copy()
834 fwalk_kwargs['dir_fd'] = fd
835 self._compare_to_walk(walk_kwargs, fwalk_kwargs)
836 finally:
837 os.close(fd)
838
839 def test_yields_correct_dir_fd(self):
Charles-François Natali7372b062012-02-05 15:15:38 +0100840 # check returned file descriptors
Larry Hastingsb4038062012-07-15 10:57:38 -0700841 for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
842 args = support.TESTFN, topdown, None
843 for root, dirs, files, rootfd in os.fwalk(*args, follow_symlinks=follow_symlinks):
Charles-François Natali7372b062012-02-05 15:15:38 +0100844 # check that the FD is valid
845 os.fstat(rootfd)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700846 # redundant check
847 os.stat(rootfd)
848 # check that listdir() returns consistent information
849 self.assertEqual(set(os.listdir(rootfd)), set(dirs) | set(files))
Charles-François Natali7372b062012-02-05 15:15:38 +0100850
851 def test_fd_leak(self):
852 # Since we're opening a lot of FDs, we must be careful to avoid leaks:
853 # we both check that calling fwalk() a large number of times doesn't
854 # yield EMFILE, and that the minimum allocated FD hasn't changed.
855 minfd = os.dup(1)
856 os.close(minfd)
857 for i in range(256):
858 for x in os.fwalk(support.TESTFN):
859 pass
860 newfd = os.dup(1)
861 self.addCleanup(os.close, newfd)
862 self.assertEqual(newfd, minfd)
863
864 def tearDown(self):
865 # cleanup
866 for root, dirs, files, rootfd in os.fwalk(support.TESTFN, topdown=False):
867 for name in files:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700868 os.unlink(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +0100869 for name in dirs:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700870 st = os.stat(name, dir_fd=rootfd, follow_symlinks=False)
Larry Hastingsb698d8e2012-06-23 16:55:07 -0700871 if stat.S_ISDIR(st.st_mode):
872 os.rmdir(name, dir_fd=rootfd)
873 else:
874 os.unlink(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +0100875 os.rmdir(support.TESTFN)
876
877
Guido van Rossume7ba4952007-06-06 23:52:48 +0000878class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000879 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000880 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000881
882 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000883 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000884 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
885 os.makedirs(path) # Should work
886 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
887 os.makedirs(path)
888
889 # Try paths with a '.' in them
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000890 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000891 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
892 os.makedirs(path)
893 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
894 'dir5', 'dir6')
895 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000896
Terry Reedy5a22b652010-12-02 07:05:56 +0000897 def test_exist_ok_existing_directory(self):
898 path = os.path.join(support.TESTFN, 'dir1')
899 mode = 0o777
900 old_mask = os.umask(0o022)
901 os.makedirs(path, mode)
902 self.assertRaises(OSError, os.makedirs, path, mode)
903 self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
904 self.assertRaises(OSError, os.makedirs, path, 0o776, exist_ok=True)
905 os.makedirs(path, mode=mode, exist_ok=True)
906 os.umask(old_mask)
907
Terry Jan Reedy4a0b6f72013-08-10 20:58:59 -0400908 @unittest.skipUnless(hasattr(os, 'chown'), 'test needs os.chown')
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700909 def test_chown_uid_gid_arguments_must_be_index(self):
910 stat = os.stat(support.TESTFN)
911 uid = stat.st_uid
912 gid = stat.st_gid
913 for value in (-1.0, -1j, decimal.Decimal(-1), fractions.Fraction(-2, 2)):
914 self.assertRaises(TypeError, os.chown, support.TESTFN, value, gid)
915 self.assertRaises(TypeError, os.chown, support.TESTFN, uid, value)
916 self.assertIsNone(os.chown(support.TESTFN, uid, gid))
917 self.assertIsNone(os.chown(support.TESTFN, -1, -1))
918
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700919 def test_exist_ok_s_isgid_directory(self):
920 path = os.path.join(support.TESTFN, 'dir1')
921 S_ISGID = stat.S_ISGID
922 mode = 0o777
923 old_mask = os.umask(0o022)
924 try:
925 existing_testfn_mode = stat.S_IMODE(
926 os.lstat(support.TESTFN).st_mode)
Ned Deilyc622f422012-08-08 20:57:24 -0700927 try:
928 os.chmod(support.TESTFN, existing_testfn_mode | S_ISGID)
Ned Deily3a2b97e2012-08-08 21:03:02 -0700929 except PermissionError:
Ned Deilyc622f422012-08-08 20:57:24 -0700930 raise unittest.SkipTest('Cannot set S_ISGID for dir.')
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700931 if (os.lstat(support.TESTFN).st_mode & S_ISGID != S_ISGID):
932 raise unittest.SkipTest('No support for S_ISGID dir mode.')
933 # The os should apply S_ISGID from the parent dir for us, but
934 # this test need not depend on that behavior. Be explicit.
935 os.makedirs(path, mode | S_ISGID)
936 # http://bugs.python.org/issue14992
937 # Should not fail when the bit is already set.
938 os.makedirs(path, mode, exist_ok=True)
939 # remove the bit.
940 os.chmod(path, stat.S_IMODE(os.lstat(path).st_mode) & ~S_ISGID)
941 with self.assertRaises(OSError):
942 # Should fail when the bit is not already set when demanded.
943 os.makedirs(path, mode | S_ISGID, exist_ok=True)
944 finally:
945 os.umask(old_mask)
Terry Reedy5a22b652010-12-02 07:05:56 +0000946
947 def test_exist_ok_existing_regular_file(self):
948 base = support.TESTFN
949 path = os.path.join(support.TESTFN, 'dir1')
950 f = open(path, 'w')
951 f.write('abc')
952 f.close()
953 self.assertRaises(OSError, os.makedirs, path)
954 self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
955 self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
956 os.remove(path)
957
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000958 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000959 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000960 'dir4', 'dir5', 'dir6')
961 # If the tests failed, the bottom-most directory ('../dir6')
962 # may not have been created, so we look for the outermost directory
963 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000964 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000965 path = os.path.dirname(path)
966
967 os.removedirs(path)
968
Andrew Svetlov405faed2012-12-25 12:18:09 +0200969
970class RemoveDirsTests(unittest.TestCase):
971 def setUp(self):
972 os.makedirs(support.TESTFN)
973
974 def tearDown(self):
975 support.rmtree(support.TESTFN)
976
977 def test_remove_all(self):
978 dira = os.path.join(support.TESTFN, 'dira')
979 os.mkdir(dira)
980 dirb = os.path.join(dira, 'dirb')
981 os.mkdir(dirb)
982 os.removedirs(dirb)
983 self.assertFalse(os.path.exists(dirb))
984 self.assertFalse(os.path.exists(dira))
985 self.assertFalse(os.path.exists(support.TESTFN))
986
987 def test_remove_partial(self):
988 dira = os.path.join(support.TESTFN, 'dira')
989 os.mkdir(dira)
990 dirb = os.path.join(dira, 'dirb')
991 os.mkdir(dirb)
992 with open(os.path.join(dira, 'file.txt'), 'w') as f:
993 f.write('text')
994 os.removedirs(dirb)
995 self.assertFalse(os.path.exists(dirb))
996 self.assertTrue(os.path.exists(dira))
997 self.assertTrue(os.path.exists(support.TESTFN))
998
999 def test_remove_nothing(self):
1000 dira = os.path.join(support.TESTFN, 'dira')
1001 os.mkdir(dira)
1002 dirb = os.path.join(dira, 'dirb')
1003 os.mkdir(dirb)
1004 with open(os.path.join(dirb, 'file.txt'), 'w') as f:
1005 f.write('text')
1006 with self.assertRaises(OSError):
1007 os.removedirs(dirb)
1008 self.assertTrue(os.path.exists(dirb))
1009 self.assertTrue(os.path.exists(dira))
1010 self.assertTrue(os.path.exists(support.TESTFN))
1011
1012
Guido van Rossume7ba4952007-06-06 23:52:48 +00001013class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +00001014 def test_devnull(self):
Victor Stinnera6d2c762011-06-30 18:20:11 +02001015 with open(os.devnull, 'wb') as f:
1016 f.write(b'hello')
1017 f.close()
1018 with open(os.devnull, 'rb') as f:
1019 self.assertEqual(f.read(), b'')
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00001020
Andrew Svetlov405faed2012-12-25 12:18:09 +02001021
Guido van Rossume7ba4952007-06-06 23:52:48 +00001022class URandomTests(unittest.TestCase):
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001023 def test_urandom_length(self):
1024 self.assertEqual(len(os.urandom(0)), 0)
1025 self.assertEqual(len(os.urandom(1)), 1)
1026 self.assertEqual(len(os.urandom(10)), 10)
1027 self.assertEqual(len(os.urandom(100)), 100)
1028 self.assertEqual(len(os.urandom(1000)), 1000)
1029
1030 def test_urandom_value(self):
1031 data1 = os.urandom(16)
1032 data2 = os.urandom(16)
1033 self.assertNotEqual(data1, data2)
1034
1035 def get_urandom_subprocess(self, count):
1036 code = '\n'.join((
1037 'import os, sys',
1038 'data = os.urandom(%s)' % count,
1039 'sys.stdout.buffer.write(data)',
1040 'sys.stdout.buffer.flush()'))
1041 out = assert_python_ok('-c', code)
1042 stdout = out[1]
1043 self.assertEqual(len(stdout), 16)
1044 return stdout
1045
1046 def test_urandom_subprocess(self):
1047 data1 = self.get_urandom_subprocess(16)
1048 data2 = self.get_urandom_subprocess(16)
1049 self.assertNotEqual(data1, data2)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +00001050
Antoine Pitrouec34ab52013-08-16 20:44:38 +02001051 @unittest.skipUnless(resource, "test requires the resource module")
1052 def test_urandom_failure(self):
Antoine Pitroueba25ba2013-08-24 20:52:27 +02001053 # Check urandom() failing when it is not able to open /dev/random.
1054 # We spawn a new process to make the test more robust (if getrlimit()
1055 # failed to restore the file descriptor limit after this, the whole
1056 # test suite would crash; this actually happened on the OS X Tiger
1057 # buildbot).
1058 code = """if 1:
1059 import errno
1060 import os
1061 import resource
1062
1063 soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
1064 resource.setrlimit(resource.RLIMIT_NOFILE, (1, hard_limit))
1065 try:
Antoine Pitrouec34ab52013-08-16 20:44:38 +02001066 os.urandom(16)
Antoine Pitroueba25ba2013-08-24 20:52:27 +02001067 except OSError as e:
1068 assert e.errno == errno.EMFILE, e.errno
1069 else:
1070 raise AssertionError("OSError not raised")
1071 """
1072 assert_python_ok('-c', code)
Antoine Pitrouec34ab52013-08-16 20:44:38 +02001073
1074
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001075@contextlib.contextmanager
1076def _execvpe_mockup(defpath=None):
1077 """
1078 Stubs out execv and execve functions when used as context manager.
1079 Records exec calls. The mock execv and execve functions always raise an
1080 exception as they would normally never return.
1081 """
1082 # A list of tuples containing (function name, first arg, args)
1083 # of calls to execv or execve that have been made.
1084 calls = []
1085
1086 def mock_execv(name, *args):
1087 calls.append(('execv', name, args))
1088 raise RuntimeError("execv called")
1089
1090 def mock_execve(name, *args):
1091 calls.append(('execve', name, args))
1092 raise OSError(errno.ENOTDIR, "execve called")
1093
1094 try:
1095 orig_execv = os.execv
1096 orig_execve = os.execve
1097 orig_defpath = os.defpath
1098 os.execv = mock_execv
1099 os.execve = mock_execve
1100 if defpath is not None:
1101 os.defpath = defpath
1102 yield calls
1103 finally:
1104 os.execv = orig_execv
1105 os.execve = orig_execve
1106 os.defpath = orig_defpath
1107
Guido van Rossume7ba4952007-06-06 23:52:48 +00001108class ExecTests(unittest.TestCase):
Mark Dickinson7cf03892010-04-16 13:45:35 +00001109 @unittest.skipIf(USING_LINUXTHREADS,
1110 "avoid triggering a linuxthreads bug: see issue #4970")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001111 def test_execvpe_with_bad_program(self):
Mark Dickinson7cf03892010-04-16 13:45:35 +00001112 self.assertRaises(OSError, os.execvpe, 'no such app-',
1113 ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001114
Thomas Heller6790d602007-08-30 17:15:14 +00001115 def test_execvpe_with_bad_arglist(self):
1116 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
1117
Gregory P. Smith4ae37772010-05-08 18:05:46 +00001118 @unittest.skipUnless(hasattr(os, '_execvpe'),
1119 "No internal os._execvpe function to test.")
Victor Stinnerb745a742010-05-18 17:17:23 +00001120 def _test_internal_execvpe(self, test_type):
1121 program_path = os.sep + 'absolutepath'
1122 if test_type is bytes:
1123 program = b'executable'
1124 fullpath = os.path.join(os.fsencode(program_path), program)
1125 native_fullpath = fullpath
1126 arguments = [b'progname', 'arg1', 'arg2']
1127 else:
1128 program = 'executable'
1129 arguments = ['progname', 'arg1', 'arg2']
1130 fullpath = os.path.join(program_path, program)
1131 if os.name != "nt":
1132 native_fullpath = os.fsencode(fullpath)
1133 else:
1134 native_fullpath = fullpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001135 env = {'spam': 'beans'}
1136
Victor Stinnerb745a742010-05-18 17:17:23 +00001137 # test os._execvpe() with an absolute path
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001138 with _execvpe_mockup() as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +00001139 self.assertRaises(RuntimeError,
1140 os._execvpe, fullpath, arguments)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001141 self.assertEqual(len(calls), 1)
1142 self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))
1143
Victor Stinnerb745a742010-05-18 17:17:23 +00001144 # test os._execvpe() with a relative path:
1145 # os.get_exec_path() returns defpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001146 with _execvpe_mockup(defpath=program_path) as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +00001147 self.assertRaises(OSError,
1148 os._execvpe, program, arguments, env=env)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001149 self.assertEqual(len(calls), 1)
Victor Stinnerb745a742010-05-18 17:17:23 +00001150 self.assertSequenceEqual(calls[0],
1151 ('execve', native_fullpath, (arguments, env)))
1152
1153 # test os._execvpe() with a relative path:
1154 # os.get_exec_path() reads the 'PATH' variable
1155 with _execvpe_mockup() as calls:
1156 env_path = env.copy()
Victor Stinner38430e22010-08-19 17:10:18 +00001157 if test_type is bytes:
1158 env_path[b'PATH'] = program_path
1159 else:
1160 env_path['PATH'] = program_path
Victor Stinnerb745a742010-05-18 17:17:23 +00001161 self.assertRaises(OSError,
1162 os._execvpe, program, arguments, env=env_path)
1163 self.assertEqual(len(calls), 1)
1164 self.assertSequenceEqual(calls[0],
1165 ('execve', native_fullpath, (arguments, env_path)))
1166
1167 def test_internal_execvpe_str(self):
1168 self._test_internal_execvpe(str)
1169 if os.name != "nt":
1170 self._test_internal_execvpe(bytes)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001171
Gregory P. Smith4ae37772010-05-08 18:05:46 +00001172
Serhiy Storchaka43767632013-11-03 21:31:38 +02001173@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001174class Win32ErrorTests(unittest.TestCase):
1175 def test_rename(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001176 self.assertRaises(OSError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001177
1178 def test_remove(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001179 self.assertRaises(OSError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001180
1181 def test_chdir(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001182 self.assertRaises(OSError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001183
1184 def test_mkdir(self):
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +00001185 f = open(support.TESTFN, "w")
Benjamin Petersonf91df042009-02-13 02:50:59 +00001186 try:
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001187 self.assertRaises(OSError, os.mkdir, support.TESTFN)
Benjamin Petersonf91df042009-02-13 02:50:59 +00001188 finally:
1189 f.close()
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +00001190 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001191
1192 def test_utime(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001193 self.assertRaises(OSError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001194
Thomas Wouters477c8d52006-05-27 19:21:47 +00001195 def test_chmod(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001196 self.assertRaises(OSError, os.chmod, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001197
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001198class TestInvalidFD(unittest.TestCase):
Benjamin Peterson05e782f2009-01-19 15:15:02 +00001199 singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001200 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
1201 #singles.append("close")
1202 #We omit close because it doesn'r raise an exception on some platforms
1203 def get_single(f):
1204 def helper(self):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001205 if hasattr(os, f):
1206 self.check(getattr(os, f))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001207 return helper
1208 for f in singles:
1209 locals()["test_"+f] = get_single(f)
1210
Benjamin Peterson7522c742009-01-19 21:00:09 +00001211 def check(self, f, *args):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001212 try:
1213 f(support.make_bad_fd(), *args)
1214 except OSError as e:
1215 self.assertEqual(e.errno, errno.EBADF)
1216 else:
1217 self.fail("%r didn't raise a OSError with a bad file descriptor"
1218 % f)
Benjamin Peterson7522c742009-01-19 21:00:09 +00001219
Serhiy Storchaka43767632013-11-03 21:31:38 +02001220 @unittest.skipUnless(hasattr(os, 'isatty'), 'test needs os.isatty()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001221 def test_isatty(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001222 self.assertEqual(os.isatty(support.make_bad_fd()), False)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001223
Serhiy Storchaka43767632013-11-03 21:31:38 +02001224 @unittest.skipUnless(hasattr(os, 'closerange'), 'test needs os.closerange()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001225 def test_closerange(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001226 fd = support.make_bad_fd()
1227 # Make sure none of the descriptors we are about to close are
1228 # currently valid (issue 6542).
1229 for i in range(10):
1230 try: os.fstat(fd+i)
1231 except OSError:
1232 pass
1233 else:
1234 break
1235 if i < 2:
1236 raise unittest.SkipTest(
1237 "Unable to acquire a range of invalid file descriptors")
1238 self.assertEqual(os.closerange(fd, fd + i-1), None)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001239
Serhiy Storchaka43767632013-11-03 21:31:38 +02001240 @unittest.skipUnless(hasattr(os, 'dup2'), 'test needs os.dup2()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001241 def test_dup2(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001242 self.check(os.dup2, 20)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001243
Serhiy Storchaka43767632013-11-03 21:31:38 +02001244 @unittest.skipUnless(hasattr(os, 'fchmod'), 'test needs os.fchmod()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001245 def test_fchmod(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001246 self.check(os.fchmod, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001247
Serhiy Storchaka43767632013-11-03 21:31:38 +02001248 @unittest.skipUnless(hasattr(os, 'fchown'), 'test needs os.fchown()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001249 def test_fchown(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001250 self.check(os.fchown, -1, -1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001251
Serhiy Storchaka43767632013-11-03 21:31:38 +02001252 @unittest.skipUnless(hasattr(os, 'fpathconf'), 'test needs os.fpathconf()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001253 def test_fpathconf(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001254 self.check(os.pathconf, "PC_NAME_MAX")
1255 self.check(os.fpathconf, "PC_NAME_MAX")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001256
Serhiy Storchaka43767632013-11-03 21:31:38 +02001257 @unittest.skipUnless(hasattr(os, 'ftruncate'), 'test needs os.ftruncate()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001258 def test_ftruncate(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001259 self.check(os.truncate, 0)
1260 self.check(os.ftruncate, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001261
Serhiy Storchaka43767632013-11-03 21:31:38 +02001262 @unittest.skipUnless(hasattr(os, 'lseek'), 'test needs os.lseek()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001263 def test_lseek(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001264 self.check(os.lseek, 0, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001265
Serhiy Storchaka43767632013-11-03 21:31:38 +02001266 @unittest.skipUnless(hasattr(os, 'read'), 'test needs os.read()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001267 def test_read(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001268 self.check(os.read, 1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001269
Serhiy Storchaka43767632013-11-03 21:31:38 +02001270 @unittest.skipUnless(hasattr(os, 'tcsetpgrp'), 'test needs os.tcsetpgrp()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001271 def test_tcsetpgrpt(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001272 self.check(os.tcsetpgrp, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001273
Serhiy Storchaka43767632013-11-03 21:31:38 +02001274 @unittest.skipUnless(hasattr(os, 'write'), 'test needs os.write()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001275 def test_write(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001276 self.check(os.write, b" ")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001277
Brian Curtin1b9df392010-11-24 20:24:31 +00001278
1279class LinkTests(unittest.TestCase):
1280 def setUp(self):
1281 self.file1 = support.TESTFN
1282 self.file2 = os.path.join(support.TESTFN + "2")
1283
Brian Curtinc0abc4e2010-11-30 23:46:54 +00001284 def tearDown(self):
Brian Curtin1b9df392010-11-24 20:24:31 +00001285 for file in (self.file1, self.file2):
1286 if os.path.exists(file):
1287 os.unlink(file)
1288
Brian Curtin1b9df392010-11-24 20:24:31 +00001289 def _test_link(self, file1, file2):
1290 with open(file1, "w") as f1:
1291 f1.write("test")
1292
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001293 with warnings.catch_warnings():
1294 warnings.simplefilter("ignore", DeprecationWarning)
1295 os.link(file1, file2)
Brian Curtin1b9df392010-11-24 20:24:31 +00001296 with open(file1, "r") as f1, open(file2, "r") as f2:
1297 self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
1298
1299 def test_link(self):
1300 self._test_link(self.file1, self.file2)
1301
1302 def test_link_bytes(self):
1303 self._test_link(bytes(self.file1, sys.getfilesystemencoding()),
1304 bytes(self.file2, sys.getfilesystemencoding()))
1305
Brian Curtinf498b752010-11-30 15:54:04 +00001306 def test_unicode_name(self):
Brian Curtin43f0c272010-11-30 15:40:04 +00001307 try:
Brian Curtinf498b752010-11-30 15:54:04 +00001308 os.fsencode("\xf1")
Brian Curtin43f0c272010-11-30 15:40:04 +00001309 except UnicodeError:
1310 raise unittest.SkipTest("Unable to encode for this platform.")
1311
Brian Curtinf498b752010-11-30 15:54:04 +00001312 self.file1 += "\xf1"
Brian Curtinfc889c42010-11-28 23:59:46 +00001313 self.file2 = self.file1 + "2"
1314 self._test_link(self.file1, self.file2)
1315
Serhiy Storchaka43767632013-11-03 21:31:38 +02001316@unittest.skipIf(sys.platform == "win32", "Posix specific tests")
1317class PosixUidGidTests(unittest.TestCase):
1318 @unittest.skipUnless(hasattr(os, 'setuid'), 'test needs os.setuid()')
1319 def test_setuid(self):
1320 if os.getuid() != 0:
1321 self.assertRaises(OSError, os.setuid, 0)
1322 self.assertRaises(OverflowError, os.setuid, 1<<32)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001323
Serhiy Storchaka43767632013-11-03 21:31:38 +02001324 @unittest.skipUnless(hasattr(os, 'setgid'), 'test needs os.setgid()')
1325 def test_setgid(self):
1326 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
1327 self.assertRaises(OSError, os.setgid, 0)
1328 self.assertRaises(OverflowError, os.setgid, 1<<32)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001329
Serhiy Storchaka43767632013-11-03 21:31:38 +02001330 @unittest.skipUnless(hasattr(os, 'seteuid'), 'test needs os.seteuid()')
1331 def test_seteuid(self):
1332 if os.getuid() != 0:
1333 self.assertRaises(OSError, os.seteuid, 0)
1334 self.assertRaises(OverflowError, os.seteuid, 1<<32)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001335
Serhiy Storchaka43767632013-11-03 21:31:38 +02001336 @unittest.skipUnless(hasattr(os, 'setegid'), 'test needs os.setegid()')
1337 def test_setegid(self):
1338 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
1339 self.assertRaises(OSError, os.setegid, 0)
1340 self.assertRaises(OverflowError, os.setegid, 1<<32)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001341
Serhiy Storchaka43767632013-11-03 21:31:38 +02001342 @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
1343 def test_setreuid(self):
1344 if os.getuid() != 0:
1345 self.assertRaises(OSError, os.setreuid, 0, 0)
1346 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
1347 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001348
Serhiy Storchaka43767632013-11-03 21:31:38 +02001349 @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
1350 def test_setreuid_neg1(self):
1351 # Needs to accept -1. We run this in a subprocess to avoid
1352 # altering the test runner's process state (issue8045).
1353 subprocess.check_call([
1354 sys.executable, '-c',
1355 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001356
Serhiy Storchaka43767632013-11-03 21:31:38 +02001357 @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
1358 def test_setregid(self):
1359 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
1360 self.assertRaises(OSError, os.setregid, 0, 0)
1361 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
1362 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001363
Serhiy Storchaka43767632013-11-03 21:31:38 +02001364 @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
1365 def test_setregid_neg1(self):
1366 # Needs to accept -1. We run this in a subprocess to avoid
1367 # altering the test runner's process state (issue8045).
1368 subprocess.check_call([
1369 sys.executable, '-c',
1370 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001371
Serhiy Storchaka43767632013-11-03 21:31:38 +02001372@unittest.skipIf(sys.platform == "win32", "Posix specific tests")
1373class Pep383Tests(unittest.TestCase):
1374 def setUp(self):
1375 if support.TESTFN_UNENCODABLE:
1376 self.dir = support.TESTFN_UNENCODABLE
1377 elif support.TESTFN_NONASCII:
1378 self.dir = support.TESTFN_NONASCII
1379 else:
1380 self.dir = support.TESTFN
1381 self.bdir = os.fsencode(self.dir)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001382
Serhiy Storchaka43767632013-11-03 21:31:38 +02001383 bytesfn = []
1384 def add_filename(fn):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001385 try:
Serhiy Storchaka43767632013-11-03 21:31:38 +02001386 fn = os.fsencode(fn)
1387 except UnicodeEncodeError:
1388 return
1389 bytesfn.append(fn)
1390 add_filename(support.TESTFN_UNICODE)
1391 if support.TESTFN_UNENCODABLE:
1392 add_filename(support.TESTFN_UNENCODABLE)
1393 if support.TESTFN_NONASCII:
1394 add_filename(support.TESTFN_NONASCII)
1395 if not bytesfn:
1396 self.skipTest("couldn't create any non-ascii filename")
Martin v. Löwis011e8422009-05-05 04:43:17 +00001397
Serhiy Storchaka43767632013-11-03 21:31:38 +02001398 self.unicodefn = set()
1399 os.mkdir(self.dir)
1400 try:
1401 for fn in bytesfn:
1402 support.create_empty_file(os.path.join(self.bdir, fn))
1403 fn = os.fsdecode(fn)
1404 if fn in self.unicodefn:
1405 raise ValueError("duplicate filename")
1406 self.unicodefn.add(fn)
1407 except:
Martin v. Löwis011e8422009-05-05 04:43:17 +00001408 shutil.rmtree(self.dir)
Serhiy Storchaka43767632013-11-03 21:31:38 +02001409 raise
Martin v. Löwis011e8422009-05-05 04:43:17 +00001410
Serhiy Storchaka43767632013-11-03 21:31:38 +02001411 def tearDown(self):
1412 shutil.rmtree(self.dir)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001413
Serhiy Storchaka43767632013-11-03 21:31:38 +02001414 def test_listdir(self):
1415 expected = self.unicodefn
1416 found = set(os.listdir(self.dir))
1417 self.assertEqual(found, expected)
1418 # test listdir without arguments
1419 current_directory = os.getcwd()
1420 try:
1421 os.chdir(os.sep)
1422 self.assertEqual(set(os.listdir()), set(os.listdir(os.sep)))
1423 finally:
1424 os.chdir(current_directory)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001425
Serhiy Storchaka43767632013-11-03 21:31:38 +02001426 def test_open(self):
1427 for fn in self.unicodefn:
1428 f = open(os.path.join(self.dir, fn), 'rb')
1429 f.close()
Victor Stinnere4110dc2013-01-01 23:05:55 +01001430
Serhiy Storchaka43767632013-11-03 21:31:38 +02001431 @unittest.skipUnless(hasattr(os, 'statvfs'),
1432 "need os.statvfs()")
1433 def test_statvfs(self):
1434 # issue #9645
1435 for fn in self.unicodefn:
1436 # should not fail with file not found error
1437 fullname = os.path.join(self.dir, fn)
1438 os.statvfs(fullname)
1439
1440 def test_stat(self):
1441 for fn in self.unicodefn:
1442 os.stat(os.path.join(self.dir, fn))
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001443
Brian Curtineb24d742010-04-12 17:16:38 +00001444@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
1445class Win32KillTests(unittest.TestCase):
Brian Curtinc3acbc32010-05-28 16:08:40 +00001446 def _kill(self, sig):
1447 # Start sys.executable as a subprocess and communicate from the
1448 # subprocess to the parent that the interpreter is ready. When it
1449 # becomes ready, send *sig* via os.kill to the subprocess and check
1450 # that the return code is equal to *sig*.
1451 import ctypes
1452 from ctypes import wintypes
1453 import msvcrt
1454
1455 # Since we can't access the contents of the process' stdout until the
1456 # process has exited, use PeekNamedPipe to see what's inside stdout
1457 # without waiting. This is done so we can tell that the interpreter
1458 # is started and running at a point where it could handle a signal.
1459 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
1460 PeekNamedPipe.restype = wintypes.BOOL
1461 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
1462 ctypes.POINTER(ctypes.c_char), # stdout buf
1463 wintypes.DWORD, # Buffer size
1464 ctypes.POINTER(wintypes.DWORD), # bytes read
1465 ctypes.POINTER(wintypes.DWORD), # bytes avail
1466 ctypes.POINTER(wintypes.DWORD)) # bytes left
1467 msg = "running"
1468 proc = subprocess.Popen([sys.executable, "-c",
1469 "import sys;"
1470 "sys.stdout.write('{}');"
1471 "sys.stdout.flush();"
1472 "input()".format(msg)],
1473 stdout=subprocess.PIPE,
1474 stderr=subprocess.PIPE,
1475 stdin=subprocess.PIPE)
Brian Curtin43ec5772010-11-05 15:17:11 +00001476 self.addCleanup(proc.stdout.close)
1477 self.addCleanup(proc.stderr.close)
1478 self.addCleanup(proc.stdin.close)
Brian Curtinc3acbc32010-05-28 16:08:40 +00001479
1480 count, max = 0, 100
1481 while count < max and proc.poll() is None:
1482 # Create a string buffer to store the result of stdout from the pipe
1483 buf = ctypes.create_string_buffer(len(msg))
1484 # Obtain the text currently in proc.stdout
1485 # Bytes read/avail/left are left as NULL and unused
1486 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
1487 buf, ctypes.sizeof(buf), None, None, None)
1488 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
1489 if buf.value:
1490 self.assertEqual(msg, buf.value.decode())
1491 break
1492 time.sleep(0.1)
1493 count += 1
1494 else:
1495 self.fail("Did not receive communication from the subprocess")
1496
Brian Curtineb24d742010-04-12 17:16:38 +00001497 os.kill(proc.pid, sig)
1498 self.assertEqual(proc.wait(), sig)
1499
1500 def test_kill_sigterm(self):
1501 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinc3acbc32010-05-28 16:08:40 +00001502 self._kill(signal.SIGTERM)
Brian Curtineb24d742010-04-12 17:16:38 +00001503
1504 def test_kill_int(self):
1505 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinc3acbc32010-05-28 16:08:40 +00001506 self._kill(100)
Brian Curtineb24d742010-04-12 17:16:38 +00001507
1508 def _kill_with_event(self, event, name):
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001509 tagname = "test_os_%s" % uuid.uuid1()
1510 m = mmap.mmap(-1, 1, tagname)
1511 m[0] = 0
Brian Curtineb24d742010-04-12 17:16:38 +00001512 # Run a script which has console control handling enabled.
1513 proc = subprocess.Popen([sys.executable,
1514 os.path.join(os.path.dirname(__file__),
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001515 "win_console_handler.py"), tagname],
Brian Curtineb24d742010-04-12 17:16:38 +00001516 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
1517 # Let the interpreter startup before we send signals. See #3137.
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001518 count, max = 0, 100
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001519 while count < max and proc.poll() is None:
Brian Curtinf668df52010-10-15 14:21:06 +00001520 if m[0] == 1:
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001521 break
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001522 time.sleep(0.1)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001523 count += 1
1524 else:
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001525 # Forcefully kill the process if we weren't able to signal it.
1526 os.kill(proc.pid, signal.SIGINT)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001527 self.fail("Subprocess didn't finish initialization")
Brian Curtineb24d742010-04-12 17:16:38 +00001528 os.kill(proc.pid, event)
1529 # proc.send_signal(event) could also be done here.
1530 # Allow time for the signal to be passed and the process to exit.
1531 time.sleep(0.5)
1532 if not proc.poll():
1533 # Forcefully kill the process if we weren't able to signal it.
1534 os.kill(proc.pid, signal.SIGINT)
1535 self.fail("subprocess did not stop on {}".format(name))
1536
1537 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
1538 def test_CTRL_C_EVENT(self):
1539 from ctypes import wintypes
1540 import ctypes
1541
1542 # Make a NULL value by creating a pointer with no argument.
1543 NULL = ctypes.POINTER(ctypes.c_int)()
1544 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
1545 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
1546 wintypes.BOOL)
1547 SetConsoleCtrlHandler.restype = wintypes.BOOL
1548
1549 # Calling this with NULL and FALSE causes the calling process to
1550 # handle CTRL+C, rather than ignore it. This property is inherited
1551 # by subprocesses.
1552 SetConsoleCtrlHandler(NULL, 0)
1553
1554 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
1555
1556 def test_CTRL_BREAK_EVENT(self):
1557 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
1558
1559
Brian Curtind40e6f72010-07-08 21:39:08 +00001560@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Tim Golden781bbeb2013-10-25 20:24:06 +01001561class Win32ListdirTests(unittest.TestCase):
1562 """Test listdir on Windows."""
1563
1564 def setUp(self):
1565 self.created_paths = []
1566 for i in range(2):
1567 dir_name = 'SUB%d' % i
1568 dir_path = os.path.join(support.TESTFN, dir_name)
1569 file_name = 'FILE%d' % i
1570 file_path = os.path.join(support.TESTFN, file_name)
1571 os.makedirs(dir_path)
1572 with open(file_path, 'w') as f:
1573 f.write("I'm %s and proud of it. Blame test_os.\n" % file_path)
1574 self.created_paths.extend([dir_name, file_name])
1575 self.created_paths.sort()
1576
1577 def tearDown(self):
1578 shutil.rmtree(support.TESTFN)
1579
1580 def test_listdir_no_extended_path(self):
1581 """Test when the path is not an "extended" path."""
1582 # unicode
1583 self.assertEqual(
1584 sorted(os.listdir(support.TESTFN)),
1585 self.created_paths)
1586 # bytes
1587 self.assertEqual(
1588 sorted(os.listdir(os.fsencode(support.TESTFN))),
1589 [os.fsencode(path) for path in self.created_paths])
1590
1591 def test_listdir_extended_path(self):
1592 """Test when the path starts with '\\\\?\\'."""
Tim Golden1cc35402013-10-25 21:26:06 +01001593 # See: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath
Tim Golden781bbeb2013-10-25 20:24:06 +01001594 # unicode
1595 path = '\\\\?\\' + os.path.abspath(support.TESTFN)
1596 self.assertEqual(
1597 sorted(os.listdir(path)),
1598 self.created_paths)
1599 # bytes
1600 path = b'\\\\?\\' + os.fsencode(os.path.abspath(support.TESTFN))
1601 self.assertEqual(
1602 sorted(os.listdir(path)),
1603 [os.fsencode(path) for path in self.created_paths])
1604
1605
1606@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Brian Curtin3b4499c2010-12-28 14:31:47 +00001607@support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +00001608class Win32SymlinkTests(unittest.TestCase):
1609 filelink = 'filelinktest'
1610 filelink_target = os.path.abspath(__file__)
1611 dirlink = 'dirlinktest'
1612 dirlink_target = os.path.dirname(filelink_target)
1613 missing_link = 'missing link'
1614
1615 def setUp(self):
1616 assert os.path.exists(self.dirlink_target)
1617 assert os.path.exists(self.filelink_target)
1618 assert not os.path.exists(self.dirlink)
1619 assert not os.path.exists(self.filelink)
1620 assert not os.path.exists(self.missing_link)
1621
1622 def tearDown(self):
1623 if os.path.exists(self.filelink):
1624 os.remove(self.filelink)
1625 if os.path.exists(self.dirlink):
1626 os.rmdir(self.dirlink)
1627 if os.path.lexists(self.missing_link):
1628 os.remove(self.missing_link)
1629
1630 def test_directory_link(self):
Jason R. Coombs3a092862013-05-27 23:21:28 -04001631 os.symlink(self.dirlink_target, self.dirlink)
Brian Curtind40e6f72010-07-08 21:39:08 +00001632 self.assertTrue(os.path.exists(self.dirlink))
1633 self.assertTrue(os.path.isdir(self.dirlink))
1634 self.assertTrue(os.path.islink(self.dirlink))
1635 self.check_stat(self.dirlink, self.dirlink_target)
1636
1637 def test_file_link(self):
1638 os.symlink(self.filelink_target, self.filelink)
1639 self.assertTrue(os.path.exists(self.filelink))
1640 self.assertTrue(os.path.isfile(self.filelink))
1641 self.assertTrue(os.path.islink(self.filelink))
1642 self.check_stat(self.filelink, self.filelink_target)
1643
1644 def _create_missing_dir_link(self):
1645 'Create a "directory" link to a non-existent target'
1646 linkname = self.missing_link
1647 if os.path.lexists(linkname):
1648 os.remove(linkname)
1649 target = r'c:\\target does not exist.29r3c740'
1650 assert not os.path.exists(target)
1651 target_is_dir = True
1652 os.symlink(target, linkname, target_is_dir)
1653
1654 def test_remove_directory_link_to_missing_target(self):
1655 self._create_missing_dir_link()
1656 # For compatibility with Unix, os.remove will check the
1657 # directory status and call RemoveDirectory if the symlink
1658 # was created with target_is_dir==True.
1659 os.remove(self.missing_link)
1660
1661 @unittest.skip("currently fails; consider for improvement")
1662 def test_isdir_on_directory_link_to_missing_target(self):
1663 self._create_missing_dir_link()
1664 # consider having isdir return true for directory links
1665 self.assertTrue(os.path.isdir(self.missing_link))
1666
1667 @unittest.skip("currently fails; consider for improvement")
1668 def test_rmdir_on_directory_link_to_missing_target(self):
1669 self._create_missing_dir_link()
1670 # consider allowing rmdir to remove directory links
1671 os.rmdir(self.missing_link)
1672
1673 def check_stat(self, link, target):
1674 self.assertEqual(os.stat(link), os.stat(target))
1675 self.assertNotEqual(os.lstat(link), os.stat(link))
1676
Brian Curtind25aef52011-06-13 15:16:04 -05001677 bytes_link = os.fsencode(link)
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001678 with warnings.catch_warnings():
1679 warnings.simplefilter("ignore", DeprecationWarning)
1680 self.assertEqual(os.stat(bytes_link), os.stat(target))
1681 self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link))
Brian Curtind25aef52011-06-13 15:16:04 -05001682
1683 def test_12084(self):
1684 level1 = os.path.abspath(support.TESTFN)
1685 level2 = os.path.join(level1, "level2")
1686 level3 = os.path.join(level2, "level3")
1687 try:
1688 os.mkdir(level1)
1689 os.mkdir(level2)
1690 os.mkdir(level3)
1691
1692 file1 = os.path.abspath(os.path.join(level1, "file1"))
1693
1694 with open(file1, "w") as f:
1695 f.write("file1")
1696
1697 orig_dir = os.getcwd()
1698 try:
1699 os.chdir(level2)
1700 link = os.path.join(level2, "link")
1701 os.symlink(os.path.relpath(file1), "link")
1702 self.assertIn("link", os.listdir(os.getcwd()))
1703
1704 # Check os.stat calls from the same dir as the link
1705 self.assertEqual(os.stat(file1), os.stat("link"))
1706
1707 # Check os.stat calls from a dir below the link
1708 os.chdir(level1)
1709 self.assertEqual(os.stat(file1),
1710 os.stat(os.path.relpath(link)))
1711
1712 # Check os.stat calls from a dir above the link
1713 os.chdir(level3)
1714 self.assertEqual(os.stat(file1),
1715 os.stat(os.path.relpath(link)))
1716 finally:
1717 os.chdir(orig_dir)
1718 except OSError as err:
1719 self.fail(err)
1720 finally:
1721 os.remove(file1)
1722 shutil.rmtree(level1)
1723
Brian Curtind40e6f72010-07-08 21:39:08 +00001724
Jason R. Coombs3a092862013-05-27 23:21:28 -04001725@support.skip_unless_symlink
1726class NonLocalSymlinkTests(unittest.TestCase):
1727
1728 def setUp(self):
1729 """
1730 Create this structure:
1731
1732 base
1733 \___ some_dir
1734 """
1735 os.makedirs('base/some_dir')
1736
1737 def tearDown(self):
1738 shutil.rmtree('base')
1739
1740 def test_directory_link_nonlocal(self):
1741 """
1742 The symlink target should resolve relative to the link, not relative
1743 to the current directory.
1744
1745 Then, link base/some_link -> base/some_dir and ensure that some_link
1746 is resolved as a directory.
1747
1748 In issue13772, it was discovered that directory detection failed if
1749 the symlink target was not specified relative to the current
1750 directory, which was a defect in the implementation.
1751 """
1752 src = os.path.join('base', 'some_link')
1753 os.symlink('some_dir', src)
1754 assert os.path.isdir(src)
1755
1756
Victor Stinnere8d51452010-08-19 01:05:19 +00001757class FSEncodingTests(unittest.TestCase):
1758 def test_nop(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001759 self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
1760 self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
Benjamin Peterson31191a92010-05-09 03:22:58 +00001761
Victor Stinnere8d51452010-08-19 01:05:19 +00001762 def test_identity(self):
1763 # assert fsdecode(fsencode(x)) == x
1764 for fn in ('unicode\u0141', 'latin\xe9', 'ascii'):
1765 try:
1766 bytesfn = os.fsencode(fn)
1767 except UnicodeEncodeError:
1768 continue
Ezio Melottib3aedd42010-11-20 19:04:17 +00001769 self.assertEqual(os.fsdecode(bytesfn), fn)
Victor Stinnere8d51452010-08-19 01:05:19 +00001770
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00001771
Brett Cannonefb00c02012-02-29 18:31:31 -05001772
1773class DeviceEncodingTests(unittest.TestCase):
1774
1775 def test_bad_fd(self):
1776 # Return None when an fd doesn't actually exist.
1777 self.assertIsNone(os.device_encoding(123456))
1778
Philip Jenveye308b7c2012-02-29 16:16:15 -08001779 @unittest.skipUnless(os.isatty(0) and (sys.platform.startswith('win') or
1780 (hasattr(locale, 'nl_langinfo') and hasattr(locale, 'CODESET'))),
Philip Jenveyd7aff2d2012-02-29 16:21:25 -08001781 'test requires a tty and either Windows or nl_langinfo(CODESET)')
Brett Cannonefb00c02012-02-29 18:31:31 -05001782 def test_device_encoding(self):
1783 encoding = os.device_encoding(0)
1784 self.assertIsNotNone(encoding)
1785 self.assertTrue(codecs.lookup(encoding))
1786
1787
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00001788class PidTests(unittest.TestCase):
1789 @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid")
1790 def test_getppid(self):
1791 p = subprocess.Popen([sys.executable, '-c',
1792 'import os; print(os.getppid())'],
1793 stdout=subprocess.PIPE)
1794 stdout, _ = p.communicate()
1795 # We are the parent of our subprocess
1796 self.assertEqual(int(stdout), os.getpid())
1797
1798
Brian Curtin0151b8e2010-09-24 13:43:43 +00001799# The introduction of this TestCase caused at least two different errors on
1800# *nix buildbots. Temporarily skip this to let the buildbots move along.
1801@unittest.skip("Skip due to platform/environment differences on *NIX buildbots")
Brian Curtine8e4b3b2010-09-23 20:04:14 +00001802@unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin")
1803class LoginTests(unittest.TestCase):
1804 def test_getlogin(self):
1805 user_name = os.getlogin()
1806 self.assertNotEqual(len(user_name), 0)
1807
1808
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001809@unittest.skipUnless(hasattr(os, 'getpriority') and hasattr(os, 'setpriority'),
1810 "needs os.getpriority and os.setpriority")
1811class ProgramPriorityTests(unittest.TestCase):
1812 """Tests for os.getpriority() and os.setpriority()."""
1813
1814 def test_set_get_priority(self):
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001815
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001816 base = os.getpriority(os.PRIO_PROCESS, os.getpid())
1817 os.setpriority(os.PRIO_PROCESS, os.getpid(), base + 1)
1818 try:
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001819 new_prio = os.getpriority(os.PRIO_PROCESS, os.getpid())
1820 if base >= 19 and new_prio <= 19:
1821 raise unittest.SkipTest(
1822 "unable to reliably test setpriority at current nice level of %s" % base)
1823 else:
1824 self.assertEqual(new_prio, base + 1)
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001825 finally:
1826 try:
1827 os.setpriority(os.PRIO_PROCESS, os.getpid(), base)
1828 except OSError as err:
Antoine Pitrou692f0382011-02-26 00:22:25 +00001829 if err.errno != errno.EACCES:
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001830 raise
1831
1832
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001833if threading is not None:
1834 class SendfileTestServer(asyncore.dispatcher, threading.Thread):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001835
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001836 class Handler(asynchat.async_chat):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001837
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001838 def __init__(self, conn):
1839 asynchat.async_chat.__init__(self, conn)
1840 self.in_buffer = []
1841 self.closed = False
1842 self.push(b"220 ready\r\n")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001843
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001844 def handle_read(self):
1845 data = self.recv(4096)
1846 self.in_buffer.append(data)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001847
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001848 def get_data(self):
1849 return b''.join(self.in_buffer)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001850
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001851 def handle_close(self):
1852 self.close()
1853 self.closed = True
1854
1855 def handle_error(self):
1856 raise
1857
1858 def __init__(self, address):
1859 threading.Thread.__init__(self)
1860 asyncore.dispatcher.__init__(self)
1861 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
1862 self.bind(address)
1863 self.listen(5)
1864 self.host, self.port = self.socket.getsockname()[:2]
1865 self.handler_instance = None
1866 self._active = False
1867 self._active_lock = threading.Lock()
1868
1869 # --- public API
1870
1871 @property
1872 def running(self):
1873 return self._active
1874
1875 def start(self):
1876 assert not self.running
1877 self.__flag = threading.Event()
1878 threading.Thread.start(self)
1879 self.__flag.wait()
1880
1881 def stop(self):
1882 assert self.running
1883 self._active = False
1884 self.join()
1885
1886 def wait(self):
1887 # wait for handler connection to be closed, then stop the server
1888 while not getattr(self.handler_instance, "closed", False):
1889 time.sleep(0.001)
1890 self.stop()
1891
1892 # --- internals
1893
1894 def run(self):
1895 self._active = True
1896 self.__flag.set()
1897 while self._active and asyncore.socket_map:
1898 self._active_lock.acquire()
1899 asyncore.loop(timeout=0.001, count=1)
1900 self._active_lock.release()
1901 asyncore.close_all()
1902
1903 def handle_accept(self):
1904 conn, addr = self.accept()
1905 self.handler_instance = self.Handler(conn)
1906
1907 def handle_connect(self):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001908 self.close()
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001909 handle_read = handle_connect
1910
1911 def writable(self):
1912 return 0
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001913
1914 def handle_error(self):
1915 raise
1916
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001917
Giampaolo Rodolà46134642011-02-25 20:01:05 +00001918@unittest.skipUnless(threading is not None, "test needs threading module")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001919@unittest.skipUnless(hasattr(os, 'sendfile'), "test needs os.sendfile()")
1920class TestSendfile(unittest.TestCase):
1921
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001922 DATA = b"12345abcde" * 16 * 1024 # 160 KB
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001923 SUPPORT_HEADERS_TRAILERS = not sys.platform.startswith("linux") and \
Giampaolo Rodolà4bc68572011-02-25 21:46:01 +00001924 not sys.platform.startswith("solaris") and \
1925 not sys.platform.startswith("sunos")
Serhiy Storchaka43767632013-11-03 21:31:38 +02001926 requires_headers_trailers = unittest.skipUnless(SUPPORT_HEADERS_TRAILERS,
1927 'requires headers and trailers support')
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001928
1929 @classmethod
1930 def setUpClass(cls):
1931 with open(support.TESTFN, "wb") as f:
1932 f.write(cls.DATA)
1933
1934 @classmethod
1935 def tearDownClass(cls):
1936 support.unlink(support.TESTFN)
1937
1938 def setUp(self):
1939 self.server = SendfileTestServer((support.HOST, 0))
1940 self.server.start()
1941 self.client = socket.socket()
1942 self.client.connect((self.server.host, self.server.port))
1943 self.client.settimeout(1)
1944 # synchronize by waiting for "220 ready" response
1945 self.client.recv(1024)
1946 self.sockno = self.client.fileno()
1947 self.file = open(support.TESTFN, 'rb')
1948 self.fileno = self.file.fileno()
1949
1950 def tearDown(self):
1951 self.file.close()
1952 self.client.close()
1953 if self.server.running:
1954 self.server.stop()
1955
1956 def sendfile_wrapper(self, sock, file, offset, nbytes, headers=[], trailers=[]):
1957 """A higher level wrapper representing how an application is
1958 supposed to use sendfile().
1959 """
1960 while 1:
1961 try:
1962 if self.SUPPORT_HEADERS_TRAILERS:
1963 return os.sendfile(sock, file, offset, nbytes, headers,
1964 trailers)
1965 else:
1966 return os.sendfile(sock, file, offset, nbytes)
1967 except OSError as err:
1968 if err.errno == errno.ECONNRESET:
1969 # disconnected
1970 raise
1971 elif err.errno in (errno.EAGAIN, errno.EBUSY):
1972 # we have to retry send data
1973 continue
1974 else:
1975 raise
1976
1977 def test_send_whole_file(self):
1978 # normal send
1979 total_sent = 0
1980 offset = 0
1981 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001982 while total_sent < len(self.DATA):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001983 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
1984 if sent == 0:
1985 break
1986 offset += sent
1987 total_sent += sent
1988 self.assertTrue(sent <= nbytes)
1989 self.assertEqual(offset, total_sent)
1990
1991 self.assertEqual(total_sent, len(self.DATA))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001992 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001993 self.client.close()
1994 self.server.wait()
1995 data = self.server.handler_instance.get_data()
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001996 self.assertEqual(len(data), len(self.DATA))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001997 self.assertEqual(data, self.DATA)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001998
1999 def test_send_at_certain_offset(self):
2000 # start sending a file at a certain offset
2001 total_sent = 0
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00002002 offset = len(self.DATA) // 2
2003 must_send = len(self.DATA) - offset
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002004 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00002005 while total_sent < must_send:
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002006 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
2007 if sent == 0:
2008 break
2009 offset += sent
2010 total_sent += sent
2011 self.assertTrue(sent <= nbytes)
2012
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00002013 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002014 self.client.close()
2015 self.server.wait()
2016 data = self.server.handler_instance.get_data()
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00002017 expected = self.DATA[len(self.DATA) // 2:]
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002018 self.assertEqual(total_sent, len(expected))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00002019 self.assertEqual(len(data), len(expected))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00002020 self.assertEqual(data, expected)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002021
2022 def test_offset_overflow(self):
2023 # specify an offset > file size
2024 offset = len(self.DATA) + 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00002025 try:
2026 sent = os.sendfile(self.sockno, self.fileno, offset, 4096)
2027 except OSError as e:
2028 # Solaris can raise EINVAL if offset >= file length, ignore.
2029 if e.errno != errno.EINVAL:
2030 raise
2031 else:
2032 self.assertEqual(sent, 0)
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00002033 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002034 self.client.close()
2035 self.server.wait()
2036 data = self.server.handler_instance.get_data()
2037 self.assertEqual(data, b'')
2038
2039 def test_invalid_offset(self):
2040 with self.assertRaises(OSError) as cm:
2041 os.sendfile(self.sockno, self.fileno, -1, 4096)
2042 self.assertEqual(cm.exception.errno, errno.EINVAL)
2043
2044 # --- headers / trailers tests
2045
Serhiy Storchaka43767632013-11-03 21:31:38 +02002046 @requires_headers_trailers
2047 def test_headers(self):
2048 total_sent = 0
2049 sent = os.sendfile(self.sockno, self.fileno, 0, 4096,
2050 headers=[b"x" * 512])
2051 total_sent += sent
2052 offset = 4096
2053 nbytes = 4096
2054 while 1:
2055 sent = self.sendfile_wrapper(self.sockno, self.fileno,
2056 offset, nbytes)
2057 if sent == 0:
2058 break
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002059 total_sent += sent
Serhiy Storchaka43767632013-11-03 21:31:38 +02002060 offset += sent
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002061
Serhiy Storchaka43767632013-11-03 21:31:38 +02002062 expected_data = b"x" * 512 + self.DATA
2063 self.assertEqual(total_sent, len(expected_data))
2064 self.client.close()
2065 self.server.wait()
2066 data = self.server.handler_instance.get_data()
2067 self.assertEqual(hash(data), hash(expected_data))
2068
2069 @requires_headers_trailers
2070 def test_trailers(self):
2071 TESTFN2 = support.TESTFN + "2"
2072 file_data = b"abcdef"
2073 with open(TESTFN2, 'wb') as f:
2074 f.write(file_data)
2075 with open(TESTFN2, 'rb')as f:
2076 self.addCleanup(os.remove, TESTFN2)
2077 os.sendfile(self.sockno, f.fileno(), 0, len(file_data),
2078 trailers=[b"1234"])
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002079 self.client.close()
2080 self.server.wait()
2081 data = self.server.handler_instance.get_data()
Serhiy Storchaka43767632013-11-03 21:31:38 +02002082 self.assertEqual(data, b"abcdef1234")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002083
Serhiy Storchaka43767632013-11-03 21:31:38 +02002084 @requires_headers_trailers
2085 @unittest.skipUnless(hasattr(os, 'SF_NODISKIO'),
2086 'test needs os.SF_NODISKIO')
2087 def test_flags(self):
2088 try:
2089 os.sendfile(self.sockno, self.fileno, 0, 4096,
2090 flags=os.SF_NODISKIO)
2091 except OSError as err:
2092 if err.errno not in (errno.EBUSY, errno.EAGAIN):
2093 raise
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002094
2095
Larry Hastings9cf065c2012-06-22 16:30:09 -07002096def supports_extended_attributes():
2097 if not hasattr(os, "setxattr"):
2098 return False
2099 try:
2100 with open(support.TESTFN, "wb") as fp:
2101 try:
2102 os.setxattr(fp.fileno(), b"user.test", b"")
2103 except OSError:
2104 return False
2105 finally:
2106 support.unlink(support.TESTFN)
2107 # Kernels < 2.6.39 don't respect setxattr flags.
2108 kernel_version = platform.release()
2109 m = re.match("2.6.(\d{1,2})", kernel_version)
2110 return m is None or int(m.group(1)) >= 39
2111
2112
2113@unittest.skipUnless(supports_extended_attributes(),
2114 "no non-broken extended attribute support")
Benjamin Peterson799bd802011-08-31 22:15:17 -04002115class ExtendedAttributeTests(unittest.TestCase):
2116
2117 def tearDown(self):
2118 support.unlink(support.TESTFN)
2119
Larry Hastings9cf065c2012-06-22 16:30:09 -07002120 def _check_xattrs_str(self, s, getxattr, setxattr, removexattr, listxattr, **kwargs):
Benjamin Peterson799bd802011-08-31 22:15:17 -04002121 fn = support.TESTFN
2122 open(fn, "wb").close()
2123 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002124 getxattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002125 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002126 init_xattr = listxattr(fn)
2127 self.assertIsInstance(init_xattr, list)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002128 setxattr(fn, s("user.test"), b"", **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002129 xattr = set(init_xattr)
2130 xattr.add("user.test")
2131 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002132 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"")
2133 setxattr(fn, s("user.test"), b"hello", os.XATTR_REPLACE, **kwargs)
2134 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"hello")
Benjamin Peterson799bd802011-08-31 22:15:17 -04002135 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002136 setxattr(fn, s("user.test"), b"bye", os.XATTR_CREATE, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002137 self.assertEqual(cm.exception.errno, errno.EEXIST)
2138 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002139 setxattr(fn, s("user.test2"), b"bye", os.XATTR_REPLACE, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002140 self.assertEqual(cm.exception.errno, errno.ENODATA)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002141 setxattr(fn, s("user.test2"), b"foo", os.XATTR_CREATE, **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002142 xattr.add("user.test2")
2143 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002144 removexattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002145 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002146 getxattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002147 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002148 xattr.remove("user.test")
2149 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002150 self.assertEqual(getxattr(fn, s("user.test2"), **kwargs), b"foo")
2151 setxattr(fn, s("user.test"), b"a"*1024, **kwargs)
2152 self.assertEqual(getxattr(fn, s("user.test"), **kwargs), b"a"*1024)
2153 removexattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002154 many = sorted("user.test{}".format(i) for i in range(100))
2155 for thing in many:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002156 setxattr(fn, thing, b"x", **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002157 self.assertEqual(set(listxattr(fn)), set(init_xattr) | set(many))
Benjamin Peterson799bd802011-08-31 22:15:17 -04002158
Larry Hastings9cf065c2012-06-22 16:30:09 -07002159 def _check_xattrs(self, *args, **kwargs):
Benjamin Peterson799bd802011-08-31 22:15:17 -04002160 def make_bytes(s):
2161 return bytes(s, "ascii")
Larry Hastings9cf065c2012-06-22 16:30:09 -07002162 self._check_xattrs_str(str, *args, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002163 support.unlink(support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002164 self._check_xattrs_str(make_bytes, *args, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002165
2166 def test_simple(self):
2167 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
2168 os.listxattr)
2169
2170 def test_lpath(self):
Larry Hastings9cf065c2012-06-22 16:30:09 -07002171 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
2172 os.listxattr, follow_symlinks=False)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002173
2174 def test_fds(self):
2175 def getxattr(path, *args):
2176 with open(path, "rb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002177 return os.getxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002178 def setxattr(path, *args):
2179 with open(path, "wb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002180 os.setxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002181 def removexattr(path, *args):
2182 with open(path, "wb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002183 os.removexattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002184 def listxattr(path, *args):
2185 with open(path, "rb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002186 return os.listxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002187 self._check_xattrs(getxattr, setxattr, removexattr, listxattr)
2188
2189
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002190@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
2191class Win32DeprecatedBytesAPI(unittest.TestCase):
2192 def test_deprecated(self):
2193 import nt
2194 filename = os.fsencode(support.TESTFN)
2195 with warnings.catch_warnings():
2196 warnings.simplefilter("error", DeprecationWarning)
2197 for func, *args in (
2198 (nt._getfullpathname, filename),
2199 (nt._isdir, filename),
2200 (os.access, filename, os.R_OK),
2201 (os.chdir, filename),
2202 (os.chmod, filename, 0o777),
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01002203 (os.getcwdb,),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002204 (os.link, filename, filename),
2205 (os.listdir, filename),
2206 (os.lstat, filename),
2207 (os.mkdir, filename),
2208 (os.open, filename, os.O_RDONLY),
2209 (os.rename, filename, filename),
2210 (os.rmdir, filename),
2211 (os.startfile, filename),
2212 (os.stat, filename),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002213 (os.unlink, filename),
2214 (os.utime, filename),
2215 ):
2216 self.assertRaises(DeprecationWarning, func, *args)
2217
Victor Stinner28216442011-11-16 00:34:44 +01002218 @support.skip_unless_symlink
2219 def test_symlink(self):
2220 filename = os.fsencode(support.TESTFN)
2221 with warnings.catch_warnings():
2222 warnings.simplefilter("error", DeprecationWarning)
2223 self.assertRaises(DeprecationWarning,
2224 os.symlink, filename, filename)
2225
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002226
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002227@unittest.skipUnless(hasattr(os, 'get_terminal_size'), "requires os.get_terminal_size")
2228class TermsizeTests(unittest.TestCase):
2229 def test_does_not_crash(self):
2230 """Check if get_terminal_size() returns a meaningful value.
2231
2232 There's no easy portable way to actually check the size of the
2233 terminal, so let's check if it returns something sensible instead.
2234 """
2235 try:
2236 size = os.get_terminal_size()
2237 except OSError as e:
Antoine Pitrou81a1fa52012-02-09 00:11:00 +01002238 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002239 # Under win32 a generic OSError can be thrown if the
2240 # handle cannot be retrieved
2241 self.skipTest("failed to query terminal size")
2242 raise
2243
Antoine Pitroucfade362012-02-08 23:48:59 +01002244 self.assertGreaterEqual(size.columns, 0)
2245 self.assertGreaterEqual(size.lines, 0)
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002246
2247 def test_stty_match(self):
2248 """Check if stty returns the same results
2249
2250 stty actually tests stdin, so get_terminal_size is invoked on
2251 stdin explicitly. If stty succeeded, then get_terminal_size()
2252 should work too.
2253 """
2254 try:
2255 size = subprocess.check_output(['stty', 'size']).decode().split()
2256 except (FileNotFoundError, subprocess.CalledProcessError):
2257 self.skipTest("stty invocation failed")
2258 expected = (int(size[1]), int(size[0])) # reversed order
2259
Antoine Pitrou81a1fa52012-02-09 00:11:00 +01002260 try:
2261 actual = os.get_terminal_size(sys.__stdin__.fileno())
2262 except OSError as e:
2263 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
2264 # Under win32 a generic OSError can be thrown if the
2265 # handle cannot be retrieved
2266 self.skipTest("failed to query terminal size")
2267 raise
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002268 self.assertEqual(expected, actual)
2269
2270
Victor Stinner292c8352012-10-30 02:17:38 +01002271class OSErrorTests(unittest.TestCase):
2272 def setUp(self):
2273 class Str(str):
2274 pass
2275
Victor Stinnerafe17062012-10-31 22:47:43 +01002276 self.bytes_filenames = []
2277 self.unicode_filenames = []
Victor Stinner292c8352012-10-30 02:17:38 +01002278 if support.TESTFN_UNENCODABLE is not None:
2279 decoded = support.TESTFN_UNENCODABLE
2280 else:
2281 decoded = support.TESTFN
Victor Stinnerafe17062012-10-31 22:47:43 +01002282 self.unicode_filenames.append(decoded)
2283 self.unicode_filenames.append(Str(decoded))
Victor Stinner292c8352012-10-30 02:17:38 +01002284 if support.TESTFN_UNDECODABLE is not None:
2285 encoded = support.TESTFN_UNDECODABLE
2286 else:
2287 encoded = os.fsencode(support.TESTFN)
Victor Stinnerafe17062012-10-31 22:47:43 +01002288 self.bytes_filenames.append(encoded)
2289 self.bytes_filenames.append(memoryview(encoded))
2290
2291 self.filenames = self.bytes_filenames + self.unicode_filenames
Victor Stinner292c8352012-10-30 02:17:38 +01002292
2293 def test_oserror_filename(self):
2294 funcs = [
Victor Stinnerafe17062012-10-31 22:47:43 +01002295 (self.filenames, os.chdir,),
2296 (self.filenames, os.chmod, 0o777),
Victor Stinnerafe17062012-10-31 22:47:43 +01002297 (self.filenames, os.lstat,),
2298 (self.filenames, os.open, os.O_RDONLY),
2299 (self.filenames, os.rmdir,),
2300 (self.filenames, os.stat,),
2301 (self.filenames, os.unlink,),
Victor Stinner292c8352012-10-30 02:17:38 +01002302 ]
2303 if sys.platform == "win32":
2304 funcs.extend((
Victor Stinnerafe17062012-10-31 22:47:43 +01002305 (self.bytes_filenames, os.rename, b"dst"),
2306 (self.bytes_filenames, os.replace, b"dst"),
2307 (self.unicode_filenames, os.rename, "dst"),
2308 (self.unicode_filenames, os.replace, "dst"),
Victor Stinner64e039a2012-11-07 00:10:14 +01002309 # Issue #16414: Don't test undecodable names with listdir()
2310 # because of a Windows bug.
2311 #
2312 # With the ANSI code page 932, os.listdir(b'\xe7') return an
2313 # empty list (instead of failing), whereas os.listdir(b'\xff')
2314 # raises a FileNotFoundError. It looks like a Windows bug:
2315 # b'\xe7' directory does not exist, FindFirstFileA(b'\xe7')
2316 # fails with ERROR_FILE_NOT_FOUND (2), instead of
2317 # ERROR_PATH_NOT_FOUND (3).
2318 (self.unicode_filenames, os.listdir,),
Victor Stinner292c8352012-10-30 02:17:38 +01002319 ))
Victor Stinnerafe17062012-10-31 22:47:43 +01002320 else:
2321 funcs.extend((
Victor Stinner64e039a2012-11-07 00:10:14 +01002322 (self.filenames, os.listdir,),
Victor Stinnerafe17062012-10-31 22:47:43 +01002323 (self.filenames, os.rename, "dst"),
2324 (self.filenames, os.replace, "dst"),
2325 ))
2326 if hasattr(os, "chown"):
2327 funcs.append((self.filenames, os.chown, 0, 0))
2328 if hasattr(os, "lchown"):
2329 funcs.append((self.filenames, os.lchown, 0, 0))
2330 if hasattr(os, "truncate"):
2331 funcs.append((self.filenames, os.truncate, 0))
Victor Stinner292c8352012-10-30 02:17:38 +01002332 if hasattr(os, "chflags"):
Victor Stinneree36c242012-11-13 09:31:51 +01002333 funcs.append((self.filenames, os.chflags, 0))
2334 if hasattr(os, "lchflags"):
2335 funcs.append((self.filenames, os.lchflags, 0))
Victor Stinner292c8352012-10-30 02:17:38 +01002336 if hasattr(os, "chroot"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002337 funcs.append((self.filenames, os.chroot,))
Victor Stinner292c8352012-10-30 02:17:38 +01002338 if hasattr(os, "link"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002339 if sys.platform == "win32":
2340 funcs.append((self.bytes_filenames, os.link, b"dst"))
2341 funcs.append((self.unicode_filenames, os.link, "dst"))
2342 else:
2343 funcs.append((self.filenames, os.link, "dst"))
Victor Stinner292c8352012-10-30 02:17:38 +01002344 if hasattr(os, "listxattr"):
2345 funcs.extend((
Victor Stinnerafe17062012-10-31 22:47:43 +01002346 (self.filenames, os.listxattr,),
2347 (self.filenames, os.getxattr, "user.test"),
2348 (self.filenames, os.setxattr, "user.test", b'user'),
2349 (self.filenames, os.removexattr, "user.test"),
Victor Stinner292c8352012-10-30 02:17:38 +01002350 ))
2351 if hasattr(os, "lchmod"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002352 funcs.append((self.filenames, os.lchmod, 0o777))
Victor Stinner292c8352012-10-30 02:17:38 +01002353 if hasattr(os, "readlink"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002354 if sys.platform == "win32":
2355 funcs.append((self.unicode_filenames, os.readlink,))
2356 else:
2357 funcs.append((self.filenames, os.readlink,))
Victor Stinner292c8352012-10-30 02:17:38 +01002358
Victor Stinnerafe17062012-10-31 22:47:43 +01002359 for filenames, func, *func_args in funcs:
2360 for name in filenames:
Victor Stinner292c8352012-10-30 02:17:38 +01002361 try:
2362 func(name, *func_args)
Victor Stinnerbd54f0e2012-10-31 01:12:55 +01002363 except OSError as err:
Victor Stinner292c8352012-10-30 02:17:38 +01002364 self.assertIs(err.filename, name)
2365 else:
2366 self.fail("No exception thrown by {}".format(func))
2367
Charles-Francois Natali44feda32013-05-20 14:40:46 +02002368class CPUCountTests(unittest.TestCase):
2369 def test_cpu_count(self):
2370 cpus = os.cpu_count()
2371 if cpus is not None:
2372 self.assertIsInstance(cpus, int)
2373 self.assertGreater(cpus, 0)
2374 else:
2375 self.skipTest("Could not determine the number of CPUs")
2376
Victor Stinnerdaf45552013-08-28 00:53:59 +02002377
2378class FDInheritanceTests(unittest.TestCase):
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002379 def test_get_set_inheritable(self):
Victor Stinnerdaf45552013-08-28 00:53:59 +02002380 fd = os.open(__file__, os.O_RDONLY)
2381 self.addCleanup(os.close, fd)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002382 self.assertEqual(os.get_inheritable(fd), False)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002383
Victor Stinnerdaf45552013-08-28 00:53:59 +02002384 os.set_inheritable(fd, True)
2385 self.assertEqual(os.get_inheritable(fd), True)
2386
Victor Stinner4f7a36f2013-09-08 14:14:38 +02002387 @unittest.skipIf(fcntl is None, "need fcntl")
2388 def test_get_inheritable_cloexec(self):
2389 fd = os.open(__file__, os.O_RDONLY)
2390 self.addCleanup(os.close, fd)
2391 self.assertEqual(os.get_inheritable(fd), False)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002392
Victor Stinner4f7a36f2013-09-08 14:14:38 +02002393 # clear FD_CLOEXEC flag
2394 flags = fcntl.fcntl(fd, fcntl.F_GETFD)
2395 flags &= ~fcntl.FD_CLOEXEC
2396 fcntl.fcntl(fd, fcntl.F_SETFD, flags)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002397
Victor Stinner4f7a36f2013-09-08 14:14:38 +02002398 self.assertEqual(os.get_inheritable(fd), True)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002399
Victor Stinner4f7a36f2013-09-08 14:14:38 +02002400 @unittest.skipIf(fcntl is None, "need fcntl")
2401 def test_set_inheritable_cloexec(self):
2402 fd = os.open(__file__, os.O_RDONLY)
2403 self.addCleanup(os.close, fd)
2404 self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
2405 fcntl.FD_CLOEXEC)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002406
Victor Stinner4f7a36f2013-09-08 14:14:38 +02002407 os.set_inheritable(fd, True)
2408 self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
2409 0)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002410
Victor Stinnerdaf45552013-08-28 00:53:59 +02002411 def test_open(self):
2412 fd = os.open(__file__, os.O_RDONLY)
2413 self.addCleanup(os.close, fd)
2414 self.assertEqual(os.get_inheritable(fd), False)
2415
2416 @unittest.skipUnless(hasattr(os, 'pipe'), "need os.pipe()")
2417 def test_pipe(self):
2418 rfd, wfd = os.pipe()
2419 self.addCleanup(os.close, rfd)
2420 self.addCleanup(os.close, wfd)
2421 self.assertEqual(os.get_inheritable(rfd), False)
2422 self.assertEqual(os.get_inheritable(wfd), False)
2423
2424 def test_dup(self):
2425 fd1 = os.open(__file__, os.O_RDONLY)
2426 self.addCleanup(os.close, fd1)
2427
2428 fd2 = os.dup(fd1)
2429 self.addCleanup(os.close, fd2)
2430 self.assertEqual(os.get_inheritable(fd2), False)
2431
2432 @unittest.skipUnless(hasattr(os, 'dup2'), "need os.dup2()")
2433 def test_dup2(self):
2434 fd = os.open(__file__, os.O_RDONLY)
2435 self.addCleanup(os.close, fd)
2436
2437 # inheritable by default
2438 fd2 = os.open(__file__, os.O_RDONLY)
2439 try:
2440 os.dup2(fd, fd2)
2441 self.assertEqual(os.get_inheritable(fd2), True)
2442 finally:
2443 os.close(fd2)
2444
2445 # force non-inheritable
2446 fd3 = os.open(__file__, os.O_RDONLY)
2447 try:
2448 os.dup2(fd, fd3, inheritable=False)
2449 self.assertEqual(os.get_inheritable(fd3), False)
2450 finally:
2451 os.close(fd3)
2452
2453 @unittest.skipUnless(hasattr(os, 'openpty'), "need os.openpty()")
2454 def test_openpty(self):
2455 master_fd, slave_fd = os.openpty()
2456 self.addCleanup(os.close, master_fd)
2457 self.addCleanup(os.close, slave_fd)
2458 self.assertEqual(os.get_inheritable(master_fd), False)
2459 self.assertEqual(os.get_inheritable(slave_fd), False)
2460
2461
Antoine Pitrouf26ad712011-07-15 23:00:56 +02002462@support.reap_threads
Fred Drake2e2be372001-09-20 21:33:42 +00002463def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002464 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002465 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002466 StatAttributeTests,
2467 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00002468 WalkTests,
Charles-François Natali7372b062012-02-05 15:15:38 +01002469 FwalkTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00002470 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +00002471 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002472 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +00002473 ExecTests,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00002474 Win32ErrorTests,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002475 TestInvalidFD,
Martin v. Löwis011e8422009-05-05 04:43:17 +00002476 PosixUidGidTests,
Brian Curtineb24d742010-04-12 17:16:38 +00002477 Pep383Tests,
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00002478 Win32KillTests,
Tim Golden781bbeb2013-10-25 20:24:06 +01002479 Win32ListdirTests,
Brian Curtind40e6f72010-07-08 21:39:08 +00002480 Win32SymlinkTests,
Jason R. Coombs3a092862013-05-27 23:21:28 -04002481 NonLocalSymlinkTests,
Victor Stinnere8d51452010-08-19 01:05:19 +00002482 FSEncodingTests,
Brett Cannonefb00c02012-02-29 18:31:31 -05002483 DeviceEncodingTests,
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00002484 PidTests,
Brian Curtine8e4b3b2010-09-23 20:04:14 +00002485 LoginTests,
Brian Curtin1b9df392010-11-24 20:24:31 +00002486 LinkTests,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002487 TestSendfile,
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00002488 ProgramPriorityTests,
Benjamin Peterson799bd802011-08-31 22:15:17 -04002489 ExtendedAttributeTests,
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002490 Win32DeprecatedBytesAPI,
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002491 TermsizeTests,
Victor Stinner292c8352012-10-30 02:17:38 +01002492 OSErrorTests,
Andrew Svetlov405faed2012-12-25 12:18:09 +02002493 RemoveDirsTests,
Charles-Francois Natali44feda32013-05-20 14:40:46 +02002494 CPUCountTests,
Victor Stinnerdaf45552013-08-28 00:53:59 +02002495 FDInheritanceTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002496 )
Fred Drake2e2be372001-09-20 21:33:42 +00002497
2498if __name__ == "__main__":
2499 test_main()