blob: 81a4d9a7e2b47faee6fca3cf44b3786f44ae0ccc [file] [log] [blame]
Fred Drake38c2ef02001-07-17 20:52:51 +00001# As a test suite for the os module, this is woefully inadequate, but this
2# does add tests for a few functions which have been determined to be more
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00003# portable than they had been thought to be.
Fred Drake38c2ef02001-07-17 20:52:51 +00004
5import os
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00006import errno
Fred Drake38c2ef02001-07-17 20:52:51 +00007import unittest
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +00008import warnings
Thomas Wouters477c8d52006-05-27 19:21:47 +00009import sys
Brian Curtineb24d742010-04-12 17:16:38 +000010import signal
11import subprocess
12import time
Martin v. Löwis011e8422009-05-05 04:43:17 +000013import shutil
Benjamin Petersonee8712c2008-05-20 21:35:26 +000014from test import support
Victor Stinnerc2d095f2010-05-17 00:14:53 +000015import contextlib
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +000016import mmap
Benjamin Peterson799bd802011-08-31 22:15:17 -040017import platform
18import re
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +000019import uuid
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000020import asyncore
21import asynchat
22import socket
Charles-François Natali7372b062012-02-05 15:15:38 +010023import itertools
24import stat
Brett Cannonefb00c02012-02-29 18:31:31 -050025import locale
26import codecs
Larry Hastingsa27b83a2013-08-08 00:19:50 -070027import decimal
28import fractions
Christian Heimes25827622013-10-12 01:27:08 +020029import pickle
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000030try:
31 import threading
32except ImportError:
33 threading = None
Antoine Pitrouec34ab52013-08-16 20:44:38 +020034try:
35 import resource
36except ImportError:
37 resource = None
Victor Stinner7ba6b0f2013-09-08 11:47:54 +020038try:
39 import fcntl
40except ImportError:
41 fcntl = None
Antoine Pitrouec34ab52013-08-16 20:44:38 +020042
Georg Brandl2daf6ae2012-02-20 19:54:16 +010043from test.script_helper import assert_python_ok
Fred Drake38c2ef02001-07-17 20:52:51 +000044
Victor Stinner034d0aa2012-06-05 01:22:15 +020045with warnings.catch_warnings():
46 warnings.simplefilter("ignore", DeprecationWarning)
47 os.stat_float_times(True)
Victor Stinner1aa54a42012-02-08 04:09:37 +010048st = os.stat(__file__)
49stat_supports_subsecond = (
50 # check if float and int timestamps are different
51 (st.st_atime != st[7])
52 or (st.st_mtime != st[8])
53 or (st.st_ctime != st[9]))
54
Mark Dickinson7cf03892010-04-16 13:45:35 +000055# Detect whether we're on a Linux system that uses the (now outdated
56# and unmaintained) linuxthreads threading library. There's an issue
57# when combining linuxthreads with a failed execv call: see
58# http://bugs.python.org/issue4970.
Victor Stinnerd5c355c2011-04-30 14:53:09 +020059if hasattr(sys, 'thread_info') and sys.thread_info.version:
60 USING_LINUXTHREADS = sys.thread_info.version.startswith("linuxthreads")
61else:
62 USING_LINUXTHREADS = False
Brian Curtineb24d742010-04-12 17:16:38 +000063
Stefan Krahebee49a2013-01-17 15:31:00 +010064# Issue #14110: Some tests fail on FreeBSD if the user is in the wheel group.
65HAVE_WHEEL_GROUP = sys.platform.startswith('freebsd') and os.getgid() == 0
66
Thomas Wouters0e3f5912006-08-11 14:57:12 +000067# Tests creating TESTFN
68class FileTests(unittest.TestCase):
69 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000070 if os.path.exists(support.TESTFN):
71 os.unlink(support.TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000072 tearDown = setUp
73
74 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000075 f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000076 os.close(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000077 self.assertTrue(os.access(support.TESTFN, os.W_OK))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000078
Christian Heimesfdab48e2008-01-20 09:06:41 +000079 def test_closerange(self):
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000080 first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
81 # We must allocate two consecutive file descriptors, otherwise
82 # it will mess up other file descriptors (perhaps even the three
83 # standard ones).
84 second = os.dup(first)
85 try:
86 retries = 0
87 while second != first + 1:
88 os.close(first)
89 retries += 1
90 if retries > 10:
91 # XXX test skipped
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000092 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000093 first, second = second, os.dup(second)
94 finally:
95 os.close(second)
Christian Heimesfdab48e2008-01-20 09:06:41 +000096 # close a fd that is open, and one that isn't
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000097 os.closerange(first, first + 2)
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000098 self.assertRaises(OSError, os.write, first, b"a")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000099
Benjamin Peterson1cc6df92010-06-30 17:39:45 +0000100 @support.cpython_only
Hirokazu Yamamoto4c19e6e2008-09-08 23:41:21 +0000101 def test_rename(self):
102 path = support.TESTFN
103 old = sys.getrefcount(path)
104 self.assertRaises(TypeError, os.rename, path, 0)
105 new = sys.getrefcount(path)
106 self.assertEqual(old, new)
107
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000108 def test_read(self):
109 with open(support.TESTFN, "w+b") as fobj:
110 fobj.write(b"spam")
111 fobj.flush()
112 fd = fobj.fileno()
113 os.lseek(fd, 0, 0)
114 s = os.read(fd, 4)
115 self.assertEqual(type(s), bytes)
116 self.assertEqual(s, b"spam")
117
118 def test_write(self):
119 # os.write() accepts bytes- and buffer-like objects but not strings
120 fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY)
121 self.assertRaises(TypeError, os.write, fd, "beans")
122 os.write(fd, b"bacon\n")
123 os.write(fd, bytearray(b"eggs\n"))
124 os.write(fd, memoryview(b"spam\n"))
125 os.close(fd)
126 with open(support.TESTFN, "rb") as fobj:
Antoine Pitroud62269f2008-09-15 23:54:52 +0000127 self.assertEqual(fobj.read().splitlines(),
128 [b"bacon", b"eggs", b"spam"])
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000129
Victor Stinnere0daff12011-03-20 23:36:35 +0100130 def write_windows_console(self, *args):
131 retcode = subprocess.call(args,
132 # use a new console to not flood the test output
133 creationflags=subprocess.CREATE_NEW_CONSOLE,
134 # use a shell to hide the console window (SW_HIDE)
135 shell=True)
136 self.assertEqual(retcode, 0)
137
138 @unittest.skipUnless(sys.platform == 'win32',
139 'test specific to the Windows console')
140 def test_write_windows_console(self):
141 # Issue #11395: the Windows console returns an error (12: not enough
142 # space error) on writing into stdout if stdout mode is binary and the
143 # length is greater than 66,000 bytes (or less, depending on heap
144 # usage).
145 code = "print('x' * 100000)"
146 self.write_windows_console(sys.executable, "-c", code)
147 self.write_windows_console(sys.executable, "-u", "-c", code)
148
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000149 def fdopen_helper(self, *args):
150 fd = os.open(support.TESTFN, os.O_RDONLY)
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200151 f = os.fdopen(fd, *args)
152 f.close()
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000153
154 def test_fdopen(self):
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200155 fd = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
156 os.close(fd)
157
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000158 self.fdopen_helper()
159 self.fdopen_helper('r')
160 self.fdopen_helper('r', 100)
161
Antoine Pitrouf3b2d882012-01-30 22:08:52 +0100162 def test_replace(self):
163 TESTFN2 = support.TESTFN + ".2"
164 with open(support.TESTFN, 'w') as f:
165 f.write("1")
166 with open(TESTFN2, 'w') as f:
167 f.write("2")
168 self.addCleanup(os.unlink, TESTFN2)
169 os.replace(support.TESTFN, TESTFN2)
170 self.assertRaises(FileNotFoundError, os.stat, support.TESTFN)
171 with open(TESTFN2, 'r') as f:
172 self.assertEqual(f.read(), "1")
173
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200174
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000175# Test attributes on return values from os.*stat* family.
176class StatAttributeTests(unittest.TestCase):
177 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000178 os.mkdir(support.TESTFN)
179 self.fname = os.path.join(support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000180 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +0000181 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000182 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000183
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000184 def tearDown(self):
185 os.unlink(self.fname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000186 os.rmdir(support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000187
Antoine Pitrou38425292010-09-21 18:19:07 +0000188 def check_stat_attributes(self, fname):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000189 if not hasattr(os, "stat"):
190 return
191
Antoine Pitrou38425292010-09-21 18:19:07 +0000192 result = os.stat(fname)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000193
194 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000195 self.assertEqual(result[stat.ST_SIZE], 3)
196 self.assertEqual(result.st_size, 3)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000197
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000198 # Make sure all the attributes are there
199 members = dir(result)
200 for name in dir(stat):
201 if name[:3] == 'ST_':
202 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000203 if name.endswith("TIME"):
204 def trunc(x): return int(x)
205 else:
206 def trunc(x): return x
Ezio Melottib3aedd42010-11-20 19:04:17 +0000207 self.assertEqual(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000208 result[getattr(stat, name)])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000209 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000210
Larry Hastings6fe20b32012-04-19 15:07:49 -0700211 # Make sure that the st_?time and st_?time_ns fields roughly agree
Larry Hastings76ad59b2012-05-03 00:30:07 -0700212 # (they should always agree up to around tens-of-microseconds)
Larry Hastings6fe20b32012-04-19 15:07:49 -0700213 for name in 'st_atime st_mtime st_ctime'.split():
214 floaty = int(getattr(result, name) * 100000)
215 nanosecondy = getattr(result, name + "_ns") // 10000
Larry Hastings76ad59b2012-05-03 00:30:07 -0700216 self.assertAlmostEqual(floaty, nanosecondy, delta=2)
Larry Hastings6fe20b32012-04-19 15:07:49 -0700217
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000218 try:
219 result[200]
Andrew Svetlov737fb892012-12-18 21:14:22 +0200220 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000221 except IndexError:
222 pass
223
224 # Make sure that assignment fails
225 try:
226 result.st_mode = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200227 self.fail("No exception raised")
Collin Winter42dae6a2007-03-28 21:44:53 +0000228 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000229 pass
230
231 try:
232 result.st_rdev = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200233 self.fail("No exception raised")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000234 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000235 pass
236
237 try:
238 result.parrot = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200239 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000240 except AttributeError:
241 pass
242
243 # Use the stat_result constructor with a too-short tuple.
244 try:
245 result2 = os.stat_result((10,))
Andrew Svetlov737fb892012-12-18 21:14:22 +0200246 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000247 except TypeError:
248 pass
249
Ezio Melotti42da6632011-03-15 05:18:48 +0200250 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000251 try:
252 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
253 except TypeError:
254 pass
255
Antoine Pitrou38425292010-09-21 18:19:07 +0000256 def test_stat_attributes(self):
257 self.check_stat_attributes(self.fname)
258
259 def test_stat_attributes_bytes(self):
260 try:
261 fname = self.fname.encode(sys.getfilesystemencoding())
262 except UnicodeEncodeError:
263 self.skipTest("cannot encode %a for the filesystem" % self.fname)
Victor Stinner1ab6c2d2011-11-15 22:27:41 +0100264 with warnings.catch_warnings():
265 warnings.simplefilter("ignore", DeprecationWarning)
266 self.check_stat_attributes(fname)
Tim Peterse0c446b2001-10-18 21:57:37 +0000267
Christian Heimes25827622013-10-12 01:27:08 +0200268 def test_stat_result_pickle(self):
269 result = os.stat(self.fname)
270 p = pickle.dumps(result)
271 self.assertIn(b'\x03cos\nstat_result\n', p)
272 unpickled = pickle.loads(p)
273 self.assertEqual(result, unpickled)
274
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000275 def test_statvfs_attributes(self):
276 if not hasattr(os, "statvfs"):
277 return
278
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000279 try:
280 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000281 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000282 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000283 if e.errno == errno.ENOSYS:
Victor Stinner370cb252013-10-12 01:33:54 +0200284 self.skipTest('os.statvfs() failed with ENOSYS')
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000285
286 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000287 self.assertEqual(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000288
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000289 # Make sure all the attributes are there.
290 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
291 'ffree', 'favail', 'flag', 'namemax')
292 for value, member in enumerate(members):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000293 self.assertEqual(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000294
295 # Make sure that assignment really fails
296 try:
297 result.f_bfree = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200298 self.fail("No exception raised")
Collin Winter42dae6a2007-03-28 21:44:53 +0000299 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000300 pass
301
302 try:
303 result.parrot = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200304 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000305 except AttributeError:
306 pass
307
308 # Use the constructor with a too-short tuple.
309 try:
310 result2 = os.statvfs_result((10,))
Andrew Svetlov737fb892012-12-18 21:14:22 +0200311 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000312 except TypeError:
313 pass
314
Ezio Melotti42da6632011-03-15 05:18:48 +0200315 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000316 try:
317 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
318 except TypeError:
319 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000320
Christian Heimes25827622013-10-12 01:27:08 +0200321 @unittest.skipUnless(hasattr(os, 'statvfs'),
322 "need os.statvfs()")
323 def test_statvfs_result_pickle(self):
324 try:
325 result = os.statvfs(self.fname)
326 except OSError as e:
327 # On AtheOS, glibc always returns ENOSYS
328 if e.errno == errno.ENOSYS:
Victor Stinner370cb252013-10-12 01:33:54 +0200329 self.skipTest('os.statvfs() failed with ENOSYS')
330
Christian Heimes25827622013-10-12 01:27:08 +0200331 p = pickle.dumps(result)
332 self.assertIn(b'\x03cos\nstatvfs_result\n', p)
333 unpickled = pickle.loads(p)
334 self.assertEqual(result, unpickled)
335
Thomas Wouters89f507f2006-12-13 04:49:30 +0000336 def test_utime_dir(self):
337 delta = 1000000
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000338 st = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000339 # round to int, because some systems may support sub-second
340 # time stamps in stat, but not in utime.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000341 os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
342 st2 = os.stat(support.TESTFN)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000343 self.assertEqual(st2.st_mtime, int(st.st_mtime-delta))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000344
Larry Hastings76ad59b2012-05-03 00:30:07 -0700345 def _test_utime(self, filename, attr, utime, delta):
Brian Curtin0277aa32011-11-06 13:50:15 -0600346 # Issue #13327 removed the requirement to pass None as the
Brian Curtin52fbea12011-11-06 13:41:17 -0600347 # second argument. Check that the previous methods of passing
348 # a time tuple or None work in addition to no argument.
Larry Hastings76ad59b2012-05-03 00:30:07 -0700349 st0 = os.stat(filename)
Brian Curtin52fbea12011-11-06 13:41:17 -0600350 # Doesn't set anything new, but sets the time tuple way
Larry Hastings76ad59b2012-05-03 00:30:07 -0700351 utime(filename, (attr(st0, "st_atime"), attr(st0, "st_mtime")))
352 # Setting the time to the time you just read, then reading again,
353 # should always return exactly the same times.
354 st1 = os.stat(filename)
355 self.assertEqual(attr(st0, "st_mtime"), attr(st1, "st_mtime"))
356 self.assertEqual(attr(st0, "st_atime"), attr(st1, "st_atime"))
Brian Curtin52fbea12011-11-06 13:41:17 -0600357 # Set to the current time in the old explicit way.
Larry Hastings76ad59b2012-05-03 00:30:07 -0700358 os.utime(filename, None)
Brian Curtin52fbea12011-11-06 13:41:17 -0600359 st2 = os.stat(support.TESTFN)
Larry Hastings76ad59b2012-05-03 00:30:07 -0700360 # Set to the current time in the new way
361 os.utime(filename)
362 st3 = os.stat(filename)
363 self.assertAlmostEqual(attr(st2, "st_mtime"), attr(st3, "st_mtime"), delta=delta)
364
365 def test_utime(self):
366 def utime(file, times):
367 return os.utime(file, times)
368 self._test_utime(self.fname, getattr, utime, 10)
369 self._test_utime(support.TESTFN, getattr, utime, 10)
370
371
372 def _test_utime_ns(self, set_times_ns, test_dir=True):
373 def getattr_ns(o, attr):
374 return getattr(o, attr + "_ns")
375 ten_s = 10 * 1000 * 1000 * 1000
376 self._test_utime(self.fname, getattr_ns, set_times_ns, ten_s)
377 if test_dir:
378 self._test_utime(support.TESTFN, getattr_ns, set_times_ns, ten_s)
379
380 def test_utime_ns(self):
381 def utime_ns(file, times):
382 return os.utime(file, ns=times)
383 self._test_utime_ns(utime_ns)
384
Larry Hastings9cf065c2012-06-22 16:30:09 -0700385 requires_utime_dir_fd = unittest.skipUnless(
386 os.utime in os.supports_dir_fd,
387 "dir_fd support for utime required for this test.")
388 requires_utime_fd = unittest.skipUnless(
389 os.utime in os.supports_fd,
390 "fd support for utime required for this test.")
391 requires_utime_nofollow_symlinks = unittest.skipUnless(
392 os.utime in os.supports_follow_symlinks,
393 "follow_symlinks support for utime required for this test.")
Larry Hastings76ad59b2012-05-03 00:30:07 -0700394
Larry Hastings9cf065c2012-06-22 16:30:09 -0700395 @requires_utime_nofollow_symlinks
Larry Hastings76ad59b2012-05-03 00:30:07 -0700396 def test_lutimes_ns(self):
397 def lutimes_ns(file, times):
Larry Hastings9cf065c2012-06-22 16:30:09 -0700398 return os.utime(file, ns=times, follow_symlinks=False)
Larry Hastings76ad59b2012-05-03 00:30:07 -0700399 self._test_utime_ns(lutimes_ns)
400
Larry Hastings9cf065c2012-06-22 16:30:09 -0700401 @requires_utime_fd
Larry Hastings76ad59b2012-05-03 00:30:07 -0700402 def test_futimes_ns(self):
403 def futimes_ns(file, times):
404 with open(file, "wb") as f:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700405 os.utime(f.fileno(), ns=times)
Larry Hastings76ad59b2012-05-03 00:30:07 -0700406 self._test_utime_ns(futimes_ns, test_dir=False)
407
408 def _utime_invalid_arguments(self, name, arg):
Larry Hastings9cf065c2012-06-22 16:30:09 -0700409 with self.assertRaises(ValueError):
Larry Hastings76ad59b2012-05-03 00:30:07 -0700410 getattr(os, name)(arg, (5, 5), ns=(5, 5))
411
412 def test_utime_invalid_arguments(self):
413 self._utime_invalid_arguments('utime', self.fname)
414
Brian Curtin52fbea12011-11-06 13:41:17 -0600415
Victor Stinner1aa54a42012-02-08 04:09:37 +0100416 @unittest.skipUnless(stat_supports_subsecond,
417 "os.stat() doesn't has a subsecond resolution")
Victor Stinnera2f7c002012-02-08 03:36:25 +0100418 def _test_utime_subsecond(self, set_time_func):
Victor Stinnerbe557de2012-02-08 03:01:11 +0100419 asec, amsec = 1, 901
420 atime = asec + amsec * 1e-3
Victor Stinnera2f7c002012-02-08 03:36:25 +0100421 msec, mmsec = 2, 901
Victor Stinnerbe557de2012-02-08 03:01:11 +0100422 mtime = msec + mmsec * 1e-3
423 filename = self.fname
Victor Stinnera2f7c002012-02-08 03:36:25 +0100424 os.utime(filename, (0, 0))
425 set_time_func(filename, atime, mtime)
Victor Stinner034d0aa2012-06-05 01:22:15 +0200426 with warnings.catch_warnings():
427 warnings.simplefilter("ignore", DeprecationWarning)
428 os.stat_float_times(True)
Victor Stinnera2f7c002012-02-08 03:36:25 +0100429 st = os.stat(filename)
430 self.assertAlmostEqual(st.st_atime, atime, places=3)
431 self.assertAlmostEqual(st.st_mtime, mtime, places=3)
Victor Stinnerbe557de2012-02-08 03:01:11 +0100432
Victor Stinnera2f7c002012-02-08 03:36:25 +0100433 def test_utime_subsecond(self):
434 def set_time(filename, atime, mtime):
435 os.utime(filename, (atime, mtime))
436 self._test_utime_subsecond(set_time)
437
Larry Hastings9cf065c2012-06-22 16:30:09 -0700438 @requires_utime_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100439 def test_futimes_subsecond(self):
440 def set_time(filename, atime, mtime):
441 with open(filename, "wb") as f:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700442 os.utime(f.fileno(), times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100443 self._test_utime_subsecond(set_time)
444
Larry Hastings9cf065c2012-06-22 16:30:09 -0700445 @requires_utime_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100446 def test_futimens_subsecond(self):
447 def set_time(filename, atime, mtime):
448 with open(filename, "wb") as f:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700449 os.utime(f.fileno(), times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100450 self._test_utime_subsecond(set_time)
451
Larry Hastings9cf065c2012-06-22 16:30:09 -0700452 @requires_utime_dir_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100453 def test_futimesat_subsecond(self):
454 def set_time(filename, atime, mtime):
455 dirname = os.path.dirname(filename)
456 dirfd = os.open(dirname, os.O_RDONLY)
457 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700458 os.utime(os.path.basename(filename), dir_fd=dirfd,
459 times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100460 finally:
461 os.close(dirfd)
462 self._test_utime_subsecond(set_time)
463
Larry Hastings9cf065c2012-06-22 16:30:09 -0700464 @requires_utime_nofollow_symlinks
Victor Stinnera2f7c002012-02-08 03:36:25 +0100465 def test_lutimes_subsecond(self):
466 def set_time(filename, atime, mtime):
Larry Hastings9cf065c2012-06-22 16:30:09 -0700467 os.utime(filename, (atime, mtime), follow_symlinks=False)
Victor Stinnera2f7c002012-02-08 03:36:25 +0100468 self._test_utime_subsecond(set_time)
469
Larry Hastings9cf065c2012-06-22 16:30:09 -0700470 @requires_utime_dir_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100471 def test_utimensat_subsecond(self):
472 def set_time(filename, atime, mtime):
473 dirname = os.path.dirname(filename)
474 dirfd = os.open(dirname, os.O_RDONLY)
475 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700476 os.utime(os.path.basename(filename), dir_fd=dirfd,
477 times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100478 finally:
479 os.close(dirfd)
480 self._test_utime_subsecond(set_time)
Victor Stinnerbe557de2012-02-08 03:01:11 +0100481
Thomas Wouters89f507f2006-12-13 04:49:30 +0000482 # Restrict test to Win32, since there is no guarantee other
483 # systems support centiseconds
484 if sys.platform == 'win32':
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000485 def get_file_system(path):
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000486 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000487 import ctypes
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000488 kernel32 = ctypes.windll.kernel32
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000489 buf = ctypes.create_unicode_buffer("", 100)
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000490 if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000491 return buf.value
492
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000493 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000494 def test_1565150(self):
495 t1 = 1159195039.25
496 os.utime(self.fname, (t1, t1))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000497 self.assertEqual(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000498
Amaury Forgeot d'Arca251a852011-01-03 00:19:11 +0000499 def test_large_time(self):
500 t1 = 5000000000 # some day in 2128
501 os.utime(self.fname, (t1, t1))
502 self.assertEqual(os.stat(self.fname).st_mtime, t1)
503
Guido van Rossumd8faa362007-04-27 19:54:29 +0000504 def test_1686475(self):
505 # Verify that an open file can be stat'ed
506 try:
507 os.stat(r"c:\pagefile.sys")
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200508 except FileNotFoundError:
509 pass # file does not exist; cannot run test
510 except OSError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000511 self.fail("Could not stat pagefile.sys")
512
Richard Oudkerk2240ac12012-07-06 12:05:32 +0100513 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
514 def test_15261(self):
515 # Verify that stat'ing a closed fd does not cause crash
516 r, w = os.pipe()
517 try:
518 os.stat(r) # should not raise error
519 finally:
520 os.close(r)
521 os.close(w)
522 with self.assertRaises(OSError) as ctx:
523 os.stat(r)
524 self.assertEqual(ctx.exception.errno, errno.EBADF)
525
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000526from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000527
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000528class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000529 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000530 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000531
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000532 def setUp(self):
533 self.__save = dict(os.environ)
Victor Stinnerb745a742010-05-18 17:17:23 +0000534 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000535 self.__saveb = dict(os.environb)
Christian Heimes90333392007-11-01 19:08:42 +0000536 for key, value in self._reference().items():
537 os.environ[key] = value
538
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000539 def tearDown(self):
540 os.environ.clear()
541 os.environ.update(self.__save)
Victor Stinnerb745a742010-05-18 17:17:23 +0000542 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000543 os.environb.clear()
544 os.environb.update(self.__saveb)
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000545
Christian Heimes90333392007-11-01 19:08:42 +0000546 def _reference(self):
547 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
548
549 def _empty_mapping(self):
550 os.environ.clear()
551 return os.environ
552
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000553 # Bug 1110478
Ezio Melottic7e139b2012-09-26 20:01:34 +0300554 @unittest.skipUnless(os.path.exists('/bin/sh'), 'requires /bin/sh')
Martin v. Löwis5510f652005-02-17 21:23:20 +0000555 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000556 os.environ.clear()
Ezio Melottic7e139b2012-09-26 20:01:34 +0300557 os.environ.update(HELLO="World")
558 with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
559 value = popen.read().strip()
560 self.assertEqual(value, "World")
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000561
Ezio Melottic7e139b2012-09-26 20:01:34 +0300562 @unittest.skipUnless(os.path.exists('/bin/sh'), 'requires /bin/sh')
Christian Heimes1a13d592007-11-08 14:16:55 +0000563 def test_os_popen_iter(self):
Ezio Melottic7e139b2012-09-26 20:01:34 +0300564 with os.popen(
565 "/bin/sh -c 'echo \"line1\nline2\nline3\"'") as popen:
566 it = iter(popen)
567 self.assertEqual(next(it), "line1\n")
568 self.assertEqual(next(it), "line2\n")
569 self.assertEqual(next(it), "line3\n")
570 self.assertRaises(StopIteration, next, it)
Christian Heimes1a13d592007-11-08 14:16:55 +0000571
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000572 # Verify environ keys and values from the OS are of the
573 # correct str type.
574 def test_keyvalue_types(self):
575 for key, val in os.environ.items():
Ezio Melottib3aedd42010-11-20 19:04:17 +0000576 self.assertEqual(type(key), str)
577 self.assertEqual(type(val), str)
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000578
Christian Heimes90333392007-11-01 19:08:42 +0000579 def test_items(self):
580 for key, value in self._reference().items():
581 self.assertEqual(os.environ.get(key), value)
582
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000583 # Issue 7310
584 def test___repr__(self):
585 """Check that the repr() of os.environ looks like environ({...})."""
586 env = os.environ
Victor Stinner96f0de92010-07-29 00:29:00 +0000587 self.assertEqual(repr(env), 'environ({{{}}})'.format(', '.join(
588 '{!r}: {!r}'.format(key, value)
589 for key, value in env.items())))
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000590
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000591 def test_get_exec_path(self):
592 defpath_list = os.defpath.split(os.pathsep)
593 test_path = ['/monty', '/python', '', '/flying/circus']
594 test_env = {'PATH': os.pathsep.join(test_path)}
595
596 saved_environ = os.environ
597 try:
598 os.environ = dict(test_env)
599 # Test that defaulting to os.environ works.
600 self.assertSequenceEqual(test_path, os.get_exec_path())
601 self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
602 finally:
603 os.environ = saved_environ
604
605 # No PATH environment variable
606 self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
607 # Empty PATH environment variable
608 self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
609 # Supplied PATH environment variable
610 self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
611
Victor Stinnerb745a742010-05-18 17:17:23 +0000612 if os.supports_bytes_environ:
613 # env cannot contain 'PATH' and b'PATH' keys
Victor Stinner38430e22010-08-19 17:10:18 +0000614 try:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000615 # ignore BytesWarning warning
616 with warnings.catch_warnings(record=True):
617 mixed_env = {'PATH': '1', b'PATH': b'2'}
Victor Stinner38430e22010-08-19 17:10:18 +0000618 except BytesWarning:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000619 # mixed_env cannot be created with python -bb
Victor Stinner38430e22010-08-19 17:10:18 +0000620 pass
621 else:
622 self.assertRaises(ValueError, os.get_exec_path, mixed_env)
Victor Stinnerb745a742010-05-18 17:17:23 +0000623
624 # bytes key and/or value
625 self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}),
626 ['abc'])
627 self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}),
628 ['abc'])
629 self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}),
630 ['abc'])
631
632 @unittest.skipUnless(os.supports_bytes_environ,
633 "os.environb required for this test.")
Victor Stinner84ae1182010-05-06 22:05:07 +0000634 def test_environb(self):
635 # os.environ -> os.environb
636 value = 'euro\u20ac'
637 try:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000638 value_bytes = value.encode(sys.getfilesystemencoding(),
639 'surrogateescape')
Victor Stinner84ae1182010-05-06 22:05:07 +0000640 except UnicodeEncodeError:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000641 msg = "U+20AC character is not encodable to %s" % (
642 sys.getfilesystemencoding(),)
Benjamin Peterson932d3f42010-05-06 22:26:31 +0000643 self.skipTest(msg)
Victor Stinner84ae1182010-05-06 22:05:07 +0000644 os.environ['unicode'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000645 self.assertEqual(os.environ['unicode'], value)
646 self.assertEqual(os.environb[b'unicode'], value_bytes)
Victor Stinner84ae1182010-05-06 22:05:07 +0000647
648 # os.environb -> os.environ
649 value = b'\xff'
650 os.environb[b'bytes'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000651 self.assertEqual(os.environb[b'bytes'], value)
Victor Stinner84ae1182010-05-06 22:05:07 +0000652 value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000653 self.assertEqual(os.environ['bytes'], value_str)
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000654
Charles-François Natali2966f102011-11-26 11:32:46 +0100655 # On FreeBSD < 7 and OS X < 10.6, unsetenv() doesn't return a value (issue
656 # #13415).
657 @support.requires_freebsd_version(7)
658 @support.requires_mac_ver(10, 6)
Victor Stinner60b385e2011-11-22 22:01:28 +0100659 def test_unset_error(self):
660 if sys.platform == "win32":
661 # an environment variable is limited to 32,767 characters
662 key = 'x' * 50000
Victor Stinnerb3f82682011-11-22 22:30:19 +0100663 self.assertRaises(ValueError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100664 else:
665 # "=" is not allowed in a variable name
666 key = 'key='
Victor Stinnerb3f82682011-11-22 22:30:19 +0100667 self.assertRaises(OSError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100668
Victor Stinner6d101392013-04-14 16:35:04 +0200669 def test_key_type(self):
670 missing = 'missingkey'
671 self.assertNotIn(missing, os.environ)
672
Victor Stinner839e5ea2013-04-14 16:43:03 +0200673 with self.assertRaises(KeyError) as cm:
Victor Stinner6d101392013-04-14 16:35:04 +0200674 os.environ[missing]
Victor Stinner839e5ea2013-04-14 16:43:03 +0200675 self.assertIs(cm.exception.args[0], missing)
Victor Stinner0c2dd0c2013-08-23 19:19:15 +0200676 self.assertTrue(cm.exception.__suppress_context__)
Victor Stinner6d101392013-04-14 16:35:04 +0200677
Victor Stinner839e5ea2013-04-14 16:43:03 +0200678 with self.assertRaises(KeyError) as cm:
Victor Stinner6d101392013-04-14 16:35:04 +0200679 del os.environ[missing]
Victor Stinner839e5ea2013-04-14 16:43:03 +0200680 self.assertIs(cm.exception.args[0], missing)
Victor Stinner0c2dd0c2013-08-23 19:19:15 +0200681 self.assertTrue(cm.exception.__suppress_context__)
682
Victor Stinner6d101392013-04-14 16:35:04 +0200683
Tim Petersc4e09402003-04-25 07:11:48 +0000684class WalkTests(unittest.TestCase):
685 """Tests for os.walk()."""
686
Charles-François Natali7372b062012-02-05 15:15:38 +0100687 def setUp(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000688 import os
689 from os.path import join
690
691 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000692 # TESTFN/
693 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000694 # tmp1
695 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000696 # tmp2
697 # SUB11/ no kids
698 # SUB2/ a file kid and a dirsymlink kid
699 # tmp3
700 # link/ a symlink to TESTFN.2
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200701 # broken_link
Guido van Rossumd8faa362007-04-27 19:54:29 +0000702 # TEST2/
703 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000704 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000705 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000706 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000707 sub2_path = join(walk_path, "SUB2")
708 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000709 tmp2_path = join(sub1_path, "tmp2")
710 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000711 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000712 t2_path = join(support.TESTFN, "TEST2")
713 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200714 link_path = join(sub2_path, "link")
715 broken_link_path = join(sub2_path, "broken_link")
Tim Petersc4e09402003-04-25 07:11:48 +0000716
717 # Create stuff.
718 os.makedirs(sub11_path)
719 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000720 os.makedirs(t2_path)
721 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000722 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000723 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
724 f.close()
Brian Curtin3b4499c2010-12-28 14:31:47 +0000725 if support.can_symlink():
Jason R. Coombs3a092862013-05-27 23:21:28 -0400726 os.symlink(os.path.abspath(t2_path), link_path)
Jason R. Coombsb501b562013-05-27 23:52:43 -0400727 os.symlink('broken', broken_link_path, True)
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200728 sub2_tree = (sub2_path, ["link"], ["broken_link", "tmp3"])
Guido van Rossumd8faa362007-04-27 19:54:29 +0000729 else:
730 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000731
732 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000733 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000734 self.assertEqual(len(all), 4)
735 # We can't know which order SUB1 and SUB2 will appear in.
736 # Not flipped: TESTFN, SUB1, SUB11, SUB2
737 # flipped: TESTFN, SUB2, SUB1, SUB11
738 flipped = all[0][1][0] != "SUB1"
739 all[0][1].sort()
Hynek Schlawackc96f5a02012-05-15 17:55:38 +0200740 all[3 - 2 * flipped][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000741 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000742 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
743 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000744 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000745
746 # Prune the search.
747 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000748 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000749 all.append((root, dirs, files))
750 # Don't descend into SUB1.
751 if 'SUB1' in dirs:
752 # Note that this also mutates the dirs we appended to all!
753 dirs.remove('SUB1')
754 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000755 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Hynek Schlawack39bf90d2012-05-15 18:40:17 +0200756 all[1][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000757 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000758
759 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000760 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000761 self.assertEqual(len(all), 4)
762 # We can't know which order SUB1 and SUB2 will appear in.
763 # Not flipped: SUB11, SUB1, SUB2, TESTFN
764 # flipped: SUB2, SUB11, SUB1, TESTFN
765 flipped = all[3][1][0] != "SUB1"
766 all[3][1].sort()
Hynek Schlawack39bf90d2012-05-15 18:40:17 +0200767 all[2 - 2 * flipped][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000768 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000769 self.assertEqual(all[flipped], (sub11_path, [], []))
770 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000771 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000772
Brian Curtin3b4499c2010-12-28 14:31:47 +0000773 if support.can_symlink():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000774 # Walk, following symlinks.
775 for root, dirs, files in os.walk(walk_path, followlinks=True):
776 if root == link_path:
777 self.assertEqual(dirs, [])
778 self.assertEqual(files, ["tmp4"])
779 break
780 else:
781 self.fail("Didn't follow symlink with followlinks=True")
782
783 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000784 # Tear everything down. This is a decent use for bottom-up on
785 # Windows, which doesn't have a recursive delete command. The
786 # (not so) subtlety is that rmdir will fail unless the dir's
787 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000788 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000789 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000790 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000791 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000792 dirname = os.path.join(root, name)
793 if not os.path.islink(dirname):
794 os.rmdir(dirname)
795 else:
796 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000797 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000798
Charles-François Natali7372b062012-02-05 15:15:38 +0100799
800@unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
801class FwalkTests(WalkTests):
802 """Tests for os.fwalk()."""
803
Larry Hastingsc48fe982012-06-25 04:49:05 -0700804 def _compare_to_walk(self, walk_kwargs, fwalk_kwargs):
805 """
806 compare with walk() results.
807 """
Larry Hastingsb4038062012-07-15 10:57:38 -0700808 walk_kwargs = walk_kwargs.copy()
809 fwalk_kwargs = fwalk_kwargs.copy()
810 for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
811 walk_kwargs.update(topdown=topdown, followlinks=follow_symlinks)
812 fwalk_kwargs.update(topdown=topdown, follow_symlinks=follow_symlinks)
Larry Hastingsc48fe982012-06-25 04:49:05 -0700813
Charles-François Natali7372b062012-02-05 15:15:38 +0100814 expected = {}
Larry Hastingsc48fe982012-06-25 04:49:05 -0700815 for root, dirs, files in os.walk(**walk_kwargs):
Charles-François Natali7372b062012-02-05 15:15:38 +0100816 expected[root] = (set(dirs), set(files))
817
Larry Hastingsc48fe982012-06-25 04:49:05 -0700818 for root, dirs, files, rootfd in os.fwalk(**fwalk_kwargs):
Charles-François Natali7372b062012-02-05 15:15:38 +0100819 self.assertIn(root, expected)
820 self.assertEqual(expected[root], (set(dirs), set(files)))
821
Larry Hastingsc48fe982012-06-25 04:49:05 -0700822 def test_compare_to_walk(self):
823 kwargs = {'top': support.TESTFN}
824 self._compare_to_walk(kwargs, kwargs)
825
Charles-François Natali7372b062012-02-05 15:15:38 +0100826 def test_dir_fd(self):
Larry Hastingsc48fe982012-06-25 04:49:05 -0700827 try:
828 fd = os.open(".", os.O_RDONLY)
829 walk_kwargs = {'top': support.TESTFN}
830 fwalk_kwargs = walk_kwargs.copy()
831 fwalk_kwargs['dir_fd'] = fd
832 self._compare_to_walk(walk_kwargs, fwalk_kwargs)
833 finally:
834 os.close(fd)
835
836 def test_yields_correct_dir_fd(self):
Charles-François Natali7372b062012-02-05 15:15:38 +0100837 # check returned file descriptors
Larry Hastingsb4038062012-07-15 10:57:38 -0700838 for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
839 args = support.TESTFN, topdown, None
840 for root, dirs, files, rootfd in os.fwalk(*args, follow_symlinks=follow_symlinks):
Charles-François Natali7372b062012-02-05 15:15:38 +0100841 # check that the FD is valid
842 os.fstat(rootfd)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700843 # redundant check
844 os.stat(rootfd)
845 # check that listdir() returns consistent information
846 self.assertEqual(set(os.listdir(rootfd)), set(dirs) | set(files))
Charles-François Natali7372b062012-02-05 15:15:38 +0100847
848 def test_fd_leak(self):
849 # Since we're opening a lot of FDs, we must be careful to avoid leaks:
850 # we both check that calling fwalk() a large number of times doesn't
851 # yield EMFILE, and that the minimum allocated FD hasn't changed.
852 minfd = os.dup(1)
853 os.close(minfd)
854 for i in range(256):
855 for x in os.fwalk(support.TESTFN):
856 pass
857 newfd = os.dup(1)
858 self.addCleanup(os.close, newfd)
859 self.assertEqual(newfd, minfd)
860
861 def tearDown(self):
862 # cleanup
863 for root, dirs, files, rootfd in os.fwalk(support.TESTFN, topdown=False):
864 for name in files:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700865 os.unlink(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +0100866 for name in dirs:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700867 st = os.stat(name, dir_fd=rootfd, follow_symlinks=False)
Larry Hastingsb698d8e2012-06-23 16:55:07 -0700868 if stat.S_ISDIR(st.st_mode):
869 os.rmdir(name, dir_fd=rootfd)
870 else:
871 os.unlink(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +0100872 os.rmdir(support.TESTFN)
873
874
Guido van Rossume7ba4952007-06-06 23:52:48 +0000875class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000876 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000877 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000878
879 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000880 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000881 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
882 os.makedirs(path) # Should work
883 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
884 os.makedirs(path)
885
886 # Try paths with a '.' in them
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000887 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000888 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
889 os.makedirs(path)
890 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
891 'dir5', 'dir6')
892 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000893
Terry Reedy5a22b652010-12-02 07:05:56 +0000894 def test_exist_ok_existing_directory(self):
895 path = os.path.join(support.TESTFN, 'dir1')
896 mode = 0o777
897 old_mask = os.umask(0o022)
898 os.makedirs(path, mode)
899 self.assertRaises(OSError, os.makedirs, path, mode)
900 self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
901 self.assertRaises(OSError, os.makedirs, path, 0o776, exist_ok=True)
902 os.makedirs(path, mode=mode, exist_ok=True)
903 os.umask(old_mask)
904
Terry Jan Reedy4a0b6f72013-08-10 20:58:59 -0400905 @unittest.skipUnless(hasattr(os, 'chown'), 'test needs os.chown')
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700906 def test_chown_uid_gid_arguments_must_be_index(self):
907 stat = os.stat(support.TESTFN)
908 uid = stat.st_uid
909 gid = stat.st_gid
910 for value in (-1.0, -1j, decimal.Decimal(-1), fractions.Fraction(-2, 2)):
911 self.assertRaises(TypeError, os.chown, support.TESTFN, value, gid)
912 self.assertRaises(TypeError, os.chown, support.TESTFN, uid, value)
913 self.assertIsNone(os.chown(support.TESTFN, uid, gid))
914 self.assertIsNone(os.chown(support.TESTFN, -1, -1))
915
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700916 def test_exist_ok_s_isgid_directory(self):
917 path = os.path.join(support.TESTFN, 'dir1')
918 S_ISGID = stat.S_ISGID
919 mode = 0o777
920 old_mask = os.umask(0o022)
921 try:
922 existing_testfn_mode = stat.S_IMODE(
923 os.lstat(support.TESTFN).st_mode)
Ned Deilyc622f422012-08-08 20:57:24 -0700924 try:
925 os.chmod(support.TESTFN, existing_testfn_mode | S_ISGID)
Ned Deily3a2b97e2012-08-08 21:03:02 -0700926 except PermissionError:
Ned Deilyc622f422012-08-08 20:57:24 -0700927 raise unittest.SkipTest('Cannot set S_ISGID for dir.')
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700928 if (os.lstat(support.TESTFN).st_mode & S_ISGID != S_ISGID):
929 raise unittest.SkipTest('No support for S_ISGID dir mode.')
930 # The os should apply S_ISGID from the parent dir for us, but
931 # this test need not depend on that behavior. Be explicit.
932 os.makedirs(path, mode | S_ISGID)
933 # http://bugs.python.org/issue14992
934 # Should not fail when the bit is already set.
935 os.makedirs(path, mode, exist_ok=True)
936 # remove the bit.
937 os.chmod(path, stat.S_IMODE(os.lstat(path).st_mode) & ~S_ISGID)
938 with self.assertRaises(OSError):
939 # Should fail when the bit is not already set when demanded.
940 os.makedirs(path, mode | S_ISGID, exist_ok=True)
941 finally:
942 os.umask(old_mask)
Terry Reedy5a22b652010-12-02 07:05:56 +0000943
944 def test_exist_ok_existing_regular_file(self):
945 base = support.TESTFN
946 path = os.path.join(support.TESTFN, 'dir1')
947 f = open(path, 'w')
948 f.write('abc')
949 f.close()
950 self.assertRaises(OSError, os.makedirs, path)
951 self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
952 self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
953 os.remove(path)
954
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000955 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000956 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000957 'dir4', 'dir5', 'dir6')
958 # If the tests failed, the bottom-most directory ('../dir6')
959 # may not have been created, so we look for the outermost directory
960 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000961 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000962 path = os.path.dirname(path)
963
964 os.removedirs(path)
965
Andrew Svetlov405faed2012-12-25 12:18:09 +0200966
967class RemoveDirsTests(unittest.TestCase):
968 def setUp(self):
969 os.makedirs(support.TESTFN)
970
971 def tearDown(self):
972 support.rmtree(support.TESTFN)
973
974 def test_remove_all(self):
975 dira = os.path.join(support.TESTFN, 'dira')
976 os.mkdir(dira)
977 dirb = os.path.join(dira, 'dirb')
978 os.mkdir(dirb)
979 os.removedirs(dirb)
980 self.assertFalse(os.path.exists(dirb))
981 self.assertFalse(os.path.exists(dira))
982 self.assertFalse(os.path.exists(support.TESTFN))
983
984 def test_remove_partial(self):
985 dira = os.path.join(support.TESTFN, 'dira')
986 os.mkdir(dira)
987 dirb = os.path.join(dira, 'dirb')
988 os.mkdir(dirb)
989 with open(os.path.join(dira, 'file.txt'), 'w') as f:
990 f.write('text')
991 os.removedirs(dirb)
992 self.assertFalse(os.path.exists(dirb))
993 self.assertTrue(os.path.exists(dira))
994 self.assertTrue(os.path.exists(support.TESTFN))
995
996 def test_remove_nothing(self):
997 dira = os.path.join(support.TESTFN, 'dira')
998 os.mkdir(dira)
999 dirb = os.path.join(dira, 'dirb')
1000 os.mkdir(dirb)
1001 with open(os.path.join(dirb, 'file.txt'), 'w') as f:
1002 f.write('text')
1003 with self.assertRaises(OSError):
1004 os.removedirs(dirb)
1005 self.assertTrue(os.path.exists(dirb))
1006 self.assertTrue(os.path.exists(dira))
1007 self.assertTrue(os.path.exists(support.TESTFN))
1008
1009
Guido van Rossume7ba4952007-06-06 23:52:48 +00001010class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +00001011 def test_devnull(self):
Victor Stinnera6d2c762011-06-30 18:20:11 +02001012 with open(os.devnull, 'wb') as f:
1013 f.write(b'hello')
1014 f.close()
1015 with open(os.devnull, 'rb') as f:
1016 self.assertEqual(f.read(), b'')
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00001017
Andrew Svetlov405faed2012-12-25 12:18:09 +02001018
Guido van Rossume7ba4952007-06-06 23:52:48 +00001019class URandomTests(unittest.TestCase):
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001020 def test_urandom_length(self):
1021 self.assertEqual(len(os.urandom(0)), 0)
1022 self.assertEqual(len(os.urandom(1)), 1)
1023 self.assertEqual(len(os.urandom(10)), 10)
1024 self.assertEqual(len(os.urandom(100)), 100)
1025 self.assertEqual(len(os.urandom(1000)), 1000)
1026
1027 def test_urandom_value(self):
1028 data1 = os.urandom(16)
1029 data2 = os.urandom(16)
1030 self.assertNotEqual(data1, data2)
1031
1032 def get_urandom_subprocess(self, count):
1033 code = '\n'.join((
1034 'import os, sys',
1035 'data = os.urandom(%s)' % count,
1036 'sys.stdout.buffer.write(data)',
1037 'sys.stdout.buffer.flush()'))
1038 out = assert_python_ok('-c', code)
1039 stdout = out[1]
1040 self.assertEqual(len(stdout), 16)
1041 return stdout
1042
1043 def test_urandom_subprocess(self):
1044 data1 = self.get_urandom_subprocess(16)
1045 data2 = self.get_urandom_subprocess(16)
1046 self.assertNotEqual(data1, data2)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +00001047
Antoine Pitrouec34ab52013-08-16 20:44:38 +02001048 @unittest.skipUnless(resource, "test requires the resource module")
1049 def test_urandom_failure(self):
Antoine Pitroueba25ba2013-08-24 20:52:27 +02001050 # Check urandom() failing when it is not able to open /dev/random.
1051 # We spawn a new process to make the test more robust (if getrlimit()
1052 # failed to restore the file descriptor limit after this, the whole
1053 # test suite would crash; this actually happened on the OS X Tiger
1054 # buildbot).
1055 code = """if 1:
1056 import errno
1057 import os
1058 import resource
1059
1060 soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
1061 resource.setrlimit(resource.RLIMIT_NOFILE, (1, hard_limit))
1062 try:
Antoine Pitrouec34ab52013-08-16 20:44:38 +02001063 os.urandom(16)
Antoine Pitroueba25ba2013-08-24 20:52:27 +02001064 except OSError as e:
1065 assert e.errno == errno.EMFILE, e.errno
1066 else:
1067 raise AssertionError("OSError not raised")
1068 """
1069 assert_python_ok('-c', code)
Antoine Pitrouec34ab52013-08-16 20:44:38 +02001070
1071
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001072@contextlib.contextmanager
1073def _execvpe_mockup(defpath=None):
1074 """
1075 Stubs out execv and execve functions when used as context manager.
1076 Records exec calls. The mock execv and execve functions always raise an
1077 exception as they would normally never return.
1078 """
1079 # A list of tuples containing (function name, first arg, args)
1080 # of calls to execv or execve that have been made.
1081 calls = []
1082
1083 def mock_execv(name, *args):
1084 calls.append(('execv', name, args))
1085 raise RuntimeError("execv called")
1086
1087 def mock_execve(name, *args):
1088 calls.append(('execve', name, args))
1089 raise OSError(errno.ENOTDIR, "execve called")
1090
1091 try:
1092 orig_execv = os.execv
1093 orig_execve = os.execve
1094 orig_defpath = os.defpath
1095 os.execv = mock_execv
1096 os.execve = mock_execve
1097 if defpath is not None:
1098 os.defpath = defpath
1099 yield calls
1100 finally:
1101 os.execv = orig_execv
1102 os.execve = orig_execve
1103 os.defpath = orig_defpath
1104
Guido van Rossume7ba4952007-06-06 23:52:48 +00001105class ExecTests(unittest.TestCase):
Mark Dickinson7cf03892010-04-16 13:45:35 +00001106 @unittest.skipIf(USING_LINUXTHREADS,
1107 "avoid triggering a linuxthreads bug: see issue #4970")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001108 def test_execvpe_with_bad_program(self):
Mark Dickinson7cf03892010-04-16 13:45:35 +00001109 self.assertRaises(OSError, os.execvpe, 'no such app-',
1110 ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001111
Thomas Heller6790d602007-08-30 17:15:14 +00001112 def test_execvpe_with_bad_arglist(self):
1113 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
1114
Gregory P. Smith4ae37772010-05-08 18:05:46 +00001115 @unittest.skipUnless(hasattr(os, '_execvpe'),
1116 "No internal os._execvpe function to test.")
Victor Stinnerb745a742010-05-18 17:17:23 +00001117 def _test_internal_execvpe(self, test_type):
1118 program_path = os.sep + 'absolutepath'
1119 if test_type is bytes:
1120 program = b'executable'
1121 fullpath = os.path.join(os.fsencode(program_path), program)
1122 native_fullpath = fullpath
1123 arguments = [b'progname', 'arg1', 'arg2']
1124 else:
1125 program = 'executable'
1126 arguments = ['progname', 'arg1', 'arg2']
1127 fullpath = os.path.join(program_path, program)
1128 if os.name != "nt":
1129 native_fullpath = os.fsencode(fullpath)
1130 else:
1131 native_fullpath = fullpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001132 env = {'spam': 'beans'}
1133
Victor Stinnerb745a742010-05-18 17:17:23 +00001134 # test os._execvpe() with an absolute path
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001135 with _execvpe_mockup() as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +00001136 self.assertRaises(RuntimeError,
1137 os._execvpe, fullpath, arguments)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001138 self.assertEqual(len(calls), 1)
1139 self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))
1140
Victor Stinnerb745a742010-05-18 17:17:23 +00001141 # test os._execvpe() with a relative path:
1142 # os.get_exec_path() returns defpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001143 with _execvpe_mockup(defpath=program_path) as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +00001144 self.assertRaises(OSError,
1145 os._execvpe, program, arguments, env=env)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001146 self.assertEqual(len(calls), 1)
Victor Stinnerb745a742010-05-18 17:17:23 +00001147 self.assertSequenceEqual(calls[0],
1148 ('execve', native_fullpath, (arguments, env)))
1149
1150 # test os._execvpe() with a relative path:
1151 # os.get_exec_path() reads the 'PATH' variable
1152 with _execvpe_mockup() as calls:
1153 env_path = env.copy()
Victor Stinner38430e22010-08-19 17:10:18 +00001154 if test_type is bytes:
1155 env_path[b'PATH'] = program_path
1156 else:
1157 env_path['PATH'] = program_path
Victor Stinnerb745a742010-05-18 17:17:23 +00001158 self.assertRaises(OSError,
1159 os._execvpe, program, arguments, env=env_path)
1160 self.assertEqual(len(calls), 1)
1161 self.assertSequenceEqual(calls[0],
1162 ('execve', native_fullpath, (arguments, env_path)))
1163
1164 def test_internal_execvpe_str(self):
1165 self._test_internal_execvpe(str)
1166 if os.name != "nt":
1167 self._test_internal_execvpe(bytes)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001168
Gregory P. Smith4ae37772010-05-08 18:05:46 +00001169
Thomas Wouters477c8d52006-05-27 19:21:47 +00001170class Win32ErrorTests(unittest.TestCase):
1171 def test_rename(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001172 self.assertRaises(OSError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001173
1174 def test_remove(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001175 self.assertRaises(OSError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001176
1177 def test_chdir(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001178 self.assertRaises(OSError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001179
1180 def test_mkdir(self):
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +00001181 f = open(support.TESTFN, "w")
Benjamin Petersonf91df042009-02-13 02:50:59 +00001182 try:
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001183 self.assertRaises(OSError, os.mkdir, support.TESTFN)
Benjamin Petersonf91df042009-02-13 02:50:59 +00001184 finally:
1185 f.close()
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +00001186 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001187
1188 def test_utime(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001189 self.assertRaises(OSError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001190
Thomas Wouters477c8d52006-05-27 19:21:47 +00001191 def test_chmod(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001192 self.assertRaises(OSError, os.chmod, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001193
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001194class TestInvalidFD(unittest.TestCase):
Benjamin Peterson05e782f2009-01-19 15:15:02 +00001195 singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001196 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
1197 #singles.append("close")
1198 #We omit close because it doesn'r raise an exception on some platforms
1199 def get_single(f):
1200 def helper(self):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001201 if hasattr(os, f):
1202 self.check(getattr(os, f))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001203 return helper
1204 for f in singles:
1205 locals()["test_"+f] = get_single(f)
1206
Benjamin Peterson7522c742009-01-19 21:00:09 +00001207 def check(self, f, *args):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001208 try:
1209 f(support.make_bad_fd(), *args)
1210 except OSError as e:
1211 self.assertEqual(e.errno, errno.EBADF)
1212 else:
1213 self.fail("%r didn't raise a OSError with a bad file descriptor"
1214 % f)
Benjamin Peterson7522c742009-01-19 21:00:09 +00001215
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001216 def test_isatty(self):
1217 if hasattr(os, "isatty"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001218 self.assertEqual(os.isatty(support.make_bad_fd()), False)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001219
1220 def test_closerange(self):
1221 if hasattr(os, "closerange"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001222 fd = support.make_bad_fd()
R. David Murray630cc482009-07-22 15:20:27 +00001223 # Make sure none of the descriptors we are about to close are
1224 # currently valid (issue 6542).
1225 for i in range(10):
1226 try: os.fstat(fd+i)
1227 except OSError:
1228 pass
1229 else:
1230 break
1231 if i < 2:
1232 raise unittest.SkipTest(
1233 "Unable to acquire a range of invalid file descriptors")
1234 self.assertEqual(os.closerange(fd, fd + i-1), None)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001235
1236 def test_dup2(self):
1237 if hasattr(os, "dup2"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001238 self.check(os.dup2, 20)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001239
1240 def test_fchmod(self):
1241 if hasattr(os, "fchmod"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001242 self.check(os.fchmod, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001243
1244 def test_fchown(self):
1245 if hasattr(os, "fchown"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001246 self.check(os.fchown, -1, -1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001247
1248 def test_fpathconf(self):
1249 if hasattr(os, "fpathconf"):
Georg Brandl306336b2012-06-24 12:55:33 +02001250 self.check(os.pathconf, "PC_NAME_MAX")
Benjamin Peterson7522c742009-01-19 21:00:09 +00001251 self.check(os.fpathconf, "PC_NAME_MAX")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001252
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001253 def test_ftruncate(self):
1254 if hasattr(os, "ftruncate"):
Georg Brandl306336b2012-06-24 12:55:33 +02001255 self.check(os.truncate, 0)
Benjamin Peterson7522c742009-01-19 21:00:09 +00001256 self.check(os.ftruncate, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001257
1258 def test_lseek(self):
1259 if hasattr(os, "lseek"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001260 self.check(os.lseek, 0, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001261
1262 def test_read(self):
1263 if hasattr(os, "read"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001264 self.check(os.read, 1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001265
1266 def test_tcsetpgrpt(self):
1267 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001268 self.check(os.tcsetpgrp, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001269
1270 def test_write(self):
1271 if hasattr(os, "write"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001272 self.check(os.write, b" ")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001273
Brian Curtin1b9df392010-11-24 20:24:31 +00001274
1275class LinkTests(unittest.TestCase):
1276 def setUp(self):
1277 self.file1 = support.TESTFN
1278 self.file2 = os.path.join(support.TESTFN + "2")
1279
Brian Curtinc0abc4e2010-11-30 23:46:54 +00001280 def tearDown(self):
Brian Curtin1b9df392010-11-24 20:24:31 +00001281 for file in (self.file1, self.file2):
1282 if os.path.exists(file):
1283 os.unlink(file)
1284
Brian Curtin1b9df392010-11-24 20:24:31 +00001285 def _test_link(self, file1, file2):
1286 with open(file1, "w") as f1:
1287 f1.write("test")
1288
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001289 with warnings.catch_warnings():
1290 warnings.simplefilter("ignore", DeprecationWarning)
1291 os.link(file1, file2)
Brian Curtin1b9df392010-11-24 20:24:31 +00001292 with open(file1, "r") as f1, open(file2, "r") as f2:
1293 self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
1294
1295 def test_link(self):
1296 self._test_link(self.file1, self.file2)
1297
1298 def test_link_bytes(self):
1299 self._test_link(bytes(self.file1, sys.getfilesystemencoding()),
1300 bytes(self.file2, sys.getfilesystemencoding()))
1301
Brian Curtinf498b752010-11-30 15:54:04 +00001302 def test_unicode_name(self):
Brian Curtin43f0c272010-11-30 15:40:04 +00001303 try:
Brian Curtinf498b752010-11-30 15:54:04 +00001304 os.fsencode("\xf1")
Brian Curtin43f0c272010-11-30 15:40:04 +00001305 except UnicodeError:
1306 raise unittest.SkipTest("Unable to encode for this platform.")
1307
Brian Curtinf498b752010-11-30 15:54:04 +00001308 self.file1 += "\xf1"
Brian Curtinfc889c42010-11-28 23:59:46 +00001309 self.file2 = self.file1 + "2"
1310 self._test_link(self.file1, self.file2)
1311
Thomas Wouters477c8d52006-05-27 19:21:47 +00001312if sys.platform != 'win32':
1313 class Win32ErrorTests(unittest.TestCase):
1314 pass
1315
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001316 class PosixUidGidTests(unittest.TestCase):
1317 if hasattr(os, 'setuid'):
1318 def test_setuid(self):
1319 if os.getuid() != 0:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001320 self.assertRaises(OSError, os.setuid, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001321 self.assertRaises(OverflowError, os.setuid, 1<<32)
1322
1323 if hasattr(os, 'setgid'):
1324 def test_setgid(self):
Stefan Krahebee49a2013-01-17 15:31:00 +01001325 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001326 self.assertRaises(OSError, os.setgid, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001327 self.assertRaises(OverflowError, os.setgid, 1<<32)
1328
1329 if hasattr(os, 'seteuid'):
1330 def test_seteuid(self):
1331 if os.getuid() != 0:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001332 self.assertRaises(OSError, os.seteuid, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001333 self.assertRaises(OverflowError, os.seteuid, 1<<32)
1334
1335 if hasattr(os, 'setegid'):
1336 def test_setegid(self):
Stefan Krahebee49a2013-01-17 15:31:00 +01001337 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001338 self.assertRaises(OSError, os.setegid, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001339 self.assertRaises(OverflowError, os.setegid, 1<<32)
1340
1341 if hasattr(os, 'setreuid'):
1342 def test_setreuid(self):
1343 if os.getuid() != 0:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001344 self.assertRaises(OSError, os.setreuid, 0, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001345 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
1346 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001347
1348 def test_setreuid_neg1(self):
1349 # Needs to accept -1. We run this in a subprocess to avoid
1350 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001351 subprocess.check_call([
1352 sys.executable, '-c',
1353 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001354
1355 if hasattr(os, 'setregid'):
1356 def test_setregid(self):
Stefan Krahebee49a2013-01-17 15:31:00 +01001357 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001358 self.assertRaises(OSError, os.setregid, 0, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001359 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
1360 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001361
1362 def test_setregid_neg1(self):
1363 # Needs to accept -1. We run this in a subprocess to avoid
1364 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001365 subprocess.check_call([
1366 sys.executable, '-c',
1367 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Martin v. Löwis011e8422009-05-05 04:43:17 +00001368
1369 class Pep383Tests(unittest.TestCase):
Martin v. Löwis011e8422009-05-05 04:43:17 +00001370 def setUp(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001371 if support.TESTFN_UNENCODABLE:
1372 self.dir = support.TESTFN_UNENCODABLE
Victor Stinner8b219b22012-11-06 23:23:43 +01001373 elif support.TESTFN_NONASCII:
1374 self.dir = support.TESTFN_NONASCII
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001375 else:
1376 self.dir = support.TESTFN
1377 self.bdir = os.fsencode(self.dir)
1378
1379 bytesfn = []
1380 def add_filename(fn):
1381 try:
1382 fn = os.fsencode(fn)
1383 except UnicodeEncodeError:
1384 return
1385 bytesfn.append(fn)
1386 add_filename(support.TESTFN_UNICODE)
1387 if support.TESTFN_UNENCODABLE:
1388 add_filename(support.TESTFN_UNENCODABLE)
Victor Stinner8b219b22012-11-06 23:23:43 +01001389 if support.TESTFN_NONASCII:
1390 add_filename(support.TESTFN_NONASCII)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001391 if not bytesfn:
1392 self.skipTest("couldn't create any non-ascii filename")
1393
1394 self.unicodefn = set()
Martin v. Löwis011e8422009-05-05 04:43:17 +00001395 os.mkdir(self.dir)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001396 try:
1397 for fn in bytesfn:
Victor Stinnerbf816222011-06-30 23:25:47 +02001398 support.create_empty_file(os.path.join(self.bdir, fn))
Victor Stinnere8d51452010-08-19 01:05:19 +00001399 fn = os.fsdecode(fn)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001400 if fn in self.unicodefn:
1401 raise ValueError("duplicate filename")
1402 self.unicodefn.add(fn)
1403 except:
1404 shutil.rmtree(self.dir)
1405 raise
Martin v. Löwis011e8422009-05-05 04:43:17 +00001406
1407 def tearDown(self):
1408 shutil.rmtree(self.dir)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001409
1410 def test_listdir(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001411 expected = self.unicodefn
1412 found = set(os.listdir(self.dir))
Ezio Melottib3aedd42010-11-20 19:04:17 +00001413 self.assertEqual(found, expected)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001414 # test listdir without arguments
1415 current_directory = os.getcwd()
1416 try:
1417 os.chdir(os.sep)
1418 self.assertEqual(set(os.listdir()), set(os.listdir(os.sep)))
1419 finally:
1420 os.chdir(current_directory)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001421
1422 def test_open(self):
1423 for fn in self.unicodefn:
Victor Stinnera6d2c762011-06-30 18:20:11 +02001424 f = open(os.path.join(self.dir, fn), 'rb')
Martin v. Löwis011e8422009-05-05 04:43:17 +00001425 f.close()
1426
Victor Stinnere4110dc2013-01-01 23:05:55 +01001427 @unittest.skipUnless(hasattr(os, 'statvfs'),
1428 "need os.statvfs()")
1429 def test_statvfs(self):
1430 # issue #9645
1431 for fn in self.unicodefn:
1432 # should not fail with file not found error
1433 fullname = os.path.join(self.dir, fn)
1434 os.statvfs(fullname)
1435
Martin v. Löwis011e8422009-05-05 04:43:17 +00001436 def test_stat(self):
1437 for fn in self.unicodefn:
1438 os.stat(os.path.join(self.dir, fn))
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001439else:
1440 class PosixUidGidTests(unittest.TestCase):
1441 pass
Martin v. Löwis011e8422009-05-05 04:43:17 +00001442 class Pep383Tests(unittest.TestCase):
1443 pass
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001444
Brian Curtineb24d742010-04-12 17:16:38 +00001445@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
1446class Win32KillTests(unittest.TestCase):
Brian Curtinc3acbc32010-05-28 16:08:40 +00001447 def _kill(self, sig):
1448 # Start sys.executable as a subprocess and communicate from the
1449 # subprocess to the parent that the interpreter is ready. When it
1450 # becomes ready, send *sig* via os.kill to the subprocess and check
1451 # that the return code is equal to *sig*.
1452 import ctypes
1453 from ctypes import wintypes
1454 import msvcrt
1455
1456 # Since we can't access the contents of the process' stdout until the
1457 # process has exited, use PeekNamedPipe to see what's inside stdout
1458 # without waiting. This is done so we can tell that the interpreter
1459 # is started and running at a point where it could handle a signal.
1460 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
1461 PeekNamedPipe.restype = wintypes.BOOL
1462 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
1463 ctypes.POINTER(ctypes.c_char), # stdout buf
1464 wintypes.DWORD, # Buffer size
1465 ctypes.POINTER(wintypes.DWORD), # bytes read
1466 ctypes.POINTER(wintypes.DWORD), # bytes avail
1467 ctypes.POINTER(wintypes.DWORD)) # bytes left
1468 msg = "running"
1469 proc = subprocess.Popen([sys.executable, "-c",
1470 "import sys;"
1471 "sys.stdout.write('{}');"
1472 "sys.stdout.flush();"
1473 "input()".format(msg)],
1474 stdout=subprocess.PIPE,
1475 stderr=subprocess.PIPE,
1476 stdin=subprocess.PIPE)
Brian Curtin43ec5772010-11-05 15:17:11 +00001477 self.addCleanup(proc.stdout.close)
1478 self.addCleanup(proc.stderr.close)
1479 self.addCleanup(proc.stdin.close)
Brian Curtinc3acbc32010-05-28 16:08:40 +00001480
1481 count, max = 0, 100
1482 while count < max and proc.poll() is None:
1483 # Create a string buffer to store the result of stdout from the pipe
1484 buf = ctypes.create_string_buffer(len(msg))
1485 # Obtain the text currently in proc.stdout
1486 # Bytes read/avail/left are left as NULL and unused
1487 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
1488 buf, ctypes.sizeof(buf), None, None, None)
1489 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
1490 if buf.value:
1491 self.assertEqual(msg, buf.value.decode())
1492 break
1493 time.sleep(0.1)
1494 count += 1
1495 else:
1496 self.fail("Did not receive communication from the subprocess")
1497
Brian Curtineb24d742010-04-12 17:16:38 +00001498 os.kill(proc.pid, sig)
1499 self.assertEqual(proc.wait(), sig)
1500
1501 def test_kill_sigterm(self):
1502 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinc3acbc32010-05-28 16:08:40 +00001503 self._kill(signal.SIGTERM)
Brian Curtineb24d742010-04-12 17:16:38 +00001504
1505 def test_kill_int(self):
1506 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinc3acbc32010-05-28 16:08:40 +00001507 self._kill(100)
Brian Curtineb24d742010-04-12 17:16:38 +00001508
1509 def _kill_with_event(self, event, name):
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001510 tagname = "test_os_%s" % uuid.uuid1()
1511 m = mmap.mmap(-1, 1, tagname)
1512 m[0] = 0
Brian Curtineb24d742010-04-12 17:16:38 +00001513 # Run a script which has console control handling enabled.
1514 proc = subprocess.Popen([sys.executable,
1515 os.path.join(os.path.dirname(__file__),
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001516 "win_console_handler.py"), tagname],
Brian Curtineb24d742010-04-12 17:16:38 +00001517 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
1518 # Let the interpreter startup before we send signals. See #3137.
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001519 count, max = 0, 100
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001520 while count < max and proc.poll() is None:
Brian Curtinf668df52010-10-15 14:21:06 +00001521 if m[0] == 1:
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001522 break
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001523 time.sleep(0.1)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001524 count += 1
1525 else:
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001526 # Forcefully kill the process if we weren't able to signal it.
1527 os.kill(proc.pid, signal.SIGINT)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001528 self.fail("Subprocess didn't finish initialization")
Brian Curtineb24d742010-04-12 17:16:38 +00001529 os.kill(proc.pid, event)
1530 # proc.send_signal(event) could also be done here.
1531 # Allow time for the signal to be passed and the process to exit.
1532 time.sleep(0.5)
1533 if not proc.poll():
1534 # Forcefully kill the process if we weren't able to signal it.
1535 os.kill(proc.pid, signal.SIGINT)
1536 self.fail("subprocess did not stop on {}".format(name))
1537
1538 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
1539 def test_CTRL_C_EVENT(self):
1540 from ctypes import wintypes
1541 import ctypes
1542
1543 # Make a NULL value by creating a pointer with no argument.
1544 NULL = ctypes.POINTER(ctypes.c_int)()
1545 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
1546 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
1547 wintypes.BOOL)
1548 SetConsoleCtrlHandler.restype = wintypes.BOOL
1549
1550 # Calling this with NULL and FALSE causes the calling process to
1551 # handle CTRL+C, rather than ignore it. This property is inherited
1552 # by subprocesses.
1553 SetConsoleCtrlHandler(NULL, 0)
1554
1555 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
1556
1557 def test_CTRL_BREAK_EVENT(self):
1558 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
1559
1560
Brian Curtind40e6f72010-07-08 21:39:08 +00001561@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Tim Golden781bbeb2013-10-25 20:24:06 +01001562class Win32ListdirTests(unittest.TestCase):
1563 """Test listdir on Windows."""
1564
1565 def setUp(self):
1566 self.created_paths = []
1567 for i in range(2):
1568 dir_name = 'SUB%d' % i
1569 dir_path = os.path.join(support.TESTFN, dir_name)
1570 file_name = 'FILE%d' % i
1571 file_path = os.path.join(support.TESTFN, file_name)
1572 os.makedirs(dir_path)
1573 with open(file_path, 'w') as f:
1574 f.write("I'm %s and proud of it. Blame test_os.\n" % file_path)
1575 self.created_paths.extend([dir_name, file_name])
1576 self.created_paths.sort()
1577
1578 def tearDown(self):
1579 shutil.rmtree(support.TESTFN)
1580
1581 def test_listdir_no_extended_path(self):
1582 """Test when the path is not an "extended" path."""
1583 # unicode
1584 self.assertEqual(
1585 sorted(os.listdir(support.TESTFN)),
1586 self.created_paths)
1587 # bytes
1588 self.assertEqual(
1589 sorted(os.listdir(os.fsencode(support.TESTFN))),
1590 [os.fsencode(path) for path in self.created_paths])
1591
1592 def test_listdir_extended_path(self):
1593 """Test when the path starts with '\\\\?\\'."""
Tim Golden1cc35402013-10-25 21:26:06 +01001594 # See: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath
Tim Golden781bbeb2013-10-25 20:24:06 +01001595 # unicode
1596 path = '\\\\?\\' + os.path.abspath(support.TESTFN)
1597 self.assertEqual(
1598 sorted(os.listdir(path)),
1599 self.created_paths)
1600 # bytes
1601 path = b'\\\\?\\' + os.fsencode(os.path.abspath(support.TESTFN))
1602 self.assertEqual(
1603 sorted(os.listdir(path)),
1604 [os.fsencode(path) for path in self.created_paths])
1605
1606
1607@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Brian Curtin3b4499c2010-12-28 14:31:47 +00001608@support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +00001609class Win32SymlinkTests(unittest.TestCase):
1610 filelink = 'filelinktest'
1611 filelink_target = os.path.abspath(__file__)
1612 dirlink = 'dirlinktest'
1613 dirlink_target = os.path.dirname(filelink_target)
1614 missing_link = 'missing link'
1615
1616 def setUp(self):
1617 assert os.path.exists(self.dirlink_target)
1618 assert os.path.exists(self.filelink_target)
1619 assert not os.path.exists(self.dirlink)
1620 assert not os.path.exists(self.filelink)
1621 assert not os.path.exists(self.missing_link)
1622
1623 def tearDown(self):
1624 if os.path.exists(self.filelink):
1625 os.remove(self.filelink)
1626 if os.path.exists(self.dirlink):
1627 os.rmdir(self.dirlink)
1628 if os.path.lexists(self.missing_link):
1629 os.remove(self.missing_link)
1630
1631 def test_directory_link(self):
Jason R. Coombs3a092862013-05-27 23:21:28 -04001632 os.symlink(self.dirlink_target, self.dirlink)
Brian Curtind40e6f72010-07-08 21:39:08 +00001633 self.assertTrue(os.path.exists(self.dirlink))
1634 self.assertTrue(os.path.isdir(self.dirlink))
1635 self.assertTrue(os.path.islink(self.dirlink))
1636 self.check_stat(self.dirlink, self.dirlink_target)
1637
1638 def test_file_link(self):
1639 os.symlink(self.filelink_target, self.filelink)
1640 self.assertTrue(os.path.exists(self.filelink))
1641 self.assertTrue(os.path.isfile(self.filelink))
1642 self.assertTrue(os.path.islink(self.filelink))
1643 self.check_stat(self.filelink, self.filelink_target)
1644
1645 def _create_missing_dir_link(self):
1646 'Create a "directory" link to a non-existent target'
1647 linkname = self.missing_link
1648 if os.path.lexists(linkname):
1649 os.remove(linkname)
1650 target = r'c:\\target does not exist.29r3c740'
1651 assert not os.path.exists(target)
1652 target_is_dir = True
1653 os.symlink(target, linkname, target_is_dir)
1654
1655 def test_remove_directory_link_to_missing_target(self):
1656 self._create_missing_dir_link()
1657 # For compatibility with Unix, os.remove will check the
1658 # directory status and call RemoveDirectory if the symlink
1659 # was created with target_is_dir==True.
1660 os.remove(self.missing_link)
1661
1662 @unittest.skip("currently fails; consider for improvement")
1663 def test_isdir_on_directory_link_to_missing_target(self):
1664 self._create_missing_dir_link()
1665 # consider having isdir return true for directory links
1666 self.assertTrue(os.path.isdir(self.missing_link))
1667
1668 @unittest.skip("currently fails; consider for improvement")
1669 def test_rmdir_on_directory_link_to_missing_target(self):
1670 self._create_missing_dir_link()
1671 # consider allowing rmdir to remove directory links
1672 os.rmdir(self.missing_link)
1673
1674 def check_stat(self, link, target):
1675 self.assertEqual(os.stat(link), os.stat(target))
1676 self.assertNotEqual(os.lstat(link), os.stat(link))
1677
Brian Curtind25aef52011-06-13 15:16:04 -05001678 bytes_link = os.fsencode(link)
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001679 with warnings.catch_warnings():
1680 warnings.simplefilter("ignore", DeprecationWarning)
1681 self.assertEqual(os.stat(bytes_link), os.stat(target))
1682 self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link))
Brian Curtind25aef52011-06-13 15:16:04 -05001683
1684 def test_12084(self):
1685 level1 = os.path.abspath(support.TESTFN)
1686 level2 = os.path.join(level1, "level2")
1687 level3 = os.path.join(level2, "level3")
1688 try:
1689 os.mkdir(level1)
1690 os.mkdir(level2)
1691 os.mkdir(level3)
1692
1693 file1 = os.path.abspath(os.path.join(level1, "file1"))
1694
1695 with open(file1, "w") as f:
1696 f.write("file1")
1697
1698 orig_dir = os.getcwd()
1699 try:
1700 os.chdir(level2)
1701 link = os.path.join(level2, "link")
1702 os.symlink(os.path.relpath(file1), "link")
1703 self.assertIn("link", os.listdir(os.getcwd()))
1704
1705 # Check os.stat calls from the same dir as the link
1706 self.assertEqual(os.stat(file1), os.stat("link"))
1707
1708 # Check os.stat calls from a dir below the link
1709 os.chdir(level1)
1710 self.assertEqual(os.stat(file1),
1711 os.stat(os.path.relpath(link)))
1712
1713 # Check os.stat calls from a dir above the link
1714 os.chdir(level3)
1715 self.assertEqual(os.stat(file1),
1716 os.stat(os.path.relpath(link)))
1717 finally:
1718 os.chdir(orig_dir)
1719 except OSError as err:
1720 self.fail(err)
1721 finally:
1722 os.remove(file1)
1723 shutil.rmtree(level1)
1724
Brian Curtind40e6f72010-07-08 21:39:08 +00001725
Jason R. Coombs3a092862013-05-27 23:21:28 -04001726@support.skip_unless_symlink
1727class NonLocalSymlinkTests(unittest.TestCase):
1728
1729 def setUp(self):
1730 """
1731 Create this structure:
1732
1733 base
1734 \___ some_dir
1735 """
1736 os.makedirs('base/some_dir')
1737
1738 def tearDown(self):
1739 shutil.rmtree('base')
1740
1741 def test_directory_link_nonlocal(self):
1742 """
1743 The symlink target should resolve relative to the link, not relative
1744 to the current directory.
1745
1746 Then, link base/some_link -> base/some_dir and ensure that some_link
1747 is resolved as a directory.
1748
1749 In issue13772, it was discovered that directory detection failed if
1750 the symlink target was not specified relative to the current
1751 directory, which was a defect in the implementation.
1752 """
1753 src = os.path.join('base', 'some_link')
1754 os.symlink('some_dir', src)
1755 assert os.path.isdir(src)
1756
1757
Victor Stinnere8d51452010-08-19 01:05:19 +00001758class FSEncodingTests(unittest.TestCase):
1759 def test_nop(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001760 self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
1761 self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
Benjamin Peterson31191a92010-05-09 03:22:58 +00001762
Victor Stinnere8d51452010-08-19 01:05:19 +00001763 def test_identity(self):
1764 # assert fsdecode(fsencode(x)) == x
1765 for fn in ('unicode\u0141', 'latin\xe9', 'ascii'):
1766 try:
1767 bytesfn = os.fsencode(fn)
1768 except UnicodeEncodeError:
1769 continue
Ezio Melottib3aedd42010-11-20 19:04:17 +00001770 self.assertEqual(os.fsdecode(bytesfn), fn)
Victor Stinnere8d51452010-08-19 01:05:19 +00001771
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00001772
Brett Cannonefb00c02012-02-29 18:31:31 -05001773
1774class DeviceEncodingTests(unittest.TestCase):
1775
1776 def test_bad_fd(self):
1777 # Return None when an fd doesn't actually exist.
1778 self.assertIsNone(os.device_encoding(123456))
1779
Philip Jenveye308b7c2012-02-29 16:16:15 -08001780 @unittest.skipUnless(os.isatty(0) and (sys.platform.startswith('win') or
1781 (hasattr(locale, 'nl_langinfo') and hasattr(locale, 'CODESET'))),
Philip Jenveyd7aff2d2012-02-29 16:21:25 -08001782 'test requires a tty and either Windows or nl_langinfo(CODESET)')
Brett Cannonefb00c02012-02-29 18:31:31 -05001783 def test_device_encoding(self):
1784 encoding = os.device_encoding(0)
1785 self.assertIsNotNone(encoding)
1786 self.assertTrue(codecs.lookup(encoding))
1787
1788
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00001789class PidTests(unittest.TestCase):
1790 @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid")
1791 def test_getppid(self):
1792 p = subprocess.Popen([sys.executable, '-c',
1793 'import os; print(os.getppid())'],
1794 stdout=subprocess.PIPE)
1795 stdout, _ = p.communicate()
1796 # We are the parent of our subprocess
1797 self.assertEqual(int(stdout), os.getpid())
1798
1799
Brian Curtin0151b8e2010-09-24 13:43:43 +00001800# The introduction of this TestCase caused at least two different errors on
1801# *nix buildbots. Temporarily skip this to let the buildbots move along.
1802@unittest.skip("Skip due to platform/environment differences on *NIX buildbots")
Brian Curtine8e4b3b2010-09-23 20:04:14 +00001803@unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin")
1804class LoginTests(unittest.TestCase):
1805 def test_getlogin(self):
1806 user_name = os.getlogin()
1807 self.assertNotEqual(len(user_name), 0)
1808
1809
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001810@unittest.skipUnless(hasattr(os, 'getpriority') and hasattr(os, 'setpriority'),
1811 "needs os.getpriority and os.setpriority")
1812class ProgramPriorityTests(unittest.TestCase):
1813 """Tests for os.getpriority() and os.setpriority()."""
1814
1815 def test_set_get_priority(self):
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001816
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001817 base = os.getpriority(os.PRIO_PROCESS, os.getpid())
1818 os.setpriority(os.PRIO_PROCESS, os.getpid(), base + 1)
1819 try:
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001820 new_prio = os.getpriority(os.PRIO_PROCESS, os.getpid())
1821 if base >= 19 and new_prio <= 19:
1822 raise unittest.SkipTest(
1823 "unable to reliably test setpriority at current nice level of %s" % base)
1824 else:
1825 self.assertEqual(new_prio, base + 1)
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001826 finally:
1827 try:
1828 os.setpriority(os.PRIO_PROCESS, os.getpid(), base)
1829 except OSError as err:
Antoine Pitrou692f0382011-02-26 00:22:25 +00001830 if err.errno != errno.EACCES:
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001831 raise
1832
1833
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001834if threading is not None:
1835 class SendfileTestServer(asyncore.dispatcher, threading.Thread):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001836
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001837 class Handler(asynchat.async_chat):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001838
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001839 def __init__(self, conn):
1840 asynchat.async_chat.__init__(self, conn)
1841 self.in_buffer = []
1842 self.closed = False
1843 self.push(b"220 ready\r\n")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001844
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001845 def handle_read(self):
1846 data = self.recv(4096)
1847 self.in_buffer.append(data)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001848
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001849 def get_data(self):
1850 return b''.join(self.in_buffer)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001851
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001852 def handle_close(self):
1853 self.close()
1854 self.closed = True
1855
1856 def handle_error(self):
1857 raise
1858
1859 def __init__(self, address):
1860 threading.Thread.__init__(self)
1861 asyncore.dispatcher.__init__(self)
1862 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
1863 self.bind(address)
1864 self.listen(5)
1865 self.host, self.port = self.socket.getsockname()[:2]
1866 self.handler_instance = None
1867 self._active = False
1868 self._active_lock = threading.Lock()
1869
1870 # --- public API
1871
1872 @property
1873 def running(self):
1874 return self._active
1875
1876 def start(self):
1877 assert not self.running
1878 self.__flag = threading.Event()
1879 threading.Thread.start(self)
1880 self.__flag.wait()
1881
1882 def stop(self):
1883 assert self.running
1884 self._active = False
1885 self.join()
1886
1887 def wait(self):
1888 # wait for handler connection to be closed, then stop the server
1889 while not getattr(self.handler_instance, "closed", False):
1890 time.sleep(0.001)
1891 self.stop()
1892
1893 # --- internals
1894
1895 def run(self):
1896 self._active = True
1897 self.__flag.set()
1898 while self._active and asyncore.socket_map:
1899 self._active_lock.acquire()
1900 asyncore.loop(timeout=0.001, count=1)
1901 self._active_lock.release()
1902 asyncore.close_all()
1903
1904 def handle_accept(self):
1905 conn, addr = self.accept()
1906 self.handler_instance = self.Handler(conn)
1907
1908 def handle_connect(self):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001909 self.close()
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001910 handle_read = handle_connect
1911
1912 def writable(self):
1913 return 0
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001914
1915 def handle_error(self):
1916 raise
1917
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001918
Giampaolo Rodolà46134642011-02-25 20:01:05 +00001919@unittest.skipUnless(threading is not None, "test needs threading module")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001920@unittest.skipUnless(hasattr(os, 'sendfile'), "test needs os.sendfile()")
1921class TestSendfile(unittest.TestCase):
1922
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001923 DATA = b"12345abcde" * 16 * 1024 # 160 KB
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001924 SUPPORT_HEADERS_TRAILERS = not sys.platform.startswith("linux") and \
Giampaolo Rodolà4bc68572011-02-25 21:46:01 +00001925 not sys.platform.startswith("solaris") and \
1926 not sys.platform.startswith("sunos")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001927
1928 @classmethod
1929 def setUpClass(cls):
1930 with open(support.TESTFN, "wb") as f:
1931 f.write(cls.DATA)
1932
1933 @classmethod
1934 def tearDownClass(cls):
1935 support.unlink(support.TESTFN)
1936
1937 def setUp(self):
1938 self.server = SendfileTestServer((support.HOST, 0))
1939 self.server.start()
1940 self.client = socket.socket()
1941 self.client.connect((self.server.host, self.server.port))
1942 self.client.settimeout(1)
1943 # synchronize by waiting for "220 ready" response
1944 self.client.recv(1024)
1945 self.sockno = self.client.fileno()
1946 self.file = open(support.TESTFN, 'rb')
1947 self.fileno = self.file.fileno()
1948
1949 def tearDown(self):
1950 self.file.close()
1951 self.client.close()
1952 if self.server.running:
1953 self.server.stop()
1954
1955 def sendfile_wrapper(self, sock, file, offset, nbytes, headers=[], trailers=[]):
1956 """A higher level wrapper representing how an application is
1957 supposed to use sendfile().
1958 """
1959 while 1:
1960 try:
1961 if self.SUPPORT_HEADERS_TRAILERS:
1962 return os.sendfile(sock, file, offset, nbytes, headers,
1963 trailers)
1964 else:
1965 return os.sendfile(sock, file, offset, nbytes)
1966 except OSError as err:
1967 if err.errno == errno.ECONNRESET:
1968 # disconnected
1969 raise
1970 elif err.errno in (errno.EAGAIN, errno.EBUSY):
1971 # we have to retry send data
1972 continue
1973 else:
1974 raise
1975
1976 def test_send_whole_file(self):
1977 # normal send
1978 total_sent = 0
1979 offset = 0
1980 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001981 while total_sent < len(self.DATA):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001982 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
1983 if sent == 0:
1984 break
1985 offset += sent
1986 total_sent += sent
1987 self.assertTrue(sent <= nbytes)
1988 self.assertEqual(offset, total_sent)
1989
1990 self.assertEqual(total_sent, len(self.DATA))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001991 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001992 self.client.close()
1993 self.server.wait()
1994 data = self.server.handler_instance.get_data()
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001995 self.assertEqual(len(data), len(self.DATA))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001996 self.assertEqual(data, self.DATA)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001997
1998 def test_send_at_certain_offset(self):
1999 # start sending a file at a certain offset
2000 total_sent = 0
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00002001 offset = len(self.DATA) // 2
2002 must_send = len(self.DATA) - offset
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002003 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00002004 while total_sent < must_send:
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002005 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
2006 if sent == 0:
2007 break
2008 offset += sent
2009 total_sent += sent
2010 self.assertTrue(sent <= nbytes)
2011
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00002012 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002013 self.client.close()
2014 self.server.wait()
2015 data = self.server.handler_instance.get_data()
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00002016 expected = self.DATA[len(self.DATA) // 2:]
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002017 self.assertEqual(total_sent, len(expected))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00002018 self.assertEqual(len(data), len(expected))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00002019 self.assertEqual(data, expected)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002020
2021 def test_offset_overflow(self):
2022 # specify an offset > file size
2023 offset = len(self.DATA) + 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00002024 try:
2025 sent = os.sendfile(self.sockno, self.fileno, offset, 4096)
2026 except OSError as e:
2027 # Solaris can raise EINVAL if offset >= file length, ignore.
2028 if e.errno != errno.EINVAL:
2029 raise
2030 else:
2031 self.assertEqual(sent, 0)
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00002032 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002033 self.client.close()
2034 self.server.wait()
2035 data = self.server.handler_instance.get_data()
2036 self.assertEqual(data, b'')
2037
2038 def test_invalid_offset(self):
2039 with self.assertRaises(OSError) as cm:
2040 os.sendfile(self.sockno, self.fileno, -1, 4096)
2041 self.assertEqual(cm.exception.errno, errno.EINVAL)
2042
2043 # --- headers / trailers tests
2044
2045 if SUPPORT_HEADERS_TRAILERS:
2046
2047 def test_headers(self):
2048 total_sent = 0
2049 sent = os.sendfile(self.sockno, self.fileno, 0, 4096,
2050 headers=[b"x" * 512])
2051 total_sent += sent
2052 offset = 4096
2053 nbytes = 4096
2054 while 1:
2055 sent = self.sendfile_wrapper(self.sockno, self.fileno,
2056 offset, nbytes)
2057 if sent == 0:
2058 break
2059 total_sent += sent
2060 offset += sent
2061
2062 expected_data = b"x" * 512 + self.DATA
2063 self.assertEqual(total_sent, len(expected_data))
2064 self.client.close()
2065 self.server.wait()
2066 data = self.server.handler_instance.get_data()
2067 self.assertEqual(hash(data), hash(expected_data))
2068
2069 def test_trailers(self):
2070 TESTFN2 = support.TESTFN + "2"
Victor Stinner5e4d6392013-08-15 11:57:02 +02002071 file_data = b"abcdef"
Brett Cannonb6376802011-03-15 17:38:22 -04002072 with open(TESTFN2, 'wb') as f:
Victor Stinner5e4d6392013-08-15 11:57:02 +02002073 f.write(file_data)
Brett Cannonb6376802011-03-15 17:38:22 -04002074 with open(TESTFN2, 'rb')as f:
2075 self.addCleanup(os.remove, TESTFN2)
Victor Stinner5e4d6392013-08-15 11:57:02 +02002076 os.sendfile(self.sockno, f.fileno(), 0, len(file_data),
2077 trailers=[b"1234"])
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002078 self.client.close()
2079 self.server.wait()
2080 data = self.server.handler_instance.get_data()
Victor Stinner5e4d6392013-08-15 11:57:02 +02002081 self.assertEqual(data, b"abcdef1234")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002082
2083 if hasattr(os, "SF_NODISKIO"):
2084 def test_flags(self):
2085 try:
2086 os.sendfile(self.sockno, self.fileno, 0, 4096,
2087 flags=os.SF_NODISKIO)
2088 except OSError as err:
2089 if err.errno not in (errno.EBUSY, errno.EAGAIN):
2090 raise
2091
2092
Larry Hastings9cf065c2012-06-22 16:30:09 -07002093def supports_extended_attributes():
2094 if not hasattr(os, "setxattr"):
2095 return False
2096 try:
2097 with open(support.TESTFN, "wb") as fp:
2098 try:
2099 os.setxattr(fp.fileno(), b"user.test", b"")
2100 except OSError:
2101 return False
2102 finally:
2103 support.unlink(support.TESTFN)
2104 # Kernels < 2.6.39 don't respect setxattr flags.
2105 kernel_version = platform.release()
2106 m = re.match("2.6.(\d{1,2})", kernel_version)
2107 return m is None or int(m.group(1)) >= 39
2108
2109
2110@unittest.skipUnless(supports_extended_attributes(),
2111 "no non-broken extended attribute support")
Benjamin Peterson799bd802011-08-31 22:15:17 -04002112class ExtendedAttributeTests(unittest.TestCase):
2113
2114 def tearDown(self):
2115 support.unlink(support.TESTFN)
2116
Larry Hastings9cf065c2012-06-22 16:30:09 -07002117 def _check_xattrs_str(self, s, getxattr, setxattr, removexattr, listxattr, **kwargs):
Benjamin Peterson799bd802011-08-31 22:15:17 -04002118 fn = support.TESTFN
2119 open(fn, "wb").close()
2120 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002121 getxattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002122 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002123 init_xattr = listxattr(fn)
2124 self.assertIsInstance(init_xattr, list)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002125 setxattr(fn, s("user.test"), b"", **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002126 xattr = set(init_xattr)
2127 xattr.add("user.test")
2128 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002129 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"")
2130 setxattr(fn, s("user.test"), b"hello", os.XATTR_REPLACE, **kwargs)
2131 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"hello")
Benjamin Peterson799bd802011-08-31 22:15:17 -04002132 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002133 setxattr(fn, s("user.test"), b"bye", os.XATTR_CREATE, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002134 self.assertEqual(cm.exception.errno, errno.EEXIST)
2135 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002136 setxattr(fn, s("user.test2"), b"bye", os.XATTR_REPLACE, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002137 self.assertEqual(cm.exception.errno, errno.ENODATA)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002138 setxattr(fn, s("user.test2"), b"foo", os.XATTR_CREATE, **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002139 xattr.add("user.test2")
2140 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002141 removexattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002142 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002143 getxattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002144 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002145 xattr.remove("user.test")
2146 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002147 self.assertEqual(getxattr(fn, s("user.test2"), **kwargs), b"foo")
2148 setxattr(fn, s("user.test"), b"a"*1024, **kwargs)
2149 self.assertEqual(getxattr(fn, s("user.test"), **kwargs), b"a"*1024)
2150 removexattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002151 many = sorted("user.test{}".format(i) for i in range(100))
2152 for thing in many:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002153 setxattr(fn, thing, b"x", **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002154 self.assertEqual(set(listxattr(fn)), set(init_xattr) | set(many))
Benjamin Peterson799bd802011-08-31 22:15:17 -04002155
Larry Hastings9cf065c2012-06-22 16:30:09 -07002156 def _check_xattrs(self, *args, **kwargs):
Benjamin Peterson799bd802011-08-31 22:15:17 -04002157 def make_bytes(s):
2158 return bytes(s, "ascii")
Larry Hastings9cf065c2012-06-22 16:30:09 -07002159 self._check_xattrs_str(str, *args, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002160 support.unlink(support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002161 self._check_xattrs_str(make_bytes, *args, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002162
2163 def test_simple(self):
2164 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
2165 os.listxattr)
2166
2167 def test_lpath(self):
Larry Hastings9cf065c2012-06-22 16:30:09 -07002168 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
2169 os.listxattr, follow_symlinks=False)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002170
2171 def test_fds(self):
2172 def getxattr(path, *args):
2173 with open(path, "rb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002174 return os.getxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002175 def setxattr(path, *args):
2176 with open(path, "wb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002177 os.setxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002178 def removexattr(path, *args):
2179 with open(path, "wb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002180 os.removexattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002181 def listxattr(path, *args):
2182 with open(path, "rb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002183 return os.listxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002184 self._check_xattrs(getxattr, setxattr, removexattr, listxattr)
2185
2186
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002187@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
2188class Win32DeprecatedBytesAPI(unittest.TestCase):
2189 def test_deprecated(self):
2190 import nt
2191 filename = os.fsencode(support.TESTFN)
2192 with warnings.catch_warnings():
2193 warnings.simplefilter("error", DeprecationWarning)
2194 for func, *args in (
2195 (nt._getfullpathname, filename),
2196 (nt._isdir, filename),
2197 (os.access, filename, os.R_OK),
2198 (os.chdir, filename),
2199 (os.chmod, filename, 0o777),
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01002200 (os.getcwdb,),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002201 (os.link, filename, filename),
2202 (os.listdir, filename),
2203 (os.lstat, filename),
2204 (os.mkdir, filename),
2205 (os.open, filename, os.O_RDONLY),
2206 (os.rename, filename, filename),
2207 (os.rmdir, filename),
2208 (os.startfile, filename),
2209 (os.stat, filename),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002210 (os.unlink, filename),
2211 (os.utime, filename),
2212 ):
2213 self.assertRaises(DeprecationWarning, func, *args)
2214
Victor Stinner28216442011-11-16 00:34:44 +01002215 @support.skip_unless_symlink
2216 def test_symlink(self):
2217 filename = os.fsencode(support.TESTFN)
2218 with warnings.catch_warnings():
2219 warnings.simplefilter("error", DeprecationWarning)
2220 self.assertRaises(DeprecationWarning,
2221 os.symlink, filename, filename)
2222
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002223
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002224@unittest.skipUnless(hasattr(os, 'get_terminal_size'), "requires os.get_terminal_size")
2225class TermsizeTests(unittest.TestCase):
2226 def test_does_not_crash(self):
2227 """Check if get_terminal_size() returns a meaningful value.
2228
2229 There's no easy portable way to actually check the size of the
2230 terminal, so let's check if it returns something sensible instead.
2231 """
2232 try:
2233 size = os.get_terminal_size()
2234 except OSError as e:
Antoine Pitrou81a1fa52012-02-09 00:11:00 +01002235 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002236 # Under win32 a generic OSError can be thrown if the
2237 # handle cannot be retrieved
2238 self.skipTest("failed to query terminal size")
2239 raise
2240
Antoine Pitroucfade362012-02-08 23:48:59 +01002241 self.assertGreaterEqual(size.columns, 0)
2242 self.assertGreaterEqual(size.lines, 0)
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002243
2244 def test_stty_match(self):
2245 """Check if stty returns the same results
2246
2247 stty actually tests stdin, so get_terminal_size is invoked on
2248 stdin explicitly. If stty succeeded, then get_terminal_size()
2249 should work too.
2250 """
2251 try:
2252 size = subprocess.check_output(['stty', 'size']).decode().split()
2253 except (FileNotFoundError, subprocess.CalledProcessError):
2254 self.skipTest("stty invocation failed")
2255 expected = (int(size[1]), int(size[0])) # reversed order
2256
Antoine Pitrou81a1fa52012-02-09 00:11:00 +01002257 try:
2258 actual = os.get_terminal_size(sys.__stdin__.fileno())
2259 except OSError as e:
2260 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
2261 # Under win32 a generic OSError can be thrown if the
2262 # handle cannot be retrieved
2263 self.skipTest("failed to query terminal size")
2264 raise
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002265 self.assertEqual(expected, actual)
2266
2267
Victor Stinner292c8352012-10-30 02:17:38 +01002268class OSErrorTests(unittest.TestCase):
2269 def setUp(self):
2270 class Str(str):
2271 pass
2272
Victor Stinnerafe17062012-10-31 22:47:43 +01002273 self.bytes_filenames = []
2274 self.unicode_filenames = []
Victor Stinner292c8352012-10-30 02:17:38 +01002275 if support.TESTFN_UNENCODABLE is not None:
2276 decoded = support.TESTFN_UNENCODABLE
2277 else:
2278 decoded = support.TESTFN
Victor Stinnerafe17062012-10-31 22:47:43 +01002279 self.unicode_filenames.append(decoded)
2280 self.unicode_filenames.append(Str(decoded))
Victor Stinner292c8352012-10-30 02:17:38 +01002281 if support.TESTFN_UNDECODABLE is not None:
2282 encoded = support.TESTFN_UNDECODABLE
2283 else:
2284 encoded = os.fsencode(support.TESTFN)
Victor Stinnerafe17062012-10-31 22:47:43 +01002285 self.bytes_filenames.append(encoded)
2286 self.bytes_filenames.append(memoryview(encoded))
2287
2288 self.filenames = self.bytes_filenames + self.unicode_filenames
Victor Stinner292c8352012-10-30 02:17:38 +01002289
2290 def test_oserror_filename(self):
2291 funcs = [
Victor Stinnerafe17062012-10-31 22:47:43 +01002292 (self.filenames, os.chdir,),
2293 (self.filenames, os.chmod, 0o777),
Victor Stinnerafe17062012-10-31 22:47:43 +01002294 (self.filenames, os.lstat,),
2295 (self.filenames, os.open, os.O_RDONLY),
2296 (self.filenames, os.rmdir,),
2297 (self.filenames, os.stat,),
2298 (self.filenames, os.unlink,),
Victor Stinner292c8352012-10-30 02:17:38 +01002299 ]
2300 if sys.platform == "win32":
2301 funcs.extend((
Victor Stinnerafe17062012-10-31 22:47:43 +01002302 (self.bytes_filenames, os.rename, b"dst"),
2303 (self.bytes_filenames, os.replace, b"dst"),
2304 (self.unicode_filenames, os.rename, "dst"),
2305 (self.unicode_filenames, os.replace, "dst"),
Victor Stinner64e039a2012-11-07 00:10:14 +01002306 # Issue #16414: Don't test undecodable names with listdir()
2307 # because of a Windows bug.
2308 #
2309 # With the ANSI code page 932, os.listdir(b'\xe7') return an
2310 # empty list (instead of failing), whereas os.listdir(b'\xff')
2311 # raises a FileNotFoundError. It looks like a Windows bug:
2312 # b'\xe7' directory does not exist, FindFirstFileA(b'\xe7')
2313 # fails with ERROR_FILE_NOT_FOUND (2), instead of
2314 # ERROR_PATH_NOT_FOUND (3).
2315 (self.unicode_filenames, os.listdir,),
Victor Stinner292c8352012-10-30 02:17:38 +01002316 ))
Victor Stinnerafe17062012-10-31 22:47:43 +01002317 else:
2318 funcs.extend((
Victor Stinner64e039a2012-11-07 00:10:14 +01002319 (self.filenames, os.listdir,),
Victor Stinnerafe17062012-10-31 22:47:43 +01002320 (self.filenames, os.rename, "dst"),
2321 (self.filenames, os.replace, "dst"),
2322 ))
2323 if hasattr(os, "chown"):
2324 funcs.append((self.filenames, os.chown, 0, 0))
2325 if hasattr(os, "lchown"):
2326 funcs.append((self.filenames, os.lchown, 0, 0))
2327 if hasattr(os, "truncate"):
2328 funcs.append((self.filenames, os.truncate, 0))
Victor Stinner292c8352012-10-30 02:17:38 +01002329 if hasattr(os, "chflags"):
Victor Stinneree36c242012-11-13 09:31:51 +01002330 funcs.append((self.filenames, os.chflags, 0))
2331 if hasattr(os, "lchflags"):
2332 funcs.append((self.filenames, os.lchflags, 0))
Victor Stinner292c8352012-10-30 02:17:38 +01002333 if hasattr(os, "chroot"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002334 funcs.append((self.filenames, os.chroot,))
Victor Stinner292c8352012-10-30 02:17:38 +01002335 if hasattr(os, "link"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002336 if sys.platform == "win32":
2337 funcs.append((self.bytes_filenames, os.link, b"dst"))
2338 funcs.append((self.unicode_filenames, os.link, "dst"))
2339 else:
2340 funcs.append((self.filenames, os.link, "dst"))
Victor Stinner292c8352012-10-30 02:17:38 +01002341 if hasattr(os, "listxattr"):
2342 funcs.extend((
Victor Stinnerafe17062012-10-31 22:47:43 +01002343 (self.filenames, os.listxattr,),
2344 (self.filenames, os.getxattr, "user.test"),
2345 (self.filenames, os.setxattr, "user.test", b'user'),
2346 (self.filenames, os.removexattr, "user.test"),
Victor Stinner292c8352012-10-30 02:17:38 +01002347 ))
2348 if hasattr(os, "lchmod"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002349 funcs.append((self.filenames, os.lchmod, 0o777))
Victor Stinner292c8352012-10-30 02:17:38 +01002350 if hasattr(os, "readlink"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002351 if sys.platform == "win32":
2352 funcs.append((self.unicode_filenames, os.readlink,))
2353 else:
2354 funcs.append((self.filenames, os.readlink,))
Victor Stinner292c8352012-10-30 02:17:38 +01002355
Victor Stinnerafe17062012-10-31 22:47:43 +01002356 for filenames, func, *func_args in funcs:
2357 for name in filenames:
Victor Stinner292c8352012-10-30 02:17:38 +01002358 try:
2359 func(name, *func_args)
Victor Stinnerbd54f0e2012-10-31 01:12:55 +01002360 except OSError as err:
Victor Stinner292c8352012-10-30 02:17:38 +01002361 self.assertIs(err.filename, name)
2362 else:
2363 self.fail("No exception thrown by {}".format(func))
2364
Charles-Francois Natali44feda32013-05-20 14:40:46 +02002365class CPUCountTests(unittest.TestCase):
2366 def test_cpu_count(self):
2367 cpus = os.cpu_count()
2368 if cpus is not None:
2369 self.assertIsInstance(cpus, int)
2370 self.assertGreater(cpus, 0)
2371 else:
2372 self.skipTest("Could not determine the number of CPUs")
2373
Victor Stinnerdaf45552013-08-28 00:53:59 +02002374
2375class FDInheritanceTests(unittest.TestCase):
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002376 def test_get_set_inheritable(self):
Victor Stinnerdaf45552013-08-28 00:53:59 +02002377 fd = os.open(__file__, os.O_RDONLY)
2378 self.addCleanup(os.close, fd)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002379 self.assertEqual(os.get_inheritable(fd), False)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002380
Victor Stinnerdaf45552013-08-28 00:53:59 +02002381 os.set_inheritable(fd, True)
2382 self.assertEqual(os.get_inheritable(fd), True)
2383
Victor Stinner4f7a36f2013-09-08 14:14:38 +02002384 @unittest.skipIf(fcntl is None, "need fcntl")
2385 def test_get_inheritable_cloexec(self):
2386 fd = os.open(__file__, os.O_RDONLY)
2387 self.addCleanup(os.close, fd)
2388 self.assertEqual(os.get_inheritable(fd), False)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002389
Victor Stinner4f7a36f2013-09-08 14:14:38 +02002390 # clear FD_CLOEXEC flag
2391 flags = fcntl.fcntl(fd, fcntl.F_GETFD)
2392 flags &= ~fcntl.FD_CLOEXEC
2393 fcntl.fcntl(fd, fcntl.F_SETFD, flags)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002394
Victor Stinner4f7a36f2013-09-08 14:14:38 +02002395 self.assertEqual(os.get_inheritable(fd), True)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002396
Victor Stinner4f7a36f2013-09-08 14:14:38 +02002397 @unittest.skipIf(fcntl is None, "need fcntl")
2398 def test_set_inheritable_cloexec(self):
2399 fd = os.open(__file__, os.O_RDONLY)
2400 self.addCleanup(os.close, fd)
2401 self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
2402 fcntl.FD_CLOEXEC)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002403
Victor Stinner4f7a36f2013-09-08 14:14:38 +02002404 os.set_inheritable(fd, True)
2405 self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
2406 0)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002407
Victor Stinnerdaf45552013-08-28 00:53:59 +02002408 def test_open(self):
2409 fd = os.open(__file__, os.O_RDONLY)
2410 self.addCleanup(os.close, fd)
2411 self.assertEqual(os.get_inheritable(fd), False)
2412
2413 @unittest.skipUnless(hasattr(os, 'pipe'), "need os.pipe()")
2414 def test_pipe(self):
2415 rfd, wfd = os.pipe()
2416 self.addCleanup(os.close, rfd)
2417 self.addCleanup(os.close, wfd)
2418 self.assertEqual(os.get_inheritable(rfd), False)
2419 self.assertEqual(os.get_inheritable(wfd), False)
2420
2421 def test_dup(self):
2422 fd1 = os.open(__file__, os.O_RDONLY)
2423 self.addCleanup(os.close, fd1)
2424
2425 fd2 = os.dup(fd1)
2426 self.addCleanup(os.close, fd2)
2427 self.assertEqual(os.get_inheritable(fd2), False)
2428
2429 @unittest.skipUnless(hasattr(os, 'dup2'), "need os.dup2()")
2430 def test_dup2(self):
2431 fd = os.open(__file__, os.O_RDONLY)
2432 self.addCleanup(os.close, fd)
2433
2434 # inheritable by default
2435 fd2 = os.open(__file__, os.O_RDONLY)
2436 try:
2437 os.dup2(fd, fd2)
2438 self.assertEqual(os.get_inheritable(fd2), True)
2439 finally:
2440 os.close(fd2)
2441
2442 # force non-inheritable
2443 fd3 = os.open(__file__, os.O_RDONLY)
2444 try:
2445 os.dup2(fd, fd3, inheritable=False)
2446 self.assertEqual(os.get_inheritable(fd3), False)
2447 finally:
2448 os.close(fd3)
2449
2450 @unittest.skipUnless(hasattr(os, 'openpty'), "need os.openpty()")
2451 def test_openpty(self):
2452 master_fd, slave_fd = os.openpty()
2453 self.addCleanup(os.close, master_fd)
2454 self.addCleanup(os.close, slave_fd)
2455 self.assertEqual(os.get_inheritable(master_fd), False)
2456 self.assertEqual(os.get_inheritable(slave_fd), False)
2457
2458
Antoine Pitrouf26ad712011-07-15 23:00:56 +02002459@support.reap_threads
Fred Drake2e2be372001-09-20 21:33:42 +00002460def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002461 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002462 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002463 StatAttributeTests,
2464 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00002465 WalkTests,
Charles-François Natali7372b062012-02-05 15:15:38 +01002466 FwalkTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00002467 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +00002468 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002469 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +00002470 ExecTests,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00002471 Win32ErrorTests,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002472 TestInvalidFD,
Martin v. Löwis011e8422009-05-05 04:43:17 +00002473 PosixUidGidTests,
Brian Curtineb24d742010-04-12 17:16:38 +00002474 Pep383Tests,
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00002475 Win32KillTests,
Tim Golden781bbeb2013-10-25 20:24:06 +01002476 Win32ListdirTests,
Brian Curtind40e6f72010-07-08 21:39:08 +00002477 Win32SymlinkTests,
Jason R. Coombs3a092862013-05-27 23:21:28 -04002478 NonLocalSymlinkTests,
Victor Stinnere8d51452010-08-19 01:05:19 +00002479 FSEncodingTests,
Brett Cannonefb00c02012-02-29 18:31:31 -05002480 DeviceEncodingTests,
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00002481 PidTests,
Brian Curtine8e4b3b2010-09-23 20:04:14 +00002482 LoginTests,
Brian Curtin1b9df392010-11-24 20:24:31 +00002483 LinkTests,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002484 TestSendfile,
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00002485 ProgramPriorityTests,
Benjamin Peterson799bd802011-08-31 22:15:17 -04002486 ExtendedAttributeTests,
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002487 Win32DeprecatedBytesAPI,
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002488 TermsizeTests,
Victor Stinner292c8352012-10-30 02:17:38 +01002489 OSErrorTests,
Andrew Svetlov405faed2012-12-25 12:18:09 +02002490 RemoveDirsTests,
Charles-Francois Natali44feda32013-05-20 14:40:46 +02002491 CPUCountTests,
Victor Stinnerdaf45552013-08-28 00:53:59 +02002492 FDInheritanceTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002493 )
Fred Drake2e2be372001-09-20 21:33:42 +00002494
2495if __name__ == "__main__":
2496 test_main()