blob: 13f9e3ab15711997198bd1878dd1d3412b3b993b [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
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000027try:
28 import threading
29except ImportError:
30 threading = None
Georg Brandl2daf6ae2012-02-20 19:54:16 +010031from test.script_helper import assert_python_ok
Fred Drake38c2ef02001-07-17 20:52:51 +000032
Victor Stinner034d0aa2012-06-05 01:22:15 +020033with warnings.catch_warnings():
34 warnings.simplefilter("ignore", DeprecationWarning)
35 os.stat_float_times(True)
Victor Stinner1aa54a42012-02-08 04:09:37 +010036st = os.stat(__file__)
37stat_supports_subsecond = (
38 # check if float and int timestamps are different
39 (st.st_atime != st[7])
40 or (st.st_mtime != st[8])
41 or (st.st_ctime != st[9]))
42
Mark Dickinson7cf03892010-04-16 13:45:35 +000043# Detect whether we're on a Linux system that uses the (now outdated
44# and unmaintained) linuxthreads threading library. There's an issue
45# when combining linuxthreads with a failed execv call: see
46# http://bugs.python.org/issue4970.
Victor Stinnerd5c355c2011-04-30 14:53:09 +020047if hasattr(sys, 'thread_info') and sys.thread_info.version:
48 USING_LINUXTHREADS = sys.thread_info.version.startswith("linuxthreads")
49else:
50 USING_LINUXTHREADS = False
Brian Curtineb24d742010-04-12 17:16:38 +000051
Thomas Wouters0e3f5912006-08-11 14:57:12 +000052# Tests creating TESTFN
53class FileTests(unittest.TestCase):
54 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000055 if os.path.exists(support.TESTFN):
56 os.unlink(support.TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000057 tearDown = setUp
58
59 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000060 f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000061 os.close(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000062 self.assertTrue(os.access(support.TESTFN, os.W_OK))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000063
Christian Heimesfdab48e2008-01-20 09:06:41 +000064 def test_closerange(self):
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000065 first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
66 # We must allocate two consecutive file descriptors, otherwise
67 # it will mess up other file descriptors (perhaps even the three
68 # standard ones).
69 second = os.dup(first)
70 try:
71 retries = 0
72 while second != first + 1:
73 os.close(first)
74 retries += 1
75 if retries > 10:
76 # XXX test skipped
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000077 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000078 first, second = second, os.dup(second)
79 finally:
80 os.close(second)
Christian Heimesfdab48e2008-01-20 09:06:41 +000081 # close a fd that is open, and one that isn't
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000082 os.closerange(first, first + 2)
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000083 self.assertRaises(OSError, os.write, first, b"a")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000084
Benjamin Peterson1cc6df92010-06-30 17:39:45 +000085 @support.cpython_only
Hirokazu Yamamoto4c19e6e2008-09-08 23:41:21 +000086 def test_rename(self):
87 path = support.TESTFN
88 old = sys.getrefcount(path)
89 self.assertRaises(TypeError, os.rename, path, 0)
90 new = sys.getrefcount(path)
91 self.assertEqual(old, new)
92
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000093 def test_read(self):
94 with open(support.TESTFN, "w+b") as fobj:
95 fobj.write(b"spam")
96 fobj.flush()
97 fd = fobj.fileno()
98 os.lseek(fd, 0, 0)
99 s = os.read(fd, 4)
100 self.assertEqual(type(s), bytes)
101 self.assertEqual(s, b"spam")
102
103 def test_write(self):
104 # os.write() accepts bytes- and buffer-like objects but not strings
105 fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY)
106 self.assertRaises(TypeError, os.write, fd, "beans")
107 os.write(fd, b"bacon\n")
108 os.write(fd, bytearray(b"eggs\n"))
109 os.write(fd, memoryview(b"spam\n"))
110 os.close(fd)
111 with open(support.TESTFN, "rb") as fobj:
Antoine Pitroud62269f2008-09-15 23:54:52 +0000112 self.assertEqual(fobj.read().splitlines(),
113 [b"bacon", b"eggs", b"spam"])
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000114
Victor Stinnere0daff12011-03-20 23:36:35 +0100115 def write_windows_console(self, *args):
116 retcode = subprocess.call(args,
117 # use a new console to not flood the test output
118 creationflags=subprocess.CREATE_NEW_CONSOLE,
119 # use a shell to hide the console window (SW_HIDE)
120 shell=True)
121 self.assertEqual(retcode, 0)
122
123 @unittest.skipUnless(sys.platform == 'win32',
124 'test specific to the Windows console')
125 def test_write_windows_console(self):
126 # Issue #11395: the Windows console returns an error (12: not enough
127 # space error) on writing into stdout if stdout mode is binary and the
128 # length is greater than 66,000 bytes (or less, depending on heap
129 # usage).
130 code = "print('x' * 100000)"
131 self.write_windows_console(sys.executable, "-c", code)
132 self.write_windows_console(sys.executable, "-u", "-c", code)
133
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000134 def fdopen_helper(self, *args):
135 fd = os.open(support.TESTFN, os.O_RDONLY)
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200136 f = os.fdopen(fd, *args)
137 f.close()
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000138
139 def test_fdopen(self):
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200140 fd = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
141 os.close(fd)
142
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000143 self.fdopen_helper()
144 self.fdopen_helper('r')
145 self.fdopen_helper('r', 100)
146
Antoine Pitrouf3b2d882012-01-30 22:08:52 +0100147 def test_replace(self):
148 TESTFN2 = support.TESTFN + ".2"
149 with open(support.TESTFN, 'w') as f:
150 f.write("1")
151 with open(TESTFN2, 'w') as f:
152 f.write("2")
153 self.addCleanup(os.unlink, TESTFN2)
154 os.replace(support.TESTFN, TESTFN2)
155 self.assertRaises(FileNotFoundError, os.stat, support.TESTFN)
156 with open(TESTFN2, 'r') as f:
157 self.assertEqual(f.read(), "1")
158
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200159
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000160# Test attributes on return values from os.*stat* family.
161class StatAttributeTests(unittest.TestCase):
162 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000163 os.mkdir(support.TESTFN)
164 self.fname = os.path.join(support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000165 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +0000166 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000167 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000168
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000169 def tearDown(self):
170 os.unlink(self.fname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000171 os.rmdir(support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000172
Antoine Pitrou38425292010-09-21 18:19:07 +0000173 def check_stat_attributes(self, fname):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000174 if not hasattr(os, "stat"):
175 return
176
Antoine Pitrou38425292010-09-21 18:19:07 +0000177 result = os.stat(fname)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000178
179 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000180 self.assertEqual(result[stat.ST_SIZE], 3)
181 self.assertEqual(result.st_size, 3)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000182
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000183 # Make sure all the attributes are there
184 members = dir(result)
185 for name in dir(stat):
186 if name[:3] == 'ST_':
187 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000188 if name.endswith("TIME"):
189 def trunc(x): return int(x)
190 else:
191 def trunc(x): return x
Ezio Melottib3aedd42010-11-20 19:04:17 +0000192 self.assertEqual(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000193 result[getattr(stat, name)])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000194 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000195
Larry Hastings6fe20b32012-04-19 15:07:49 -0700196 # Make sure that the st_?time and st_?time_ns fields roughly agree
Larry Hastings76ad59b2012-05-03 00:30:07 -0700197 # (they should always agree up to around tens-of-microseconds)
Larry Hastings6fe20b32012-04-19 15:07:49 -0700198 for name in 'st_atime st_mtime st_ctime'.split():
199 floaty = int(getattr(result, name) * 100000)
200 nanosecondy = getattr(result, name + "_ns") // 10000
Larry Hastings76ad59b2012-05-03 00:30:07 -0700201 self.assertAlmostEqual(floaty, nanosecondy, delta=2)
Larry Hastings6fe20b32012-04-19 15:07:49 -0700202
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000203 try:
204 result[200]
205 self.fail("No exception thrown")
206 except IndexError:
207 pass
208
209 # Make sure that assignment fails
210 try:
211 result.st_mode = 1
212 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000213 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000214 pass
215
216 try:
217 result.st_rdev = 1
218 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000219 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000220 pass
221
222 try:
223 result.parrot = 1
224 self.fail("No exception thrown")
225 except AttributeError:
226 pass
227
228 # Use the stat_result constructor with a too-short tuple.
229 try:
230 result2 = os.stat_result((10,))
231 self.fail("No exception thrown")
232 except TypeError:
233 pass
234
Ezio Melotti42da6632011-03-15 05:18:48 +0200235 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000236 try:
237 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
238 except TypeError:
239 pass
240
Antoine Pitrou38425292010-09-21 18:19:07 +0000241 def test_stat_attributes(self):
242 self.check_stat_attributes(self.fname)
243
244 def test_stat_attributes_bytes(self):
245 try:
246 fname = self.fname.encode(sys.getfilesystemencoding())
247 except UnicodeEncodeError:
248 self.skipTest("cannot encode %a for the filesystem" % self.fname)
Victor Stinner1ab6c2d2011-11-15 22:27:41 +0100249 with warnings.catch_warnings():
250 warnings.simplefilter("ignore", DeprecationWarning)
251 self.check_stat_attributes(fname)
Tim Peterse0c446b2001-10-18 21:57:37 +0000252
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000253 def test_statvfs_attributes(self):
254 if not hasattr(os, "statvfs"):
255 return
256
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000257 try:
258 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000259 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000260 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000261 if e.errno == errno.ENOSYS:
262 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000263
264 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000265 self.assertEqual(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000266
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000267 # Make sure all the attributes are there.
268 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
269 'ffree', 'favail', 'flag', 'namemax')
270 for value, member in enumerate(members):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000271 self.assertEqual(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000272
273 # Make sure that assignment really fails
274 try:
275 result.f_bfree = 1
276 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000277 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000278 pass
279
280 try:
281 result.parrot = 1
282 self.fail("No exception thrown")
283 except AttributeError:
284 pass
285
286 # Use the constructor with a too-short tuple.
287 try:
288 result2 = os.statvfs_result((10,))
289 self.fail("No exception thrown")
290 except TypeError:
291 pass
292
Ezio Melotti42da6632011-03-15 05:18:48 +0200293 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000294 try:
295 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
296 except TypeError:
297 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000298
Thomas Wouters89f507f2006-12-13 04:49:30 +0000299 def test_utime_dir(self):
300 delta = 1000000
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000301 st = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000302 # round to int, because some systems may support sub-second
303 # time stamps in stat, but not in utime.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000304 os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
305 st2 = os.stat(support.TESTFN)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000306 self.assertEqual(st2.st_mtime, int(st.st_mtime-delta))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000307
Larry Hastings76ad59b2012-05-03 00:30:07 -0700308 def _test_utime(self, filename, attr, utime, delta):
Brian Curtin0277aa32011-11-06 13:50:15 -0600309 # Issue #13327 removed the requirement to pass None as the
Brian Curtin52fbea12011-11-06 13:41:17 -0600310 # second argument. Check that the previous methods of passing
311 # a time tuple or None work in addition to no argument.
Larry Hastings76ad59b2012-05-03 00:30:07 -0700312 st0 = os.stat(filename)
Brian Curtin52fbea12011-11-06 13:41:17 -0600313 # Doesn't set anything new, but sets the time tuple way
Larry Hastings76ad59b2012-05-03 00:30:07 -0700314 utime(filename, (attr(st0, "st_atime"), attr(st0, "st_mtime")))
315 # Setting the time to the time you just read, then reading again,
316 # should always return exactly the same times.
317 st1 = os.stat(filename)
318 self.assertEqual(attr(st0, "st_mtime"), attr(st1, "st_mtime"))
319 self.assertEqual(attr(st0, "st_atime"), attr(st1, "st_atime"))
Brian Curtin52fbea12011-11-06 13:41:17 -0600320 # Set to the current time in the old explicit way.
Larry Hastings76ad59b2012-05-03 00:30:07 -0700321 os.utime(filename, None)
Brian Curtin52fbea12011-11-06 13:41:17 -0600322 st2 = os.stat(support.TESTFN)
Larry Hastings76ad59b2012-05-03 00:30:07 -0700323 # Set to the current time in the new way
324 os.utime(filename)
325 st3 = os.stat(filename)
326 self.assertAlmostEqual(attr(st2, "st_mtime"), attr(st3, "st_mtime"), delta=delta)
327
328 def test_utime(self):
329 def utime(file, times):
330 return os.utime(file, times)
331 self._test_utime(self.fname, getattr, utime, 10)
332 self._test_utime(support.TESTFN, getattr, utime, 10)
333
334
335 def _test_utime_ns(self, set_times_ns, test_dir=True):
336 def getattr_ns(o, attr):
337 return getattr(o, attr + "_ns")
338 ten_s = 10 * 1000 * 1000 * 1000
339 self._test_utime(self.fname, getattr_ns, set_times_ns, ten_s)
340 if test_dir:
341 self._test_utime(support.TESTFN, getattr_ns, set_times_ns, ten_s)
342
343 def test_utime_ns(self):
344 def utime_ns(file, times):
345 return os.utime(file, ns=times)
346 self._test_utime_ns(utime_ns)
347
Larry Hastings9cf065c2012-06-22 16:30:09 -0700348 requires_utime_dir_fd = unittest.skipUnless(
349 os.utime in os.supports_dir_fd,
350 "dir_fd support for utime required for this test.")
351 requires_utime_fd = unittest.skipUnless(
352 os.utime in os.supports_fd,
353 "fd support for utime required for this test.")
354 requires_utime_nofollow_symlinks = unittest.skipUnless(
355 os.utime in os.supports_follow_symlinks,
356 "follow_symlinks support for utime required for this test.")
Larry Hastings76ad59b2012-05-03 00:30:07 -0700357
Larry Hastings9cf065c2012-06-22 16:30:09 -0700358 @requires_utime_nofollow_symlinks
Larry Hastings76ad59b2012-05-03 00:30:07 -0700359 def test_lutimes_ns(self):
360 def lutimes_ns(file, times):
Larry Hastings9cf065c2012-06-22 16:30:09 -0700361 return os.utime(file, ns=times, follow_symlinks=False)
Larry Hastings76ad59b2012-05-03 00:30:07 -0700362 self._test_utime_ns(lutimes_ns)
363
Larry Hastings9cf065c2012-06-22 16:30:09 -0700364 @requires_utime_fd
Larry Hastings76ad59b2012-05-03 00:30:07 -0700365 def test_futimes_ns(self):
366 def futimes_ns(file, times):
367 with open(file, "wb") as f:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700368 os.utime(f.fileno(), ns=times)
Larry Hastings76ad59b2012-05-03 00:30:07 -0700369 self._test_utime_ns(futimes_ns, test_dir=False)
370
371 def _utime_invalid_arguments(self, name, arg):
Larry Hastings9cf065c2012-06-22 16:30:09 -0700372 with self.assertRaises(ValueError):
Larry Hastings76ad59b2012-05-03 00:30:07 -0700373 getattr(os, name)(arg, (5, 5), ns=(5, 5))
374
375 def test_utime_invalid_arguments(self):
376 self._utime_invalid_arguments('utime', self.fname)
377
Brian Curtin52fbea12011-11-06 13:41:17 -0600378
Victor Stinner1aa54a42012-02-08 04:09:37 +0100379 @unittest.skipUnless(stat_supports_subsecond,
380 "os.stat() doesn't has a subsecond resolution")
Victor Stinnera2f7c002012-02-08 03:36:25 +0100381 def _test_utime_subsecond(self, set_time_func):
Victor Stinnerbe557de2012-02-08 03:01:11 +0100382 asec, amsec = 1, 901
383 atime = asec + amsec * 1e-3
Victor Stinnera2f7c002012-02-08 03:36:25 +0100384 msec, mmsec = 2, 901
Victor Stinnerbe557de2012-02-08 03:01:11 +0100385 mtime = msec + mmsec * 1e-3
386 filename = self.fname
Victor Stinnera2f7c002012-02-08 03:36:25 +0100387 os.utime(filename, (0, 0))
388 set_time_func(filename, atime, mtime)
Victor Stinner034d0aa2012-06-05 01:22:15 +0200389 with warnings.catch_warnings():
390 warnings.simplefilter("ignore", DeprecationWarning)
391 os.stat_float_times(True)
Victor Stinnera2f7c002012-02-08 03:36:25 +0100392 st = os.stat(filename)
393 self.assertAlmostEqual(st.st_atime, atime, places=3)
394 self.assertAlmostEqual(st.st_mtime, mtime, places=3)
Victor Stinnerbe557de2012-02-08 03:01:11 +0100395
Victor Stinnera2f7c002012-02-08 03:36:25 +0100396 def test_utime_subsecond(self):
397 def set_time(filename, atime, mtime):
398 os.utime(filename, (atime, mtime))
399 self._test_utime_subsecond(set_time)
400
Larry Hastings9cf065c2012-06-22 16:30:09 -0700401 @requires_utime_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100402 def test_futimes_subsecond(self):
403 def set_time(filename, atime, mtime):
404 with open(filename, "wb") as f:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700405 os.utime(f.fileno(), times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100406 self._test_utime_subsecond(set_time)
407
Larry Hastings9cf065c2012-06-22 16:30:09 -0700408 @requires_utime_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100409 def test_futimens_subsecond(self):
410 def set_time(filename, atime, mtime):
411 with open(filename, "wb") as f:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700412 os.utime(f.fileno(), times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100413 self._test_utime_subsecond(set_time)
414
Larry Hastings9cf065c2012-06-22 16:30:09 -0700415 @requires_utime_dir_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100416 def test_futimesat_subsecond(self):
417 def set_time(filename, atime, mtime):
418 dirname = os.path.dirname(filename)
419 dirfd = os.open(dirname, os.O_RDONLY)
420 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700421 os.utime(os.path.basename(filename), dir_fd=dirfd,
422 times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100423 finally:
424 os.close(dirfd)
425 self._test_utime_subsecond(set_time)
426
Larry Hastings9cf065c2012-06-22 16:30:09 -0700427 @requires_utime_nofollow_symlinks
Victor Stinnera2f7c002012-02-08 03:36:25 +0100428 def test_lutimes_subsecond(self):
429 def set_time(filename, atime, mtime):
Larry Hastings9cf065c2012-06-22 16:30:09 -0700430 os.utime(filename, (atime, mtime), follow_symlinks=False)
Victor Stinnera2f7c002012-02-08 03:36:25 +0100431 self._test_utime_subsecond(set_time)
432
Larry Hastings9cf065c2012-06-22 16:30:09 -0700433 @requires_utime_dir_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100434 def test_utimensat_subsecond(self):
435 def set_time(filename, atime, mtime):
436 dirname = os.path.dirname(filename)
437 dirfd = os.open(dirname, os.O_RDONLY)
438 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700439 os.utime(os.path.basename(filename), dir_fd=dirfd,
440 times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100441 finally:
442 os.close(dirfd)
443 self._test_utime_subsecond(set_time)
Victor Stinnerbe557de2012-02-08 03:01:11 +0100444
Thomas Wouters89f507f2006-12-13 04:49:30 +0000445 # Restrict test to Win32, since there is no guarantee other
446 # systems support centiseconds
447 if sys.platform == 'win32':
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000448 def get_file_system(path):
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000449 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000450 import ctypes
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000451 kernel32 = ctypes.windll.kernel32
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000452 buf = ctypes.create_unicode_buffer("", 100)
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000453 if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000454 return buf.value
455
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000456 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000457 def test_1565150(self):
458 t1 = 1159195039.25
459 os.utime(self.fname, (t1, t1))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000460 self.assertEqual(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000461
Amaury Forgeot d'Arca251a852011-01-03 00:19:11 +0000462 def test_large_time(self):
463 t1 = 5000000000 # some day in 2128
464 os.utime(self.fname, (t1, t1))
465 self.assertEqual(os.stat(self.fname).st_mtime, t1)
466
Guido van Rossumd8faa362007-04-27 19:54:29 +0000467 def test_1686475(self):
468 # Verify that an open file can be stat'ed
469 try:
470 os.stat(r"c:\pagefile.sys")
471 except WindowsError as e:
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000472 if e.errno == 2: # file does not exist; cannot run test
Guido van Rossumd8faa362007-04-27 19:54:29 +0000473 return
474 self.fail("Could not stat pagefile.sys")
475
Richard Oudkerk2240ac12012-07-06 12:05:32 +0100476 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
477 def test_15261(self):
478 # Verify that stat'ing a closed fd does not cause crash
479 r, w = os.pipe()
480 try:
481 os.stat(r) # should not raise error
482 finally:
483 os.close(r)
484 os.close(w)
485 with self.assertRaises(OSError) as ctx:
486 os.stat(r)
487 self.assertEqual(ctx.exception.errno, errno.EBADF)
488
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000489from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000490
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000491class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000492 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000493 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000494
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000495 def setUp(self):
496 self.__save = dict(os.environ)
Victor Stinnerb745a742010-05-18 17:17:23 +0000497 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000498 self.__saveb = dict(os.environb)
Christian Heimes90333392007-11-01 19:08:42 +0000499 for key, value in self._reference().items():
500 os.environ[key] = value
501
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000502 def tearDown(self):
503 os.environ.clear()
504 os.environ.update(self.__save)
Victor Stinnerb745a742010-05-18 17:17:23 +0000505 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000506 os.environb.clear()
507 os.environb.update(self.__saveb)
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000508
Christian Heimes90333392007-11-01 19:08:42 +0000509 def _reference(self):
510 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
511
512 def _empty_mapping(self):
513 os.environ.clear()
514 return os.environ
515
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000516 # Bug 1110478
Ezio Melottic7e139b2012-09-26 20:01:34 +0300517 @unittest.skipUnless(os.path.exists('/bin/sh'), 'requires /bin/sh')
Martin v. Löwis5510f652005-02-17 21:23:20 +0000518 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000519 os.environ.clear()
Ezio Melottic7e139b2012-09-26 20:01:34 +0300520 os.environ.update(HELLO="World")
521 with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
522 value = popen.read().strip()
523 self.assertEqual(value, "World")
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000524
Ezio Melottic7e139b2012-09-26 20:01:34 +0300525 @unittest.skipUnless(os.path.exists('/bin/sh'), 'requires /bin/sh')
Christian Heimes1a13d592007-11-08 14:16:55 +0000526 def test_os_popen_iter(self):
Ezio Melottic7e139b2012-09-26 20:01:34 +0300527 with os.popen(
528 "/bin/sh -c 'echo \"line1\nline2\nline3\"'") as popen:
529 it = iter(popen)
530 self.assertEqual(next(it), "line1\n")
531 self.assertEqual(next(it), "line2\n")
532 self.assertEqual(next(it), "line3\n")
533 self.assertRaises(StopIteration, next, it)
Christian Heimes1a13d592007-11-08 14:16:55 +0000534
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000535 # Verify environ keys and values from the OS are of the
536 # correct str type.
537 def test_keyvalue_types(self):
538 for key, val in os.environ.items():
Ezio Melottib3aedd42010-11-20 19:04:17 +0000539 self.assertEqual(type(key), str)
540 self.assertEqual(type(val), str)
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000541
Christian Heimes90333392007-11-01 19:08:42 +0000542 def test_items(self):
543 for key, value in self._reference().items():
544 self.assertEqual(os.environ.get(key), value)
545
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000546 # Issue 7310
547 def test___repr__(self):
548 """Check that the repr() of os.environ looks like environ({...})."""
549 env = os.environ
Victor Stinner96f0de92010-07-29 00:29:00 +0000550 self.assertEqual(repr(env), 'environ({{{}}})'.format(', '.join(
551 '{!r}: {!r}'.format(key, value)
552 for key, value in env.items())))
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000553
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000554 def test_get_exec_path(self):
555 defpath_list = os.defpath.split(os.pathsep)
556 test_path = ['/monty', '/python', '', '/flying/circus']
557 test_env = {'PATH': os.pathsep.join(test_path)}
558
559 saved_environ = os.environ
560 try:
561 os.environ = dict(test_env)
562 # Test that defaulting to os.environ works.
563 self.assertSequenceEqual(test_path, os.get_exec_path())
564 self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
565 finally:
566 os.environ = saved_environ
567
568 # No PATH environment variable
569 self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
570 # Empty PATH environment variable
571 self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
572 # Supplied PATH environment variable
573 self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
574
Victor Stinnerb745a742010-05-18 17:17:23 +0000575 if os.supports_bytes_environ:
576 # env cannot contain 'PATH' and b'PATH' keys
Victor Stinner38430e22010-08-19 17:10:18 +0000577 try:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000578 # ignore BytesWarning warning
579 with warnings.catch_warnings(record=True):
580 mixed_env = {'PATH': '1', b'PATH': b'2'}
Victor Stinner38430e22010-08-19 17:10:18 +0000581 except BytesWarning:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000582 # mixed_env cannot be created with python -bb
Victor Stinner38430e22010-08-19 17:10:18 +0000583 pass
584 else:
585 self.assertRaises(ValueError, os.get_exec_path, mixed_env)
Victor Stinnerb745a742010-05-18 17:17:23 +0000586
587 # bytes key and/or value
588 self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}),
589 ['abc'])
590 self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}),
591 ['abc'])
592 self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}),
593 ['abc'])
594
595 @unittest.skipUnless(os.supports_bytes_environ,
596 "os.environb required for this test.")
Victor Stinner84ae1182010-05-06 22:05:07 +0000597 def test_environb(self):
598 # os.environ -> os.environb
599 value = 'euro\u20ac'
600 try:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000601 value_bytes = value.encode(sys.getfilesystemencoding(),
602 'surrogateescape')
Victor Stinner84ae1182010-05-06 22:05:07 +0000603 except UnicodeEncodeError:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000604 msg = "U+20AC character is not encodable to %s" % (
605 sys.getfilesystemencoding(),)
Benjamin Peterson932d3f42010-05-06 22:26:31 +0000606 self.skipTest(msg)
Victor Stinner84ae1182010-05-06 22:05:07 +0000607 os.environ['unicode'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000608 self.assertEqual(os.environ['unicode'], value)
609 self.assertEqual(os.environb[b'unicode'], value_bytes)
Victor Stinner84ae1182010-05-06 22:05:07 +0000610
611 # os.environb -> os.environ
612 value = b'\xff'
613 os.environb[b'bytes'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000614 self.assertEqual(os.environb[b'bytes'], value)
Victor Stinner84ae1182010-05-06 22:05:07 +0000615 value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000616 self.assertEqual(os.environ['bytes'], value_str)
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000617
Charles-François Natali2966f102011-11-26 11:32:46 +0100618 # On FreeBSD < 7 and OS X < 10.6, unsetenv() doesn't return a value (issue
619 # #13415).
620 @support.requires_freebsd_version(7)
621 @support.requires_mac_ver(10, 6)
Victor Stinner60b385e2011-11-22 22:01:28 +0100622 def test_unset_error(self):
623 if sys.platform == "win32":
624 # an environment variable is limited to 32,767 characters
625 key = 'x' * 50000
Victor Stinnerb3f82682011-11-22 22:30:19 +0100626 self.assertRaises(ValueError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100627 else:
628 # "=" is not allowed in a variable name
629 key = 'key='
Victor Stinnerb3f82682011-11-22 22:30:19 +0100630 self.assertRaises(OSError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100631
Tim Petersc4e09402003-04-25 07:11:48 +0000632class WalkTests(unittest.TestCase):
633 """Tests for os.walk()."""
634
Charles-François Natali7372b062012-02-05 15:15:38 +0100635 def setUp(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000636 import os
637 from os.path import join
638
639 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000640 # TESTFN/
641 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000642 # tmp1
643 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000644 # tmp2
645 # SUB11/ no kids
646 # SUB2/ a file kid and a dirsymlink kid
647 # tmp3
648 # link/ a symlink to TESTFN.2
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200649 # broken_link
Guido van Rossumd8faa362007-04-27 19:54:29 +0000650 # TEST2/
651 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000652 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000653 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000654 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000655 sub2_path = join(walk_path, "SUB2")
656 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000657 tmp2_path = join(sub1_path, "tmp2")
658 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000659 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000660 t2_path = join(support.TESTFN, "TEST2")
661 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200662 link_path = join(sub2_path, "link")
663 broken_link_path = join(sub2_path, "broken_link")
Tim Petersc4e09402003-04-25 07:11:48 +0000664
665 # Create stuff.
666 os.makedirs(sub11_path)
667 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000668 os.makedirs(t2_path)
669 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000670 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000671 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
672 f.close()
Brian Curtin3b4499c2010-12-28 14:31:47 +0000673 if support.can_symlink():
Antoine Pitrou5311c1d2012-01-24 08:59:28 +0100674 if os.name == 'nt':
675 def symlink_to_dir(src, dest):
676 os.symlink(src, dest, True)
677 else:
678 symlink_to_dir = os.symlink
679 symlink_to_dir(os.path.abspath(t2_path), link_path)
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200680 symlink_to_dir('broken', broken_link_path)
681 sub2_tree = (sub2_path, ["link"], ["broken_link", "tmp3"])
Guido van Rossumd8faa362007-04-27 19:54:29 +0000682 else:
683 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000684
685 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000686 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000687 self.assertEqual(len(all), 4)
688 # We can't know which order SUB1 and SUB2 will appear in.
689 # Not flipped: TESTFN, SUB1, SUB11, SUB2
690 # flipped: TESTFN, SUB2, SUB1, SUB11
691 flipped = all[0][1][0] != "SUB1"
692 all[0][1].sort()
Hynek Schlawackc96f5a02012-05-15 17:55:38 +0200693 all[3 - 2 * flipped][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000694 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000695 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
696 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000697 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000698
699 # Prune the search.
700 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000701 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000702 all.append((root, dirs, files))
703 # Don't descend into SUB1.
704 if 'SUB1' in dirs:
705 # Note that this also mutates the dirs we appended to all!
706 dirs.remove('SUB1')
707 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000708 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Hynek Schlawack39bf90d2012-05-15 18:40:17 +0200709 all[1][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000710 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000711
712 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000713 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000714 self.assertEqual(len(all), 4)
715 # We can't know which order SUB1 and SUB2 will appear in.
716 # Not flipped: SUB11, SUB1, SUB2, TESTFN
717 # flipped: SUB2, SUB11, SUB1, TESTFN
718 flipped = all[3][1][0] != "SUB1"
719 all[3][1].sort()
Hynek Schlawack39bf90d2012-05-15 18:40:17 +0200720 all[2 - 2 * flipped][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000721 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000722 self.assertEqual(all[flipped], (sub11_path, [], []))
723 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000724 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000725
Brian Curtin3b4499c2010-12-28 14:31:47 +0000726 if support.can_symlink():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000727 # Walk, following symlinks.
728 for root, dirs, files in os.walk(walk_path, followlinks=True):
729 if root == link_path:
730 self.assertEqual(dirs, [])
731 self.assertEqual(files, ["tmp4"])
732 break
733 else:
734 self.fail("Didn't follow symlink with followlinks=True")
735
736 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000737 # Tear everything down. This is a decent use for bottom-up on
738 # Windows, which doesn't have a recursive delete command. The
739 # (not so) subtlety is that rmdir will fail unless the dir's
740 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000741 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000742 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000743 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000744 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000745 dirname = os.path.join(root, name)
746 if not os.path.islink(dirname):
747 os.rmdir(dirname)
748 else:
749 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000750 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000751
Charles-François Natali7372b062012-02-05 15:15:38 +0100752
753@unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
754class FwalkTests(WalkTests):
755 """Tests for os.fwalk()."""
756
Larry Hastingsc48fe982012-06-25 04:49:05 -0700757 def _compare_to_walk(self, walk_kwargs, fwalk_kwargs):
758 """
759 compare with walk() results.
760 """
Larry Hastingsb4038062012-07-15 10:57:38 -0700761 walk_kwargs = walk_kwargs.copy()
762 fwalk_kwargs = fwalk_kwargs.copy()
763 for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
764 walk_kwargs.update(topdown=topdown, followlinks=follow_symlinks)
765 fwalk_kwargs.update(topdown=topdown, follow_symlinks=follow_symlinks)
Larry Hastingsc48fe982012-06-25 04:49:05 -0700766
Charles-François Natali7372b062012-02-05 15:15:38 +0100767 expected = {}
Larry Hastingsc48fe982012-06-25 04:49:05 -0700768 for root, dirs, files in os.walk(**walk_kwargs):
Charles-François Natali7372b062012-02-05 15:15:38 +0100769 expected[root] = (set(dirs), set(files))
770
Larry Hastingsc48fe982012-06-25 04:49:05 -0700771 for root, dirs, files, rootfd in os.fwalk(**fwalk_kwargs):
Charles-François Natali7372b062012-02-05 15:15:38 +0100772 self.assertIn(root, expected)
773 self.assertEqual(expected[root], (set(dirs), set(files)))
774
Larry Hastingsc48fe982012-06-25 04:49:05 -0700775 def test_compare_to_walk(self):
776 kwargs = {'top': support.TESTFN}
777 self._compare_to_walk(kwargs, kwargs)
778
Charles-François Natali7372b062012-02-05 15:15:38 +0100779 def test_dir_fd(self):
Larry Hastingsc48fe982012-06-25 04:49:05 -0700780 try:
781 fd = os.open(".", os.O_RDONLY)
782 walk_kwargs = {'top': support.TESTFN}
783 fwalk_kwargs = walk_kwargs.copy()
784 fwalk_kwargs['dir_fd'] = fd
785 self._compare_to_walk(walk_kwargs, fwalk_kwargs)
786 finally:
787 os.close(fd)
788
789 def test_yields_correct_dir_fd(self):
Charles-François Natali7372b062012-02-05 15:15:38 +0100790 # check returned file descriptors
Larry Hastingsb4038062012-07-15 10:57:38 -0700791 for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
792 args = support.TESTFN, topdown, None
793 for root, dirs, files, rootfd in os.fwalk(*args, follow_symlinks=follow_symlinks):
Charles-François Natali7372b062012-02-05 15:15:38 +0100794 # check that the FD is valid
795 os.fstat(rootfd)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700796 # redundant check
797 os.stat(rootfd)
798 # check that listdir() returns consistent information
799 self.assertEqual(set(os.listdir(rootfd)), set(dirs) | set(files))
Charles-François Natali7372b062012-02-05 15:15:38 +0100800
801 def test_fd_leak(self):
802 # Since we're opening a lot of FDs, we must be careful to avoid leaks:
803 # we both check that calling fwalk() a large number of times doesn't
804 # yield EMFILE, and that the minimum allocated FD hasn't changed.
805 minfd = os.dup(1)
806 os.close(minfd)
807 for i in range(256):
808 for x in os.fwalk(support.TESTFN):
809 pass
810 newfd = os.dup(1)
811 self.addCleanup(os.close, newfd)
812 self.assertEqual(newfd, minfd)
813
814 def tearDown(self):
815 # cleanup
816 for root, dirs, files, rootfd in os.fwalk(support.TESTFN, topdown=False):
817 for name in files:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700818 os.unlink(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +0100819 for name in dirs:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700820 st = os.stat(name, dir_fd=rootfd, follow_symlinks=False)
Larry Hastingsb698d8e2012-06-23 16:55:07 -0700821 if stat.S_ISDIR(st.st_mode):
822 os.rmdir(name, dir_fd=rootfd)
823 else:
824 os.unlink(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +0100825 os.rmdir(support.TESTFN)
826
827
Guido van Rossume7ba4952007-06-06 23:52:48 +0000828class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000829 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000830 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000831
832 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000833 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000834 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
835 os.makedirs(path) # Should work
836 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
837 os.makedirs(path)
838
839 # Try paths with a '.' in them
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000840 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000841 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
842 os.makedirs(path)
843 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
844 'dir5', 'dir6')
845 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000846
Terry Reedy5a22b652010-12-02 07:05:56 +0000847 def test_exist_ok_existing_directory(self):
848 path = os.path.join(support.TESTFN, 'dir1')
849 mode = 0o777
850 old_mask = os.umask(0o022)
851 os.makedirs(path, mode)
852 self.assertRaises(OSError, os.makedirs, path, mode)
853 self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
854 self.assertRaises(OSError, os.makedirs, path, 0o776, exist_ok=True)
855 os.makedirs(path, mode=mode, exist_ok=True)
856 os.umask(old_mask)
857
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700858 def test_exist_ok_s_isgid_directory(self):
859 path = os.path.join(support.TESTFN, 'dir1')
860 S_ISGID = stat.S_ISGID
861 mode = 0o777
862 old_mask = os.umask(0o022)
863 try:
864 existing_testfn_mode = stat.S_IMODE(
865 os.lstat(support.TESTFN).st_mode)
Ned Deilyc622f422012-08-08 20:57:24 -0700866 try:
867 os.chmod(support.TESTFN, existing_testfn_mode | S_ISGID)
Ned Deily3a2b97e2012-08-08 21:03:02 -0700868 except PermissionError:
Ned Deilyc622f422012-08-08 20:57:24 -0700869 raise unittest.SkipTest('Cannot set S_ISGID for dir.')
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700870 if (os.lstat(support.TESTFN).st_mode & S_ISGID != S_ISGID):
871 raise unittest.SkipTest('No support for S_ISGID dir mode.')
872 # The os should apply S_ISGID from the parent dir for us, but
873 # this test need not depend on that behavior. Be explicit.
874 os.makedirs(path, mode | S_ISGID)
875 # http://bugs.python.org/issue14992
876 # Should not fail when the bit is already set.
877 os.makedirs(path, mode, exist_ok=True)
878 # remove the bit.
879 os.chmod(path, stat.S_IMODE(os.lstat(path).st_mode) & ~S_ISGID)
880 with self.assertRaises(OSError):
881 # Should fail when the bit is not already set when demanded.
882 os.makedirs(path, mode | S_ISGID, exist_ok=True)
883 finally:
884 os.umask(old_mask)
Terry Reedy5a22b652010-12-02 07:05:56 +0000885
886 def test_exist_ok_existing_regular_file(self):
887 base = support.TESTFN
888 path = os.path.join(support.TESTFN, 'dir1')
889 f = open(path, 'w')
890 f.write('abc')
891 f.close()
892 self.assertRaises(OSError, os.makedirs, path)
893 self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
894 self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
895 os.remove(path)
896
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000897 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000898 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000899 'dir4', 'dir5', 'dir6')
900 # If the tests failed, the bottom-most directory ('../dir6')
901 # may not have been created, so we look for the outermost directory
902 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000903 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000904 path = os.path.dirname(path)
905
906 os.removedirs(path)
907
Guido van Rossume7ba4952007-06-06 23:52:48 +0000908class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000909 def test_devnull(self):
Victor Stinnera6d2c762011-06-30 18:20:11 +0200910 with open(os.devnull, 'wb') as f:
911 f.write(b'hello')
912 f.close()
913 with open(os.devnull, 'rb') as f:
914 self.assertEqual(f.read(), b'')
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000915
Guido van Rossume7ba4952007-06-06 23:52:48 +0000916class URandomTests(unittest.TestCase):
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100917 def test_urandom_length(self):
918 self.assertEqual(len(os.urandom(0)), 0)
919 self.assertEqual(len(os.urandom(1)), 1)
920 self.assertEqual(len(os.urandom(10)), 10)
921 self.assertEqual(len(os.urandom(100)), 100)
922 self.assertEqual(len(os.urandom(1000)), 1000)
923
924 def test_urandom_value(self):
925 data1 = os.urandom(16)
926 data2 = os.urandom(16)
927 self.assertNotEqual(data1, data2)
928
929 def get_urandom_subprocess(self, count):
930 code = '\n'.join((
931 'import os, sys',
932 'data = os.urandom(%s)' % count,
933 'sys.stdout.buffer.write(data)',
934 'sys.stdout.buffer.flush()'))
935 out = assert_python_ok('-c', code)
936 stdout = out[1]
937 self.assertEqual(len(stdout), 16)
938 return stdout
939
940 def test_urandom_subprocess(self):
941 data1 = self.get_urandom_subprocess(16)
942 data2 = self.get_urandom_subprocess(16)
943 self.assertNotEqual(data1, data2)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000944
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000945@contextlib.contextmanager
946def _execvpe_mockup(defpath=None):
947 """
948 Stubs out execv and execve functions when used as context manager.
949 Records exec calls. The mock execv and execve functions always raise an
950 exception as they would normally never return.
951 """
952 # A list of tuples containing (function name, first arg, args)
953 # of calls to execv or execve that have been made.
954 calls = []
955
956 def mock_execv(name, *args):
957 calls.append(('execv', name, args))
958 raise RuntimeError("execv called")
959
960 def mock_execve(name, *args):
961 calls.append(('execve', name, args))
962 raise OSError(errno.ENOTDIR, "execve called")
963
964 try:
965 orig_execv = os.execv
966 orig_execve = os.execve
967 orig_defpath = os.defpath
968 os.execv = mock_execv
969 os.execve = mock_execve
970 if defpath is not None:
971 os.defpath = defpath
972 yield calls
973 finally:
974 os.execv = orig_execv
975 os.execve = orig_execve
976 os.defpath = orig_defpath
977
Guido van Rossume7ba4952007-06-06 23:52:48 +0000978class ExecTests(unittest.TestCase):
Mark Dickinson7cf03892010-04-16 13:45:35 +0000979 @unittest.skipIf(USING_LINUXTHREADS,
980 "avoid triggering a linuxthreads bug: see issue #4970")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000981 def test_execvpe_with_bad_program(self):
Mark Dickinson7cf03892010-04-16 13:45:35 +0000982 self.assertRaises(OSError, os.execvpe, 'no such app-',
983 ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000984
Thomas Heller6790d602007-08-30 17:15:14 +0000985 def test_execvpe_with_bad_arglist(self):
986 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
987
Gregory P. Smith4ae37772010-05-08 18:05:46 +0000988 @unittest.skipUnless(hasattr(os, '_execvpe'),
989 "No internal os._execvpe function to test.")
Victor Stinnerb745a742010-05-18 17:17:23 +0000990 def _test_internal_execvpe(self, test_type):
991 program_path = os.sep + 'absolutepath'
992 if test_type is bytes:
993 program = b'executable'
994 fullpath = os.path.join(os.fsencode(program_path), program)
995 native_fullpath = fullpath
996 arguments = [b'progname', 'arg1', 'arg2']
997 else:
998 program = 'executable'
999 arguments = ['progname', 'arg1', 'arg2']
1000 fullpath = os.path.join(program_path, program)
1001 if os.name != "nt":
1002 native_fullpath = os.fsencode(fullpath)
1003 else:
1004 native_fullpath = fullpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001005 env = {'spam': 'beans'}
1006
Victor Stinnerb745a742010-05-18 17:17:23 +00001007 # test os._execvpe() with an absolute path
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001008 with _execvpe_mockup() as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +00001009 self.assertRaises(RuntimeError,
1010 os._execvpe, fullpath, arguments)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001011 self.assertEqual(len(calls), 1)
1012 self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))
1013
Victor Stinnerb745a742010-05-18 17:17:23 +00001014 # test os._execvpe() with a relative path:
1015 # os.get_exec_path() returns defpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001016 with _execvpe_mockup(defpath=program_path) as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +00001017 self.assertRaises(OSError,
1018 os._execvpe, program, arguments, env=env)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001019 self.assertEqual(len(calls), 1)
Victor Stinnerb745a742010-05-18 17:17:23 +00001020 self.assertSequenceEqual(calls[0],
1021 ('execve', native_fullpath, (arguments, env)))
1022
1023 # test os._execvpe() with a relative path:
1024 # os.get_exec_path() reads the 'PATH' variable
1025 with _execvpe_mockup() as calls:
1026 env_path = env.copy()
Victor Stinner38430e22010-08-19 17:10:18 +00001027 if test_type is bytes:
1028 env_path[b'PATH'] = program_path
1029 else:
1030 env_path['PATH'] = program_path
Victor Stinnerb745a742010-05-18 17:17:23 +00001031 self.assertRaises(OSError,
1032 os._execvpe, program, arguments, env=env_path)
1033 self.assertEqual(len(calls), 1)
1034 self.assertSequenceEqual(calls[0],
1035 ('execve', native_fullpath, (arguments, env_path)))
1036
1037 def test_internal_execvpe_str(self):
1038 self._test_internal_execvpe(str)
1039 if os.name != "nt":
1040 self._test_internal_execvpe(bytes)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001041
Gregory P. Smith4ae37772010-05-08 18:05:46 +00001042
Thomas Wouters477c8d52006-05-27 19:21:47 +00001043class Win32ErrorTests(unittest.TestCase):
1044 def test_rename(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001045 self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001046
1047 def test_remove(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001048 self.assertRaises(WindowsError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001049
1050 def test_chdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001051 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001052
1053 def test_mkdir(self):
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +00001054 f = open(support.TESTFN, "w")
Benjamin Petersonf91df042009-02-13 02:50:59 +00001055 try:
1056 self.assertRaises(WindowsError, os.mkdir, support.TESTFN)
1057 finally:
1058 f.close()
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +00001059 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001060
1061 def test_utime(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001062 self.assertRaises(WindowsError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001063
Thomas Wouters477c8d52006-05-27 19:21:47 +00001064 def test_chmod(self):
Benjamin Petersonf91df042009-02-13 02:50:59 +00001065 self.assertRaises(WindowsError, os.chmod, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001066
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001067class TestInvalidFD(unittest.TestCase):
Benjamin Peterson05e782f2009-01-19 15:15:02 +00001068 singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001069 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
1070 #singles.append("close")
1071 #We omit close because it doesn'r raise an exception on some platforms
1072 def get_single(f):
1073 def helper(self):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001074 if hasattr(os, f):
1075 self.check(getattr(os, f))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001076 return helper
1077 for f in singles:
1078 locals()["test_"+f] = get_single(f)
1079
Benjamin Peterson7522c742009-01-19 21:00:09 +00001080 def check(self, f, *args):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001081 try:
1082 f(support.make_bad_fd(), *args)
1083 except OSError as e:
1084 self.assertEqual(e.errno, errno.EBADF)
1085 else:
1086 self.fail("%r didn't raise a OSError with a bad file descriptor"
1087 % f)
Benjamin Peterson7522c742009-01-19 21:00:09 +00001088
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001089 def test_isatty(self):
1090 if hasattr(os, "isatty"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001091 self.assertEqual(os.isatty(support.make_bad_fd()), False)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001092
1093 def test_closerange(self):
1094 if hasattr(os, "closerange"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001095 fd = support.make_bad_fd()
R. David Murray630cc482009-07-22 15:20:27 +00001096 # Make sure none of the descriptors we are about to close are
1097 # currently valid (issue 6542).
1098 for i in range(10):
1099 try: os.fstat(fd+i)
1100 except OSError:
1101 pass
1102 else:
1103 break
1104 if i < 2:
1105 raise unittest.SkipTest(
1106 "Unable to acquire a range of invalid file descriptors")
1107 self.assertEqual(os.closerange(fd, fd + i-1), None)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001108
1109 def test_dup2(self):
1110 if hasattr(os, "dup2"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001111 self.check(os.dup2, 20)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001112
1113 def test_fchmod(self):
1114 if hasattr(os, "fchmod"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001115 self.check(os.fchmod, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001116
1117 def test_fchown(self):
1118 if hasattr(os, "fchown"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001119 self.check(os.fchown, -1, -1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001120
1121 def test_fpathconf(self):
1122 if hasattr(os, "fpathconf"):
Georg Brandl306336b2012-06-24 12:55:33 +02001123 self.check(os.pathconf, "PC_NAME_MAX")
Benjamin Peterson7522c742009-01-19 21:00:09 +00001124 self.check(os.fpathconf, "PC_NAME_MAX")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001125
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001126 def test_ftruncate(self):
1127 if hasattr(os, "ftruncate"):
Georg Brandl306336b2012-06-24 12:55:33 +02001128 self.check(os.truncate, 0)
Benjamin Peterson7522c742009-01-19 21:00:09 +00001129 self.check(os.ftruncate, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001130
1131 def test_lseek(self):
1132 if hasattr(os, "lseek"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001133 self.check(os.lseek, 0, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001134
1135 def test_read(self):
1136 if hasattr(os, "read"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001137 self.check(os.read, 1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001138
1139 def test_tcsetpgrpt(self):
1140 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001141 self.check(os.tcsetpgrp, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001142
1143 def test_write(self):
1144 if hasattr(os, "write"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001145 self.check(os.write, b" ")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001146
Brian Curtin1b9df392010-11-24 20:24:31 +00001147
1148class LinkTests(unittest.TestCase):
1149 def setUp(self):
1150 self.file1 = support.TESTFN
1151 self.file2 = os.path.join(support.TESTFN + "2")
1152
Brian Curtinc0abc4e2010-11-30 23:46:54 +00001153 def tearDown(self):
Brian Curtin1b9df392010-11-24 20:24:31 +00001154 for file in (self.file1, self.file2):
1155 if os.path.exists(file):
1156 os.unlink(file)
1157
Brian Curtin1b9df392010-11-24 20:24:31 +00001158 def _test_link(self, file1, file2):
1159 with open(file1, "w") as f1:
1160 f1.write("test")
1161
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001162 with warnings.catch_warnings():
1163 warnings.simplefilter("ignore", DeprecationWarning)
1164 os.link(file1, file2)
Brian Curtin1b9df392010-11-24 20:24:31 +00001165 with open(file1, "r") as f1, open(file2, "r") as f2:
1166 self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
1167
1168 def test_link(self):
1169 self._test_link(self.file1, self.file2)
1170
1171 def test_link_bytes(self):
1172 self._test_link(bytes(self.file1, sys.getfilesystemencoding()),
1173 bytes(self.file2, sys.getfilesystemencoding()))
1174
Brian Curtinf498b752010-11-30 15:54:04 +00001175 def test_unicode_name(self):
Brian Curtin43f0c272010-11-30 15:40:04 +00001176 try:
Brian Curtinf498b752010-11-30 15:54:04 +00001177 os.fsencode("\xf1")
Brian Curtin43f0c272010-11-30 15:40:04 +00001178 except UnicodeError:
1179 raise unittest.SkipTest("Unable to encode for this platform.")
1180
Brian Curtinf498b752010-11-30 15:54:04 +00001181 self.file1 += "\xf1"
Brian Curtinfc889c42010-11-28 23:59:46 +00001182 self.file2 = self.file1 + "2"
1183 self._test_link(self.file1, self.file2)
1184
Thomas Wouters477c8d52006-05-27 19:21:47 +00001185if sys.platform != 'win32':
1186 class Win32ErrorTests(unittest.TestCase):
1187 pass
1188
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001189 class PosixUidGidTests(unittest.TestCase):
1190 if hasattr(os, 'setuid'):
1191 def test_setuid(self):
1192 if os.getuid() != 0:
1193 self.assertRaises(os.error, os.setuid, 0)
1194 self.assertRaises(OverflowError, os.setuid, 1<<32)
1195
1196 if hasattr(os, 'setgid'):
1197 def test_setgid(self):
1198 if os.getuid() != 0:
1199 self.assertRaises(os.error, os.setgid, 0)
1200 self.assertRaises(OverflowError, os.setgid, 1<<32)
1201
1202 if hasattr(os, 'seteuid'):
1203 def test_seteuid(self):
1204 if os.getuid() != 0:
1205 self.assertRaises(os.error, os.seteuid, 0)
1206 self.assertRaises(OverflowError, os.seteuid, 1<<32)
1207
1208 if hasattr(os, 'setegid'):
1209 def test_setegid(self):
1210 if os.getuid() != 0:
1211 self.assertRaises(os.error, os.setegid, 0)
1212 self.assertRaises(OverflowError, os.setegid, 1<<32)
1213
1214 if hasattr(os, 'setreuid'):
1215 def test_setreuid(self):
1216 if os.getuid() != 0:
1217 self.assertRaises(os.error, os.setreuid, 0, 0)
1218 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
1219 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001220
1221 def test_setreuid_neg1(self):
1222 # Needs to accept -1. We run this in a subprocess to avoid
1223 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001224 subprocess.check_call([
1225 sys.executable, '-c',
1226 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001227
1228 if hasattr(os, 'setregid'):
1229 def test_setregid(self):
1230 if os.getuid() != 0:
1231 self.assertRaises(os.error, os.setregid, 0, 0)
1232 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
1233 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001234
1235 def test_setregid_neg1(self):
1236 # Needs to accept -1. We run this in a subprocess to avoid
1237 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001238 subprocess.check_call([
1239 sys.executable, '-c',
1240 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Martin v. Löwis011e8422009-05-05 04:43:17 +00001241
1242 class Pep383Tests(unittest.TestCase):
Martin v. Löwis011e8422009-05-05 04:43:17 +00001243 def setUp(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001244 if support.TESTFN_UNENCODABLE:
1245 self.dir = support.TESTFN_UNENCODABLE
Victor Stinner8b219b22012-11-06 23:23:43 +01001246 elif support.TESTFN_NONASCII:
1247 self.dir = support.TESTFN_NONASCII
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001248 else:
1249 self.dir = support.TESTFN
1250 self.bdir = os.fsencode(self.dir)
1251
1252 bytesfn = []
1253 def add_filename(fn):
1254 try:
1255 fn = os.fsencode(fn)
1256 except UnicodeEncodeError:
1257 return
1258 bytesfn.append(fn)
1259 add_filename(support.TESTFN_UNICODE)
1260 if support.TESTFN_UNENCODABLE:
1261 add_filename(support.TESTFN_UNENCODABLE)
Victor Stinner8b219b22012-11-06 23:23:43 +01001262 if support.TESTFN_NONASCII:
1263 add_filename(support.TESTFN_NONASCII)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001264 if not bytesfn:
1265 self.skipTest("couldn't create any non-ascii filename")
1266
1267 self.unicodefn = set()
Martin v. Löwis011e8422009-05-05 04:43:17 +00001268 os.mkdir(self.dir)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001269 try:
1270 for fn in bytesfn:
Victor Stinnerbf816222011-06-30 23:25:47 +02001271 support.create_empty_file(os.path.join(self.bdir, fn))
Victor Stinnere8d51452010-08-19 01:05:19 +00001272 fn = os.fsdecode(fn)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001273 if fn in self.unicodefn:
1274 raise ValueError("duplicate filename")
1275 self.unicodefn.add(fn)
1276 except:
1277 shutil.rmtree(self.dir)
1278 raise
Martin v. Löwis011e8422009-05-05 04:43:17 +00001279
1280 def tearDown(self):
1281 shutil.rmtree(self.dir)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001282
1283 def test_listdir(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001284 expected = self.unicodefn
1285 found = set(os.listdir(self.dir))
Ezio Melottib3aedd42010-11-20 19:04:17 +00001286 self.assertEqual(found, expected)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001287 # test listdir without arguments
1288 current_directory = os.getcwd()
1289 try:
1290 os.chdir(os.sep)
1291 self.assertEqual(set(os.listdir()), set(os.listdir(os.sep)))
1292 finally:
1293 os.chdir(current_directory)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001294
1295 def test_open(self):
1296 for fn in self.unicodefn:
Victor Stinnera6d2c762011-06-30 18:20:11 +02001297 f = open(os.path.join(self.dir, fn), 'rb')
Martin v. Löwis011e8422009-05-05 04:43:17 +00001298 f.close()
1299
1300 def test_stat(self):
1301 for fn in self.unicodefn:
1302 os.stat(os.path.join(self.dir, fn))
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001303else:
1304 class PosixUidGidTests(unittest.TestCase):
1305 pass
Martin v. Löwis011e8422009-05-05 04:43:17 +00001306 class Pep383Tests(unittest.TestCase):
1307 pass
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001308
Brian Curtineb24d742010-04-12 17:16:38 +00001309@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
1310class Win32KillTests(unittest.TestCase):
Brian Curtinc3acbc32010-05-28 16:08:40 +00001311 def _kill(self, sig):
1312 # Start sys.executable as a subprocess and communicate from the
1313 # subprocess to the parent that the interpreter is ready. When it
1314 # becomes ready, send *sig* via os.kill to the subprocess and check
1315 # that the return code is equal to *sig*.
1316 import ctypes
1317 from ctypes import wintypes
1318 import msvcrt
1319
1320 # Since we can't access the contents of the process' stdout until the
1321 # process has exited, use PeekNamedPipe to see what's inside stdout
1322 # without waiting. This is done so we can tell that the interpreter
1323 # is started and running at a point where it could handle a signal.
1324 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
1325 PeekNamedPipe.restype = wintypes.BOOL
1326 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
1327 ctypes.POINTER(ctypes.c_char), # stdout buf
1328 wintypes.DWORD, # Buffer size
1329 ctypes.POINTER(wintypes.DWORD), # bytes read
1330 ctypes.POINTER(wintypes.DWORD), # bytes avail
1331 ctypes.POINTER(wintypes.DWORD)) # bytes left
1332 msg = "running"
1333 proc = subprocess.Popen([sys.executable, "-c",
1334 "import sys;"
1335 "sys.stdout.write('{}');"
1336 "sys.stdout.flush();"
1337 "input()".format(msg)],
1338 stdout=subprocess.PIPE,
1339 stderr=subprocess.PIPE,
1340 stdin=subprocess.PIPE)
Brian Curtin43ec5772010-11-05 15:17:11 +00001341 self.addCleanup(proc.stdout.close)
1342 self.addCleanup(proc.stderr.close)
1343 self.addCleanup(proc.stdin.close)
Brian Curtinc3acbc32010-05-28 16:08:40 +00001344
1345 count, max = 0, 100
1346 while count < max and proc.poll() is None:
1347 # Create a string buffer to store the result of stdout from the pipe
1348 buf = ctypes.create_string_buffer(len(msg))
1349 # Obtain the text currently in proc.stdout
1350 # Bytes read/avail/left are left as NULL and unused
1351 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
1352 buf, ctypes.sizeof(buf), None, None, None)
1353 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
1354 if buf.value:
1355 self.assertEqual(msg, buf.value.decode())
1356 break
1357 time.sleep(0.1)
1358 count += 1
1359 else:
1360 self.fail("Did not receive communication from the subprocess")
1361
Brian Curtineb24d742010-04-12 17:16:38 +00001362 os.kill(proc.pid, sig)
1363 self.assertEqual(proc.wait(), sig)
1364
1365 def test_kill_sigterm(self):
1366 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinc3acbc32010-05-28 16:08:40 +00001367 self._kill(signal.SIGTERM)
Brian Curtineb24d742010-04-12 17:16:38 +00001368
1369 def test_kill_int(self):
1370 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinc3acbc32010-05-28 16:08:40 +00001371 self._kill(100)
Brian Curtineb24d742010-04-12 17:16:38 +00001372
1373 def _kill_with_event(self, event, name):
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001374 tagname = "test_os_%s" % uuid.uuid1()
1375 m = mmap.mmap(-1, 1, tagname)
1376 m[0] = 0
Brian Curtineb24d742010-04-12 17:16:38 +00001377 # Run a script which has console control handling enabled.
1378 proc = subprocess.Popen([sys.executable,
1379 os.path.join(os.path.dirname(__file__),
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001380 "win_console_handler.py"), tagname],
Brian Curtineb24d742010-04-12 17:16:38 +00001381 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
1382 # Let the interpreter startup before we send signals. See #3137.
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001383 count, max = 0, 100
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001384 while count < max and proc.poll() is None:
Brian Curtinf668df52010-10-15 14:21:06 +00001385 if m[0] == 1:
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001386 break
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001387 time.sleep(0.1)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001388 count += 1
1389 else:
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001390 # Forcefully kill the process if we weren't able to signal it.
1391 os.kill(proc.pid, signal.SIGINT)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001392 self.fail("Subprocess didn't finish initialization")
Brian Curtineb24d742010-04-12 17:16:38 +00001393 os.kill(proc.pid, event)
1394 # proc.send_signal(event) could also be done here.
1395 # Allow time for the signal to be passed and the process to exit.
1396 time.sleep(0.5)
1397 if not proc.poll():
1398 # Forcefully kill the process if we weren't able to signal it.
1399 os.kill(proc.pid, signal.SIGINT)
1400 self.fail("subprocess did not stop on {}".format(name))
1401
1402 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
1403 def test_CTRL_C_EVENT(self):
1404 from ctypes import wintypes
1405 import ctypes
1406
1407 # Make a NULL value by creating a pointer with no argument.
1408 NULL = ctypes.POINTER(ctypes.c_int)()
1409 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
1410 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
1411 wintypes.BOOL)
1412 SetConsoleCtrlHandler.restype = wintypes.BOOL
1413
1414 # Calling this with NULL and FALSE causes the calling process to
1415 # handle CTRL+C, rather than ignore it. This property is inherited
1416 # by subprocesses.
1417 SetConsoleCtrlHandler(NULL, 0)
1418
1419 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
1420
1421 def test_CTRL_BREAK_EVENT(self):
1422 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
1423
1424
Brian Curtind40e6f72010-07-08 21:39:08 +00001425@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Brian Curtin3b4499c2010-12-28 14:31:47 +00001426@support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +00001427class Win32SymlinkTests(unittest.TestCase):
1428 filelink = 'filelinktest'
1429 filelink_target = os.path.abspath(__file__)
1430 dirlink = 'dirlinktest'
1431 dirlink_target = os.path.dirname(filelink_target)
1432 missing_link = 'missing link'
1433
1434 def setUp(self):
1435 assert os.path.exists(self.dirlink_target)
1436 assert os.path.exists(self.filelink_target)
1437 assert not os.path.exists(self.dirlink)
1438 assert not os.path.exists(self.filelink)
1439 assert not os.path.exists(self.missing_link)
1440
1441 def tearDown(self):
1442 if os.path.exists(self.filelink):
1443 os.remove(self.filelink)
1444 if os.path.exists(self.dirlink):
1445 os.rmdir(self.dirlink)
1446 if os.path.lexists(self.missing_link):
1447 os.remove(self.missing_link)
1448
1449 def test_directory_link(self):
Antoine Pitrou5311c1d2012-01-24 08:59:28 +01001450 os.symlink(self.dirlink_target, self.dirlink, True)
Brian Curtind40e6f72010-07-08 21:39:08 +00001451 self.assertTrue(os.path.exists(self.dirlink))
1452 self.assertTrue(os.path.isdir(self.dirlink))
1453 self.assertTrue(os.path.islink(self.dirlink))
1454 self.check_stat(self.dirlink, self.dirlink_target)
1455
1456 def test_file_link(self):
1457 os.symlink(self.filelink_target, self.filelink)
1458 self.assertTrue(os.path.exists(self.filelink))
1459 self.assertTrue(os.path.isfile(self.filelink))
1460 self.assertTrue(os.path.islink(self.filelink))
1461 self.check_stat(self.filelink, self.filelink_target)
1462
1463 def _create_missing_dir_link(self):
1464 'Create a "directory" link to a non-existent target'
1465 linkname = self.missing_link
1466 if os.path.lexists(linkname):
1467 os.remove(linkname)
1468 target = r'c:\\target does not exist.29r3c740'
1469 assert not os.path.exists(target)
1470 target_is_dir = True
1471 os.symlink(target, linkname, target_is_dir)
1472
1473 def test_remove_directory_link_to_missing_target(self):
1474 self._create_missing_dir_link()
1475 # For compatibility with Unix, os.remove will check the
1476 # directory status and call RemoveDirectory if the symlink
1477 # was created with target_is_dir==True.
1478 os.remove(self.missing_link)
1479
1480 @unittest.skip("currently fails; consider for improvement")
1481 def test_isdir_on_directory_link_to_missing_target(self):
1482 self._create_missing_dir_link()
1483 # consider having isdir return true for directory links
1484 self.assertTrue(os.path.isdir(self.missing_link))
1485
1486 @unittest.skip("currently fails; consider for improvement")
1487 def test_rmdir_on_directory_link_to_missing_target(self):
1488 self._create_missing_dir_link()
1489 # consider allowing rmdir to remove directory links
1490 os.rmdir(self.missing_link)
1491
1492 def check_stat(self, link, target):
1493 self.assertEqual(os.stat(link), os.stat(target))
1494 self.assertNotEqual(os.lstat(link), os.stat(link))
1495
Brian Curtind25aef52011-06-13 15:16:04 -05001496 bytes_link = os.fsencode(link)
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001497 with warnings.catch_warnings():
1498 warnings.simplefilter("ignore", DeprecationWarning)
1499 self.assertEqual(os.stat(bytes_link), os.stat(target))
1500 self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link))
Brian Curtind25aef52011-06-13 15:16:04 -05001501
1502 def test_12084(self):
1503 level1 = os.path.abspath(support.TESTFN)
1504 level2 = os.path.join(level1, "level2")
1505 level3 = os.path.join(level2, "level3")
1506 try:
1507 os.mkdir(level1)
1508 os.mkdir(level2)
1509 os.mkdir(level3)
1510
1511 file1 = os.path.abspath(os.path.join(level1, "file1"))
1512
1513 with open(file1, "w") as f:
1514 f.write("file1")
1515
1516 orig_dir = os.getcwd()
1517 try:
1518 os.chdir(level2)
1519 link = os.path.join(level2, "link")
1520 os.symlink(os.path.relpath(file1), "link")
1521 self.assertIn("link", os.listdir(os.getcwd()))
1522
1523 # Check os.stat calls from the same dir as the link
1524 self.assertEqual(os.stat(file1), os.stat("link"))
1525
1526 # Check os.stat calls from a dir below the link
1527 os.chdir(level1)
1528 self.assertEqual(os.stat(file1),
1529 os.stat(os.path.relpath(link)))
1530
1531 # Check os.stat calls from a dir above the link
1532 os.chdir(level3)
1533 self.assertEqual(os.stat(file1),
1534 os.stat(os.path.relpath(link)))
1535 finally:
1536 os.chdir(orig_dir)
1537 except OSError as err:
1538 self.fail(err)
1539 finally:
1540 os.remove(file1)
1541 shutil.rmtree(level1)
1542
Brian Curtind40e6f72010-07-08 21:39:08 +00001543
Victor Stinnere8d51452010-08-19 01:05:19 +00001544class FSEncodingTests(unittest.TestCase):
1545 def test_nop(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001546 self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
1547 self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
Benjamin Peterson31191a92010-05-09 03:22:58 +00001548
Victor Stinnere8d51452010-08-19 01:05:19 +00001549 def test_identity(self):
1550 # assert fsdecode(fsencode(x)) == x
1551 for fn in ('unicode\u0141', 'latin\xe9', 'ascii'):
1552 try:
1553 bytesfn = os.fsencode(fn)
1554 except UnicodeEncodeError:
1555 continue
Ezio Melottib3aedd42010-11-20 19:04:17 +00001556 self.assertEqual(os.fsdecode(bytesfn), fn)
Victor Stinnere8d51452010-08-19 01:05:19 +00001557
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00001558
Brett Cannonefb00c02012-02-29 18:31:31 -05001559
1560class DeviceEncodingTests(unittest.TestCase):
1561
1562 def test_bad_fd(self):
1563 # Return None when an fd doesn't actually exist.
1564 self.assertIsNone(os.device_encoding(123456))
1565
Philip Jenveye308b7c2012-02-29 16:16:15 -08001566 @unittest.skipUnless(os.isatty(0) and (sys.platform.startswith('win') or
1567 (hasattr(locale, 'nl_langinfo') and hasattr(locale, 'CODESET'))),
Philip Jenveyd7aff2d2012-02-29 16:21:25 -08001568 'test requires a tty and either Windows or nl_langinfo(CODESET)')
Brett Cannonefb00c02012-02-29 18:31:31 -05001569 def test_device_encoding(self):
1570 encoding = os.device_encoding(0)
1571 self.assertIsNotNone(encoding)
1572 self.assertTrue(codecs.lookup(encoding))
1573
1574
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00001575class PidTests(unittest.TestCase):
1576 @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid")
1577 def test_getppid(self):
1578 p = subprocess.Popen([sys.executable, '-c',
1579 'import os; print(os.getppid())'],
1580 stdout=subprocess.PIPE)
1581 stdout, _ = p.communicate()
1582 # We are the parent of our subprocess
1583 self.assertEqual(int(stdout), os.getpid())
1584
1585
Brian Curtin0151b8e2010-09-24 13:43:43 +00001586# The introduction of this TestCase caused at least two different errors on
1587# *nix buildbots. Temporarily skip this to let the buildbots move along.
1588@unittest.skip("Skip due to platform/environment differences on *NIX buildbots")
Brian Curtine8e4b3b2010-09-23 20:04:14 +00001589@unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin")
1590class LoginTests(unittest.TestCase):
1591 def test_getlogin(self):
1592 user_name = os.getlogin()
1593 self.assertNotEqual(len(user_name), 0)
1594
1595
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001596@unittest.skipUnless(hasattr(os, 'getpriority') and hasattr(os, 'setpriority'),
1597 "needs os.getpriority and os.setpriority")
1598class ProgramPriorityTests(unittest.TestCase):
1599 """Tests for os.getpriority() and os.setpriority()."""
1600
1601 def test_set_get_priority(self):
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001602
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001603 base = os.getpriority(os.PRIO_PROCESS, os.getpid())
1604 os.setpriority(os.PRIO_PROCESS, os.getpid(), base + 1)
1605 try:
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001606 new_prio = os.getpriority(os.PRIO_PROCESS, os.getpid())
1607 if base >= 19 and new_prio <= 19:
1608 raise unittest.SkipTest(
1609 "unable to reliably test setpriority at current nice level of %s" % base)
1610 else:
1611 self.assertEqual(new_prio, base + 1)
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001612 finally:
1613 try:
1614 os.setpriority(os.PRIO_PROCESS, os.getpid(), base)
1615 except OSError as err:
Antoine Pitrou692f0382011-02-26 00:22:25 +00001616 if err.errno != errno.EACCES:
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001617 raise
1618
1619
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001620if threading is not None:
1621 class SendfileTestServer(asyncore.dispatcher, threading.Thread):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001622
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001623 class Handler(asynchat.async_chat):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001624
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001625 def __init__(self, conn):
1626 asynchat.async_chat.__init__(self, conn)
1627 self.in_buffer = []
1628 self.closed = False
1629 self.push(b"220 ready\r\n")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001630
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001631 def handle_read(self):
1632 data = self.recv(4096)
1633 self.in_buffer.append(data)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001634
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001635 def get_data(self):
1636 return b''.join(self.in_buffer)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001637
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001638 def handle_close(self):
1639 self.close()
1640 self.closed = True
1641
1642 def handle_error(self):
1643 raise
1644
1645 def __init__(self, address):
1646 threading.Thread.__init__(self)
1647 asyncore.dispatcher.__init__(self)
1648 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
1649 self.bind(address)
1650 self.listen(5)
1651 self.host, self.port = self.socket.getsockname()[:2]
1652 self.handler_instance = None
1653 self._active = False
1654 self._active_lock = threading.Lock()
1655
1656 # --- public API
1657
1658 @property
1659 def running(self):
1660 return self._active
1661
1662 def start(self):
1663 assert not self.running
1664 self.__flag = threading.Event()
1665 threading.Thread.start(self)
1666 self.__flag.wait()
1667
1668 def stop(self):
1669 assert self.running
1670 self._active = False
1671 self.join()
1672
1673 def wait(self):
1674 # wait for handler connection to be closed, then stop the server
1675 while not getattr(self.handler_instance, "closed", False):
1676 time.sleep(0.001)
1677 self.stop()
1678
1679 # --- internals
1680
1681 def run(self):
1682 self._active = True
1683 self.__flag.set()
1684 while self._active and asyncore.socket_map:
1685 self._active_lock.acquire()
1686 asyncore.loop(timeout=0.001, count=1)
1687 self._active_lock.release()
1688 asyncore.close_all()
1689
1690 def handle_accept(self):
1691 conn, addr = self.accept()
1692 self.handler_instance = self.Handler(conn)
1693
1694 def handle_connect(self):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001695 self.close()
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001696 handle_read = handle_connect
1697
1698 def writable(self):
1699 return 0
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001700
1701 def handle_error(self):
1702 raise
1703
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001704
Giampaolo Rodolà46134642011-02-25 20:01:05 +00001705@unittest.skipUnless(threading is not None, "test needs threading module")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001706@unittest.skipUnless(hasattr(os, 'sendfile'), "test needs os.sendfile()")
1707class TestSendfile(unittest.TestCase):
1708
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001709 DATA = b"12345abcde" * 16 * 1024 # 160 KB
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001710 SUPPORT_HEADERS_TRAILERS = not sys.platform.startswith("linux") and \
Giampaolo Rodolà4bc68572011-02-25 21:46:01 +00001711 not sys.platform.startswith("solaris") and \
1712 not sys.platform.startswith("sunos")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001713
1714 @classmethod
1715 def setUpClass(cls):
1716 with open(support.TESTFN, "wb") as f:
1717 f.write(cls.DATA)
1718
1719 @classmethod
1720 def tearDownClass(cls):
1721 support.unlink(support.TESTFN)
1722
1723 def setUp(self):
1724 self.server = SendfileTestServer((support.HOST, 0))
1725 self.server.start()
1726 self.client = socket.socket()
1727 self.client.connect((self.server.host, self.server.port))
1728 self.client.settimeout(1)
1729 # synchronize by waiting for "220 ready" response
1730 self.client.recv(1024)
1731 self.sockno = self.client.fileno()
1732 self.file = open(support.TESTFN, 'rb')
1733 self.fileno = self.file.fileno()
1734
1735 def tearDown(self):
1736 self.file.close()
1737 self.client.close()
1738 if self.server.running:
1739 self.server.stop()
1740
1741 def sendfile_wrapper(self, sock, file, offset, nbytes, headers=[], trailers=[]):
1742 """A higher level wrapper representing how an application is
1743 supposed to use sendfile().
1744 """
1745 while 1:
1746 try:
1747 if self.SUPPORT_HEADERS_TRAILERS:
1748 return os.sendfile(sock, file, offset, nbytes, headers,
1749 trailers)
1750 else:
1751 return os.sendfile(sock, file, offset, nbytes)
1752 except OSError as err:
1753 if err.errno == errno.ECONNRESET:
1754 # disconnected
1755 raise
1756 elif err.errno in (errno.EAGAIN, errno.EBUSY):
1757 # we have to retry send data
1758 continue
1759 else:
1760 raise
1761
1762 def test_send_whole_file(self):
1763 # normal send
1764 total_sent = 0
1765 offset = 0
1766 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001767 while total_sent < len(self.DATA):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001768 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
1769 if sent == 0:
1770 break
1771 offset += sent
1772 total_sent += sent
1773 self.assertTrue(sent <= nbytes)
1774 self.assertEqual(offset, total_sent)
1775
1776 self.assertEqual(total_sent, len(self.DATA))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001777 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001778 self.client.close()
1779 self.server.wait()
1780 data = self.server.handler_instance.get_data()
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001781 self.assertEqual(len(data), len(self.DATA))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001782 self.assertEqual(data, self.DATA)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001783
1784 def test_send_at_certain_offset(self):
1785 # start sending a file at a certain offset
1786 total_sent = 0
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001787 offset = len(self.DATA) // 2
1788 must_send = len(self.DATA) - offset
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001789 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001790 while total_sent < must_send:
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001791 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
1792 if sent == 0:
1793 break
1794 offset += sent
1795 total_sent += sent
1796 self.assertTrue(sent <= nbytes)
1797
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001798 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001799 self.client.close()
1800 self.server.wait()
1801 data = self.server.handler_instance.get_data()
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001802 expected = self.DATA[len(self.DATA) // 2:]
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001803 self.assertEqual(total_sent, len(expected))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001804 self.assertEqual(len(data), len(expected))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001805 self.assertEqual(data, expected)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001806
1807 def test_offset_overflow(self):
1808 # specify an offset > file size
1809 offset = len(self.DATA) + 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001810 try:
1811 sent = os.sendfile(self.sockno, self.fileno, offset, 4096)
1812 except OSError as e:
1813 # Solaris can raise EINVAL if offset >= file length, ignore.
1814 if e.errno != errno.EINVAL:
1815 raise
1816 else:
1817 self.assertEqual(sent, 0)
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001818 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001819 self.client.close()
1820 self.server.wait()
1821 data = self.server.handler_instance.get_data()
1822 self.assertEqual(data, b'')
1823
1824 def test_invalid_offset(self):
1825 with self.assertRaises(OSError) as cm:
1826 os.sendfile(self.sockno, self.fileno, -1, 4096)
1827 self.assertEqual(cm.exception.errno, errno.EINVAL)
1828
1829 # --- headers / trailers tests
1830
1831 if SUPPORT_HEADERS_TRAILERS:
1832
1833 def test_headers(self):
1834 total_sent = 0
1835 sent = os.sendfile(self.sockno, self.fileno, 0, 4096,
1836 headers=[b"x" * 512])
1837 total_sent += sent
1838 offset = 4096
1839 nbytes = 4096
1840 while 1:
1841 sent = self.sendfile_wrapper(self.sockno, self.fileno,
1842 offset, nbytes)
1843 if sent == 0:
1844 break
1845 total_sent += sent
1846 offset += sent
1847
1848 expected_data = b"x" * 512 + self.DATA
1849 self.assertEqual(total_sent, len(expected_data))
1850 self.client.close()
1851 self.server.wait()
1852 data = self.server.handler_instance.get_data()
1853 self.assertEqual(hash(data), hash(expected_data))
1854
1855 def test_trailers(self):
1856 TESTFN2 = support.TESTFN + "2"
Brett Cannonb6376802011-03-15 17:38:22 -04001857 with open(TESTFN2, 'wb') as f:
1858 f.write(b"abcde")
1859 with open(TESTFN2, 'rb')as f:
1860 self.addCleanup(os.remove, TESTFN2)
1861 os.sendfile(self.sockno, f.fileno(), 0, 4096,
1862 trailers=[b"12345"])
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001863 self.client.close()
1864 self.server.wait()
1865 data = self.server.handler_instance.get_data()
1866 self.assertEqual(data, b"abcde12345")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001867
1868 if hasattr(os, "SF_NODISKIO"):
1869 def test_flags(self):
1870 try:
1871 os.sendfile(self.sockno, self.fileno, 0, 4096,
1872 flags=os.SF_NODISKIO)
1873 except OSError as err:
1874 if err.errno not in (errno.EBUSY, errno.EAGAIN):
1875 raise
1876
1877
Larry Hastings9cf065c2012-06-22 16:30:09 -07001878def supports_extended_attributes():
1879 if not hasattr(os, "setxattr"):
1880 return False
1881 try:
1882 with open(support.TESTFN, "wb") as fp:
1883 try:
1884 os.setxattr(fp.fileno(), b"user.test", b"")
1885 except OSError:
1886 return False
1887 finally:
1888 support.unlink(support.TESTFN)
1889 # Kernels < 2.6.39 don't respect setxattr flags.
1890 kernel_version = platform.release()
1891 m = re.match("2.6.(\d{1,2})", kernel_version)
1892 return m is None or int(m.group(1)) >= 39
1893
1894
1895@unittest.skipUnless(supports_extended_attributes(),
1896 "no non-broken extended attribute support")
Benjamin Peterson799bd802011-08-31 22:15:17 -04001897class ExtendedAttributeTests(unittest.TestCase):
1898
1899 def tearDown(self):
1900 support.unlink(support.TESTFN)
1901
Larry Hastings9cf065c2012-06-22 16:30:09 -07001902 def _check_xattrs_str(self, s, getxattr, setxattr, removexattr, listxattr, **kwargs):
Benjamin Peterson799bd802011-08-31 22:15:17 -04001903 fn = support.TESTFN
1904 open(fn, "wb").close()
1905 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001906 getxattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001907 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02001908 init_xattr = listxattr(fn)
1909 self.assertIsInstance(init_xattr, list)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001910 setxattr(fn, s("user.test"), b"", **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02001911 xattr = set(init_xattr)
1912 xattr.add("user.test")
1913 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001914 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"")
1915 setxattr(fn, s("user.test"), b"hello", os.XATTR_REPLACE, **kwargs)
1916 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"hello")
Benjamin Peterson799bd802011-08-31 22:15:17 -04001917 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001918 setxattr(fn, s("user.test"), b"bye", os.XATTR_CREATE, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001919 self.assertEqual(cm.exception.errno, errno.EEXIST)
1920 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001921 setxattr(fn, s("user.test2"), b"bye", os.XATTR_REPLACE, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001922 self.assertEqual(cm.exception.errno, errno.ENODATA)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001923 setxattr(fn, s("user.test2"), b"foo", os.XATTR_CREATE, **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02001924 xattr.add("user.test2")
1925 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001926 removexattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001927 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001928 getxattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001929 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02001930 xattr.remove("user.test")
1931 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001932 self.assertEqual(getxattr(fn, s("user.test2"), **kwargs), b"foo")
1933 setxattr(fn, s("user.test"), b"a"*1024, **kwargs)
1934 self.assertEqual(getxattr(fn, s("user.test"), **kwargs), b"a"*1024)
1935 removexattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001936 many = sorted("user.test{}".format(i) for i in range(100))
1937 for thing in many:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001938 setxattr(fn, thing, b"x", **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02001939 self.assertEqual(set(listxattr(fn)), set(init_xattr) | set(many))
Benjamin Peterson799bd802011-08-31 22:15:17 -04001940
Larry Hastings9cf065c2012-06-22 16:30:09 -07001941 def _check_xattrs(self, *args, **kwargs):
Benjamin Peterson799bd802011-08-31 22:15:17 -04001942 def make_bytes(s):
1943 return bytes(s, "ascii")
Larry Hastings9cf065c2012-06-22 16:30:09 -07001944 self._check_xattrs_str(str, *args, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001945 support.unlink(support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001946 self._check_xattrs_str(make_bytes, *args, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001947
1948 def test_simple(self):
1949 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
1950 os.listxattr)
1951
1952 def test_lpath(self):
Larry Hastings9cf065c2012-06-22 16:30:09 -07001953 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
1954 os.listxattr, follow_symlinks=False)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001955
1956 def test_fds(self):
1957 def getxattr(path, *args):
1958 with open(path, "rb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001959 return os.getxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001960 def setxattr(path, *args):
1961 with open(path, "wb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001962 os.setxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001963 def removexattr(path, *args):
1964 with open(path, "wb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001965 os.removexattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001966 def listxattr(path, *args):
1967 with open(path, "rb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001968 return os.listxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001969 self._check_xattrs(getxattr, setxattr, removexattr, listxattr)
1970
1971
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001972@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
1973class Win32DeprecatedBytesAPI(unittest.TestCase):
1974 def test_deprecated(self):
1975 import nt
1976 filename = os.fsencode(support.TESTFN)
1977 with warnings.catch_warnings():
1978 warnings.simplefilter("error", DeprecationWarning)
1979 for func, *args in (
1980 (nt._getfullpathname, filename),
1981 (nt._isdir, filename),
1982 (os.access, filename, os.R_OK),
1983 (os.chdir, filename),
1984 (os.chmod, filename, 0o777),
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01001985 (os.getcwdb,),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001986 (os.link, filename, filename),
1987 (os.listdir, filename),
1988 (os.lstat, filename),
1989 (os.mkdir, filename),
1990 (os.open, filename, os.O_RDONLY),
1991 (os.rename, filename, filename),
1992 (os.rmdir, filename),
1993 (os.startfile, filename),
1994 (os.stat, filename),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001995 (os.unlink, filename),
1996 (os.utime, filename),
1997 ):
1998 self.assertRaises(DeprecationWarning, func, *args)
1999
Victor Stinner28216442011-11-16 00:34:44 +01002000 @support.skip_unless_symlink
2001 def test_symlink(self):
2002 filename = os.fsencode(support.TESTFN)
2003 with warnings.catch_warnings():
2004 warnings.simplefilter("error", DeprecationWarning)
2005 self.assertRaises(DeprecationWarning,
2006 os.symlink, filename, filename)
2007
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002008
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002009@unittest.skipUnless(hasattr(os, 'get_terminal_size'), "requires os.get_terminal_size")
2010class TermsizeTests(unittest.TestCase):
2011 def test_does_not_crash(self):
2012 """Check if get_terminal_size() returns a meaningful value.
2013
2014 There's no easy portable way to actually check the size of the
2015 terminal, so let's check if it returns something sensible instead.
2016 """
2017 try:
2018 size = os.get_terminal_size()
2019 except OSError as e:
Antoine Pitrou81a1fa52012-02-09 00:11:00 +01002020 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002021 # Under win32 a generic OSError can be thrown if the
2022 # handle cannot be retrieved
2023 self.skipTest("failed to query terminal size")
2024 raise
2025
Antoine Pitroucfade362012-02-08 23:48:59 +01002026 self.assertGreaterEqual(size.columns, 0)
2027 self.assertGreaterEqual(size.lines, 0)
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002028
2029 def test_stty_match(self):
2030 """Check if stty returns the same results
2031
2032 stty actually tests stdin, so get_terminal_size is invoked on
2033 stdin explicitly. If stty succeeded, then get_terminal_size()
2034 should work too.
2035 """
2036 try:
2037 size = subprocess.check_output(['stty', 'size']).decode().split()
2038 except (FileNotFoundError, subprocess.CalledProcessError):
2039 self.skipTest("stty invocation failed")
2040 expected = (int(size[1]), int(size[0])) # reversed order
2041
Antoine Pitrou81a1fa52012-02-09 00:11:00 +01002042 try:
2043 actual = os.get_terminal_size(sys.__stdin__.fileno())
2044 except OSError as e:
2045 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
2046 # Under win32 a generic OSError can be thrown if the
2047 # handle cannot be retrieved
2048 self.skipTest("failed to query terminal size")
2049 raise
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002050 self.assertEqual(expected, actual)
2051
2052
Victor Stinner292c8352012-10-30 02:17:38 +01002053class OSErrorTests(unittest.TestCase):
2054 def setUp(self):
2055 class Str(str):
2056 pass
2057
Victor Stinnerafe17062012-10-31 22:47:43 +01002058 self.bytes_filenames = []
2059 self.unicode_filenames = []
Victor Stinner292c8352012-10-30 02:17:38 +01002060 if support.TESTFN_UNENCODABLE is not None:
2061 decoded = support.TESTFN_UNENCODABLE
2062 else:
2063 decoded = support.TESTFN
Victor Stinnerafe17062012-10-31 22:47:43 +01002064 self.unicode_filenames.append(decoded)
2065 self.unicode_filenames.append(Str(decoded))
Victor Stinner292c8352012-10-30 02:17:38 +01002066 if support.TESTFN_UNDECODABLE is not None:
2067 encoded = support.TESTFN_UNDECODABLE
2068 else:
2069 encoded = os.fsencode(support.TESTFN)
Victor Stinnerafe17062012-10-31 22:47:43 +01002070 self.bytes_filenames.append(encoded)
2071 self.bytes_filenames.append(memoryview(encoded))
2072
2073 self.filenames = self.bytes_filenames + self.unicode_filenames
Victor Stinner292c8352012-10-30 02:17:38 +01002074
2075 def test_oserror_filename(self):
2076 funcs = [
Victor Stinnerafe17062012-10-31 22:47:43 +01002077 (self.filenames, os.chdir,),
2078 (self.filenames, os.chmod, 0o777),
Victor Stinnerafe17062012-10-31 22:47:43 +01002079 (self.filenames, os.lstat,),
2080 (self.filenames, os.open, os.O_RDONLY),
2081 (self.filenames, os.rmdir,),
2082 (self.filenames, os.stat,),
2083 (self.filenames, os.unlink,),
Victor Stinner292c8352012-10-30 02:17:38 +01002084 ]
2085 if sys.platform == "win32":
2086 funcs.extend((
Victor Stinnerafe17062012-10-31 22:47:43 +01002087 (self.bytes_filenames, os.rename, b"dst"),
2088 (self.bytes_filenames, os.replace, b"dst"),
2089 (self.unicode_filenames, os.rename, "dst"),
2090 (self.unicode_filenames, os.replace, "dst"),
Victor Stinner64e039a2012-11-07 00:10:14 +01002091 # Issue #16414: Don't test undecodable names with listdir()
2092 # because of a Windows bug.
2093 #
2094 # With the ANSI code page 932, os.listdir(b'\xe7') return an
2095 # empty list (instead of failing), whereas os.listdir(b'\xff')
2096 # raises a FileNotFoundError. It looks like a Windows bug:
2097 # b'\xe7' directory does not exist, FindFirstFileA(b'\xe7')
2098 # fails with ERROR_FILE_NOT_FOUND (2), instead of
2099 # ERROR_PATH_NOT_FOUND (3).
2100 (self.unicode_filenames, os.listdir,),
Victor Stinner292c8352012-10-30 02:17:38 +01002101 ))
Victor Stinnerafe17062012-10-31 22:47:43 +01002102 else:
2103 funcs.extend((
Victor Stinner64e039a2012-11-07 00:10:14 +01002104 (self.filenames, os.listdir,),
Victor Stinnerafe17062012-10-31 22:47:43 +01002105 (self.filenames, os.rename, "dst"),
2106 (self.filenames, os.replace, "dst"),
2107 ))
2108 if hasattr(os, "chown"):
2109 funcs.append((self.filenames, os.chown, 0, 0))
2110 if hasattr(os, "lchown"):
2111 funcs.append((self.filenames, os.lchown, 0, 0))
2112 if hasattr(os, "truncate"):
2113 funcs.append((self.filenames, os.truncate, 0))
Victor Stinner292c8352012-10-30 02:17:38 +01002114 if hasattr(os, "chflags"):
Victor Stinneree36c242012-11-13 09:31:51 +01002115 funcs.append((self.filenames, os.chflags, 0))
2116 if hasattr(os, "lchflags"):
2117 funcs.append((self.filenames, os.lchflags, 0))
Victor Stinner292c8352012-10-30 02:17:38 +01002118 if hasattr(os, "chroot"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002119 funcs.append((self.filenames, os.chroot,))
Victor Stinner292c8352012-10-30 02:17:38 +01002120 if hasattr(os, "link"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002121 if sys.platform == "win32":
2122 funcs.append((self.bytes_filenames, os.link, b"dst"))
2123 funcs.append((self.unicode_filenames, os.link, "dst"))
2124 else:
2125 funcs.append((self.filenames, os.link, "dst"))
Victor Stinner292c8352012-10-30 02:17:38 +01002126 if hasattr(os, "listxattr"):
2127 funcs.extend((
Victor Stinnerafe17062012-10-31 22:47:43 +01002128 (self.filenames, os.listxattr,),
2129 (self.filenames, os.getxattr, "user.test"),
2130 (self.filenames, os.setxattr, "user.test", b'user'),
2131 (self.filenames, os.removexattr, "user.test"),
Victor Stinner292c8352012-10-30 02:17:38 +01002132 ))
2133 if hasattr(os, "lchmod"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002134 funcs.append((self.filenames, os.lchmod, 0o777))
Victor Stinner292c8352012-10-30 02:17:38 +01002135 if hasattr(os, "readlink"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002136 if sys.platform == "win32":
2137 funcs.append((self.unicode_filenames, os.readlink,))
2138 else:
2139 funcs.append((self.filenames, os.readlink,))
Victor Stinner292c8352012-10-30 02:17:38 +01002140
Victor Stinnerafe17062012-10-31 22:47:43 +01002141 for filenames, func, *func_args in funcs:
2142 for name in filenames:
Victor Stinner292c8352012-10-30 02:17:38 +01002143 try:
2144 func(name, *func_args)
Victor Stinnerbd54f0e2012-10-31 01:12:55 +01002145 except OSError as err:
Victor Stinner292c8352012-10-30 02:17:38 +01002146 self.assertIs(err.filename, name)
2147 else:
2148 self.fail("No exception thrown by {}".format(func))
2149
Antoine Pitrouf26ad712011-07-15 23:00:56 +02002150@support.reap_threads
Fred Drake2e2be372001-09-20 21:33:42 +00002151def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002152 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002153 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002154 StatAttributeTests,
2155 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00002156 WalkTests,
Charles-François Natali7372b062012-02-05 15:15:38 +01002157 FwalkTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00002158 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +00002159 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002160 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +00002161 ExecTests,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00002162 Win32ErrorTests,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002163 TestInvalidFD,
Martin v. Löwis011e8422009-05-05 04:43:17 +00002164 PosixUidGidTests,
Brian Curtineb24d742010-04-12 17:16:38 +00002165 Pep383Tests,
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00002166 Win32KillTests,
Brian Curtind40e6f72010-07-08 21:39:08 +00002167 Win32SymlinkTests,
Victor Stinnere8d51452010-08-19 01:05:19 +00002168 FSEncodingTests,
Brett Cannonefb00c02012-02-29 18:31:31 -05002169 DeviceEncodingTests,
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00002170 PidTests,
Brian Curtine8e4b3b2010-09-23 20:04:14 +00002171 LoginTests,
Brian Curtin1b9df392010-11-24 20:24:31 +00002172 LinkTests,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002173 TestSendfile,
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00002174 ProgramPriorityTests,
Benjamin Peterson799bd802011-08-31 22:15:17 -04002175 ExtendedAttributeTests,
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002176 Win32DeprecatedBytesAPI,
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002177 TermsizeTests,
Victor Stinner292c8352012-10-30 02:17:38 +01002178 OSErrorTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002179 )
Fred Drake2e2be372001-09-20 21:33:42 +00002180
2181if __name__ == "__main__":
2182 test_main()