blob: 0d49b99341cc34edec34413a70fa99cec5f41b5f [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
Victor Stinnere12e7aa2015-06-12 21:58:00 +02005import asynchat
6import asyncore
7import codecs
Victor Stinnerc2d095f2010-05-17 00:14:53 +00008import contextlib
Victor Stinnere12e7aa2015-06-12 21:58:00 +02009import decimal
10import errno
11import fractions
12import itertools
13import locale
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +000014import mmap
Victor Stinnere12e7aa2015-06-12 21:58:00 +020015import os
16import pickle
Benjamin Peterson799bd802011-08-31 22:15:17 -040017import platform
18import re
Victor Stinnere12e7aa2015-06-12 21:58:00 +020019import shutil
20import signal
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000021import socket
Charles-François Natali7372b062012-02-05 15:15:38 +010022import stat
Victor Stinnere12e7aa2015-06-12 21:58:00 +020023import subprocess
24import sys
Victor Stinnerfe02e392014-12-21 01:16:38 +010025import sysconfig
Victor Stinnere12e7aa2015-06-12 21:58:00 +020026import time
27import unittest
28import uuid
29import warnings
30from test import support
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000031try:
32 import threading
33except ImportError:
34 threading = None
Antoine Pitrouec34ab52013-08-16 20:44:38 +020035try:
36 import resource
37except ImportError:
38 resource = None
Victor Stinner7ba6b0f2013-09-08 11:47:54 +020039try:
40 import fcntl
41except ImportError:
42 fcntl = None
Antoine Pitrouec34ab52013-08-16 20:44:38 +020043
Georg Brandl2daf6ae2012-02-20 19:54:16 +010044from test.script_helper import assert_python_ok
Fred Drake38c2ef02001-07-17 20:52:51 +000045
Mark Dickinson7cf03892010-04-16 13:45:35 +000046# Detect whether we're on a Linux system that uses the (now outdated
47# and unmaintained) linuxthreads threading library. There's an issue
48# when combining linuxthreads with a failed execv call: see
49# http://bugs.python.org/issue4970.
Victor Stinnerd5c355c2011-04-30 14:53:09 +020050if hasattr(sys, 'thread_info') and sys.thread_info.version:
51 USING_LINUXTHREADS = sys.thread_info.version.startswith("linuxthreads")
52else:
53 USING_LINUXTHREADS = False
Brian Curtineb24d742010-04-12 17:16:38 +000054
Stefan Krahebee49a2013-01-17 15:31:00 +010055# Issue #14110: Some tests fail on FreeBSD if the user is in the wheel group.
56HAVE_WHEEL_GROUP = sys.platform.startswith('freebsd') and os.getgid() == 0
57
Thomas Wouters0e3f5912006-08-11 14:57:12 +000058# Tests creating TESTFN
59class FileTests(unittest.TestCase):
60 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000061 if os.path.exists(support.TESTFN):
62 os.unlink(support.TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000063 tearDown = setUp
64
65 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000066 f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000067 os.close(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000068 self.assertTrue(os.access(support.TESTFN, os.W_OK))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000069
Christian Heimesfdab48e2008-01-20 09:06:41 +000070 def test_closerange(self):
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000071 first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
72 # We must allocate two consecutive file descriptors, otherwise
73 # it will mess up other file descriptors (perhaps even the three
74 # standard ones).
75 second = os.dup(first)
76 try:
77 retries = 0
78 while second != first + 1:
79 os.close(first)
80 retries += 1
81 if retries > 10:
82 # XXX test skipped
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000083 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000084 first, second = second, os.dup(second)
85 finally:
86 os.close(second)
Christian Heimesfdab48e2008-01-20 09:06:41 +000087 # close a fd that is open, and one that isn't
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000088 os.closerange(first, first + 2)
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000089 self.assertRaises(OSError, os.write, first, b"a")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000090
Benjamin Peterson1cc6df92010-06-30 17:39:45 +000091 @support.cpython_only
Hirokazu Yamamoto4c19e6e2008-09-08 23:41:21 +000092 def test_rename(self):
93 path = support.TESTFN
94 old = sys.getrefcount(path)
95 self.assertRaises(TypeError, os.rename, path, 0)
96 new = sys.getrefcount(path)
97 self.assertEqual(old, new)
98
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000099 def test_read(self):
100 with open(support.TESTFN, "w+b") as fobj:
101 fobj.write(b"spam")
102 fobj.flush()
103 fd = fobj.fileno()
104 os.lseek(fd, 0, 0)
105 s = os.read(fd, 4)
106 self.assertEqual(type(s), bytes)
107 self.assertEqual(s, b"spam")
108
109 def test_write(self):
110 # os.write() accepts bytes- and buffer-like objects but not strings
111 fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY)
112 self.assertRaises(TypeError, os.write, fd, "beans")
113 os.write(fd, b"bacon\n")
114 os.write(fd, bytearray(b"eggs\n"))
115 os.write(fd, memoryview(b"spam\n"))
116 os.close(fd)
117 with open(support.TESTFN, "rb") as fobj:
Antoine Pitroud62269f2008-09-15 23:54:52 +0000118 self.assertEqual(fobj.read().splitlines(),
119 [b"bacon", b"eggs", b"spam"])
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000120
Victor Stinnere0daff12011-03-20 23:36:35 +0100121 def write_windows_console(self, *args):
122 retcode = subprocess.call(args,
123 # use a new console to not flood the test output
124 creationflags=subprocess.CREATE_NEW_CONSOLE,
125 # use a shell to hide the console window (SW_HIDE)
126 shell=True)
127 self.assertEqual(retcode, 0)
128
129 @unittest.skipUnless(sys.platform == 'win32',
130 'test specific to the Windows console')
131 def test_write_windows_console(self):
132 # Issue #11395: the Windows console returns an error (12: not enough
133 # space error) on writing into stdout if stdout mode is binary and the
134 # length is greater than 66,000 bytes (or less, depending on heap
135 # usage).
136 code = "print('x' * 100000)"
137 self.write_windows_console(sys.executable, "-c", code)
138 self.write_windows_console(sys.executable, "-u", "-c", code)
139
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000140 def fdopen_helper(self, *args):
141 fd = os.open(support.TESTFN, os.O_RDONLY)
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200142 f = os.fdopen(fd, *args)
143 f.close()
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000144
145 def test_fdopen(self):
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200146 fd = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
147 os.close(fd)
148
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000149 self.fdopen_helper()
150 self.fdopen_helper('r')
151 self.fdopen_helper('r', 100)
152
Antoine Pitrouf3b2d882012-01-30 22:08:52 +0100153 def test_replace(self):
154 TESTFN2 = support.TESTFN + ".2"
155 with open(support.TESTFN, 'w') as f:
156 f.write("1")
157 with open(TESTFN2, 'w') as f:
158 f.write("2")
159 self.addCleanup(os.unlink, TESTFN2)
160 os.replace(support.TESTFN, TESTFN2)
161 self.assertRaises(FileNotFoundError, os.stat, support.TESTFN)
162 with open(TESTFN2, 'r') as f:
163 self.assertEqual(f.read(), "1")
164
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200165
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000166# Test attributes on return values from os.*stat* family.
167class StatAttributeTests(unittest.TestCase):
168 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000169 os.mkdir(support.TESTFN)
170 self.fname = os.path.join(support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000171 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +0000172 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000173 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000174
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000175 def tearDown(self):
176 os.unlink(self.fname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000177 os.rmdir(support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000178
Serhiy Storchaka43767632013-11-03 21:31:38 +0200179 @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
Antoine Pitrou38425292010-09-21 18:19:07 +0000180 def check_stat_attributes(self, fname):
Antoine Pitrou38425292010-09-21 18:19:07 +0000181 result = os.stat(fname)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000182
183 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000184 self.assertEqual(result[stat.ST_SIZE], 3)
185 self.assertEqual(result.st_size, 3)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000186
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000187 # Make sure all the attributes are there
188 members = dir(result)
189 for name in dir(stat):
190 if name[:3] == 'ST_':
191 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000192 if name.endswith("TIME"):
193 def trunc(x): return int(x)
194 else:
195 def trunc(x): return x
Ezio Melottib3aedd42010-11-20 19:04:17 +0000196 self.assertEqual(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000197 result[getattr(stat, name)])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000198 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000199
Larry Hastings6fe20b32012-04-19 15:07:49 -0700200 # Make sure that the st_?time and st_?time_ns fields roughly agree
Larry Hastings76ad59b2012-05-03 00:30:07 -0700201 # (they should always agree up to around tens-of-microseconds)
Larry Hastings6fe20b32012-04-19 15:07:49 -0700202 for name in 'st_atime st_mtime st_ctime'.split():
203 floaty = int(getattr(result, name) * 100000)
204 nanosecondy = getattr(result, name + "_ns") // 10000
Larry Hastings76ad59b2012-05-03 00:30:07 -0700205 self.assertAlmostEqual(floaty, nanosecondy, delta=2)
Larry Hastings6fe20b32012-04-19 15:07:49 -0700206
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000207 try:
208 result[200]
Andrew Svetlov737fb892012-12-18 21:14:22 +0200209 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000210 except IndexError:
211 pass
212
213 # Make sure that assignment fails
214 try:
215 result.st_mode = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200216 self.fail("No exception raised")
Collin Winter42dae6a2007-03-28 21:44:53 +0000217 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000218 pass
219
220 try:
221 result.st_rdev = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200222 self.fail("No exception raised")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000223 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000224 pass
225
226 try:
227 result.parrot = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200228 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000229 except AttributeError:
230 pass
231
232 # Use the stat_result constructor with a too-short tuple.
233 try:
234 result2 = os.stat_result((10,))
Andrew Svetlov737fb892012-12-18 21:14:22 +0200235 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000236 except TypeError:
237 pass
238
Ezio Melotti42da6632011-03-15 05:18:48 +0200239 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000240 try:
241 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
242 except TypeError:
243 pass
244
Antoine Pitrou38425292010-09-21 18:19:07 +0000245 def test_stat_attributes(self):
246 self.check_stat_attributes(self.fname)
247
248 def test_stat_attributes_bytes(self):
249 try:
250 fname = self.fname.encode(sys.getfilesystemencoding())
251 except UnicodeEncodeError:
252 self.skipTest("cannot encode %a for the filesystem" % self.fname)
Victor Stinner1ab6c2d2011-11-15 22:27:41 +0100253 with warnings.catch_warnings():
254 warnings.simplefilter("ignore", DeprecationWarning)
255 self.check_stat_attributes(fname)
Tim Peterse0c446b2001-10-18 21:57:37 +0000256
Christian Heimes25827622013-10-12 01:27:08 +0200257 def test_stat_result_pickle(self):
258 result = os.stat(self.fname)
Serhiy Storchakabad12572014-12-15 14:03:42 +0200259 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
260 p = pickle.dumps(result, proto)
261 self.assertIn(b'stat_result', p)
262 if proto < 4:
263 self.assertIn(b'cos\nstat_result\n', p)
264 unpickled = pickle.loads(p)
265 self.assertEqual(result, unpickled)
Christian Heimes25827622013-10-12 01:27:08 +0200266
Serhiy Storchaka43767632013-11-03 21:31:38 +0200267 @unittest.skipUnless(hasattr(os, 'statvfs'), 'test needs os.statvfs()')
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000268 def test_statvfs_attributes(self):
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000269 try:
270 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000271 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000272 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000273 if e.errno == errno.ENOSYS:
Victor Stinner370cb252013-10-12 01:33:54 +0200274 self.skipTest('os.statvfs() failed with ENOSYS')
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000275
276 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000277 self.assertEqual(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000278
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000279 # Make sure all the attributes are there.
280 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
281 'ffree', 'favail', 'flag', 'namemax')
282 for value, member in enumerate(members):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000283 self.assertEqual(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000284
285 # Make sure that assignment really fails
286 try:
287 result.f_bfree = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200288 self.fail("No exception raised")
Collin Winter42dae6a2007-03-28 21:44:53 +0000289 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000290 pass
291
292 try:
293 result.parrot = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200294 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000295 except AttributeError:
296 pass
297
298 # Use the constructor with a too-short tuple.
299 try:
300 result2 = os.statvfs_result((10,))
Andrew Svetlov737fb892012-12-18 21:14:22 +0200301 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000302 except TypeError:
303 pass
304
Ezio Melotti42da6632011-03-15 05:18:48 +0200305 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000306 try:
307 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
308 except TypeError:
309 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000310
Christian Heimes25827622013-10-12 01:27:08 +0200311 @unittest.skipUnless(hasattr(os, 'statvfs'),
312 "need os.statvfs()")
313 def test_statvfs_result_pickle(self):
314 try:
315 result = os.statvfs(self.fname)
316 except OSError as e:
317 # On AtheOS, glibc always returns ENOSYS
318 if e.errno == errno.ENOSYS:
Victor Stinner370cb252013-10-12 01:33:54 +0200319 self.skipTest('os.statvfs() failed with ENOSYS')
320
Serhiy Storchakabad12572014-12-15 14:03:42 +0200321 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
322 p = pickle.dumps(result, proto)
323 self.assertIn(b'statvfs_result', p)
324 if proto < 4:
325 self.assertIn(b'cos\nstatvfs_result\n', p)
326 unpickled = pickle.loads(p)
327 self.assertEqual(result, unpickled)
Christian Heimes25827622013-10-12 01:27:08 +0200328
Serhiy Storchaka43767632013-11-03 21:31:38 +0200329 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
330 def test_1686475(self):
331 # Verify that an open file can be stat'ed
332 try:
333 os.stat(r"c:\pagefile.sys")
334 except FileNotFoundError:
Zachary Ware101d9e72013-12-08 00:44:27 -0600335 self.skipTest(r'c:\pagefile.sys does not exist')
Serhiy Storchaka43767632013-11-03 21:31:38 +0200336 except OSError as e:
337 self.fail("Could not stat pagefile.sys")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000338
Serhiy Storchaka43767632013-11-03 21:31:38 +0200339 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
340 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
341 def test_15261(self):
342 # Verify that stat'ing a closed fd does not cause crash
343 r, w = os.pipe()
344 try:
345 os.stat(r) # should not raise error
346 finally:
347 os.close(r)
348 os.close(w)
349 with self.assertRaises(OSError) as ctx:
350 os.stat(r)
351 self.assertEqual(ctx.exception.errno, errno.EBADF)
Richard Oudkerk2240ac12012-07-06 12:05:32 +0100352
Victor Stinnere12e7aa2015-06-12 21:58:00 +0200353
354class UtimeTests(unittest.TestCase):
355 def setUp(self):
356 self.dirname = support.TESTFN
357 self.fname = os.path.join(self.dirname, "f1")
358
359 self.addCleanup(support.rmtree, self.dirname)
360 os.mkdir(self.dirname)
361 with open(self.fname, 'wb') as fp:
362 fp.write(b"ABC")
363
364 # ensure that st_atime and st_mtime are float
365 with warnings.catch_warnings():
366 warnings.simplefilter("ignore", DeprecationWarning)
367
368 old_state = os.stat_float_times(-1)
369 self.addCleanup(os.stat_float_times, old_state)
370
371 os.stat_float_times(True)
372
373 def support_subsecond(self, filename):
374 # Heuristic to check if the filesystem supports timestamp with
375 # subsecond resolution: check if float and int timestamps are different
376 st = os.stat(filename)
377 return ((st.st_atime != st[7])
378 or (st.st_mtime != st[8])
379 or (st.st_ctime != st[9]))
380
381 def _test_utime(self, set_time, filename=None):
382 if not filename:
383 filename = self.fname
384
385 support_subsecond = self.support_subsecond(filename)
386 if support_subsecond:
387 # Timestamp with a resolution of 1 microsecond (10^-6).
388 #
389 # The resolution of the C internal function used by os.utime()
390 # depends on the platform: 1 sec, 1 us, 1 ns. Writing a portable
391 # test with a resolution of 1 ns requires more work:
392 # see the issue #15745.
393 atime_ns = 1002003000 # 1.002003 seconds
394 mtime_ns = 4005006000 # 4.005006 seconds
395 else:
396 # use a resolution of 1 second
397 atime_ns = 5 * 10**9
398 mtime_ns = 8 * 10**9
399
400 set_time(filename, (atime_ns, mtime_ns))
401 st = os.stat(filename)
402
403 if support_subsecond:
404 self.assertAlmostEqual(st.st_atime, atime_ns * 1e-9, delta=1e-6)
405 self.assertAlmostEqual(st.st_mtime, mtime_ns * 1e-9, delta=1e-6)
406 else:
407 self.assertEqual(st.st_atime, atime_ns * 1e-9)
408 self.assertEqual(st.st_mtime, mtime_ns * 1e-9)
409 self.assertEqual(st.st_atime_ns, atime_ns)
410 self.assertEqual(st.st_mtime_ns, mtime_ns)
411
412 def test_utime(self):
413 def set_time(filename, ns):
414 # test the ns keyword parameter
415 os.utime(filename, ns=ns)
416 self._test_utime(set_time)
417
418 @staticmethod
419 def ns_to_sec(ns):
420 # Convert a number of nanosecond (int) to a number of seconds (float).
421 # Round towards infinity by adding 0.5 nanosecond to avoid rounding
422 # issue, os.utime() rounds towards minus infinity.
423 return (ns * 1e-9) + 0.5e-9
424
425 def test_utime_by_indexed(self):
426 # pass times as floating point seconds as the second indexed parameter
427 def set_time(filename, ns):
428 atime_ns, mtime_ns = ns
429 atime = self.ns_to_sec(atime_ns)
430 mtime = self.ns_to_sec(mtime_ns)
431 # test utimensat(timespec), utimes(timeval), utime(utimbuf)
432 # or utime(time_t)
433 os.utime(filename, (atime, mtime))
434 self._test_utime(set_time)
435
436 def test_utime_by_times(self):
437 def set_time(filename, ns):
438 atime_ns, mtime_ns = ns
439 atime = self.ns_to_sec(atime_ns)
440 mtime = self.ns_to_sec(mtime_ns)
441 # test the times keyword parameter
442 os.utime(filename, times=(atime, mtime))
443 self._test_utime(set_time)
444
445 @unittest.skipUnless(os.utime in os.supports_follow_symlinks,
446 "follow_symlinks support for utime required "
447 "for this test.")
448 def test_utime_nofollow_symlinks(self):
449 def set_time(filename, ns):
450 # use follow_symlinks=False to test utimensat(timespec)
451 # or lutimes(timeval)
452 os.utime(filename, ns=ns, follow_symlinks=False)
453 self._test_utime(set_time)
454
455 @unittest.skipUnless(os.utime in os.supports_fd,
456 "fd support for utime required for this test.")
457 def test_utime_fd(self):
458 def set_time(filename, ns):
459 with open(filename, 'wb') as fp:
460 # use a file descriptor to test futimens(timespec)
461 # or futimes(timeval)
462 os.utime(fp.fileno(), ns=ns)
463 self._test_utime(set_time)
464
465 @unittest.skipUnless(os.utime in os.supports_dir_fd,
466 "dir_fd support for utime required for this test.")
467 def test_utime_dir_fd(self):
468 def set_time(filename, ns):
469 dirname, name = os.path.split(filename)
470 dirfd = os.open(dirname, os.O_RDONLY)
471 try:
472 # pass dir_fd to test utimensat(timespec) or futimesat(timeval)
473 os.utime(name, dir_fd=dirfd, ns=ns)
474 finally:
475 os.close(dirfd)
476 self._test_utime(set_time)
477
478 def test_utime_directory(self):
479 def set_time(filename, ns):
480 # test calling os.utime() on a directory
481 os.utime(filename, ns=ns)
482 self._test_utime(set_time, filename=self.dirname)
483
484 def _test_utime_current(self, set_time):
485 # Get the system clock
486 current = time.time()
487
488 # Call os.utime() to set the timestamp to the current system clock
489 set_time(self.fname)
490
491 if not self.support_subsecond(self.fname):
492 delta = 1.0
493 else:
494 # On Windows, the usual resolution of time.time() is 15.6 ms
495 delta = 0.020
496 st = os.stat(self.fname)
497 msg = ("st_time=%r, current=%r, dt=%r"
498 % (st.st_mtime, current, st.st_mtime - current))
499 self.assertAlmostEqual(st.st_mtime, current,
500 delta=delta, msg=msg)
501
502 def test_utime_current(self):
503 def set_time(filename):
504 # Set to the current time in the new way
505 os.utime(self.fname)
506 self._test_utime_current(set_time)
507
508 def test_utime_current_old(self):
509 def set_time(filename):
510 # Set to the current time in the old explicit way.
511 os.utime(self.fname, None)
512 self._test_utime_current(set_time)
513
514 def get_file_system(self, path):
515 if sys.platform == 'win32':
516 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
517 import ctypes
518 kernel32 = ctypes.windll.kernel32
519 buf = ctypes.create_unicode_buffer("", 100)
520 ok = kernel32.GetVolumeInformationW(root, None, 0,
521 None, None, None,
522 buf, len(buf))
523 if ok:
524 return buf.value
525 # return None if the filesystem is unknown
526
527 def test_large_time(self):
528 # Many filesystems are limited to the year 2038. At least, the test
529 # pass with NTFS filesystem.
530 if self.get_file_system(self.dirname) != "NTFS":
531 self.skipTest("requires NTFS")
532
533 large = 5000000000 # some day in 2128
534 os.utime(self.fname, (large, large))
535 self.assertEqual(os.stat(self.fname).st_mtime, large)
536
537 def test_utime_invalid_arguments(self):
538 # seconds and nanoseconds parameters are mutually exclusive
539 with self.assertRaises(ValueError):
540 os.utime(self.fname, (5, 5), ns=(5, 5))
541
542
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000543from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000544
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000545class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000546 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000547 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000548
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000549 def setUp(self):
550 self.__save = dict(os.environ)
Victor Stinnerb745a742010-05-18 17:17:23 +0000551 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000552 self.__saveb = dict(os.environb)
Christian Heimes90333392007-11-01 19:08:42 +0000553 for key, value in self._reference().items():
554 os.environ[key] = value
555
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000556 def tearDown(self):
557 os.environ.clear()
558 os.environ.update(self.__save)
Victor Stinnerb745a742010-05-18 17:17:23 +0000559 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000560 os.environb.clear()
561 os.environb.update(self.__saveb)
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000562
Christian Heimes90333392007-11-01 19:08:42 +0000563 def _reference(self):
564 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
565
566 def _empty_mapping(self):
567 os.environ.clear()
568 return os.environ
569
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000570 # Bug 1110478
Ezio Melottic7e139b2012-09-26 20:01:34 +0300571 @unittest.skipUnless(os.path.exists('/bin/sh'), 'requires /bin/sh')
Martin v. Löwis5510f652005-02-17 21:23:20 +0000572 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000573 os.environ.clear()
Ezio Melottic7e139b2012-09-26 20:01:34 +0300574 os.environ.update(HELLO="World")
575 with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
576 value = popen.read().strip()
577 self.assertEqual(value, "World")
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000578
Ezio Melottic7e139b2012-09-26 20:01:34 +0300579 @unittest.skipUnless(os.path.exists('/bin/sh'), 'requires /bin/sh')
Christian Heimes1a13d592007-11-08 14:16:55 +0000580 def test_os_popen_iter(self):
Ezio Melottic7e139b2012-09-26 20:01:34 +0300581 with os.popen(
582 "/bin/sh -c 'echo \"line1\nline2\nline3\"'") as popen:
583 it = iter(popen)
584 self.assertEqual(next(it), "line1\n")
585 self.assertEqual(next(it), "line2\n")
586 self.assertEqual(next(it), "line3\n")
587 self.assertRaises(StopIteration, next, it)
Christian Heimes1a13d592007-11-08 14:16:55 +0000588
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000589 # Verify environ keys and values from the OS are of the
590 # correct str type.
591 def test_keyvalue_types(self):
592 for key, val in os.environ.items():
Ezio Melottib3aedd42010-11-20 19:04:17 +0000593 self.assertEqual(type(key), str)
594 self.assertEqual(type(val), str)
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000595
Christian Heimes90333392007-11-01 19:08:42 +0000596 def test_items(self):
597 for key, value in self._reference().items():
598 self.assertEqual(os.environ.get(key), value)
599
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000600 # Issue 7310
601 def test___repr__(self):
602 """Check that the repr() of os.environ looks like environ({...})."""
603 env = os.environ
Victor Stinner96f0de92010-07-29 00:29:00 +0000604 self.assertEqual(repr(env), 'environ({{{}}})'.format(', '.join(
605 '{!r}: {!r}'.format(key, value)
606 for key, value in env.items())))
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000607
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000608 def test_get_exec_path(self):
609 defpath_list = os.defpath.split(os.pathsep)
610 test_path = ['/monty', '/python', '', '/flying/circus']
611 test_env = {'PATH': os.pathsep.join(test_path)}
612
613 saved_environ = os.environ
614 try:
615 os.environ = dict(test_env)
616 # Test that defaulting to os.environ works.
617 self.assertSequenceEqual(test_path, os.get_exec_path())
618 self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
619 finally:
620 os.environ = saved_environ
621
622 # No PATH environment variable
623 self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
624 # Empty PATH environment variable
625 self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
626 # Supplied PATH environment variable
627 self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
628
Victor Stinnerb745a742010-05-18 17:17:23 +0000629 if os.supports_bytes_environ:
630 # env cannot contain 'PATH' and b'PATH' keys
Victor Stinner38430e22010-08-19 17:10:18 +0000631 try:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000632 # ignore BytesWarning warning
633 with warnings.catch_warnings(record=True):
634 mixed_env = {'PATH': '1', b'PATH': b'2'}
Victor Stinner38430e22010-08-19 17:10:18 +0000635 except BytesWarning:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000636 # mixed_env cannot be created with python -bb
Victor Stinner38430e22010-08-19 17:10:18 +0000637 pass
638 else:
639 self.assertRaises(ValueError, os.get_exec_path, mixed_env)
Victor Stinnerb745a742010-05-18 17:17:23 +0000640
641 # bytes key and/or value
642 self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}),
643 ['abc'])
644 self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}),
645 ['abc'])
646 self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}),
647 ['abc'])
648
649 @unittest.skipUnless(os.supports_bytes_environ,
650 "os.environb required for this test.")
Victor Stinner84ae1182010-05-06 22:05:07 +0000651 def test_environb(self):
652 # os.environ -> os.environb
653 value = 'euro\u20ac'
654 try:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000655 value_bytes = value.encode(sys.getfilesystemencoding(),
656 'surrogateescape')
Victor Stinner84ae1182010-05-06 22:05:07 +0000657 except UnicodeEncodeError:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000658 msg = "U+20AC character is not encodable to %s" % (
659 sys.getfilesystemencoding(),)
Benjamin Peterson932d3f42010-05-06 22:26:31 +0000660 self.skipTest(msg)
Victor Stinner84ae1182010-05-06 22:05:07 +0000661 os.environ['unicode'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000662 self.assertEqual(os.environ['unicode'], value)
663 self.assertEqual(os.environb[b'unicode'], value_bytes)
Victor Stinner84ae1182010-05-06 22:05:07 +0000664
665 # os.environb -> os.environ
666 value = b'\xff'
667 os.environb[b'bytes'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000668 self.assertEqual(os.environb[b'bytes'], value)
Victor Stinner84ae1182010-05-06 22:05:07 +0000669 value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000670 self.assertEqual(os.environ['bytes'], value_str)
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000671
Charles-François Natali2966f102011-11-26 11:32:46 +0100672 # On FreeBSD < 7 and OS X < 10.6, unsetenv() doesn't return a value (issue
673 # #13415).
674 @support.requires_freebsd_version(7)
675 @support.requires_mac_ver(10, 6)
Victor Stinner60b385e2011-11-22 22:01:28 +0100676 def test_unset_error(self):
677 if sys.platform == "win32":
678 # an environment variable is limited to 32,767 characters
679 key = 'x' * 50000
Victor Stinnerb3f82682011-11-22 22:30:19 +0100680 self.assertRaises(ValueError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100681 else:
682 # "=" is not allowed in a variable name
683 key = 'key='
Victor Stinnerb3f82682011-11-22 22:30:19 +0100684 self.assertRaises(OSError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100685
Victor Stinner6d101392013-04-14 16:35:04 +0200686 def test_key_type(self):
687 missing = 'missingkey'
688 self.assertNotIn(missing, os.environ)
689
Victor Stinner839e5ea2013-04-14 16:43:03 +0200690 with self.assertRaises(KeyError) as cm:
Victor Stinner6d101392013-04-14 16:35:04 +0200691 os.environ[missing]
Victor Stinner839e5ea2013-04-14 16:43:03 +0200692 self.assertIs(cm.exception.args[0], missing)
Victor Stinner0c2dd0c2013-08-23 19:19:15 +0200693 self.assertTrue(cm.exception.__suppress_context__)
Victor Stinner6d101392013-04-14 16:35:04 +0200694
Victor Stinner839e5ea2013-04-14 16:43:03 +0200695 with self.assertRaises(KeyError) as cm:
Victor Stinner6d101392013-04-14 16:35:04 +0200696 del os.environ[missing]
Victor Stinner839e5ea2013-04-14 16:43:03 +0200697 self.assertIs(cm.exception.args[0], missing)
Victor Stinner0c2dd0c2013-08-23 19:19:15 +0200698 self.assertTrue(cm.exception.__suppress_context__)
699
Victor Stinner6d101392013-04-14 16:35:04 +0200700
Tim Petersc4e09402003-04-25 07:11:48 +0000701class WalkTests(unittest.TestCase):
702 """Tests for os.walk()."""
703
Victor Stinner0561c532015-03-12 10:28:24 +0100704 # Wrapper to hide minor differences between os.walk and os.fwalk
705 # to tests both functions with the same code base
706 def walk(self, directory, topdown=True, follow_symlinks=False):
707 walk_it = os.walk(directory,
708 topdown=topdown,
709 followlinks=follow_symlinks)
710 for root, dirs, files in walk_it:
711 yield (root, dirs, files)
712
Charles-François Natali7372b062012-02-05 15:15:38 +0100713 def setUp(self):
Victor Stinner0561c532015-03-12 10:28:24 +0100714 join = os.path.join
Tim Petersc4e09402003-04-25 07:11:48 +0000715
716 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000717 # TESTFN/
718 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000719 # tmp1
720 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000721 # tmp2
722 # SUB11/ no kids
723 # SUB2/ a file kid and a dirsymlink kid
724 # tmp3
725 # link/ a symlink to TESTFN.2
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200726 # broken_link
Guido van Rossumd8faa362007-04-27 19:54:29 +0000727 # TEST2/
728 # tmp4 a lone file
Victor Stinner0561c532015-03-12 10:28:24 +0100729 self.walk_path = join(support.TESTFN, "TEST1")
730 self.sub1_path = join(self.walk_path, "SUB1")
731 self.sub11_path = join(self.sub1_path, "SUB11")
732 sub2_path = join(self.walk_path, "SUB2")
733 tmp1_path = join(self.walk_path, "tmp1")
734 tmp2_path = join(self.sub1_path, "tmp2")
Tim Petersc4e09402003-04-25 07:11:48 +0000735 tmp3_path = join(sub2_path, "tmp3")
Victor Stinner0561c532015-03-12 10:28:24 +0100736 self.link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000737 t2_path = join(support.TESTFN, "TEST2")
738 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200739 broken_link_path = join(sub2_path, "broken_link")
Tim Petersc4e09402003-04-25 07:11:48 +0000740
741 # Create stuff.
Victor Stinner0561c532015-03-12 10:28:24 +0100742 os.makedirs(self.sub11_path)
Tim Petersc4e09402003-04-25 07:11:48 +0000743 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000744 os.makedirs(t2_path)
Victor Stinner0561c532015-03-12 10:28:24 +0100745
Guido van Rossumd8faa362007-04-27 19:54:29 +0000746 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000747 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000748 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
749 f.close()
750
Victor Stinner0561c532015-03-12 10:28:24 +0100751 if support.can_symlink():
752 os.symlink(os.path.abspath(t2_path), self.link_path)
753 os.symlink('broken', broken_link_path, True)
754 self.sub2_tree = (sub2_path, ["link"], ["broken_link", "tmp3"])
755 else:
756 self.sub2_tree = (sub2_path, [], ["tmp3"])
757
758 def test_walk_topdown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000759 # Walk top-down.
Victor Stinner0561c532015-03-12 10:28:24 +0100760 all = list(os.walk(self.walk_path))
761
Tim Petersc4e09402003-04-25 07:11:48 +0000762 self.assertEqual(len(all), 4)
763 # We can't know which order SUB1 and SUB2 will appear in.
764 # Not flipped: TESTFN, SUB1, SUB11, SUB2
765 # flipped: TESTFN, SUB2, SUB1, SUB11
766 flipped = all[0][1][0] != "SUB1"
767 all[0][1].sort()
Hynek Schlawackc96f5a02012-05-15 17:55:38 +0200768 all[3 - 2 * flipped][-1].sort()
Victor Stinner0561c532015-03-12 10:28:24 +0100769 self.assertEqual(all[0], (self.walk_path, ["SUB1", "SUB2"], ["tmp1"]))
770 self.assertEqual(all[1 + flipped], (self.sub1_path, ["SUB11"], ["tmp2"]))
771 self.assertEqual(all[2 + flipped], (self.sub11_path, [], []))
772 self.assertEqual(all[3 - 2 * flipped], self.sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000773
Victor Stinner0561c532015-03-12 10:28:24 +0100774 def test_walk_prune(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000775 # Prune the search.
776 all = []
Victor Stinner0561c532015-03-12 10:28:24 +0100777 for root, dirs, files in self.walk(self.walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000778 all.append((root, dirs, files))
779 # Don't descend into SUB1.
780 if 'SUB1' in dirs:
781 # Note that this also mutates the dirs we appended to all!
782 dirs.remove('SUB1')
Tim Petersc4e09402003-04-25 07:11:48 +0000783
Victor Stinner0561c532015-03-12 10:28:24 +0100784 self.assertEqual(len(all), 2)
785 self.assertEqual(all[0],
786 (self.walk_path, ["SUB2"], ["tmp1"]))
787
788 all[1][-1].sort()
789 self.assertEqual(all[1], self.sub2_tree)
790
791 def test_walk_bottom_up(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000792 # Walk bottom-up.
Victor Stinner0561c532015-03-12 10:28:24 +0100793 all = list(self.walk(self.walk_path, topdown=False))
794
Tim Petersc4e09402003-04-25 07:11:48 +0000795 self.assertEqual(len(all), 4)
796 # We can't know which order SUB1 and SUB2 will appear in.
797 # Not flipped: SUB11, SUB1, SUB2, TESTFN
798 # flipped: SUB2, SUB11, SUB1, TESTFN
799 flipped = all[3][1][0] != "SUB1"
800 all[3][1].sort()
Hynek Schlawack39bf90d2012-05-15 18:40:17 +0200801 all[2 - 2 * flipped][-1].sort()
Victor Stinner0561c532015-03-12 10:28:24 +0100802 self.assertEqual(all[3],
803 (self.walk_path, ["SUB1", "SUB2"], ["tmp1"]))
804 self.assertEqual(all[flipped],
805 (self.sub11_path, [], []))
806 self.assertEqual(all[flipped + 1],
807 (self.sub1_path, ["SUB11"], ["tmp2"]))
808 self.assertEqual(all[2 - 2 * flipped],
809 self.sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000810
Victor Stinner0561c532015-03-12 10:28:24 +0100811 def test_walk_symlink(self):
812 if not support.can_symlink():
813 self.skipTest("need symlink support")
814
815 # Walk, following symlinks.
816 walk_it = self.walk(self.walk_path, follow_symlinks=True)
817 for root, dirs, files in walk_it:
818 if root == self.link_path:
819 self.assertEqual(dirs, [])
820 self.assertEqual(files, ["tmp4"])
821 break
822 else:
823 self.fail("Didn't follow symlink with followlinks=True")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000824
825 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000826 # Tear everything down. This is a decent use for bottom-up on
827 # Windows, which doesn't have a recursive delete command. The
828 # (not so) subtlety is that rmdir will fail unless the dir's
829 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000830 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000831 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000832 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000833 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000834 dirname = os.path.join(root, name)
835 if not os.path.islink(dirname):
836 os.rmdir(dirname)
837 else:
838 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000839 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000840
Charles-François Natali7372b062012-02-05 15:15:38 +0100841
842@unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
843class FwalkTests(WalkTests):
844 """Tests for os.fwalk()."""
845
Victor Stinner0561c532015-03-12 10:28:24 +0100846 def walk(self, directory, topdown=True, follow_symlinks=False):
847 walk_it = os.fwalk(directory,
848 topdown=topdown,
849 follow_symlinks=follow_symlinks)
850 for root, dirs, files, root_fd in walk_it:
851 yield (root, dirs, files)
852
853
Larry Hastingsc48fe982012-06-25 04:49:05 -0700854 def _compare_to_walk(self, walk_kwargs, fwalk_kwargs):
855 """
856 compare with walk() results.
857 """
Larry Hastingsb4038062012-07-15 10:57:38 -0700858 walk_kwargs = walk_kwargs.copy()
859 fwalk_kwargs = fwalk_kwargs.copy()
860 for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
861 walk_kwargs.update(topdown=topdown, followlinks=follow_symlinks)
862 fwalk_kwargs.update(topdown=topdown, follow_symlinks=follow_symlinks)
Larry Hastingsc48fe982012-06-25 04:49:05 -0700863
Charles-François Natali7372b062012-02-05 15:15:38 +0100864 expected = {}
Larry Hastingsc48fe982012-06-25 04:49:05 -0700865 for root, dirs, files in os.walk(**walk_kwargs):
Charles-François Natali7372b062012-02-05 15:15:38 +0100866 expected[root] = (set(dirs), set(files))
867
Larry Hastingsc48fe982012-06-25 04:49:05 -0700868 for root, dirs, files, rootfd in os.fwalk(**fwalk_kwargs):
Charles-François Natali7372b062012-02-05 15:15:38 +0100869 self.assertIn(root, expected)
870 self.assertEqual(expected[root], (set(dirs), set(files)))
871
Larry Hastingsc48fe982012-06-25 04:49:05 -0700872 def test_compare_to_walk(self):
873 kwargs = {'top': support.TESTFN}
874 self._compare_to_walk(kwargs, kwargs)
875
Charles-François Natali7372b062012-02-05 15:15:38 +0100876 def test_dir_fd(self):
Larry Hastingsc48fe982012-06-25 04:49:05 -0700877 try:
878 fd = os.open(".", os.O_RDONLY)
879 walk_kwargs = {'top': support.TESTFN}
880 fwalk_kwargs = walk_kwargs.copy()
881 fwalk_kwargs['dir_fd'] = fd
882 self._compare_to_walk(walk_kwargs, fwalk_kwargs)
883 finally:
884 os.close(fd)
885
886 def test_yields_correct_dir_fd(self):
Charles-François Natali7372b062012-02-05 15:15:38 +0100887 # check returned file descriptors
Larry Hastingsb4038062012-07-15 10:57:38 -0700888 for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
889 args = support.TESTFN, topdown, None
890 for root, dirs, files, rootfd in os.fwalk(*args, follow_symlinks=follow_symlinks):
Charles-François Natali7372b062012-02-05 15:15:38 +0100891 # check that the FD is valid
892 os.fstat(rootfd)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700893 # redundant check
894 os.stat(rootfd)
895 # check that listdir() returns consistent information
896 self.assertEqual(set(os.listdir(rootfd)), set(dirs) | set(files))
Charles-François Natali7372b062012-02-05 15:15:38 +0100897
898 def test_fd_leak(self):
899 # Since we're opening a lot of FDs, we must be careful to avoid leaks:
900 # we both check that calling fwalk() a large number of times doesn't
901 # yield EMFILE, and that the minimum allocated FD hasn't changed.
902 minfd = os.dup(1)
903 os.close(minfd)
904 for i in range(256):
905 for x in os.fwalk(support.TESTFN):
906 pass
907 newfd = os.dup(1)
908 self.addCleanup(os.close, newfd)
909 self.assertEqual(newfd, minfd)
910
911 def tearDown(self):
912 # cleanup
913 for root, dirs, files, rootfd in os.fwalk(support.TESTFN, topdown=False):
914 for name in files:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700915 os.unlink(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +0100916 for name in dirs:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700917 st = os.stat(name, dir_fd=rootfd, follow_symlinks=False)
Larry Hastingsb698d8e2012-06-23 16:55:07 -0700918 if stat.S_ISDIR(st.st_mode):
919 os.rmdir(name, dir_fd=rootfd)
920 else:
921 os.unlink(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +0100922 os.rmdir(support.TESTFN)
923
924
Guido van Rossume7ba4952007-06-06 23:52:48 +0000925class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000926 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000927 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000928
929 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000930 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000931 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
932 os.makedirs(path) # Should work
933 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
934 os.makedirs(path)
935
936 # Try paths with a '.' in them
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000937 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000938 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
939 os.makedirs(path)
940 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
941 'dir5', 'dir6')
942 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000943
Terry Reedy5a22b652010-12-02 07:05:56 +0000944 def test_exist_ok_existing_directory(self):
945 path = os.path.join(support.TESTFN, 'dir1')
946 mode = 0o777
947 old_mask = os.umask(0o022)
948 os.makedirs(path, mode)
949 self.assertRaises(OSError, os.makedirs, path, mode)
950 self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
Benjamin Peterson4717e212014-04-01 19:17:57 -0400951 os.makedirs(path, 0o776, exist_ok=True)
Terry Reedy5a22b652010-12-02 07:05:56 +0000952 os.makedirs(path, mode=mode, exist_ok=True)
953 os.umask(old_mask)
954
Terry Jan Reedy4a0b6f72013-08-10 20:58:59 -0400955 @unittest.skipUnless(hasattr(os, 'chown'), 'test needs os.chown')
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700956 def test_chown_uid_gid_arguments_must_be_index(self):
957 stat = os.stat(support.TESTFN)
958 uid = stat.st_uid
959 gid = stat.st_gid
960 for value in (-1.0, -1j, decimal.Decimal(-1), fractions.Fraction(-2, 2)):
961 self.assertRaises(TypeError, os.chown, support.TESTFN, value, gid)
962 self.assertRaises(TypeError, os.chown, support.TESTFN, uid, value)
963 self.assertIsNone(os.chown(support.TESTFN, uid, gid))
964 self.assertIsNone(os.chown(support.TESTFN, -1, -1))
965
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700966 def test_exist_ok_s_isgid_directory(self):
967 path = os.path.join(support.TESTFN, 'dir1')
968 S_ISGID = stat.S_ISGID
969 mode = 0o777
970 old_mask = os.umask(0o022)
971 try:
972 existing_testfn_mode = stat.S_IMODE(
973 os.lstat(support.TESTFN).st_mode)
Ned Deilyc622f422012-08-08 20:57:24 -0700974 try:
975 os.chmod(support.TESTFN, existing_testfn_mode | S_ISGID)
Ned Deily3a2b97e2012-08-08 21:03:02 -0700976 except PermissionError:
Ned Deilyc622f422012-08-08 20:57:24 -0700977 raise unittest.SkipTest('Cannot set S_ISGID for dir.')
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700978 if (os.lstat(support.TESTFN).st_mode & S_ISGID != S_ISGID):
979 raise unittest.SkipTest('No support for S_ISGID dir mode.')
980 # The os should apply S_ISGID from the parent dir for us, but
981 # this test need not depend on that behavior. Be explicit.
982 os.makedirs(path, mode | S_ISGID)
983 # http://bugs.python.org/issue14992
984 # Should not fail when the bit is already set.
985 os.makedirs(path, mode, exist_ok=True)
986 # remove the bit.
987 os.chmod(path, stat.S_IMODE(os.lstat(path).st_mode) & ~S_ISGID)
Benjamin Petersonee5f1c12014-04-01 19:13:18 -0400988 # May work even when the bit is not already set when demanded.
989 os.makedirs(path, mode | S_ISGID, exist_ok=True)
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700990 finally:
991 os.umask(old_mask)
Terry Reedy5a22b652010-12-02 07:05:56 +0000992
993 def test_exist_ok_existing_regular_file(self):
994 base = support.TESTFN
995 path = os.path.join(support.TESTFN, 'dir1')
996 f = open(path, 'w')
997 f.write('abc')
998 f.close()
999 self.assertRaises(OSError, os.makedirs, path)
1000 self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
1001 self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
1002 os.remove(path)
1003
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00001004 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001005 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00001006 'dir4', 'dir5', 'dir6')
1007 # If the tests failed, the bottom-most directory ('../dir6')
1008 # may not have been created, so we look for the outermost directory
1009 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001010 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00001011 path = os.path.dirname(path)
1012
1013 os.removedirs(path)
1014
Andrew Svetlov405faed2012-12-25 12:18:09 +02001015
1016class RemoveDirsTests(unittest.TestCase):
1017 def setUp(self):
1018 os.makedirs(support.TESTFN)
1019
1020 def tearDown(self):
1021 support.rmtree(support.TESTFN)
1022
1023 def test_remove_all(self):
1024 dira = os.path.join(support.TESTFN, 'dira')
1025 os.mkdir(dira)
1026 dirb = os.path.join(dira, 'dirb')
1027 os.mkdir(dirb)
1028 os.removedirs(dirb)
1029 self.assertFalse(os.path.exists(dirb))
1030 self.assertFalse(os.path.exists(dira))
1031 self.assertFalse(os.path.exists(support.TESTFN))
1032
1033 def test_remove_partial(self):
1034 dira = os.path.join(support.TESTFN, 'dira')
1035 os.mkdir(dira)
1036 dirb = os.path.join(dira, 'dirb')
1037 os.mkdir(dirb)
1038 with open(os.path.join(dira, 'file.txt'), 'w') as f:
1039 f.write('text')
1040 os.removedirs(dirb)
1041 self.assertFalse(os.path.exists(dirb))
1042 self.assertTrue(os.path.exists(dira))
1043 self.assertTrue(os.path.exists(support.TESTFN))
1044
1045 def test_remove_nothing(self):
1046 dira = os.path.join(support.TESTFN, 'dira')
1047 os.mkdir(dira)
1048 dirb = os.path.join(dira, 'dirb')
1049 os.mkdir(dirb)
1050 with open(os.path.join(dirb, 'file.txt'), 'w') as f:
1051 f.write('text')
1052 with self.assertRaises(OSError):
1053 os.removedirs(dirb)
1054 self.assertTrue(os.path.exists(dirb))
1055 self.assertTrue(os.path.exists(dira))
1056 self.assertTrue(os.path.exists(support.TESTFN))
1057
1058
Guido van Rossume7ba4952007-06-06 23:52:48 +00001059class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +00001060 def test_devnull(self):
Victor Stinnera6d2c762011-06-30 18:20:11 +02001061 with open(os.devnull, 'wb') as f:
1062 f.write(b'hello')
1063 f.close()
1064 with open(os.devnull, 'rb') as f:
1065 self.assertEqual(f.read(), b'')
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00001066
Andrew Svetlov405faed2012-12-25 12:18:09 +02001067
Guido van Rossume7ba4952007-06-06 23:52:48 +00001068class URandomTests(unittest.TestCase):
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001069 def test_urandom_length(self):
1070 self.assertEqual(len(os.urandom(0)), 0)
1071 self.assertEqual(len(os.urandom(1)), 1)
1072 self.assertEqual(len(os.urandom(10)), 10)
1073 self.assertEqual(len(os.urandom(100)), 100)
1074 self.assertEqual(len(os.urandom(1000)), 1000)
1075
1076 def test_urandom_value(self):
1077 data1 = os.urandom(16)
1078 data2 = os.urandom(16)
1079 self.assertNotEqual(data1, data2)
1080
1081 def get_urandom_subprocess(self, count):
1082 code = '\n'.join((
1083 'import os, sys',
1084 'data = os.urandom(%s)' % count,
1085 'sys.stdout.buffer.write(data)',
1086 'sys.stdout.buffer.flush()'))
1087 out = assert_python_ok('-c', code)
1088 stdout = out[1]
1089 self.assertEqual(len(stdout), 16)
1090 return stdout
1091
1092 def test_urandom_subprocess(self):
1093 data1 = self.get_urandom_subprocess(16)
1094 data2 = self.get_urandom_subprocess(16)
1095 self.assertNotEqual(data1, data2)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +00001096
Victor Stinnerfe02e392014-12-21 01:16:38 +01001097
1098HAVE_GETENTROPY = (sysconfig.get_config_var('HAVE_GETENTROPY') == 1)
1099
1100@unittest.skipIf(HAVE_GETENTROPY,
1101 "getentropy() does not use a file descriptor")
1102class URandomFDTests(unittest.TestCase):
Antoine Pitrouec34ab52013-08-16 20:44:38 +02001103 @unittest.skipUnless(resource, "test requires the resource module")
1104 def test_urandom_failure(self):
Antoine Pitroueba25ba2013-08-24 20:52:27 +02001105 # Check urandom() failing when it is not able to open /dev/random.
1106 # We spawn a new process to make the test more robust (if getrlimit()
1107 # failed to restore the file descriptor limit after this, the whole
1108 # test suite would crash; this actually happened on the OS X Tiger
1109 # buildbot).
1110 code = """if 1:
1111 import errno
1112 import os
1113 import resource
1114
1115 soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
1116 resource.setrlimit(resource.RLIMIT_NOFILE, (1, hard_limit))
1117 try:
Antoine Pitrouec34ab52013-08-16 20:44:38 +02001118 os.urandom(16)
Antoine Pitroueba25ba2013-08-24 20:52:27 +02001119 except OSError as e:
1120 assert e.errno == errno.EMFILE, e.errno
1121 else:
1122 raise AssertionError("OSError not raised")
1123 """
1124 assert_python_ok('-c', code)
Antoine Pitrouec34ab52013-08-16 20:44:38 +02001125
Antoine Pitroue472aea2014-04-26 14:33:03 +02001126 def test_urandom_fd_closed(self):
1127 # Issue #21207: urandom() should reopen its fd to /dev/urandom if
1128 # closed.
1129 code = """if 1:
1130 import os
1131 import sys
1132 os.urandom(4)
1133 os.closerange(3, 256)
1134 sys.stdout.buffer.write(os.urandom(4))
1135 """
1136 rc, out, err = assert_python_ok('-Sc', code)
1137
1138 def test_urandom_fd_reopened(self):
1139 # Issue #21207: urandom() should detect its fd to /dev/urandom
1140 # changed to something else, and reopen it.
1141 with open(support.TESTFN, 'wb') as f:
1142 f.write(b"x" * 256)
1143 self.addCleanup(os.unlink, support.TESTFN)
1144 code = """if 1:
1145 import os
1146 import sys
1147 os.urandom(4)
1148 for fd in range(3, 256):
1149 try:
1150 os.close(fd)
1151 except OSError:
1152 pass
1153 else:
1154 # Found the urandom fd (XXX hopefully)
1155 break
1156 os.closerange(3, 256)
1157 with open({TESTFN!r}, 'rb') as f:
1158 os.dup2(f.fileno(), fd)
1159 sys.stdout.buffer.write(os.urandom(4))
1160 sys.stdout.buffer.write(os.urandom(4))
1161 """.format(TESTFN=support.TESTFN)
1162 rc, out, err = assert_python_ok('-Sc', code)
1163 self.assertEqual(len(out), 8)
1164 self.assertNotEqual(out[0:4], out[4:8])
1165 rc, out2, err2 = assert_python_ok('-Sc', code)
1166 self.assertEqual(len(out2), 8)
1167 self.assertNotEqual(out2, out)
1168
Antoine Pitrouec34ab52013-08-16 20:44:38 +02001169
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001170@contextlib.contextmanager
1171def _execvpe_mockup(defpath=None):
1172 """
1173 Stubs out execv and execve functions when used as context manager.
1174 Records exec calls. The mock execv and execve functions always raise an
1175 exception as they would normally never return.
1176 """
1177 # A list of tuples containing (function name, first arg, args)
1178 # of calls to execv or execve that have been made.
1179 calls = []
1180
1181 def mock_execv(name, *args):
1182 calls.append(('execv', name, args))
1183 raise RuntimeError("execv called")
1184
1185 def mock_execve(name, *args):
1186 calls.append(('execve', name, args))
1187 raise OSError(errno.ENOTDIR, "execve called")
1188
1189 try:
1190 orig_execv = os.execv
1191 orig_execve = os.execve
1192 orig_defpath = os.defpath
1193 os.execv = mock_execv
1194 os.execve = mock_execve
1195 if defpath is not None:
1196 os.defpath = defpath
1197 yield calls
1198 finally:
1199 os.execv = orig_execv
1200 os.execve = orig_execve
1201 os.defpath = orig_defpath
1202
Guido van Rossume7ba4952007-06-06 23:52:48 +00001203class ExecTests(unittest.TestCase):
Mark Dickinson7cf03892010-04-16 13:45:35 +00001204 @unittest.skipIf(USING_LINUXTHREADS,
1205 "avoid triggering a linuxthreads bug: see issue #4970")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001206 def test_execvpe_with_bad_program(self):
Mark Dickinson7cf03892010-04-16 13:45:35 +00001207 self.assertRaises(OSError, os.execvpe, 'no such app-',
1208 ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001209
Thomas Heller6790d602007-08-30 17:15:14 +00001210 def test_execvpe_with_bad_arglist(self):
1211 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
1212
Gregory P. Smith4ae37772010-05-08 18:05:46 +00001213 @unittest.skipUnless(hasattr(os, '_execvpe'),
1214 "No internal os._execvpe function to test.")
Victor Stinnerb745a742010-05-18 17:17:23 +00001215 def _test_internal_execvpe(self, test_type):
1216 program_path = os.sep + 'absolutepath'
1217 if test_type is bytes:
1218 program = b'executable'
1219 fullpath = os.path.join(os.fsencode(program_path), program)
1220 native_fullpath = fullpath
1221 arguments = [b'progname', 'arg1', 'arg2']
1222 else:
1223 program = 'executable'
1224 arguments = ['progname', 'arg1', 'arg2']
1225 fullpath = os.path.join(program_path, program)
1226 if os.name != "nt":
1227 native_fullpath = os.fsencode(fullpath)
1228 else:
1229 native_fullpath = fullpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001230 env = {'spam': 'beans'}
1231
Victor Stinnerb745a742010-05-18 17:17:23 +00001232 # test os._execvpe() with an absolute path
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001233 with _execvpe_mockup() as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +00001234 self.assertRaises(RuntimeError,
1235 os._execvpe, fullpath, arguments)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001236 self.assertEqual(len(calls), 1)
1237 self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))
1238
Victor Stinnerb745a742010-05-18 17:17:23 +00001239 # test os._execvpe() with a relative path:
1240 # os.get_exec_path() returns defpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001241 with _execvpe_mockup(defpath=program_path) as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +00001242 self.assertRaises(OSError,
1243 os._execvpe, program, arguments, env=env)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001244 self.assertEqual(len(calls), 1)
Victor Stinnerb745a742010-05-18 17:17:23 +00001245 self.assertSequenceEqual(calls[0],
1246 ('execve', native_fullpath, (arguments, env)))
1247
1248 # test os._execvpe() with a relative path:
1249 # os.get_exec_path() reads the 'PATH' variable
1250 with _execvpe_mockup() as calls:
1251 env_path = env.copy()
Victor Stinner38430e22010-08-19 17:10:18 +00001252 if test_type is bytes:
1253 env_path[b'PATH'] = program_path
1254 else:
1255 env_path['PATH'] = program_path
Victor Stinnerb745a742010-05-18 17:17:23 +00001256 self.assertRaises(OSError,
1257 os._execvpe, program, arguments, env=env_path)
1258 self.assertEqual(len(calls), 1)
1259 self.assertSequenceEqual(calls[0],
1260 ('execve', native_fullpath, (arguments, env_path)))
1261
1262 def test_internal_execvpe_str(self):
1263 self._test_internal_execvpe(str)
1264 if os.name != "nt":
1265 self._test_internal_execvpe(bytes)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001266
Gregory P. Smith4ae37772010-05-08 18:05:46 +00001267
Serhiy Storchaka43767632013-11-03 21:31:38 +02001268@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001269class Win32ErrorTests(unittest.TestCase):
1270 def test_rename(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001271 self.assertRaises(OSError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001272
1273 def test_remove(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001274 self.assertRaises(OSError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001275
1276 def test_chdir(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001277 self.assertRaises(OSError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001278
1279 def test_mkdir(self):
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +00001280 f = open(support.TESTFN, "w")
Benjamin Petersonf91df042009-02-13 02:50:59 +00001281 try:
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001282 self.assertRaises(OSError, os.mkdir, support.TESTFN)
Benjamin Petersonf91df042009-02-13 02:50:59 +00001283 finally:
1284 f.close()
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +00001285 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001286
1287 def test_utime(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001288 self.assertRaises(OSError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001289
Thomas Wouters477c8d52006-05-27 19:21:47 +00001290 def test_chmod(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001291 self.assertRaises(OSError, os.chmod, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001292
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001293class TestInvalidFD(unittest.TestCase):
Benjamin Peterson05e782f2009-01-19 15:15:02 +00001294 singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001295 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
1296 #singles.append("close")
1297 #We omit close because it doesn'r raise an exception on some platforms
1298 def get_single(f):
1299 def helper(self):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001300 if hasattr(os, f):
1301 self.check(getattr(os, f))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001302 return helper
1303 for f in singles:
1304 locals()["test_"+f] = get_single(f)
1305
Benjamin Peterson7522c742009-01-19 21:00:09 +00001306 def check(self, f, *args):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001307 try:
1308 f(support.make_bad_fd(), *args)
1309 except OSError as e:
1310 self.assertEqual(e.errno, errno.EBADF)
1311 else:
1312 self.fail("%r didn't raise a OSError with a bad file descriptor"
1313 % f)
Benjamin Peterson7522c742009-01-19 21:00:09 +00001314
Serhiy Storchaka43767632013-11-03 21:31:38 +02001315 @unittest.skipUnless(hasattr(os, 'isatty'), 'test needs os.isatty()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001316 def test_isatty(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001317 self.assertEqual(os.isatty(support.make_bad_fd()), False)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001318
Serhiy Storchaka43767632013-11-03 21:31:38 +02001319 @unittest.skipUnless(hasattr(os, 'closerange'), 'test needs os.closerange()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001320 def test_closerange(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001321 fd = support.make_bad_fd()
1322 # Make sure none of the descriptors we are about to close are
1323 # currently valid (issue 6542).
1324 for i in range(10):
1325 try: os.fstat(fd+i)
1326 except OSError:
1327 pass
1328 else:
1329 break
1330 if i < 2:
1331 raise unittest.SkipTest(
1332 "Unable to acquire a range of invalid file descriptors")
1333 self.assertEqual(os.closerange(fd, fd + i-1), None)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001334
Serhiy Storchaka43767632013-11-03 21:31:38 +02001335 @unittest.skipUnless(hasattr(os, 'dup2'), 'test needs os.dup2()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001336 def test_dup2(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001337 self.check(os.dup2, 20)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001338
Serhiy Storchaka43767632013-11-03 21:31:38 +02001339 @unittest.skipUnless(hasattr(os, 'fchmod'), 'test needs os.fchmod()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001340 def test_fchmod(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001341 self.check(os.fchmod, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001342
Serhiy Storchaka43767632013-11-03 21:31:38 +02001343 @unittest.skipUnless(hasattr(os, 'fchown'), 'test needs os.fchown()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001344 def test_fchown(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001345 self.check(os.fchown, -1, -1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001346
Serhiy Storchaka43767632013-11-03 21:31:38 +02001347 @unittest.skipUnless(hasattr(os, 'fpathconf'), 'test needs os.fpathconf()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001348 def test_fpathconf(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001349 self.check(os.pathconf, "PC_NAME_MAX")
1350 self.check(os.fpathconf, "PC_NAME_MAX")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001351
Serhiy Storchaka43767632013-11-03 21:31:38 +02001352 @unittest.skipUnless(hasattr(os, 'ftruncate'), 'test needs os.ftruncate()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001353 def test_ftruncate(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001354 self.check(os.truncate, 0)
1355 self.check(os.ftruncate, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001356
Serhiy Storchaka43767632013-11-03 21:31:38 +02001357 @unittest.skipUnless(hasattr(os, 'lseek'), 'test needs os.lseek()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001358 def test_lseek(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001359 self.check(os.lseek, 0, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001360
Serhiy Storchaka43767632013-11-03 21:31:38 +02001361 @unittest.skipUnless(hasattr(os, 'read'), 'test needs os.read()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001362 def test_read(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001363 self.check(os.read, 1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001364
Victor Stinner57ddf782014-01-08 15:21:28 +01001365 @unittest.skipUnless(hasattr(os, 'readv'), 'test needs os.readv()')
1366 def test_readv(self):
1367 buf = bytearray(10)
1368 self.check(os.readv, [buf])
1369
Serhiy Storchaka43767632013-11-03 21:31:38 +02001370 @unittest.skipUnless(hasattr(os, 'tcsetpgrp'), 'test needs os.tcsetpgrp()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001371 def test_tcsetpgrpt(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001372 self.check(os.tcsetpgrp, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001373
Serhiy Storchaka43767632013-11-03 21:31:38 +02001374 @unittest.skipUnless(hasattr(os, 'write'), 'test needs os.write()')
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001375 def test_write(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +02001376 self.check(os.write, b" ")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001377
Victor Stinner57ddf782014-01-08 15:21:28 +01001378 @unittest.skipUnless(hasattr(os, 'writev'), 'test needs os.writev()')
1379 def test_writev(self):
1380 self.check(os.writev, [b'abc'])
1381
Brian Curtin1b9df392010-11-24 20:24:31 +00001382
1383class LinkTests(unittest.TestCase):
1384 def setUp(self):
1385 self.file1 = support.TESTFN
1386 self.file2 = os.path.join(support.TESTFN + "2")
1387
Brian Curtinc0abc4e2010-11-30 23:46:54 +00001388 def tearDown(self):
Brian Curtin1b9df392010-11-24 20:24:31 +00001389 for file in (self.file1, self.file2):
1390 if os.path.exists(file):
1391 os.unlink(file)
1392
Brian Curtin1b9df392010-11-24 20:24:31 +00001393 def _test_link(self, file1, file2):
1394 with open(file1, "w") as f1:
1395 f1.write("test")
1396
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001397 with warnings.catch_warnings():
1398 warnings.simplefilter("ignore", DeprecationWarning)
1399 os.link(file1, file2)
Brian Curtin1b9df392010-11-24 20:24:31 +00001400 with open(file1, "r") as f1, open(file2, "r") as f2:
1401 self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
1402
1403 def test_link(self):
1404 self._test_link(self.file1, self.file2)
1405
1406 def test_link_bytes(self):
1407 self._test_link(bytes(self.file1, sys.getfilesystemencoding()),
1408 bytes(self.file2, sys.getfilesystemencoding()))
1409
Brian Curtinf498b752010-11-30 15:54:04 +00001410 def test_unicode_name(self):
Brian Curtin43f0c272010-11-30 15:40:04 +00001411 try:
Brian Curtinf498b752010-11-30 15:54:04 +00001412 os.fsencode("\xf1")
Brian Curtin43f0c272010-11-30 15:40:04 +00001413 except UnicodeError:
1414 raise unittest.SkipTest("Unable to encode for this platform.")
1415
Brian Curtinf498b752010-11-30 15:54:04 +00001416 self.file1 += "\xf1"
Brian Curtinfc889c42010-11-28 23:59:46 +00001417 self.file2 = self.file1 + "2"
1418 self._test_link(self.file1, self.file2)
1419
Serhiy Storchaka43767632013-11-03 21:31:38 +02001420@unittest.skipIf(sys.platform == "win32", "Posix specific tests")
1421class PosixUidGidTests(unittest.TestCase):
1422 @unittest.skipUnless(hasattr(os, 'setuid'), 'test needs os.setuid()')
1423 def test_setuid(self):
1424 if os.getuid() != 0:
1425 self.assertRaises(OSError, os.setuid, 0)
1426 self.assertRaises(OverflowError, os.setuid, 1<<32)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001427
Serhiy Storchaka43767632013-11-03 21:31:38 +02001428 @unittest.skipUnless(hasattr(os, 'setgid'), 'test needs os.setgid()')
1429 def test_setgid(self):
1430 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
1431 self.assertRaises(OSError, os.setgid, 0)
1432 self.assertRaises(OverflowError, os.setgid, 1<<32)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001433
Serhiy Storchaka43767632013-11-03 21:31:38 +02001434 @unittest.skipUnless(hasattr(os, 'seteuid'), 'test needs os.seteuid()')
1435 def test_seteuid(self):
1436 if os.getuid() != 0:
1437 self.assertRaises(OSError, os.seteuid, 0)
1438 self.assertRaises(OverflowError, os.seteuid, 1<<32)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001439
Serhiy Storchaka43767632013-11-03 21:31:38 +02001440 @unittest.skipUnless(hasattr(os, 'setegid'), 'test needs os.setegid()')
1441 def test_setegid(self):
1442 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
1443 self.assertRaises(OSError, os.setegid, 0)
1444 self.assertRaises(OverflowError, os.setegid, 1<<32)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001445
Serhiy Storchaka43767632013-11-03 21:31:38 +02001446 @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
1447 def test_setreuid(self):
1448 if os.getuid() != 0:
1449 self.assertRaises(OSError, os.setreuid, 0, 0)
1450 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
1451 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001452
Serhiy Storchaka43767632013-11-03 21:31:38 +02001453 @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
1454 def test_setreuid_neg1(self):
1455 # Needs to accept -1. We run this in a subprocess to avoid
1456 # altering the test runner's process state (issue8045).
1457 subprocess.check_call([
1458 sys.executable, '-c',
1459 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001460
Serhiy Storchaka43767632013-11-03 21:31:38 +02001461 @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
1462 def test_setregid(self):
1463 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
1464 self.assertRaises(OSError, os.setregid, 0, 0)
1465 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
1466 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001467
Serhiy Storchaka43767632013-11-03 21:31:38 +02001468 @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
1469 def test_setregid_neg1(self):
1470 # Needs to accept -1. We run this in a subprocess to avoid
1471 # altering the test runner's process state (issue8045).
1472 subprocess.check_call([
1473 sys.executable, '-c',
1474 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001475
Serhiy Storchaka43767632013-11-03 21:31:38 +02001476@unittest.skipIf(sys.platform == "win32", "Posix specific tests")
1477class Pep383Tests(unittest.TestCase):
1478 def setUp(self):
1479 if support.TESTFN_UNENCODABLE:
1480 self.dir = support.TESTFN_UNENCODABLE
1481 elif support.TESTFN_NONASCII:
1482 self.dir = support.TESTFN_NONASCII
1483 else:
1484 self.dir = support.TESTFN
1485 self.bdir = os.fsencode(self.dir)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001486
Serhiy Storchaka43767632013-11-03 21:31:38 +02001487 bytesfn = []
1488 def add_filename(fn):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001489 try:
Serhiy Storchaka43767632013-11-03 21:31:38 +02001490 fn = os.fsencode(fn)
1491 except UnicodeEncodeError:
1492 return
1493 bytesfn.append(fn)
1494 add_filename(support.TESTFN_UNICODE)
1495 if support.TESTFN_UNENCODABLE:
1496 add_filename(support.TESTFN_UNENCODABLE)
1497 if support.TESTFN_NONASCII:
1498 add_filename(support.TESTFN_NONASCII)
1499 if not bytesfn:
1500 self.skipTest("couldn't create any non-ascii filename")
Martin v. Löwis011e8422009-05-05 04:43:17 +00001501
Serhiy Storchaka43767632013-11-03 21:31:38 +02001502 self.unicodefn = set()
1503 os.mkdir(self.dir)
1504 try:
1505 for fn in bytesfn:
1506 support.create_empty_file(os.path.join(self.bdir, fn))
1507 fn = os.fsdecode(fn)
1508 if fn in self.unicodefn:
1509 raise ValueError("duplicate filename")
1510 self.unicodefn.add(fn)
1511 except:
Martin v. Löwis011e8422009-05-05 04:43:17 +00001512 shutil.rmtree(self.dir)
Serhiy Storchaka43767632013-11-03 21:31:38 +02001513 raise
Martin v. Löwis011e8422009-05-05 04:43:17 +00001514
Serhiy Storchaka43767632013-11-03 21:31:38 +02001515 def tearDown(self):
1516 shutil.rmtree(self.dir)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001517
Serhiy Storchaka43767632013-11-03 21:31:38 +02001518 def test_listdir(self):
1519 expected = self.unicodefn
1520 found = set(os.listdir(self.dir))
1521 self.assertEqual(found, expected)
1522 # test listdir without arguments
1523 current_directory = os.getcwd()
1524 try:
1525 os.chdir(os.sep)
1526 self.assertEqual(set(os.listdir()), set(os.listdir(os.sep)))
1527 finally:
1528 os.chdir(current_directory)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001529
Serhiy Storchaka43767632013-11-03 21:31:38 +02001530 def test_open(self):
1531 for fn in self.unicodefn:
1532 f = open(os.path.join(self.dir, fn), 'rb')
1533 f.close()
Victor Stinnere4110dc2013-01-01 23:05:55 +01001534
Serhiy Storchaka43767632013-11-03 21:31:38 +02001535 @unittest.skipUnless(hasattr(os, 'statvfs'),
1536 "need os.statvfs()")
1537 def test_statvfs(self):
1538 # issue #9645
1539 for fn in self.unicodefn:
1540 # should not fail with file not found error
1541 fullname = os.path.join(self.dir, fn)
1542 os.statvfs(fullname)
1543
1544 def test_stat(self):
1545 for fn in self.unicodefn:
1546 os.stat(os.path.join(self.dir, fn))
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001547
Brian Curtineb24d742010-04-12 17:16:38 +00001548@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
1549class Win32KillTests(unittest.TestCase):
Brian Curtinc3acbc32010-05-28 16:08:40 +00001550 def _kill(self, sig):
1551 # Start sys.executable as a subprocess and communicate from the
1552 # subprocess to the parent that the interpreter is ready. When it
1553 # becomes ready, send *sig* via os.kill to the subprocess and check
1554 # that the return code is equal to *sig*.
1555 import ctypes
1556 from ctypes import wintypes
1557 import msvcrt
1558
1559 # Since we can't access the contents of the process' stdout until the
1560 # process has exited, use PeekNamedPipe to see what's inside stdout
1561 # without waiting. This is done so we can tell that the interpreter
1562 # is started and running at a point where it could handle a signal.
1563 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
1564 PeekNamedPipe.restype = wintypes.BOOL
1565 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
1566 ctypes.POINTER(ctypes.c_char), # stdout buf
1567 wintypes.DWORD, # Buffer size
1568 ctypes.POINTER(wintypes.DWORD), # bytes read
1569 ctypes.POINTER(wintypes.DWORD), # bytes avail
1570 ctypes.POINTER(wintypes.DWORD)) # bytes left
1571 msg = "running"
1572 proc = subprocess.Popen([sys.executable, "-c",
1573 "import sys;"
1574 "sys.stdout.write('{}');"
1575 "sys.stdout.flush();"
1576 "input()".format(msg)],
1577 stdout=subprocess.PIPE,
1578 stderr=subprocess.PIPE,
1579 stdin=subprocess.PIPE)
Brian Curtin43ec5772010-11-05 15:17:11 +00001580 self.addCleanup(proc.stdout.close)
1581 self.addCleanup(proc.stderr.close)
1582 self.addCleanup(proc.stdin.close)
Brian Curtinc3acbc32010-05-28 16:08:40 +00001583
1584 count, max = 0, 100
1585 while count < max and proc.poll() is None:
1586 # Create a string buffer to store the result of stdout from the pipe
1587 buf = ctypes.create_string_buffer(len(msg))
1588 # Obtain the text currently in proc.stdout
1589 # Bytes read/avail/left are left as NULL and unused
1590 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
1591 buf, ctypes.sizeof(buf), None, None, None)
1592 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
1593 if buf.value:
1594 self.assertEqual(msg, buf.value.decode())
1595 break
1596 time.sleep(0.1)
1597 count += 1
1598 else:
1599 self.fail("Did not receive communication from the subprocess")
1600
Brian Curtineb24d742010-04-12 17:16:38 +00001601 os.kill(proc.pid, sig)
1602 self.assertEqual(proc.wait(), sig)
1603
1604 def test_kill_sigterm(self):
1605 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinc3acbc32010-05-28 16:08:40 +00001606 self._kill(signal.SIGTERM)
Brian Curtineb24d742010-04-12 17:16:38 +00001607
1608 def test_kill_int(self):
1609 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinc3acbc32010-05-28 16:08:40 +00001610 self._kill(100)
Brian Curtineb24d742010-04-12 17:16:38 +00001611
1612 def _kill_with_event(self, event, name):
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001613 tagname = "test_os_%s" % uuid.uuid1()
1614 m = mmap.mmap(-1, 1, tagname)
1615 m[0] = 0
Brian Curtineb24d742010-04-12 17:16:38 +00001616 # Run a script which has console control handling enabled.
1617 proc = subprocess.Popen([sys.executable,
1618 os.path.join(os.path.dirname(__file__),
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001619 "win_console_handler.py"), tagname],
Brian Curtineb24d742010-04-12 17:16:38 +00001620 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
1621 # Let the interpreter startup before we send signals. See #3137.
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001622 count, max = 0, 100
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001623 while count < max and proc.poll() is None:
Brian Curtinf668df52010-10-15 14:21:06 +00001624 if m[0] == 1:
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001625 break
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001626 time.sleep(0.1)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001627 count += 1
1628 else:
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001629 # Forcefully kill the process if we weren't able to signal it.
1630 os.kill(proc.pid, signal.SIGINT)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001631 self.fail("Subprocess didn't finish initialization")
Brian Curtineb24d742010-04-12 17:16:38 +00001632 os.kill(proc.pid, event)
1633 # proc.send_signal(event) could also be done here.
1634 # Allow time for the signal to be passed and the process to exit.
1635 time.sleep(0.5)
1636 if not proc.poll():
1637 # Forcefully kill the process if we weren't able to signal it.
1638 os.kill(proc.pid, signal.SIGINT)
1639 self.fail("subprocess did not stop on {}".format(name))
1640
1641 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
1642 def test_CTRL_C_EVENT(self):
1643 from ctypes import wintypes
1644 import ctypes
1645
1646 # Make a NULL value by creating a pointer with no argument.
1647 NULL = ctypes.POINTER(ctypes.c_int)()
1648 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
1649 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
1650 wintypes.BOOL)
1651 SetConsoleCtrlHandler.restype = wintypes.BOOL
1652
1653 # Calling this with NULL and FALSE causes the calling process to
1654 # handle CTRL+C, rather than ignore it. This property is inherited
1655 # by subprocesses.
1656 SetConsoleCtrlHandler(NULL, 0)
1657
1658 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
1659
1660 def test_CTRL_BREAK_EVENT(self):
1661 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
1662
1663
Brian Curtind40e6f72010-07-08 21:39:08 +00001664@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Tim Golden781bbeb2013-10-25 20:24:06 +01001665class Win32ListdirTests(unittest.TestCase):
1666 """Test listdir on Windows."""
1667
1668 def setUp(self):
1669 self.created_paths = []
1670 for i in range(2):
1671 dir_name = 'SUB%d' % i
1672 dir_path = os.path.join(support.TESTFN, dir_name)
1673 file_name = 'FILE%d' % i
1674 file_path = os.path.join(support.TESTFN, file_name)
1675 os.makedirs(dir_path)
1676 with open(file_path, 'w') as f:
1677 f.write("I'm %s and proud of it. Blame test_os.\n" % file_path)
1678 self.created_paths.extend([dir_name, file_name])
1679 self.created_paths.sort()
1680
1681 def tearDown(self):
1682 shutil.rmtree(support.TESTFN)
1683
1684 def test_listdir_no_extended_path(self):
1685 """Test when the path is not an "extended" path."""
1686 # unicode
1687 self.assertEqual(
1688 sorted(os.listdir(support.TESTFN)),
1689 self.created_paths)
1690 # bytes
1691 self.assertEqual(
1692 sorted(os.listdir(os.fsencode(support.TESTFN))),
1693 [os.fsencode(path) for path in self.created_paths])
1694
1695 def test_listdir_extended_path(self):
1696 """Test when the path starts with '\\\\?\\'."""
Tim Golden1cc35402013-10-25 21:26:06 +01001697 # See: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath
Tim Golden781bbeb2013-10-25 20:24:06 +01001698 # unicode
1699 path = '\\\\?\\' + os.path.abspath(support.TESTFN)
1700 self.assertEqual(
1701 sorted(os.listdir(path)),
1702 self.created_paths)
1703 # bytes
1704 path = b'\\\\?\\' + os.fsencode(os.path.abspath(support.TESTFN))
1705 self.assertEqual(
1706 sorted(os.listdir(path)),
1707 [os.fsencode(path) for path in self.created_paths])
1708
1709
1710@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Brian Curtin3b4499c2010-12-28 14:31:47 +00001711@support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +00001712class Win32SymlinkTests(unittest.TestCase):
1713 filelink = 'filelinktest'
1714 filelink_target = os.path.abspath(__file__)
1715 dirlink = 'dirlinktest'
1716 dirlink_target = os.path.dirname(filelink_target)
1717 missing_link = 'missing link'
1718
1719 def setUp(self):
1720 assert os.path.exists(self.dirlink_target)
1721 assert os.path.exists(self.filelink_target)
1722 assert not os.path.exists(self.dirlink)
1723 assert not os.path.exists(self.filelink)
1724 assert not os.path.exists(self.missing_link)
1725
1726 def tearDown(self):
1727 if os.path.exists(self.filelink):
1728 os.remove(self.filelink)
1729 if os.path.exists(self.dirlink):
1730 os.rmdir(self.dirlink)
1731 if os.path.lexists(self.missing_link):
1732 os.remove(self.missing_link)
1733
1734 def test_directory_link(self):
Jason R. Coombs3a092862013-05-27 23:21:28 -04001735 os.symlink(self.dirlink_target, self.dirlink)
Brian Curtind40e6f72010-07-08 21:39:08 +00001736 self.assertTrue(os.path.exists(self.dirlink))
1737 self.assertTrue(os.path.isdir(self.dirlink))
1738 self.assertTrue(os.path.islink(self.dirlink))
1739 self.check_stat(self.dirlink, self.dirlink_target)
1740
1741 def test_file_link(self):
1742 os.symlink(self.filelink_target, self.filelink)
1743 self.assertTrue(os.path.exists(self.filelink))
1744 self.assertTrue(os.path.isfile(self.filelink))
1745 self.assertTrue(os.path.islink(self.filelink))
1746 self.check_stat(self.filelink, self.filelink_target)
1747
1748 def _create_missing_dir_link(self):
1749 'Create a "directory" link to a non-existent target'
1750 linkname = self.missing_link
1751 if os.path.lexists(linkname):
1752 os.remove(linkname)
1753 target = r'c:\\target does not exist.29r3c740'
1754 assert not os.path.exists(target)
1755 target_is_dir = True
1756 os.symlink(target, linkname, target_is_dir)
1757
1758 def test_remove_directory_link_to_missing_target(self):
1759 self._create_missing_dir_link()
1760 # For compatibility with Unix, os.remove will check the
1761 # directory status and call RemoveDirectory if the symlink
1762 # was created with target_is_dir==True.
1763 os.remove(self.missing_link)
1764
1765 @unittest.skip("currently fails; consider for improvement")
1766 def test_isdir_on_directory_link_to_missing_target(self):
1767 self._create_missing_dir_link()
1768 # consider having isdir return true for directory links
1769 self.assertTrue(os.path.isdir(self.missing_link))
1770
1771 @unittest.skip("currently fails; consider for improvement")
1772 def test_rmdir_on_directory_link_to_missing_target(self):
1773 self._create_missing_dir_link()
1774 # consider allowing rmdir to remove directory links
1775 os.rmdir(self.missing_link)
1776
1777 def check_stat(self, link, target):
1778 self.assertEqual(os.stat(link), os.stat(target))
1779 self.assertNotEqual(os.lstat(link), os.stat(link))
1780
Brian Curtind25aef52011-06-13 15:16:04 -05001781 bytes_link = os.fsencode(link)
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001782 with warnings.catch_warnings():
1783 warnings.simplefilter("ignore", DeprecationWarning)
1784 self.assertEqual(os.stat(bytes_link), os.stat(target))
1785 self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link))
Brian Curtind25aef52011-06-13 15:16:04 -05001786
1787 def test_12084(self):
1788 level1 = os.path.abspath(support.TESTFN)
1789 level2 = os.path.join(level1, "level2")
1790 level3 = os.path.join(level2, "level3")
1791 try:
1792 os.mkdir(level1)
1793 os.mkdir(level2)
1794 os.mkdir(level3)
1795
1796 file1 = os.path.abspath(os.path.join(level1, "file1"))
1797
1798 with open(file1, "w") as f:
1799 f.write("file1")
1800
1801 orig_dir = os.getcwd()
1802 try:
1803 os.chdir(level2)
1804 link = os.path.join(level2, "link")
1805 os.symlink(os.path.relpath(file1), "link")
1806 self.assertIn("link", os.listdir(os.getcwd()))
1807
1808 # Check os.stat calls from the same dir as the link
1809 self.assertEqual(os.stat(file1), os.stat("link"))
1810
1811 # Check os.stat calls from a dir below the link
1812 os.chdir(level1)
1813 self.assertEqual(os.stat(file1),
1814 os.stat(os.path.relpath(link)))
1815
1816 # Check os.stat calls from a dir above the link
1817 os.chdir(level3)
1818 self.assertEqual(os.stat(file1),
1819 os.stat(os.path.relpath(link)))
1820 finally:
1821 os.chdir(orig_dir)
1822 except OSError as err:
1823 self.fail(err)
1824 finally:
1825 os.remove(file1)
1826 shutil.rmtree(level1)
1827
Brian Curtind40e6f72010-07-08 21:39:08 +00001828
Jason R. Coombs3a092862013-05-27 23:21:28 -04001829@support.skip_unless_symlink
1830class NonLocalSymlinkTests(unittest.TestCase):
1831
1832 def setUp(self):
1833 """
1834 Create this structure:
1835
1836 base
1837 \___ some_dir
1838 """
1839 os.makedirs('base/some_dir')
1840
1841 def tearDown(self):
1842 shutil.rmtree('base')
1843
1844 def test_directory_link_nonlocal(self):
1845 """
1846 The symlink target should resolve relative to the link, not relative
1847 to the current directory.
1848
1849 Then, link base/some_link -> base/some_dir and ensure that some_link
1850 is resolved as a directory.
1851
1852 In issue13772, it was discovered that directory detection failed if
1853 the symlink target was not specified relative to the current
1854 directory, which was a defect in the implementation.
1855 """
1856 src = os.path.join('base', 'some_link')
1857 os.symlink('some_dir', src)
1858 assert os.path.isdir(src)
1859
1860
Victor Stinnere8d51452010-08-19 01:05:19 +00001861class FSEncodingTests(unittest.TestCase):
1862 def test_nop(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001863 self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
1864 self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
Benjamin Peterson31191a92010-05-09 03:22:58 +00001865
Victor Stinnere8d51452010-08-19 01:05:19 +00001866 def test_identity(self):
1867 # assert fsdecode(fsencode(x)) == x
1868 for fn in ('unicode\u0141', 'latin\xe9', 'ascii'):
1869 try:
1870 bytesfn = os.fsencode(fn)
1871 except UnicodeEncodeError:
1872 continue
Ezio Melottib3aedd42010-11-20 19:04:17 +00001873 self.assertEqual(os.fsdecode(bytesfn), fn)
Victor Stinnere8d51452010-08-19 01:05:19 +00001874
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00001875
Brett Cannonefb00c02012-02-29 18:31:31 -05001876
1877class DeviceEncodingTests(unittest.TestCase):
1878
1879 def test_bad_fd(self):
1880 # Return None when an fd doesn't actually exist.
1881 self.assertIsNone(os.device_encoding(123456))
1882
Philip Jenveye308b7c2012-02-29 16:16:15 -08001883 @unittest.skipUnless(os.isatty(0) and (sys.platform.startswith('win') or
1884 (hasattr(locale, 'nl_langinfo') and hasattr(locale, 'CODESET'))),
Philip Jenveyd7aff2d2012-02-29 16:21:25 -08001885 'test requires a tty and either Windows or nl_langinfo(CODESET)')
Brett Cannonefb00c02012-02-29 18:31:31 -05001886 def test_device_encoding(self):
1887 encoding = os.device_encoding(0)
1888 self.assertIsNotNone(encoding)
1889 self.assertTrue(codecs.lookup(encoding))
1890
1891
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00001892class PidTests(unittest.TestCase):
1893 @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid")
1894 def test_getppid(self):
1895 p = subprocess.Popen([sys.executable, '-c',
1896 'import os; print(os.getppid())'],
1897 stdout=subprocess.PIPE)
1898 stdout, _ = p.communicate()
1899 # We are the parent of our subprocess
1900 self.assertEqual(int(stdout), os.getpid())
1901
1902
Brian Curtin0151b8e2010-09-24 13:43:43 +00001903# The introduction of this TestCase caused at least two different errors on
1904# *nix buildbots. Temporarily skip this to let the buildbots move along.
1905@unittest.skip("Skip due to platform/environment differences on *NIX buildbots")
Brian Curtine8e4b3b2010-09-23 20:04:14 +00001906@unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin")
1907class LoginTests(unittest.TestCase):
1908 def test_getlogin(self):
1909 user_name = os.getlogin()
1910 self.assertNotEqual(len(user_name), 0)
1911
1912
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001913@unittest.skipUnless(hasattr(os, 'getpriority') and hasattr(os, 'setpriority'),
1914 "needs os.getpriority and os.setpriority")
1915class ProgramPriorityTests(unittest.TestCase):
1916 """Tests for os.getpriority() and os.setpriority()."""
1917
1918 def test_set_get_priority(self):
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001919
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001920 base = os.getpriority(os.PRIO_PROCESS, os.getpid())
1921 os.setpriority(os.PRIO_PROCESS, os.getpid(), base + 1)
1922 try:
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001923 new_prio = os.getpriority(os.PRIO_PROCESS, os.getpid())
1924 if base >= 19 and new_prio <= 19:
1925 raise unittest.SkipTest(
1926 "unable to reliably test setpriority at current nice level of %s" % base)
1927 else:
1928 self.assertEqual(new_prio, base + 1)
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001929 finally:
1930 try:
1931 os.setpriority(os.PRIO_PROCESS, os.getpid(), base)
1932 except OSError as err:
Antoine Pitrou692f0382011-02-26 00:22:25 +00001933 if err.errno != errno.EACCES:
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001934 raise
1935
1936
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001937if threading is not None:
1938 class SendfileTestServer(asyncore.dispatcher, threading.Thread):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001939
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001940 class Handler(asynchat.async_chat):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001941
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001942 def __init__(self, conn):
1943 asynchat.async_chat.__init__(self, conn)
1944 self.in_buffer = []
1945 self.closed = False
1946 self.push(b"220 ready\r\n")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001947
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001948 def handle_read(self):
1949 data = self.recv(4096)
1950 self.in_buffer.append(data)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001951
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001952 def get_data(self):
1953 return b''.join(self.in_buffer)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001954
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001955 def handle_close(self):
1956 self.close()
1957 self.closed = True
1958
1959 def handle_error(self):
1960 raise
1961
1962 def __init__(self, address):
1963 threading.Thread.__init__(self)
1964 asyncore.dispatcher.__init__(self)
1965 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
1966 self.bind(address)
1967 self.listen(5)
1968 self.host, self.port = self.socket.getsockname()[:2]
1969 self.handler_instance = None
1970 self._active = False
1971 self._active_lock = threading.Lock()
1972
1973 # --- public API
1974
1975 @property
1976 def running(self):
1977 return self._active
1978
1979 def start(self):
1980 assert not self.running
1981 self.__flag = threading.Event()
1982 threading.Thread.start(self)
1983 self.__flag.wait()
1984
1985 def stop(self):
1986 assert self.running
1987 self._active = False
1988 self.join()
1989
1990 def wait(self):
1991 # wait for handler connection to be closed, then stop the server
1992 while not getattr(self.handler_instance, "closed", False):
1993 time.sleep(0.001)
1994 self.stop()
1995
1996 # --- internals
1997
1998 def run(self):
1999 self._active = True
2000 self.__flag.set()
2001 while self._active and asyncore.socket_map:
2002 self._active_lock.acquire()
2003 asyncore.loop(timeout=0.001, count=1)
2004 self._active_lock.release()
2005 asyncore.close_all()
2006
2007 def handle_accept(self):
2008 conn, addr = self.accept()
2009 self.handler_instance = self.Handler(conn)
2010
2011 def handle_connect(self):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002012 self.close()
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02002013 handle_read = handle_connect
2014
2015 def writable(self):
2016 return 0
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002017
2018 def handle_error(self):
2019 raise
2020
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002021
Giampaolo Rodolà46134642011-02-25 20:01:05 +00002022@unittest.skipUnless(threading is not None, "test needs threading module")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002023@unittest.skipUnless(hasattr(os, 'sendfile'), "test needs os.sendfile()")
2024class TestSendfile(unittest.TestCase):
2025
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00002026 DATA = b"12345abcde" * 16 * 1024 # 160 KB
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002027 SUPPORT_HEADERS_TRAILERS = not sys.platform.startswith("linux") and \
Giampaolo Rodolà4bc68572011-02-25 21:46:01 +00002028 not sys.platform.startswith("solaris") and \
2029 not sys.platform.startswith("sunos")
Serhiy Storchaka43767632013-11-03 21:31:38 +02002030 requires_headers_trailers = unittest.skipUnless(SUPPORT_HEADERS_TRAILERS,
2031 'requires headers and trailers support')
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002032
2033 @classmethod
2034 def setUpClass(cls):
2035 with open(support.TESTFN, "wb") as f:
2036 f.write(cls.DATA)
2037
2038 @classmethod
2039 def tearDownClass(cls):
2040 support.unlink(support.TESTFN)
2041
2042 def setUp(self):
2043 self.server = SendfileTestServer((support.HOST, 0))
2044 self.server.start()
2045 self.client = socket.socket()
2046 self.client.connect((self.server.host, self.server.port))
2047 self.client.settimeout(1)
2048 # synchronize by waiting for "220 ready" response
2049 self.client.recv(1024)
2050 self.sockno = self.client.fileno()
2051 self.file = open(support.TESTFN, 'rb')
2052 self.fileno = self.file.fileno()
2053
2054 def tearDown(self):
2055 self.file.close()
2056 self.client.close()
2057 if self.server.running:
2058 self.server.stop()
2059
2060 def sendfile_wrapper(self, sock, file, offset, nbytes, headers=[], trailers=[]):
2061 """A higher level wrapper representing how an application is
2062 supposed to use sendfile().
2063 """
2064 while 1:
2065 try:
2066 if self.SUPPORT_HEADERS_TRAILERS:
2067 return os.sendfile(sock, file, offset, nbytes, headers,
2068 trailers)
2069 else:
2070 return os.sendfile(sock, file, offset, nbytes)
2071 except OSError as err:
2072 if err.errno == errno.ECONNRESET:
2073 # disconnected
2074 raise
2075 elif err.errno in (errno.EAGAIN, errno.EBUSY):
2076 # we have to retry send data
2077 continue
2078 else:
2079 raise
2080
2081 def test_send_whole_file(self):
2082 # normal send
2083 total_sent = 0
2084 offset = 0
2085 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00002086 while total_sent < len(self.DATA):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002087 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
2088 if sent == 0:
2089 break
2090 offset += sent
2091 total_sent += sent
2092 self.assertTrue(sent <= nbytes)
2093 self.assertEqual(offset, total_sent)
2094
2095 self.assertEqual(total_sent, len(self.DATA))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00002096 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002097 self.client.close()
2098 self.server.wait()
2099 data = self.server.handler_instance.get_data()
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00002100 self.assertEqual(len(data), len(self.DATA))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00002101 self.assertEqual(data, self.DATA)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002102
2103 def test_send_at_certain_offset(self):
2104 # start sending a file at a certain offset
2105 total_sent = 0
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00002106 offset = len(self.DATA) // 2
2107 must_send = len(self.DATA) - offset
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002108 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00002109 while total_sent < must_send:
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002110 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
2111 if sent == 0:
2112 break
2113 offset += sent
2114 total_sent += sent
2115 self.assertTrue(sent <= nbytes)
2116
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00002117 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002118 self.client.close()
2119 self.server.wait()
2120 data = self.server.handler_instance.get_data()
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00002121 expected = self.DATA[len(self.DATA) // 2:]
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002122 self.assertEqual(total_sent, len(expected))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00002123 self.assertEqual(len(data), len(expected))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00002124 self.assertEqual(data, expected)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002125
2126 def test_offset_overflow(self):
2127 # specify an offset > file size
2128 offset = len(self.DATA) + 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00002129 try:
2130 sent = os.sendfile(self.sockno, self.fileno, offset, 4096)
2131 except OSError as e:
2132 # Solaris can raise EINVAL if offset >= file length, ignore.
2133 if e.errno != errno.EINVAL:
2134 raise
2135 else:
2136 self.assertEqual(sent, 0)
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00002137 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002138 self.client.close()
2139 self.server.wait()
2140 data = self.server.handler_instance.get_data()
2141 self.assertEqual(data, b'')
2142
2143 def test_invalid_offset(self):
2144 with self.assertRaises(OSError) as cm:
2145 os.sendfile(self.sockno, self.fileno, -1, 4096)
2146 self.assertEqual(cm.exception.errno, errno.EINVAL)
2147
2148 # --- headers / trailers tests
2149
Serhiy Storchaka43767632013-11-03 21:31:38 +02002150 @requires_headers_trailers
2151 def test_headers(self):
2152 total_sent = 0
2153 sent = os.sendfile(self.sockno, self.fileno, 0, 4096,
2154 headers=[b"x" * 512])
2155 total_sent += sent
2156 offset = 4096
2157 nbytes = 4096
2158 while 1:
2159 sent = self.sendfile_wrapper(self.sockno, self.fileno,
2160 offset, nbytes)
2161 if sent == 0:
2162 break
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002163 total_sent += sent
Serhiy Storchaka43767632013-11-03 21:31:38 +02002164 offset += sent
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002165
Serhiy Storchaka43767632013-11-03 21:31:38 +02002166 expected_data = b"x" * 512 + self.DATA
2167 self.assertEqual(total_sent, len(expected_data))
2168 self.client.close()
2169 self.server.wait()
2170 data = self.server.handler_instance.get_data()
2171 self.assertEqual(hash(data), hash(expected_data))
2172
2173 @requires_headers_trailers
2174 def test_trailers(self):
2175 TESTFN2 = support.TESTFN + "2"
2176 file_data = b"abcdef"
2177 with open(TESTFN2, 'wb') as f:
2178 f.write(file_data)
2179 with open(TESTFN2, 'rb')as f:
2180 self.addCleanup(os.remove, TESTFN2)
2181 os.sendfile(self.sockno, f.fileno(), 0, len(file_data),
2182 trailers=[b"1234"])
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002183 self.client.close()
2184 self.server.wait()
2185 data = self.server.handler_instance.get_data()
Serhiy Storchaka43767632013-11-03 21:31:38 +02002186 self.assertEqual(data, b"abcdef1234")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002187
Serhiy Storchaka43767632013-11-03 21:31:38 +02002188 @requires_headers_trailers
2189 @unittest.skipUnless(hasattr(os, 'SF_NODISKIO'),
2190 'test needs os.SF_NODISKIO')
2191 def test_flags(self):
2192 try:
2193 os.sendfile(self.sockno, self.fileno, 0, 4096,
2194 flags=os.SF_NODISKIO)
2195 except OSError as err:
2196 if err.errno not in (errno.EBUSY, errno.EAGAIN):
2197 raise
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002198
2199
Larry Hastings9cf065c2012-06-22 16:30:09 -07002200def supports_extended_attributes():
2201 if not hasattr(os, "setxattr"):
2202 return False
2203 try:
2204 with open(support.TESTFN, "wb") as fp:
2205 try:
2206 os.setxattr(fp.fileno(), b"user.test", b"")
2207 except OSError:
2208 return False
2209 finally:
2210 support.unlink(support.TESTFN)
2211 # Kernels < 2.6.39 don't respect setxattr flags.
2212 kernel_version = platform.release()
2213 m = re.match("2.6.(\d{1,2})", kernel_version)
2214 return m is None or int(m.group(1)) >= 39
2215
2216
2217@unittest.skipUnless(supports_extended_attributes(),
2218 "no non-broken extended attribute support")
Benjamin Peterson799bd802011-08-31 22:15:17 -04002219class ExtendedAttributeTests(unittest.TestCase):
2220
2221 def tearDown(self):
2222 support.unlink(support.TESTFN)
2223
Larry Hastings9cf065c2012-06-22 16:30:09 -07002224 def _check_xattrs_str(self, s, getxattr, setxattr, removexattr, listxattr, **kwargs):
Benjamin Peterson799bd802011-08-31 22:15:17 -04002225 fn = support.TESTFN
2226 open(fn, "wb").close()
2227 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002228 getxattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002229 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002230 init_xattr = listxattr(fn)
2231 self.assertIsInstance(init_xattr, list)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002232 setxattr(fn, s("user.test"), b"", **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002233 xattr = set(init_xattr)
2234 xattr.add("user.test")
2235 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002236 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"")
2237 setxattr(fn, s("user.test"), b"hello", os.XATTR_REPLACE, **kwargs)
2238 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"hello")
Benjamin Peterson799bd802011-08-31 22:15:17 -04002239 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002240 setxattr(fn, s("user.test"), b"bye", os.XATTR_CREATE, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002241 self.assertEqual(cm.exception.errno, errno.EEXIST)
2242 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002243 setxattr(fn, s("user.test2"), b"bye", os.XATTR_REPLACE, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002244 self.assertEqual(cm.exception.errno, errno.ENODATA)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002245 setxattr(fn, s("user.test2"), b"foo", os.XATTR_CREATE, **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002246 xattr.add("user.test2")
2247 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002248 removexattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002249 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002250 getxattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002251 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002252 xattr.remove("user.test")
2253 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002254 self.assertEqual(getxattr(fn, s("user.test2"), **kwargs), b"foo")
2255 setxattr(fn, s("user.test"), b"a"*1024, **kwargs)
2256 self.assertEqual(getxattr(fn, s("user.test"), **kwargs), b"a"*1024)
2257 removexattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002258 many = sorted("user.test{}".format(i) for i in range(100))
2259 for thing in many:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002260 setxattr(fn, thing, b"x", **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002261 self.assertEqual(set(listxattr(fn)), set(init_xattr) | set(many))
Benjamin Peterson799bd802011-08-31 22:15:17 -04002262
Larry Hastings9cf065c2012-06-22 16:30:09 -07002263 def _check_xattrs(self, *args, **kwargs):
Benjamin Peterson799bd802011-08-31 22:15:17 -04002264 def make_bytes(s):
2265 return bytes(s, "ascii")
Larry Hastings9cf065c2012-06-22 16:30:09 -07002266 self._check_xattrs_str(str, *args, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002267 support.unlink(support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002268 self._check_xattrs_str(make_bytes, *args, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002269
2270 def test_simple(self):
2271 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
2272 os.listxattr)
2273
2274 def test_lpath(self):
Larry Hastings9cf065c2012-06-22 16:30:09 -07002275 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
2276 os.listxattr, follow_symlinks=False)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002277
2278 def test_fds(self):
2279 def getxattr(path, *args):
2280 with open(path, "rb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002281 return os.getxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002282 def setxattr(path, *args):
2283 with open(path, "wb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002284 os.setxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002285 def removexattr(path, *args):
2286 with open(path, "wb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002287 os.removexattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002288 def listxattr(path, *args):
2289 with open(path, "rb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002290 return os.listxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002291 self._check_xattrs(getxattr, setxattr, removexattr, listxattr)
2292
2293
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002294@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
2295class Win32DeprecatedBytesAPI(unittest.TestCase):
2296 def test_deprecated(self):
2297 import nt
2298 filename = os.fsencode(support.TESTFN)
2299 with warnings.catch_warnings():
2300 warnings.simplefilter("error", DeprecationWarning)
2301 for func, *args in (
2302 (nt._getfullpathname, filename),
2303 (nt._isdir, filename),
2304 (os.access, filename, os.R_OK),
2305 (os.chdir, filename),
2306 (os.chmod, filename, 0o777),
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01002307 (os.getcwdb,),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002308 (os.link, filename, filename),
2309 (os.listdir, filename),
2310 (os.lstat, filename),
2311 (os.mkdir, filename),
2312 (os.open, filename, os.O_RDONLY),
2313 (os.rename, filename, filename),
2314 (os.rmdir, filename),
2315 (os.startfile, filename),
2316 (os.stat, filename),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002317 (os.unlink, filename),
2318 (os.utime, filename),
2319 ):
2320 self.assertRaises(DeprecationWarning, func, *args)
2321
Victor Stinner28216442011-11-16 00:34:44 +01002322 @support.skip_unless_symlink
2323 def test_symlink(self):
2324 filename = os.fsencode(support.TESTFN)
2325 with warnings.catch_warnings():
2326 warnings.simplefilter("error", DeprecationWarning)
2327 self.assertRaises(DeprecationWarning,
2328 os.symlink, filename, filename)
2329
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002330
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002331@unittest.skipUnless(hasattr(os, 'get_terminal_size'), "requires os.get_terminal_size")
2332class TermsizeTests(unittest.TestCase):
2333 def test_does_not_crash(self):
2334 """Check if get_terminal_size() returns a meaningful value.
2335
2336 There's no easy portable way to actually check the size of the
2337 terminal, so let's check if it returns something sensible instead.
2338 """
2339 try:
2340 size = os.get_terminal_size()
2341 except OSError as e:
Antoine Pitrou81a1fa52012-02-09 00:11:00 +01002342 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002343 # Under win32 a generic OSError can be thrown if the
2344 # handle cannot be retrieved
2345 self.skipTest("failed to query terminal size")
2346 raise
2347
Antoine Pitroucfade362012-02-08 23:48:59 +01002348 self.assertGreaterEqual(size.columns, 0)
2349 self.assertGreaterEqual(size.lines, 0)
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002350
2351 def test_stty_match(self):
2352 """Check if stty returns the same results
2353
2354 stty actually tests stdin, so get_terminal_size is invoked on
2355 stdin explicitly. If stty succeeded, then get_terminal_size()
2356 should work too.
2357 """
2358 try:
2359 size = subprocess.check_output(['stty', 'size']).decode().split()
2360 except (FileNotFoundError, subprocess.CalledProcessError):
2361 self.skipTest("stty invocation failed")
2362 expected = (int(size[1]), int(size[0])) # reversed order
2363
Antoine Pitrou81a1fa52012-02-09 00:11:00 +01002364 try:
2365 actual = os.get_terminal_size(sys.__stdin__.fileno())
2366 except OSError as e:
2367 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
2368 # Under win32 a generic OSError can be thrown if the
2369 # handle cannot be retrieved
2370 self.skipTest("failed to query terminal size")
2371 raise
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002372 self.assertEqual(expected, actual)
2373
2374
Victor Stinner292c8352012-10-30 02:17:38 +01002375class OSErrorTests(unittest.TestCase):
2376 def setUp(self):
2377 class Str(str):
2378 pass
2379
Victor Stinnerafe17062012-10-31 22:47:43 +01002380 self.bytes_filenames = []
2381 self.unicode_filenames = []
Victor Stinner292c8352012-10-30 02:17:38 +01002382 if support.TESTFN_UNENCODABLE is not None:
2383 decoded = support.TESTFN_UNENCODABLE
2384 else:
2385 decoded = support.TESTFN
Victor Stinnerafe17062012-10-31 22:47:43 +01002386 self.unicode_filenames.append(decoded)
2387 self.unicode_filenames.append(Str(decoded))
Victor Stinner292c8352012-10-30 02:17:38 +01002388 if support.TESTFN_UNDECODABLE is not None:
2389 encoded = support.TESTFN_UNDECODABLE
2390 else:
2391 encoded = os.fsencode(support.TESTFN)
Victor Stinnerafe17062012-10-31 22:47:43 +01002392 self.bytes_filenames.append(encoded)
2393 self.bytes_filenames.append(memoryview(encoded))
2394
2395 self.filenames = self.bytes_filenames + self.unicode_filenames
Victor Stinner292c8352012-10-30 02:17:38 +01002396
2397 def test_oserror_filename(self):
2398 funcs = [
Victor Stinnerafe17062012-10-31 22:47:43 +01002399 (self.filenames, os.chdir,),
2400 (self.filenames, os.chmod, 0o777),
Victor Stinnerafe17062012-10-31 22:47:43 +01002401 (self.filenames, os.lstat,),
2402 (self.filenames, os.open, os.O_RDONLY),
2403 (self.filenames, os.rmdir,),
2404 (self.filenames, os.stat,),
2405 (self.filenames, os.unlink,),
Victor Stinner292c8352012-10-30 02:17:38 +01002406 ]
2407 if sys.platform == "win32":
2408 funcs.extend((
Victor Stinnerafe17062012-10-31 22:47:43 +01002409 (self.bytes_filenames, os.rename, b"dst"),
2410 (self.bytes_filenames, os.replace, b"dst"),
2411 (self.unicode_filenames, os.rename, "dst"),
2412 (self.unicode_filenames, os.replace, "dst"),
Victor Stinner64e039a2012-11-07 00:10:14 +01002413 # Issue #16414: Don't test undecodable names with listdir()
2414 # because of a Windows bug.
2415 #
2416 # With the ANSI code page 932, os.listdir(b'\xe7') return an
2417 # empty list (instead of failing), whereas os.listdir(b'\xff')
2418 # raises a FileNotFoundError. It looks like a Windows bug:
2419 # b'\xe7' directory does not exist, FindFirstFileA(b'\xe7')
2420 # fails with ERROR_FILE_NOT_FOUND (2), instead of
2421 # ERROR_PATH_NOT_FOUND (3).
2422 (self.unicode_filenames, os.listdir,),
Victor Stinner292c8352012-10-30 02:17:38 +01002423 ))
Victor Stinnerafe17062012-10-31 22:47:43 +01002424 else:
2425 funcs.extend((
Victor Stinner64e039a2012-11-07 00:10:14 +01002426 (self.filenames, os.listdir,),
Victor Stinnerafe17062012-10-31 22:47:43 +01002427 (self.filenames, os.rename, "dst"),
2428 (self.filenames, os.replace, "dst"),
2429 ))
2430 if hasattr(os, "chown"):
2431 funcs.append((self.filenames, os.chown, 0, 0))
2432 if hasattr(os, "lchown"):
2433 funcs.append((self.filenames, os.lchown, 0, 0))
2434 if hasattr(os, "truncate"):
2435 funcs.append((self.filenames, os.truncate, 0))
Victor Stinner292c8352012-10-30 02:17:38 +01002436 if hasattr(os, "chflags"):
Victor Stinneree36c242012-11-13 09:31:51 +01002437 funcs.append((self.filenames, os.chflags, 0))
2438 if hasattr(os, "lchflags"):
2439 funcs.append((self.filenames, os.lchflags, 0))
Victor Stinner292c8352012-10-30 02:17:38 +01002440 if hasattr(os, "chroot"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002441 funcs.append((self.filenames, os.chroot,))
Victor Stinner292c8352012-10-30 02:17:38 +01002442 if hasattr(os, "link"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002443 if sys.platform == "win32":
2444 funcs.append((self.bytes_filenames, os.link, b"dst"))
2445 funcs.append((self.unicode_filenames, os.link, "dst"))
2446 else:
2447 funcs.append((self.filenames, os.link, "dst"))
Victor Stinner292c8352012-10-30 02:17:38 +01002448 if hasattr(os, "listxattr"):
2449 funcs.extend((
Victor Stinnerafe17062012-10-31 22:47:43 +01002450 (self.filenames, os.listxattr,),
2451 (self.filenames, os.getxattr, "user.test"),
2452 (self.filenames, os.setxattr, "user.test", b'user'),
2453 (self.filenames, os.removexattr, "user.test"),
Victor Stinner292c8352012-10-30 02:17:38 +01002454 ))
2455 if hasattr(os, "lchmod"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002456 funcs.append((self.filenames, os.lchmod, 0o777))
Victor Stinner292c8352012-10-30 02:17:38 +01002457 if hasattr(os, "readlink"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002458 if sys.platform == "win32":
2459 funcs.append((self.unicode_filenames, os.readlink,))
2460 else:
2461 funcs.append((self.filenames, os.readlink,))
Victor Stinner292c8352012-10-30 02:17:38 +01002462
Victor Stinnerafe17062012-10-31 22:47:43 +01002463 for filenames, func, *func_args in funcs:
2464 for name in filenames:
Victor Stinner292c8352012-10-30 02:17:38 +01002465 try:
2466 func(name, *func_args)
Victor Stinnerbd54f0e2012-10-31 01:12:55 +01002467 except OSError as err:
Victor Stinner292c8352012-10-30 02:17:38 +01002468 self.assertIs(err.filename, name)
2469 else:
2470 self.fail("No exception thrown by {}".format(func))
2471
Charles-Francois Natali44feda32013-05-20 14:40:46 +02002472class CPUCountTests(unittest.TestCase):
2473 def test_cpu_count(self):
2474 cpus = os.cpu_count()
2475 if cpus is not None:
2476 self.assertIsInstance(cpus, int)
2477 self.assertGreater(cpus, 0)
2478 else:
2479 self.skipTest("Could not determine the number of CPUs")
2480
Victor Stinnerdaf45552013-08-28 00:53:59 +02002481
2482class FDInheritanceTests(unittest.TestCase):
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002483 def test_get_set_inheritable(self):
Victor Stinnerdaf45552013-08-28 00:53:59 +02002484 fd = os.open(__file__, os.O_RDONLY)
2485 self.addCleanup(os.close, fd)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002486 self.assertEqual(os.get_inheritable(fd), False)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002487
Victor Stinnerdaf45552013-08-28 00:53:59 +02002488 os.set_inheritable(fd, True)
2489 self.assertEqual(os.get_inheritable(fd), True)
2490
Victor Stinner4f7a36f2013-09-08 14:14:38 +02002491 @unittest.skipIf(fcntl is None, "need fcntl")
2492 def test_get_inheritable_cloexec(self):
2493 fd = os.open(__file__, os.O_RDONLY)
2494 self.addCleanup(os.close, fd)
2495 self.assertEqual(os.get_inheritable(fd), False)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002496
Victor Stinner4f7a36f2013-09-08 14:14:38 +02002497 # clear FD_CLOEXEC flag
2498 flags = fcntl.fcntl(fd, fcntl.F_GETFD)
2499 flags &= ~fcntl.FD_CLOEXEC
2500 fcntl.fcntl(fd, fcntl.F_SETFD, flags)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002501
Victor Stinner4f7a36f2013-09-08 14:14:38 +02002502 self.assertEqual(os.get_inheritable(fd), True)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002503
Victor Stinner4f7a36f2013-09-08 14:14:38 +02002504 @unittest.skipIf(fcntl is None, "need fcntl")
2505 def test_set_inheritable_cloexec(self):
2506 fd = os.open(__file__, os.O_RDONLY)
2507 self.addCleanup(os.close, fd)
2508 self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
2509 fcntl.FD_CLOEXEC)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002510
Victor Stinner4f7a36f2013-09-08 14:14:38 +02002511 os.set_inheritable(fd, True)
2512 self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
2513 0)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002514
Victor Stinnerdaf45552013-08-28 00:53:59 +02002515 def test_open(self):
2516 fd = os.open(__file__, os.O_RDONLY)
2517 self.addCleanup(os.close, fd)
2518 self.assertEqual(os.get_inheritable(fd), False)
2519
2520 @unittest.skipUnless(hasattr(os, 'pipe'), "need os.pipe()")
2521 def test_pipe(self):
2522 rfd, wfd = os.pipe()
2523 self.addCleanup(os.close, rfd)
2524 self.addCleanup(os.close, wfd)
2525 self.assertEqual(os.get_inheritable(rfd), False)
2526 self.assertEqual(os.get_inheritable(wfd), False)
2527
2528 def test_dup(self):
2529 fd1 = os.open(__file__, os.O_RDONLY)
2530 self.addCleanup(os.close, fd1)
2531
2532 fd2 = os.dup(fd1)
2533 self.addCleanup(os.close, fd2)
2534 self.assertEqual(os.get_inheritable(fd2), False)
2535
2536 @unittest.skipUnless(hasattr(os, 'dup2'), "need os.dup2()")
2537 def test_dup2(self):
2538 fd = os.open(__file__, os.O_RDONLY)
2539 self.addCleanup(os.close, fd)
2540
2541 # inheritable by default
2542 fd2 = os.open(__file__, os.O_RDONLY)
2543 try:
2544 os.dup2(fd, fd2)
2545 self.assertEqual(os.get_inheritable(fd2), True)
2546 finally:
2547 os.close(fd2)
2548
2549 # force non-inheritable
2550 fd3 = os.open(__file__, os.O_RDONLY)
2551 try:
2552 os.dup2(fd, fd3, inheritable=False)
2553 self.assertEqual(os.get_inheritable(fd3), False)
2554 finally:
2555 os.close(fd3)
2556
2557 @unittest.skipUnless(hasattr(os, 'openpty'), "need os.openpty()")
2558 def test_openpty(self):
2559 master_fd, slave_fd = os.openpty()
2560 self.addCleanup(os.close, master_fd)
2561 self.addCleanup(os.close, slave_fd)
2562 self.assertEqual(os.get_inheritable(master_fd), False)
2563 self.assertEqual(os.get_inheritable(slave_fd), False)
2564
2565
Antoine Pitrouf26ad712011-07-15 23:00:56 +02002566@support.reap_threads
Fred Drake2e2be372001-09-20 21:33:42 +00002567def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002568 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002569 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002570 StatAttributeTests,
Victor Stinnere12e7aa2015-06-12 21:58:00 +02002571 UtimeTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002572 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00002573 WalkTests,
Charles-François Natali7372b062012-02-05 15:15:38 +01002574 FwalkTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00002575 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +00002576 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002577 URandomTests,
Ned Deilyab6b9f82015-03-17 04:30:08 -07002578 URandomFDTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +00002579 ExecTests,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00002580 Win32ErrorTests,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002581 TestInvalidFD,
Martin v. Löwis011e8422009-05-05 04:43:17 +00002582 PosixUidGidTests,
Brian Curtineb24d742010-04-12 17:16:38 +00002583 Pep383Tests,
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00002584 Win32KillTests,
Tim Golden781bbeb2013-10-25 20:24:06 +01002585 Win32ListdirTests,
Brian Curtind40e6f72010-07-08 21:39:08 +00002586 Win32SymlinkTests,
Jason R. Coombs3a092862013-05-27 23:21:28 -04002587 NonLocalSymlinkTests,
Victor Stinnere8d51452010-08-19 01:05:19 +00002588 FSEncodingTests,
Brett Cannonefb00c02012-02-29 18:31:31 -05002589 DeviceEncodingTests,
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00002590 PidTests,
Brian Curtine8e4b3b2010-09-23 20:04:14 +00002591 LoginTests,
Brian Curtin1b9df392010-11-24 20:24:31 +00002592 LinkTests,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002593 TestSendfile,
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00002594 ProgramPriorityTests,
Benjamin Peterson799bd802011-08-31 22:15:17 -04002595 ExtendedAttributeTests,
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002596 Win32DeprecatedBytesAPI,
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002597 TermsizeTests,
Victor Stinner292c8352012-10-30 02:17:38 +01002598 OSErrorTests,
Andrew Svetlov405faed2012-12-25 12:18:09 +02002599 RemoveDirsTests,
Charles-Francois Natali44feda32013-05-20 14:40:46 +02002600 CPUCountTests,
Victor Stinnerdaf45552013-08-28 00:53:59 +02002601 FDInheritanceTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002602 )
Fred Drake2e2be372001-09-20 21:33:42 +00002603
2604if __name__ == "__main__":
2605 test_main()