blob: ab44d011e5e886a8a78a065e522bd08df2af2b62 [file] [log] [blame]
Fred Drake38c2ef02001-07-17 20:52:51 +00001# As a test suite for the os module, this is woefully inadequate, but this
2# does add tests for a few functions which have been determined to be more
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00003# portable than they had been thought to be.
Fred Drake38c2ef02001-07-17 20:52:51 +00004
5import os
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00006import errno
Fred Drake38c2ef02001-07-17 20:52:51 +00007import unittest
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +00008import warnings
Thomas Wouters477c8d52006-05-27 19:21:47 +00009import sys
Brian Curtineb24d742010-04-12 17:16:38 +000010import signal
11import subprocess
12import time
Martin v. Löwis011e8422009-05-05 04:43:17 +000013import shutil
Benjamin Petersonee8712c2008-05-20 21:35:26 +000014from test import support
Victor Stinnerc2d095f2010-05-17 00:14:53 +000015import contextlib
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +000016import mmap
Benjamin Peterson799bd802011-08-31 22:15:17 -040017import platform
18import re
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +000019import uuid
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000020import asyncore
21import asynchat
22import socket
Charles-François Natali7372b062012-02-05 15:15:38 +010023import itertools
24import stat
Brett Cannonefb00c02012-02-29 18:31:31 -050025import locale
26import codecs
Larry Hastingsa27b83a2013-08-08 00:19:50 -070027import decimal
28import fractions
Christian Heimes25827622013-10-12 01:27:08 +020029import pickle
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000030try:
31 import threading
32except ImportError:
33 threading = None
Antoine Pitrouec34ab52013-08-16 20:44:38 +020034try:
35 import resource
36except ImportError:
37 resource = None
Victor Stinner7ba6b0f2013-09-08 11:47:54 +020038try:
39 import fcntl
40except ImportError:
41 fcntl = None
Antoine Pitrouec34ab52013-08-16 20:44:38 +020042
Georg Brandl2daf6ae2012-02-20 19:54:16 +010043from test.script_helper import assert_python_ok
Fred Drake38c2ef02001-07-17 20:52:51 +000044
Victor Stinner034d0aa2012-06-05 01:22:15 +020045with warnings.catch_warnings():
46 warnings.simplefilter("ignore", DeprecationWarning)
47 os.stat_float_times(True)
Victor Stinner1aa54a42012-02-08 04:09:37 +010048st = os.stat(__file__)
49stat_supports_subsecond = (
50 # check if float and int timestamps are different
51 (st.st_atime != st[7])
52 or (st.st_mtime != st[8])
53 or (st.st_ctime != st[9]))
54
Mark Dickinson7cf03892010-04-16 13:45:35 +000055# Detect whether we're on a Linux system that uses the (now outdated
56# and unmaintained) linuxthreads threading library. There's an issue
57# when combining linuxthreads with a failed execv call: see
58# http://bugs.python.org/issue4970.
Victor Stinnerd5c355c2011-04-30 14:53:09 +020059if hasattr(sys, 'thread_info') and sys.thread_info.version:
60 USING_LINUXTHREADS = sys.thread_info.version.startswith("linuxthreads")
61else:
62 USING_LINUXTHREADS = False
Brian Curtineb24d742010-04-12 17:16:38 +000063
Stefan Krahebee49a2013-01-17 15:31:00 +010064# Issue #14110: Some tests fail on FreeBSD if the user is in the wheel group.
65HAVE_WHEEL_GROUP = sys.platform.startswith('freebsd') and os.getgid() == 0
66
Thomas Wouters0e3f5912006-08-11 14:57:12 +000067# Tests creating TESTFN
68class FileTests(unittest.TestCase):
69 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000070 if os.path.exists(support.TESTFN):
71 os.unlink(support.TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000072 tearDown = setUp
73
74 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000075 f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000076 os.close(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000077 self.assertTrue(os.access(support.TESTFN, os.W_OK))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000078
Christian Heimesfdab48e2008-01-20 09:06:41 +000079 def test_closerange(self):
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000080 first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
81 # We must allocate two consecutive file descriptors, otherwise
82 # it will mess up other file descriptors (perhaps even the three
83 # standard ones).
84 second = os.dup(first)
85 try:
86 retries = 0
87 while second != first + 1:
88 os.close(first)
89 retries += 1
90 if retries > 10:
91 # XXX test skipped
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000092 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000093 first, second = second, os.dup(second)
94 finally:
95 os.close(second)
Christian Heimesfdab48e2008-01-20 09:06:41 +000096 # close a fd that is open, and one that isn't
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000097 os.closerange(first, first + 2)
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000098 self.assertRaises(OSError, os.write, first, b"a")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000099
Benjamin Peterson1cc6df92010-06-30 17:39:45 +0000100 @support.cpython_only
Hirokazu Yamamoto4c19e6e2008-09-08 23:41:21 +0000101 def test_rename(self):
102 path = support.TESTFN
103 old = sys.getrefcount(path)
104 self.assertRaises(TypeError, os.rename, path, 0)
105 new = sys.getrefcount(path)
106 self.assertEqual(old, new)
107
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000108 def test_read(self):
109 with open(support.TESTFN, "w+b") as fobj:
110 fobj.write(b"spam")
111 fobj.flush()
112 fd = fobj.fileno()
113 os.lseek(fd, 0, 0)
114 s = os.read(fd, 4)
115 self.assertEqual(type(s), bytes)
116 self.assertEqual(s, b"spam")
117
118 def test_write(self):
119 # os.write() accepts bytes- and buffer-like objects but not strings
120 fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY)
121 self.assertRaises(TypeError, os.write, fd, "beans")
122 os.write(fd, b"bacon\n")
123 os.write(fd, bytearray(b"eggs\n"))
124 os.write(fd, memoryview(b"spam\n"))
125 os.close(fd)
126 with open(support.TESTFN, "rb") as fobj:
Antoine Pitroud62269f2008-09-15 23:54:52 +0000127 self.assertEqual(fobj.read().splitlines(),
128 [b"bacon", b"eggs", b"spam"])
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000129
Victor Stinnere0daff12011-03-20 23:36:35 +0100130 def write_windows_console(self, *args):
131 retcode = subprocess.call(args,
132 # use a new console to not flood the test output
133 creationflags=subprocess.CREATE_NEW_CONSOLE,
134 # use a shell to hide the console window (SW_HIDE)
135 shell=True)
136 self.assertEqual(retcode, 0)
137
138 @unittest.skipUnless(sys.platform == 'win32',
139 'test specific to the Windows console')
140 def test_write_windows_console(self):
141 # Issue #11395: the Windows console returns an error (12: not enough
142 # space error) on writing into stdout if stdout mode is binary and the
143 # length is greater than 66,000 bytes (or less, depending on heap
144 # usage).
145 code = "print('x' * 100000)"
146 self.write_windows_console(sys.executable, "-c", code)
147 self.write_windows_console(sys.executable, "-u", "-c", code)
148
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000149 def fdopen_helper(self, *args):
150 fd = os.open(support.TESTFN, os.O_RDONLY)
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200151 f = os.fdopen(fd, *args)
152 f.close()
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000153
154 def test_fdopen(self):
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200155 fd = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
156 os.close(fd)
157
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000158 self.fdopen_helper()
159 self.fdopen_helper('r')
160 self.fdopen_helper('r', 100)
161
Antoine Pitrouf3b2d882012-01-30 22:08:52 +0100162 def test_replace(self):
163 TESTFN2 = support.TESTFN + ".2"
164 with open(support.TESTFN, 'w') as f:
165 f.write("1")
166 with open(TESTFN2, 'w') as f:
167 f.write("2")
168 self.addCleanup(os.unlink, TESTFN2)
169 os.replace(support.TESTFN, TESTFN2)
170 self.assertRaises(FileNotFoundError, os.stat, support.TESTFN)
171 with open(TESTFN2, 'r') as f:
172 self.assertEqual(f.read(), "1")
173
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200174
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000175# Test attributes on return values from os.*stat* family.
176class StatAttributeTests(unittest.TestCase):
177 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000178 os.mkdir(support.TESTFN)
179 self.fname = os.path.join(support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000180 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +0000181 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000182 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000183
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000184 def tearDown(self):
185 os.unlink(self.fname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000186 os.rmdir(support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000187
Antoine Pitrou38425292010-09-21 18:19:07 +0000188 def check_stat_attributes(self, fname):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000189 if not hasattr(os, "stat"):
190 return
191
Antoine Pitrou38425292010-09-21 18:19:07 +0000192 result = os.stat(fname)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000193
194 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000195 self.assertEqual(result[stat.ST_SIZE], 3)
196 self.assertEqual(result.st_size, 3)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000197
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000198 # Make sure all the attributes are there
199 members = dir(result)
200 for name in dir(stat):
201 if name[:3] == 'ST_':
202 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000203 if name.endswith("TIME"):
204 def trunc(x): return int(x)
205 else:
206 def trunc(x): return x
Ezio Melottib3aedd42010-11-20 19:04:17 +0000207 self.assertEqual(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000208 result[getattr(stat, name)])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000209 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000210
Larry Hastings6fe20b32012-04-19 15:07:49 -0700211 # Make sure that the st_?time and st_?time_ns fields roughly agree
Larry Hastings76ad59b2012-05-03 00:30:07 -0700212 # (they should always agree up to around tens-of-microseconds)
Larry Hastings6fe20b32012-04-19 15:07:49 -0700213 for name in 'st_atime st_mtime st_ctime'.split():
214 floaty = int(getattr(result, name) * 100000)
215 nanosecondy = getattr(result, name + "_ns") // 10000
Larry Hastings76ad59b2012-05-03 00:30:07 -0700216 self.assertAlmostEqual(floaty, nanosecondy, delta=2)
Larry Hastings6fe20b32012-04-19 15:07:49 -0700217
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000218 try:
219 result[200]
Andrew Svetlov737fb892012-12-18 21:14:22 +0200220 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000221 except IndexError:
222 pass
223
224 # Make sure that assignment fails
225 try:
226 result.st_mode = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200227 self.fail("No exception raised")
Collin Winter42dae6a2007-03-28 21:44:53 +0000228 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000229 pass
230
231 try:
232 result.st_rdev = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200233 self.fail("No exception raised")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000234 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000235 pass
236
237 try:
238 result.parrot = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200239 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000240 except AttributeError:
241 pass
242
243 # Use the stat_result constructor with a too-short tuple.
244 try:
245 result2 = os.stat_result((10,))
Andrew Svetlov737fb892012-12-18 21:14:22 +0200246 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000247 except TypeError:
248 pass
249
Ezio Melotti42da6632011-03-15 05:18:48 +0200250 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000251 try:
252 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
253 except TypeError:
254 pass
255
Antoine Pitrou38425292010-09-21 18:19:07 +0000256 def test_stat_attributes(self):
257 self.check_stat_attributes(self.fname)
258
259 def test_stat_attributes_bytes(self):
260 try:
261 fname = self.fname.encode(sys.getfilesystemencoding())
262 except UnicodeEncodeError:
263 self.skipTest("cannot encode %a for the filesystem" % self.fname)
Victor Stinner1ab6c2d2011-11-15 22:27:41 +0100264 with warnings.catch_warnings():
265 warnings.simplefilter("ignore", DeprecationWarning)
266 self.check_stat_attributes(fname)
Tim Peterse0c446b2001-10-18 21:57:37 +0000267
Christian Heimes25827622013-10-12 01:27:08 +0200268 def test_stat_result_pickle(self):
269 result = os.stat(self.fname)
270 p = pickle.dumps(result)
271 self.assertIn(b'\x03cos\nstat_result\n', p)
272 unpickled = pickle.loads(p)
273 self.assertEqual(result, unpickled)
274
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000275 def test_statvfs_attributes(self):
276 if not hasattr(os, "statvfs"):
277 return
278
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000279 try:
280 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000281 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000282 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000283 if e.errno == errno.ENOSYS:
284 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000285
286 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000287 self.assertEqual(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000288
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000289 # Make sure all the attributes are there.
290 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
291 'ffree', 'favail', 'flag', 'namemax')
292 for value, member in enumerate(members):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000293 self.assertEqual(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000294
295 # Make sure that assignment really fails
296 try:
297 result.f_bfree = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200298 self.fail("No exception raised")
Collin Winter42dae6a2007-03-28 21:44:53 +0000299 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000300 pass
301
302 try:
303 result.parrot = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200304 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000305 except AttributeError:
306 pass
307
308 # Use the constructor with a too-short tuple.
309 try:
310 result2 = os.statvfs_result((10,))
Andrew Svetlov737fb892012-12-18 21:14:22 +0200311 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000312 except TypeError:
313 pass
314
Ezio Melotti42da6632011-03-15 05:18:48 +0200315 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000316 try:
317 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
318 except TypeError:
319 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000320
Christian Heimes25827622013-10-12 01:27:08 +0200321 @unittest.skipUnless(hasattr(os, 'statvfs'),
322 "need os.statvfs()")
323 def test_statvfs_result_pickle(self):
324 try:
325 result = os.statvfs(self.fname)
326 except OSError as e:
327 # On AtheOS, glibc always returns ENOSYS
328 if e.errno == errno.ENOSYS:
329 return
330 p = pickle.dumps(result)
331 self.assertIn(b'\x03cos\nstatvfs_result\n', p)
332 unpickled = pickle.loads(p)
333 self.assertEqual(result, unpickled)
334
Thomas Wouters89f507f2006-12-13 04:49:30 +0000335 def test_utime_dir(self):
336 delta = 1000000
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000337 st = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000338 # round to int, because some systems may support sub-second
339 # time stamps in stat, but not in utime.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000340 os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
341 st2 = os.stat(support.TESTFN)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000342 self.assertEqual(st2.st_mtime, int(st.st_mtime-delta))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000343
Larry Hastings76ad59b2012-05-03 00:30:07 -0700344 def _test_utime(self, filename, attr, utime, delta):
Brian Curtin0277aa32011-11-06 13:50:15 -0600345 # Issue #13327 removed the requirement to pass None as the
Brian Curtin52fbea12011-11-06 13:41:17 -0600346 # second argument. Check that the previous methods of passing
347 # a time tuple or None work in addition to no argument.
Larry Hastings76ad59b2012-05-03 00:30:07 -0700348 st0 = os.stat(filename)
Brian Curtin52fbea12011-11-06 13:41:17 -0600349 # Doesn't set anything new, but sets the time tuple way
Larry Hastings76ad59b2012-05-03 00:30:07 -0700350 utime(filename, (attr(st0, "st_atime"), attr(st0, "st_mtime")))
351 # Setting the time to the time you just read, then reading again,
352 # should always return exactly the same times.
353 st1 = os.stat(filename)
354 self.assertEqual(attr(st0, "st_mtime"), attr(st1, "st_mtime"))
355 self.assertEqual(attr(st0, "st_atime"), attr(st1, "st_atime"))
Brian Curtin52fbea12011-11-06 13:41:17 -0600356 # Set to the current time in the old explicit way.
Larry Hastings76ad59b2012-05-03 00:30:07 -0700357 os.utime(filename, None)
Brian Curtin52fbea12011-11-06 13:41:17 -0600358 st2 = os.stat(support.TESTFN)
Larry Hastings76ad59b2012-05-03 00:30:07 -0700359 # Set to the current time in the new way
360 os.utime(filename)
361 st3 = os.stat(filename)
362 self.assertAlmostEqual(attr(st2, "st_mtime"), attr(st3, "st_mtime"), delta=delta)
363
364 def test_utime(self):
365 def utime(file, times):
366 return os.utime(file, times)
367 self._test_utime(self.fname, getattr, utime, 10)
368 self._test_utime(support.TESTFN, getattr, utime, 10)
369
370
371 def _test_utime_ns(self, set_times_ns, test_dir=True):
372 def getattr_ns(o, attr):
373 return getattr(o, attr + "_ns")
374 ten_s = 10 * 1000 * 1000 * 1000
375 self._test_utime(self.fname, getattr_ns, set_times_ns, ten_s)
376 if test_dir:
377 self._test_utime(support.TESTFN, getattr_ns, set_times_ns, ten_s)
378
379 def test_utime_ns(self):
380 def utime_ns(file, times):
381 return os.utime(file, ns=times)
382 self._test_utime_ns(utime_ns)
383
Larry Hastings9cf065c2012-06-22 16:30:09 -0700384 requires_utime_dir_fd = unittest.skipUnless(
385 os.utime in os.supports_dir_fd,
386 "dir_fd support for utime required for this test.")
387 requires_utime_fd = unittest.skipUnless(
388 os.utime in os.supports_fd,
389 "fd support for utime required for this test.")
390 requires_utime_nofollow_symlinks = unittest.skipUnless(
391 os.utime in os.supports_follow_symlinks,
392 "follow_symlinks support for utime required for this test.")
Larry Hastings76ad59b2012-05-03 00:30:07 -0700393
Larry Hastings9cf065c2012-06-22 16:30:09 -0700394 @requires_utime_nofollow_symlinks
Larry Hastings76ad59b2012-05-03 00:30:07 -0700395 def test_lutimes_ns(self):
396 def lutimes_ns(file, times):
Larry Hastings9cf065c2012-06-22 16:30:09 -0700397 return os.utime(file, ns=times, follow_symlinks=False)
Larry Hastings76ad59b2012-05-03 00:30:07 -0700398 self._test_utime_ns(lutimes_ns)
399
Larry Hastings9cf065c2012-06-22 16:30:09 -0700400 @requires_utime_fd
Larry Hastings76ad59b2012-05-03 00:30:07 -0700401 def test_futimes_ns(self):
402 def futimes_ns(file, times):
403 with open(file, "wb") as f:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700404 os.utime(f.fileno(), ns=times)
Larry Hastings76ad59b2012-05-03 00:30:07 -0700405 self._test_utime_ns(futimes_ns, test_dir=False)
406
407 def _utime_invalid_arguments(self, name, arg):
Larry Hastings9cf065c2012-06-22 16:30:09 -0700408 with self.assertRaises(ValueError):
Larry Hastings76ad59b2012-05-03 00:30:07 -0700409 getattr(os, name)(arg, (5, 5), ns=(5, 5))
410
411 def test_utime_invalid_arguments(self):
412 self._utime_invalid_arguments('utime', self.fname)
413
Brian Curtin52fbea12011-11-06 13:41:17 -0600414
Victor Stinner1aa54a42012-02-08 04:09:37 +0100415 @unittest.skipUnless(stat_supports_subsecond,
416 "os.stat() doesn't has a subsecond resolution")
Victor Stinnera2f7c002012-02-08 03:36:25 +0100417 def _test_utime_subsecond(self, set_time_func):
Victor Stinnerbe557de2012-02-08 03:01:11 +0100418 asec, amsec = 1, 901
419 atime = asec + amsec * 1e-3
Victor Stinnera2f7c002012-02-08 03:36:25 +0100420 msec, mmsec = 2, 901
Victor Stinnerbe557de2012-02-08 03:01:11 +0100421 mtime = msec + mmsec * 1e-3
422 filename = self.fname
Victor Stinnera2f7c002012-02-08 03:36:25 +0100423 os.utime(filename, (0, 0))
424 set_time_func(filename, atime, mtime)
Victor Stinner034d0aa2012-06-05 01:22:15 +0200425 with warnings.catch_warnings():
426 warnings.simplefilter("ignore", DeprecationWarning)
427 os.stat_float_times(True)
Victor Stinnera2f7c002012-02-08 03:36:25 +0100428 st = os.stat(filename)
429 self.assertAlmostEqual(st.st_atime, atime, places=3)
430 self.assertAlmostEqual(st.st_mtime, mtime, places=3)
Victor Stinnerbe557de2012-02-08 03:01:11 +0100431
Victor Stinnera2f7c002012-02-08 03:36:25 +0100432 def test_utime_subsecond(self):
433 def set_time(filename, atime, mtime):
434 os.utime(filename, (atime, mtime))
435 self._test_utime_subsecond(set_time)
436
Larry Hastings9cf065c2012-06-22 16:30:09 -0700437 @requires_utime_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100438 def test_futimes_subsecond(self):
439 def set_time(filename, atime, mtime):
440 with open(filename, "wb") as f:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700441 os.utime(f.fileno(), times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100442 self._test_utime_subsecond(set_time)
443
Larry Hastings9cf065c2012-06-22 16:30:09 -0700444 @requires_utime_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100445 def test_futimens_subsecond(self):
446 def set_time(filename, atime, mtime):
447 with open(filename, "wb") as f:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700448 os.utime(f.fileno(), times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100449 self._test_utime_subsecond(set_time)
450
Larry Hastings9cf065c2012-06-22 16:30:09 -0700451 @requires_utime_dir_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100452 def test_futimesat_subsecond(self):
453 def set_time(filename, atime, mtime):
454 dirname = os.path.dirname(filename)
455 dirfd = os.open(dirname, os.O_RDONLY)
456 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700457 os.utime(os.path.basename(filename), dir_fd=dirfd,
458 times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100459 finally:
460 os.close(dirfd)
461 self._test_utime_subsecond(set_time)
462
Larry Hastings9cf065c2012-06-22 16:30:09 -0700463 @requires_utime_nofollow_symlinks
Victor Stinnera2f7c002012-02-08 03:36:25 +0100464 def test_lutimes_subsecond(self):
465 def set_time(filename, atime, mtime):
Larry Hastings9cf065c2012-06-22 16:30:09 -0700466 os.utime(filename, (atime, mtime), follow_symlinks=False)
Victor Stinnera2f7c002012-02-08 03:36:25 +0100467 self._test_utime_subsecond(set_time)
468
Larry Hastings9cf065c2012-06-22 16:30:09 -0700469 @requires_utime_dir_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100470 def test_utimensat_subsecond(self):
471 def set_time(filename, atime, mtime):
472 dirname = os.path.dirname(filename)
473 dirfd = os.open(dirname, os.O_RDONLY)
474 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700475 os.utime(os.path.basename(filename), dir_fd=dirfd,
476 times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100477 finally:
478 os.close(dirfd)
479 self._test_utime_subsecond(set_time)
Victor Stinnerbe557de2012-02-08 03:01:11 +0100480
Thomas Wouters89f507f2006-12-13 04:49:30 +0000481 # Restrict test to Win32, since there is no guarantee other
482 # systems support centiseconds
483 if sys.platform == 'win32':
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000484 def get_file_system(path):
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000485 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000486 import ctypes
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000487 kernel32 = ctypes.windll.kernel32
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000488 buf = ctypes.create_unicode_buffer("", 100)
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000489 if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000490 return buf.value
491
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000492 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000493 def test_1565150(self):
494 t1 = 1159195039.25
495 os.utime(self.fname, (t1, t1))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000496 self.assertEqual(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000497
Amaury Forgeot d'Arca251a852011-01-03 00:19:11 +0000498 def test_large_time(self):
499 t1 = 5000000000 # some day in 2128
500 os.utime(self.fname, (t1, t1))
501 self.assertEqual(os.stat(self.fname).st_mtime, t1)
502
Guido van Rossumd8faa362007-04-27 19:54:29 +0000503 def test_1686475(self):
504 # Verify that an open file can be stat'ed
505 try:
506 os.stat(r"c:\pagefile.sys")
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200507 except FileNotFoundError:
508 pass # file does not exist; cannot run test
509 except OSError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000510 self.fail("Could not stat pagefile.sys")
511
Richard Oudkerk2240ac12012-07-06 12:05:32 +0100512 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
513 def test_15261(self):
514 # Verify that stat'ing a closed fd does not cause crash
515 r, w = os.pipe()
516 try:
517 os.stat(r) # should not raise error
518 finally:
519 os.close(r)
520 os.close(w)
521 with self.assertRaises(OSError) as ctx:
522 os.stat(r)
523 self.assertEqual(ctx.exception.errno, errno.EBADF)
524
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000525from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000526
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000527class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000528 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000529 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000530
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000531 def setUp(self):
532 self.__save = dict(os.environ)
Victor Stinnerb745a742010-05-18 17:17:23 +0000533 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000534 self.__saveb = dict(os.environb)
Christian Heimes90333392007-11-01 19:08:42 +0000535 for key, value in self._reference().items():
536 os.environ[key] = value
537
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000538 def tearDown(self):
539 os.environ.clear()
540 os.environ.update(self.__save)
Victor Stinnerb745a742010-05-18 17:17:23 +0000541 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000542 os.environb.clear()
543 os.environb.update(self.__saveb)
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000544
Christian Heimes90333392007-11-01 19:08:42 +0000545 def _reference(self):
546 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
547
548 def _empty_mapping(self):
549 os.environ.clear()
550 return os.environ
551
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000552 # Bug 1110478
Ezio Melottic7e139b2012-09-26 20:01:34 +0300553 @unittest.skipUnless(os.path.exists('/bin/sh'), 'requires /bin/sh')
Martin v. Löwis5510f652005-02-17 21:23:20 +0000554 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000555 os.environ.clear()
Ezio Melottic7e139b2012-09-26 20:01:34 +0300556 os.environ.update(HELLO="World")
557 with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
558 value = popen.read().strip()
559 self.assertEqual(value, "World")
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000560
Ezio Melottic7e139b2012-09-26 20:01:34 +0300561 @unittest.skipUnless(os.path.exists('/bin/sh'), 'requires /bin/sh')
Christian Heimes1a13d592007-11-08 14:16:55 +0000562 def test_os_popen_iter(self):
Ezio Melottic7e139b2012-09-26 20:01:34 +0300563 with os.popen(
564 "/bin/sh -c 'echo \"line1\nline2\nline3\"'") as popen:
565 it = iter(popen)
566 self.assertEqual(next(it), "line1\n")
567 self.assertEqual(next(it), "line2\n")
568 self.assertEqual(next(it), "line3\n")
569 self.assertRaises(StopIteration, next, it)
Christian Heimes1a13d592007-11-08 14:16:55 +0000570
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000571 # Verify environ keys and values from the OS are of the
572 # correct str type.
573 def test_keyvalue_types(self):
574 for key, val in os.environ.items():
Ezio Melottib3aedd42010-11-20 19:04:17 +0000575 self.assertEqual(type(key), str)
576 self.assertEqual(type(val), str)
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000577
Christian Heimes90333392007-11-01 19:08:42 +0000578 def test_items(self):
579 for key, value in self._reference().items():
580 self.assertEqual(os.environ.get(key), value)
581
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000582 # Issue 7310
583 def test___repr__(self):
584 """Check that the repr() of os.environ looks like environ({...})."""
585 env = os.environ
Victor Stinner96f0de92010-07-29 00:29:00 +0000586 self.assertEqual(repr(env), 'environ({{{}}})'.format(', '.join(
587 '{!r}: {!r}'.format(key, value)
588 for key, value in env.items())))
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000589
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000590 def test_get_exec_path(self):
591 defpath_list = os.defpath.split(os.pathsep)
592 test_path = ['/monty', '/python', '', '/flying/circus']
593 test_env = {'PATH': os.pathsep.join(test_path)}
594
595 saved_environ = os.environ
596 try:
597 os.environ = dict(test_env)
598 # Test that defaulting to os.environ works.
599 self.assertSequenceEqual(test_path, os.get_exec_path())
600 self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
601 finally:
602 os.environ = saved_environ
603
604 # No PATH environment variable
605 self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
606 # Empty PATH environment variable
607 self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
608 # Supplied PATH environment variable
609 self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
610
Victor Stinnerb745a742010-05-18 17:17:23 +0000611 if os.supports_bytes_environ:
612 # env cannot contain 'PATH' and b'PATH' keys
Victor Stinner38430e22010-08-19 17:10:18 +0000613 try:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000614 # ignore BytesWarning warning
615 with warnings.catch_warnings(record=True):
616 mixed_env = {'PATH': '1', b'PATH': b'2'}
Victor Stinner38430e22010-08-19 17:10:18 +0000617 except BytesWarning:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000618 # mixed_env cannot be created with python -bb
Victor Stinner38430e22010-08-19 17:10:18 +0000619 pass
620 else:
621 self.assertRaises(ValueError, os.get_exec_path, mixed_env)
Victor Stinnerb745a742010-05-18 17:17:23 +0000622
623 # bytes key and/or value
624 self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}),
625 ['abc'])
626 self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}),
627 ['abc'])
628 self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}),
629 ['abc'])
630
631 @unittest.skipUnless(os.supports_bytes_environ,
632 "os.environb required for this test.")
Victor Stinner84ae1182010-05-06 22:05:07 +0000633 def test_environb(self):
634 # os.environ -> os.environb
635 value = 'euro\u20ac'
636 try:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000637 value_bytes = value.encode(sys.getfilesystemencoding(),
638 'surrogateescape')
Victor Stinner84ae1182010-05-06 22:05:07 +0000639 except UnicodeEncodeError:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000640 msg = "U+20AC character is not encodable to %s" % (
641 sys.getfilesystemencoding(),)
Benjamin Peterson932d3f42010-05-06 22:26:31 +0000642 self.skipTest(msg)
Victor Stinner84ae1182010-05-06 22:05:07 +0000643 os.environ['unicode'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000644 self.assertEqual(os.environ['unicode'], value)
645 self.assertEqual(os.environb[b'unicode'], value_bytes)
Victor Stinner84ae1182010-05-06 22:05:07 +0000646
647 # os.environb -> os.environ
648 value = b'\xff'
649 os.environb[b'bytes'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000650 self.assertEqual(os.environb[b'bytes'], value)
Victor Stinner84ae1182010-05-06 22:05:07 +0000651 value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000652 self.assertEqual(os.environ['bytes'], value_str)
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000653
Charles-François Natali2966f102011-11-26 11:32:46 +0100654 # On FreeBSD < 7 and OS X < 10.6, unsetenv() doesn't return a value (issue
655 # #13415).
656 @support.requires_freebsd_version(7)
657 @support.requires_mac_ver(10, 6)
Victor Stinner60b385e2011-11-22 22:01:28 +0100658 def test_unset_error(self):
659 if sys.platform == "win32":
660 # an environment variable is limited to 32,767 characters
661 key = 'x' * 50000
Victor Stinnerb3f82682011-11-22 22:30:19 +0100662 self.assertRaises(ValueError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100663 else:
664 # "=" is not allowed in a variable name
665 key = 'key='
Victor Stinnerb3f82682011-11-22 22:30:19 +0100666 self.assertRaises(OSError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100667
Victor Stinner6d101392013-04-14 16:35:04 +0200668 def test_key_type(self):
669 missing = 'missingkey'
670 self.assertNotIn(missing, os.environ)
671
Victor Stinner839e5ea2013-04-14 16:43:03 +0200672 with self.assertRaises(KeyError) as cm:
Victor Stinner6d101392013-04-14 16:35:04 +0200673 os.environ[missing]
Victor Stinner839e5ea2013-04-14 16:43:03 +0200674 self.assertIs(cm.exception.args[0], missing)
Victor Stinner0c2dd0c2013-08-23 19:19:15 +0200675 self.assertTrue(cm.exception.__suppress_context__)
Victor Stinner6d101392013-04-14 16:35:04 +0200676
Victor Stinner839e5ea2013-04-14 16:43:03 +0200677 with self.assertRaises(KeyError) as cm:
Victor Stinner6d101392013-04-14 16:35:04 +0200678 del os.environ[missing]
Victor Stinner839e5ea2013-04-14 16:43:03 +0200679 self.assertIs(cm.exception.args[0], missing)
Victor Stinner0c2dd0c2013-08-23 19:19:15 +0200680 self.assertTrue(cm.exception.__suppress_context__)
681
Victor Stinner6d101392013-04-14 16:35:04 +0200682
Tim Petersc4e09402003-04-25 07:11:48 +0000683class WalkTests(unittest.TestCase):
684 """Tests for os.walk()."""
685
Charles-François Natali7372b062012-02-05 15:15:38 +0100686 def setUp(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000687 import os
688 from os.path import join
689
690 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000691 # TESTFN/
692 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000693 # tmp1
694 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000695 # tmp2
696 # SUB11/ no kids
697 # SUB2/ a file kid and a dirsymlink kid
698 # tmp3
699 # link/ a symlink to TESTFN.2
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200700 # broken_link
Guido van Rossumd8faa362007-04-27 19:54:29 +0000701 # TEST2/
702 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000703 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000704 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000705 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000706 sub2_path = join(walk_path, "SUB2")
707 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000708 tmp2_path = join(sub1_path, "tmp2")
709 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000710 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000711 t2_path = join(support.TESTFN, "TEST2")
712 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200713 link_path = join(sub2_path, "link")
714 broken_link_path = join(sub2_path, "broken_link")
Tim Petersc4e09402003-04-25 07:11:48 +0000715
716 # Create stuff.
717 os.makedirs(sub11_path)
718 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000719 os.makedirs(t2_path)
720 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000721 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000722 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
723 f.close()
Brian Curtin3b4499c2010-12-28 14:31:47 +0000724 if support.can_symlink():
Jason R. Coombs3a092862013-05-27 23:21:28 -0400725 os.symlink(os.path.abspath(t2_path), link_path)
Jason R. Coombsb501b562013-05-27 23:52:43 -0400726 os.symlink('broken', broken_link_path, True)
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200727 sub2_tree = (sub2_path, ["link"], ["broken_link", "tmp3"])
Guido van Rossumd8faa362007-04-27 19:54:29 +0000728 else:
729 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000730
731 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000732 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000733 self.assertEqual(len(all), 4)
734 # We can't know which order SUB1 and SUB2 will appear in.
735 # Not flipped: TESTFN, SUB1, SUB11, SUB2
736 # flipped: TESTFN, SUB2, SUB1, SUB11
737 flipped = all[0][1][0] != "SUB1"
738 all[0][1].sort()
Hynek Schlawackc96f5a02012-05-15 17:55:38 +0200739 all[3 - 2 * flipped][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000740 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000741 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
742 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000743 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000744
745 # Prune the search.
746 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000747 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000748 all.append((root, dirs, files))
749 # Don't descend into SUB1.
750 if 'SUB1' in dirs:
751 # Note that this also mutates the dirs we appended to all!
752 dirs.remove('SUB1')
753 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000754 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Hynek Schlawack39bf90d2012-05-15 18:40:17 +0200755 all[1][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000756 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000757
758 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000759 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000760 self.assertEqual(len(all), 4)
761 # We can't know which order SUB1 and SUB2 will appear in.
762 # Not flipped: SUB11, SUB1, SUB2, TESTFN
763 # flipped: SUB2, SUB11, SUB1, TESTFN
764 flipped = all[3][1][0] != "SUB1"
765 all[3][1].sort()
Hynek Schlawack39bf90d2012-05-15 18:40:17 +0200766 all[2 - 2 * flipped][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000767 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000768 self.assertEqual(all[flipped], (sub11_path, [], []))
769 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000770 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000771
Brian Curtin3b4499c2010-12-28 14:31:47 +0000772 if support.can_symlink():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000773 # Walk, following symlinks.
774 for root, dirs, files in os.walk(walk_path, followlinks=True):
775 if root == link_path:
776 self.assertEqual(dirs, [])
777 self.assertEqual(files, ["tmp4"])
778 break
779 else:
780 self.fail("Didn't follow symlink with followlinks=True")
781
782 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000783 # Tear everything down. This is a decent use for bottom-up on
784 # Windows, which doesn't have a recursive delete command. The
785 # (not so) subtlety is that rmdir will fail unless the dir's
786 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000787 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000788 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000789 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000790 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000791 dirname = os.path.join(root, name)
792 if not os.path.islink(dirname):
793 os.rmdir(dirname)
794 else:
795 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000796 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000797
Charles-François Natali7372b062012-02-05 15:15:38 +0100798
799@unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
800class FwalkTests(WalkTests):
801 """Tests for os.fwalk()."""
802
Larry Hastingsc48fe982012-06-25 04:49:05 -0700803 def _compare_to_walk(self, walk_kwargs, fwalk_kwargs):
804 """
805 compare with walk() results.
806 """
Larry Hastingsb4038062012-07-15 10:57:38 -0700807 walk_kwargs = walk_kwargs.copy()
808 fwalk_kwargs = fwalk_kwargs.copy()
809 for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
810 walk_kwargs.update(topdown=topdown, followlinks=follow_symlinks)
811 fwalk_kwargs.update(topdown=topdown, follow_symlinks=follow_symlinks)
Larry Hastingsc48fe982012-06-25 04:49:05 -0700812
Charles-François Natali7372b062012-02-05 15:15:38 +0100813 expected = {}
Larry Hastingsc48fe982012-06-25 04:49:05 -0700814 for root, dirs, files in os.walk(**walk_kwargs):
Charles-François Natali7372b062012-02-05 15:15:38 +0100815 expected[root] = (set(dirs), set(files))
816
Larry Hastingsc48fe982012-06-25 04:49:05 -0700817 for root, dirs, files, rootfd in os.fwalk(**fwalk_kwargs):
Charles-François Natali7372b062012-02-05 15:15:38 +0100818 self.assertIn(root, expected)
819 self.assertEqual(expected[root], (set(dirs), set(files)))
820
Larry Hastingsc48fe982012-06-25 04:49:05 -0700821 def test_compare_to_walk(self):
822 kwargs = {'top': support.TESTFN}
823 self._compare_to_walk(kwargs, kwargs)
824
Charles-François Natali7372b062012-02-05 15:15:38 +0100825 def test_dir_fd(self):
Larry Hastingsc48fe982012-06-25 04:49:05 -0700826 try:
827 fd = os.open(".", os.O_RDONLY)
828 walk_kwargs = {'top': support.TESTFN}
829 fwalk_kwargs = walk_kwargs.copy()
830 fwalk_kwargs['dir_fd'] = fd
831 self._compare_to_walk(walk_kwargs, fwalk_kwargs)
832 finally:
833 os.close(fd)
834
835 def test_yields_correct_dir_fd(self):
Charles-François Natali7372b062012-02-05 15:15:38 +0100836 # check returned file descriptors
Larry Hastingsb4038062012-07-15 10:57:38 -0700837 for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
838 args = support.TESTFN, topdown, None
839 for root, dirs, files, rootfd in os.fwalk(*args, follow_symlinks=follow_symlinks):
Charles-François Natali7372b062012-02-05 15:15:38 +0100840 # check that the FD is valid
841 os.fstat(rootfd)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700842 # redundant check
843 os.stat(rootfd)
844 # check that listdir() returns consistent information
845 self.assertEqual(set(os.listdir(rootfd)), set(dirs) | set(files))
Charles-François Natali7372b062012-02-05 15:15:38 +0100846
847 def test_fd_leak(self):
848 # Since we're opening a lot of FDs, we must be careful to avoid leaks:
849 # we both check that calling fwalk() a large number of times doesn't
850 # yield EMFILE, and that the minimum allocated FD hasn't changed.
851 minfd = os.dup(1)
852 os.close(minfd)
853 for i in range(256):
854 for x in os.fwalk(support.TESTFN):
855 pass
856 newfd = os.dup(1)
857 self.addCleanup(os.close, newfd)
858 self.assertEqual(newfd, minfd)
859
860 def tearDown(self):
861 # cleanup
862 for root, dirs, files, rootfd in os.fwalk(support.TESTFN, topdown=False):
863 for name in files:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700864 os.unlink(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +0100865 for name in dirs:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700866 st = os.stat(name, dir_fd=rootfd, follow_symlinks=False)
Larry Hastingsb698d8e2012-06-23 16:55:07 -0700867 if stat.S_ISDIR(st.st_mode):
868 os.rmdir(name, dir_fd=rootfd)
869 else:
870 os.unlink(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +0100871 os.rmdir(support.TESTFN)
872
873
Guido van Rossume7ba4952007-06-06 23:52:48 +0000874class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000875 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000876 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000877
878 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000879 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000880 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
881 os.makedirs(path) # Should work
882 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
883 os.makedirs(path)
884
885 # Try paths with a '.' in them
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000886 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000887 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
888 os.makedirs(path)
889 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
890 'dir5', 'dir6')
891 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000892
Terry Reedy5a22b652010-12-02 07:05:56 +0000893 def test_exist_ok_existing_directory(self):
894 path = os.path.join(support.TESTFN, 'dir1')
895 mode = 0o777
896 old_mask = os.umask(0o022)
897 os.makedirs(path, mode)
898 self.assertRaises(OSError, os.makedirs, path, mode)
899 self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
900 self.assertRaises(OSError, os.makedirs, path, 0o776, exist_ok=True)
901 os.makedirs(path, mode=mode, exist_ok=True)
902 os.umask(old_mask)
903
Terry Jan Reedy4a0b6f72013-08-10 20:58:59 -0400904 @unittest.skipUnless(hasattr(os, 'chown'), 'test needs os.chown')
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700905 def test_chown_uid_gid_arguments_must_be_index(self):
906 stat = os.stat(support.TESTFN)
907 uid = stat.st_uid
908 gid = stat.st_gid
909 for value in (-1.0, -1j, decimal.Decimal(-1), fractions.Fraction(-2, 2)):
910 self.assertRaises(TypeError, os.chown, support.TESTFN, value, gid)
911 self.assertRaises(TypeError, os.chown, support.TESTFN, uid, value)
912 self.assertIsNone(os.chown(support.TESTFN, uid, gid))
913 self.assertIsNone(os.chown(support.TESTFN, -1, -1))
914
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700915 def test_exist_ok_s_isgid_directory(self):
916 path = os.path.join(support.TESTFN, 'dir1')
917 S_ISGID = stat.S_ISGID
918 mode = 0o777
919 old_mask = os.umask(0o022)
920 try:
921 existing_testfn_mode = stat.S_IMODE(
922 os.lstat(support.TESTFN).st_mode)
Ned Deilyc622f422012-08-08 20:57:24 -0700923 try:
924 os.chmod(support.TESTFN, existing_testfn_mode | S_ISGID)
Ned Deily3a2b97e2012-08-08 21:03:02 -0700925 except PermissionError:
Ned Deilyc622f422012-08-08 20:57:24 -0700926 raise unittest.SkipTest('Cannot set S_ISGID for dir.')
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700927 if (os.lstat(support.TESTFN).st_mode & S_ISGID != S_ISGID):
928 raise unittest.SkipTest('No support for S_ISGID dir mode.')
929 # The os should apply S_ISGID from the parent dir for us, but
930 # this test need not depend on that behavior. Be explicit.
931 os.makedirs(path, mode | S_ISGID)
932 # http://bugs.python.org/issue14992
933 # Should not fail when the bit is already set.
934 os.makedirs(path, mode, exist_ok=True)
935 # remove the bit.
936 os.chmod(path, stat.S_IMODE(os.lstat(path).st_mode) & ~S_ISGID)
937 with self.assertRaises(OSError):
938 # Should fail when the bit is not already set when demanded.
939 os.makedirs(path, mode | S_ISGID, exist_ok=True)
940 finally:
941 os.umask(old_mask)
Terry Reedy5a22b652010-12-02 07:05:56 +0000942
943 def test_exist_ok_existing_regular_file(self):
944 base = support.TESTFN
945 path = os.path.join(support.TESTFN, 'dir1')
946 f = open(path, 'w')
947 f.write('abc')
948 f.close()
949 self.assertRaises(OSError, os.makedirs, path)
950 self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
951 self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
952 os.remove(path)
953
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000954 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000955 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000956 'dir4', 'dir5', 'dir6')
957 # If the tests failed, the bottom-most directory ('../dir6')
958 # may not have been created, so we look for the outermost directory
959 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000960 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000961 path = os.path.dirname(path)
962
963 os.removedirs(path)
964
Andrew Svetlov405faed2012-12-25 12:18:09 +0200965
966class RemoveDirsTests(unittest.TestCase):
967 def setUp(self):
968 os.makedirs(support.TESTFN)
969
970 def tearDown(self):
971 support.rmtree(support.TESTFN)
972
973 def test_remove_all(self):
974 dira = os.path.join(support.TESTFN, 'dira')
975 os.mkdir(dira)
976 dirb = os.path.join(dira, 'dirb')
977 os.mkdir(dirb)
978 os.removedirs(dirb)
979 self.assertFalse(os.path.exists(dirb))
980 self.assertFalse(os.path.exists(dira))
981 self.assertFalse(os.path.exists(support.TESTFN))
982
983 def test_remove_partial(self):
984 dira = os.path.join(support.TESTFN, 'dira')
985 os.mkdir(dira)
986 dirb = os.path.join(dira, 'dirb')
987 os.mkdir(dirb)
988 with open(os.path.join(dira, 'file.txt'), 'w') as f:
989 f.write('text')
990 os.removedirs(dirb)
991 self.assertFalse(os.path.exists(dirb))
992 self.assertTrue(os.path.exists(dira))
993 self.assertTrue(os.path.exists(support.TESTFN))
994
995 def test_remove_nothing(self):
996 dira = os.path.join(support.TESTFN, 'dira')
997 os.mkdir(dira)
998 dirb = os.path.join(dira, 'dirb')
999 os.mkdir(dirb)
1000 with open(os.path.join(dirb, 'file.txt'), 'w') as f:
1001 f.write('text')
1002 with self.assertRaises(OSError):
1003 os.removedirs(dirb)
1004 self.assertTrue(os.path.exists(dirb))
1005 self.assertTrue(os.path.exists(dira))
1006 self.assertTrue(os.path.exists(support.TESTFN))
1007
1008
Guido van Rossume7ba4952007-06-06 23:52:48 +00001009class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +00001010 def test_devnull(self):
Victor Stinnera6d2c762011-06-30 18:20:11 +02001011 with open(os.devnull, 'wb') as f:
1012 f.write(b'hello')
1013 f.close()
1014 with open(os.devnull, 'rb') as f:
1015 self.assertEqual(f.read(), b'')
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00001016
Andrew Svetlov405faed2012-12-25 12:18:09 +02001017
Guido van Rossume7ba4952007-06-06 23:52:48 +00001018class URandomTests(unittest.TestCase):
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001019 def test_urandom_length(self):
1020 self.assertEqual(len(os.urandom(0)), 0)
1021 self.assertEqual(len(os.urandom(1)), 1)
1022 self.assertEqual(len(os.urandom(10)), 10)
1023 self.assertEqual(len(os.urandom(100)), 100)
1024 self.assertEqual(len(os.urandom(1000)), 1000)
1025
1026 def test_urandom_value(self):
1027 data1 = os.urandom(16)
1028 data2 = os.urandom(16)
1029 self.assertNotEqual(data1, data2)
1030
1031 def get_urandom_subprocess(self, count):
1032 code = '\n'.join((
1033 'import os, sys',
1034 'data = os.urandom(%s)' % count,
1035 'sys.stdout.buffer.write(data)',
1036 'sys.stdout.buffer.flush()'))
1037 out = assert_python_ok('-c', code)
1038 stdout = out[1]
1039 self.assertEqual(len(stdout), 16)
1040 return stdout
1041
1042 def test_urandom_subprocess(self):
1043 data1 = self.get_urandom_subprocess(16)
1044 data2 = self.get_urandom_subprocess(16)
1045 self.assertNotEqual(data1, data2)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +00001046
Antoine Pitrouec34ab52013-08-16 20:44:38 +02001047 @unittest.skipUnless(resource, "test requires the resource module")
1048 def test_urandom_failure(self):
Antoine Pitroueba25ba2013-08-24 20:52:27 +02001049 # Check urandom() failing when it is not able to open /dev/random.
1050 # We spawn a new process to make the test more robust (if getrlimit()
1051 # failed to restore the file descriptor limit after this, the whole
1052 # test suite would crash; this actually happened on the OS X Tiger
1053 # buildbot).
1054 code = """if 1:
1055 import errno
1056 import os
1057 import resource
1058
1059 soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
1060 resource.setrlimit(resource.RLIMIT_NOFILE, (1, hard_limit))
1061 try:
Antoine Pitrouec34ab52013-08-16 20:44:38 +02001062 os.urandom(16)
Antoine Pitroueba25ba2013-08-24 20:52:27 +02001063 except OSError as e:
1064 assert e.errno == errno.EMFILE, e.errno
1065 else:
1066 raise AssertionError("OSError not raised")
1067 """
1068 assert_python_ok('-c', code)
Antoine Pitrouec34ab52013-08-16 20:44:38 +02001069
1070
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001071@contextlib.contextmanager
1072def _execvpe_mockup(defpath=None):
1073 """
1074 Stubs out execv and execve functions when used as context manager.
1075 Records exec calls. The mock execv and execve functions always raise an
1076 exception as they would normally never return.
1077 """
1078 # A list of tuples containing (function name, first arg, args)
1079 # of calls to execv or execve that have been made.
1080 calls = []
1081
1082 def mock_execv(name, *args):
1083 calls.append(('execv', name, args))
1084 raise RuntimeError("execv called")
1085
1086 def mock_execve(name, *args):
1087 calls.append(('execve', name, args))
1088 raise OSError(errno.ENOTDIR, "execve called")
1089
1090 try:
1091 orig_execv = os.execv
1092 orig_execve = os.execve
1093 orig_defpath = os.defpath
1094 os.execv = mock_execv
1095 os.execve = mock_execve
1096 if defpath is not None:
1097 os.defpath = defpath
1098 yield calls
1099 finally:
1100 os.execv = orig_execv
1101 os.execve = orig_execve
1102 os.defpath = orig_defpath
1103
Guido van Rossume7ba4952007-06-06 23:52:48 +00001104class ExecTests(unittest.TestCase):
Mark Dickinson7cf03892010-04-16 13:45:35 +00001105 @unittest.skipIf(USING_LINUXTHREADS,
1106 "avoid triggering a linuxthreads bug: see issue #4970")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001107 def test_execvpe_with_bad_program(self):
Mark Dickinson7cf03892010-04-16 13:45:35 +00001108 self.assertRaises(OSError, os.execvpe, 'no such app-',
1109 ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001110
Thomas Heller6790d602007-08-30 17:15:14 +00001111 def test_execvpe_with_bad_arglist(self):
1112 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
1113
Gregory P. Smith4ae37772010-05-08 18:05:46 +00001114 @unittest.skipUnless(hasattr(os, '_execvpe'),
1115 "No internal os._execvpe function to test.")
Victor Stinnerb745a742010-05-18 17:17:23 +00001116 def _test_internal_execvpe(self, test_type):
1117 program_path = os.sep + 'absolutepath'
1118 if test_type is bytes:
1119 program = b'executable'
1120 fullpath = os.path.join(os.fsencode(program_path), program)
1121 native_fullpath = fullpath
1122 arguments = [b'progname', 'arg1', 'arg2']
1123 else:
1124 program = 'executable'
1125 arguments = ['progname', 'arg1', 'arg2']
1126 fullpath = os.path.join(program_path, program)
1127 if os.name != "nt":
1128 native_fullpath = os.fsencode(fullpath)
1129 else:
1130 native_fullpath = fullpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001131 env = {'spam': 'beans'}
1132
Victor Stinnerb745a742010-05-18 17:17:23 +00001133 # test os._execvpe() with an absolute path
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001134 with _execvpe_mockup() as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +00001135 self.assertRaises(RuntimeError,
1136 os._execvpe, fullpath, arguments)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001137 self.assertEqual(len(calls), 1)
1138 self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))
1139
Victor Stinnerb745a742010-05-18 17:17:23 +00001140 # test os._execvpe() with a relative path:
1141 # os.get_exec_path() returns defpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001142 with _execvpe_mockup(defpath=program_path) as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +00001143 self.assertRaises(OSError,
1144 os._execvpe, program, arguments, env=env)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001145 self.assertEqual(len(calls), 1)
Victor Stinnerb745a742010-05-18 17:17:23 +00001146 self.assertSequenceEqual(calls[0],
1147 ('execve', native_fullpath, (arguments, env)))
1148
1149 # test os._execvpe() with a relative path:
1150 # os.get_exec_path() reads the 'PATH' variable
1151 with _execvpe_mockup() as calls:
1152 env_path = env.copy()
Victor Stinner38430e22010-08-19 17:10:18 +00001153 if test_type is bytes:
1154 env_path[b'PATH'] = program_path
1155 else:
1156 env_path['PATH'] = program_path
Victor Stinnerb745a742010-05-18 17:17:23 +00001157 self.assertRaises(OSError,
1158 os._execvpe, program, arguments, env=env_path)
1159 self.assertEqual(len(calls), 1)
1160 self.assertSequenceEqual(calls[0],
1161 ('execve', native_fullpath, (arguments, env_path)))
1162
1163 def test_internal_execvpe_str(self):
1164 self._test_internal_execvpe(str)
1165 if os.name != "nt":
1166 self._test_internal_execvpe(bytes)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001167
Gregory P. Smith4ae37772010-05-08 18:05:46 +00001168
Thomas Wouters477c8d52006-05-27 19:21:47 +00001169class Win32ErrorTests(unittest.TestCase):
1170 def test_rename(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001171 self.assertRaises(OSError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001172
1173 def test_remove(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001174 self.assertRaises(OSError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001175
1176 def test_chdir(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001177 self.assertRaises(OSError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001178
1179 def test_mkdir(self):
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +00001180 f = open(support.TESTFN, "w")
Benjamin Petersonf91df042009-02-13 02:50:59 +00001181 try:
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001182 self.assertRaises(OSError, os.mkdir, support.TESTFN)
Benjamin Petersonf91df042009-02-13 02:50:59 +00001183 finally:
1184 f.close()
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +00001185 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001186
1187 def test_utime(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001188 self.assertRaises(OSError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001189
Thomas Wouters477c8d52006-05-27 19:21:47 +00001190 def test_chmod(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001191 self.assertRaises(OSError, os.chmod, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001192
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001193class TestInvalidFD(unittest.TestCase):
Benjamin Peterson05e782f2009-01-19 15:15:02 +00001194 singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001195 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
1196 #singles.append("close")
1197 #We omit close because it doesn'r raise an exception on some platforms
1198 def get_single(f):
1199 def helper(self):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001200 if hasattr(os, f):
1201 self.check(getattr(os, f))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001202 return helper
1203 for f in singles:
1204 locals()["test_"+f] = get_single(f)
1205
Benjamin Peterson7522c742009-01-19 21:00:09 +00001206 def check(self, f, *args):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001207 try:
1208 f(support.make_bad_fd(), *args)
1209 except OSError as e:
1210 self.assertEqual(e.errno, errno.EBADF)
1211 else:
1212 self.fail("%r didn't raise a OSError with a bad file descriptor"
1213 % f)
Benjamin Peterson7522c742009-01-19 21:00:09 +00001214
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001215 def test_isatty(self):
1216 if hasattr(os, "isatty"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001217 self.assertEqual(os.isatty(support.make_bad_fd()), False)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001218
1219 def test_closerange(self):
1220 if hasattr(os, "closerange"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001221 fd = support.make_bad_fd()
R. David Murray630cc482009-07-22 15:20:27 +00001222 # Make sure none of the descriptors we are about to close are
1223 # currently valid (issue 6542).
1224 for i in range(10):
1225 try: os.fstat(fd+i)
1226 except OSError:
1227 pass
1228 else:
1229 break
1230 if i < 2:
1231 raise unittest.SkipTest(
1232 "Unable to acquire a range of invalid file descriptors")
1233 self.assertEqual(os.closerange(fd, fd + i-1), None)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001234
1235 def test_dup2(self):
1236 if hasattr(os, "dup2"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001237 self.check(os.dup2, 20)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001238
1239 def test_fchmod(self):
1240 if hasattr(os, "fchmod"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001241 self.check(os.fchmod, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001242
1243 def test_fchown(self):
1244 if hasattr(os, "fchown"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001245 self.check(os.fchown, -1, -1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001246
1247 def test_fpathconf(self):
1248 if hasattr(os, "fpathconf"):
Georg Brandl306336b2012-06-24 12:55:33 +02001249 self.check(os.pathconf, "PC_NAME_MAX")
Benjamin Peterson7522c742009-01-19 21:00:09 +00001250 self.check(os.fpathconf, "PC_NAME_MAX")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001251
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001252 def test_ftruncate(self):
1253 if hasattr(os, "ftruncate"):
Georg Brandl306336b2012-06-24 12:55:33 +02001254 self.check(os.truncate, 0)
Benjamin Peterson7522c742009-01-19 21:00:09 +00001255 self.check(os.ftruncate, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001256
1257 def test_lseek(self):
1258 if hasattr(os, "lseek"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001259 self.check(os.lseek, 0, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001260
1261 def test_read(self):
1262 if hasattr(os, "read"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001263 self.check(os.read, 1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001264
1265 def test_tcsetpgrpt(self):
1266 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001267 self.check(os.tcsetpgrp, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001268
1269 def test_write(self):
1270 if hasattr(os, "write"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001271 self.check(os.write, b" ")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001272
Brian Curtin1b9df392010-11-24 20:24:31 +00001273
1274class LinkTests(unittest.TestCase):
1275 def setUp(self):
1276 self.file1 = support.TESTFN
1277 self.file2 = os.path.join(support.TESTFN + "2")
1278
Brian Curtinc0abc4e2010-11-30 23:46:54 +00001279 def tearDown(self):
Brian Curtin1b9df392010-11-24 20:24:31 +00001280 for file in (self.file1, self.file2):
1281 if os.path.exists(file):
1282 os.unlink(file)
1283
Brian Curtin1b9df392010-11-24 20:24:31 +00001284 def _test_link(self, file1, file2):
1285 with open(file1, "w") as f1:
1286 f1.write("test")
1287
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001288 with warnings.catch_warnings():
1289 warnings.simplefilter("ignore", DeprecationWarning)
1290 os.link(file1, file2)
Brian Curtin1b9df392010-11-24 20:24:31 +00001291 with open(file1, "r") as f1, open(file2, "r") as f2:
1292 self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
1293
1294 def test_link(self):
1295 self._test_link(self.file1, self.file2)
1296
1297 def test_link_bytes(self):
1298 self._test_link(bytes(self.file1, sys.getfilesystemencoding()),
1299 bytes(self.file2, sys.getfilesystemencoding()))
1300
Brian Curtinf498b752010-11-30 15:54:04 +00001301 def test_unicode_name(self):
Brian Curtin43f0c272010-11-30 15:40:04 +00001302 try:
Brian Curtinf498b752010-11-30 15:54:04 +00001303 os.fsencode("\xf1")
Brian Curtin43f0c272010-11-30 15:40:04 +00001304 except UnicodeError:
1305 raise unittest.SkipTest("Unable to encode for this platform.")
1306
Brian Curtinf498b752010-11-30 15:54:04 +00001307 self.file1 += "\xf1"
Brian Curtinfc889c42010-11-28 23:59:46 +00001308 self.file2 = self.file1 + "2"
1309 self._test_link(self.file1, self.file2)
1310
Thomas Wouters477c8d52006-05-27 19:21:47 +00001311if sys.platform != 'win32':
1312 class Win32ErrorTests(unittest.TestCase):
1313 pass
1314
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001315 class PosixUidGidTests(unittest.TestCase):
1316 if hasattr(os, 'setuid'):
1317 def test_setuid(self):
1318 if os.getuid() != 0:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001319 self.assertRaises(OSError, os.setuid, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001320 self.assertRaises(OverflowError, os.setuid, 1<<32)
1321
1322 if hasattr(os, 'setgid'):
1323 def test_setgid(self):
Stefan Krahebee49a2013-01-17 15:31:00 +01001324 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001325 self.assertRaises(OSError, os.setgid, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001326 self.assertRaises(OverflowError, os.setgid, 1<<32)
1327
1328 if hasattr(os, 'seteuid'):
1329 def test_seteuid(self):
1330 if os.getuid() != 0:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001331 self.assertRaises(OSError, os.seteuid, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001332 self.assertRaises(OverflowError, os.seteuid, 1<<32)
1333
1334 if hasattr(os, 'setegid'):
1335 def test_setegid(self):
Stefan Krahebee49a2013-01-17 15:31:00 +01001336 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001337 self.assertRaises(OSError, os.setegid, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001338 self.assertRaises(OverflowError, os.setegid, 1<<32)
1339
1340 if hasattr(os, 'setreuid'):
1341 def test_setreuid(self):
1342 if os.getuid() != 0:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001343 self.assertRaises(OSError, os.setreuid, 0, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001344 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
1345 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001346
1347 def test_setreuid_neg1(self):
1348 # Needs to accept -1. We run this in a subprocess to avoid
1349 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001350 subprocess.check_call([
1351 sys.executable, '-c',
1352 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001353
1354 if hasattr(os, 'setregid'):
1355 def test_setregid(self):
Stefan Krahebee49a2013-01-17 15:31:00 +01001356 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001357 self.assertRaises(OSError, os.setregid, 0, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001358 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
1359 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001360
1361 def test_setregid_neg1(self):
1362 # Needs to accept -1. We run this in a subprocess to avoid
1363 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001364 subprocess.check_call([
1365 sys.executable, '-c',
1366 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Martin v. Löwis011e8422009-05-05 04:43:17 +00001367
1368 class Pep383Tests(unittest.TestCase):
Martin v. Löwis011e8422009-05-05 04:43:17 +00001369 def setUp(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001370 if support.TESTFN_UNENCODABLE:
1371 self.dir = support.TESTFN_UNENCODABLE
Victor Stinner8b219b22012-11-06 23:23:43 +01001372 elif support.TESTFN_NONASCII:
1373 self.dir = support.TESTFN_NONASCII
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001374 else:
1375 self.dir = support.TESTFN
1376 self.bdir = os.fsencode(self.dir)
1377
1378 bytesfn = []
1379 def add_filename(fn):
1380 try:
1381 fn = os.fsencode(fn)
1382 except UnicodeEncodeError:
1383 return
1384 bytesfn.append(fn)
1385 add_filename(support.TESTFN_UNICODE)
1386 if support.TESTFN_UNENCODABLE:
1387 add_filename(support.TESTFN_UNENCODABLE)
Victor Stinner8b219b22012-11-06 23:23:43 +01001388 if support.TESTFN_NONASCII:
1389 add_filename(support.TESTFN_NONASCII)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001390 if not bytesfn:
1391 self.skipTest("couldn't create any non-ascii filename")
1392
1393 self.unicodefn = set()
Martin v. Löwis011e8422009-05-05 04:43:17 +00001394 os.mkdir(self.dir)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001395 try:
1396 for fn in bytesfn:
Victor Stinnerbf816222011-06-30 23:25:47 +02001397 support.create_empty_file(os.path.join(self.bdir, fn))
Victor Stinnere8d51452010-08-19 01:05:19 +00001398 fn = os.fsdecode(fn)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001399 if fn in self.unicodefn:
1400 raise ValueError("duplicate filename")
1401 self.unicodefn.add(fn)
1402 except:
1403 shutil.rmtree(self.dir)
1404 raise
Martin v. Löwis011e8422009-05-05 04:43:17 +00001405
1406 def tearDown(self):
1407 shutil.rmtree(self.dir)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001408
1409 def test_listdir(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001410 expected = self.unicodefn
1411 found = set(os.listdir(self.dir))
Ezio Melottib3aedd42010-11-20 19:04:17 +00001412 self.assertEqual(found, expected)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001413 # test listdir without arguments
1414 current_directory = os.getcwd()
1415 try:
1416 os.chdir(os.sep)
1417 self.assertEqual(set(os.listdir()), set(os.listdir(os.sep)))
1418 finally:
1419 os.chdir(current_directory)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001420
1421 def test_open(self):
1422 for fn in self.unicodefn:
Victor Stinnera6d2c762011-06-30 18:20:11 +02001423 f = open(os.path.join(self.dir, fn), 'rb')
Martin v. Löwis011e8422009-05-05 04:43:17 +00001424 f.close()
1425
Victor Stinnere4110dc2013-01-01 23:05:55 +01001426 @unittest.skipUnless(hasattr(os, 'statvfs'),
1427 "need os.statvfs()")
1428 def test_statvfs(self):
1429 # issue #9645
1430 for fn in self.unicodefn:
1431 # should not fail with file not found error
1432 fullname = os.path.join(self.dir, fn)
1433 os.statvfs(fullname)
1434
Martin v. Löwis011e8422009-05-05 04:43:17 +00001435 def test_stat(self):
1436 for fn in self.unicodefn:
1437 os.stat(os.path.join(self.dir, fn))
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001438else:
1439 class PosixUidGidTests(unittest.TestCase):
1440 pass
Martin v. Löwis011e8422009-05-05 04:43:17 +00001441 class Pep383Tests(unittest.TestCase):
1442 pass
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001443
Brian Curtineb24d742010-04-12 17:16:38 +00001444@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
1445class Win32KillTests(unittest.TestCase):
Brian Curtinc3acbc32010-05-28 16:08:40 +00001446 def _kill(self, sig):
1447 # Start sys.executable as a subprocess and communicate from the
1448 # subprocess to the parent that the interpreter is ready. When it
1449 # becomes ready, send *sig* via os.kill to the subprocess and check
1450 # that the return code is equal to *sig*.
1451 import ctypes
1452 from ctypes import wintypes
1453 import msvcrt
1454
1455 # Since we can't access the contents of the process' stdout until the
1456 # process has exited, use PeekNamedPipe to see what's inside stdout
1457 # without waiting. This is done so we can tell that the interpreter
1458 # is started and running at a point where it could handle a signal.
1459 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
1460 PeekNamedPipe.restype = wintypes.BOOL
1461 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
1462 ctypes.POINTER(ctypes.c_char), # stdout buf
1463 wintypes.DWORD, # Buffer size
1464 ctypes.POINTER(wintypes.DWORD), # bytes read
1465 ctypes.POINTER(wintypes.DWORD), # bytes avail
1466 ctypes.POINTER(wintypes.DWORD)) # bytes left
1467 msg = "running"
1468 proc = subprocess.Popen([sys.executable, "-c",
1469 "import sys;"
1470 "sys.stdout.write('{}');"
1471 "sys.stdout.flush();"
1472 "input()".format(msg)],
1473 stdout=subprocess.PIPE,
1474 stderr=subprocess.PIPE,
1475 stdin=subprocess.PIPE)
Brian Curtin43ec5772010-11-05 15:17:11 +00001476 self.addCleanup(proc.stdout.close)
1477 self.addCleanup(proc.stderr.close)
1478 self.addCleanup(proc.stdin.close)
Brian Curtinc3acbc32010-05-28 16:08:40 +00001479
1480 count, max = 0, 100
1481 while count < max and proc.poll() is None:
1482 # Create a string buffer to store the result of stdout from the pipe
1483 buf = ctypes.create_string_buffer(len(msg))
1484 # Obtain the text currently in proc.stdout
1485 # Bytes read/avail/left are left as NULL and unused
1486 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
1487 buf, ctypes.sizeof(buf), None, None, None)
1488 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
1489 if buf.value:
1490 self.assertEqual(msg, buf.value.decode())
1491 break
1492 time.sleep(0.1)
1493 count += 1
1494 else:
1495 self.fail("Did not receive communication from the subprocess")
1496
Brian Curtineb24d742010-04-12 17:16:38 +00001497 os.kill(proc.pid, sig)
1498 self.assertEqual(proc.wait(), sig)
1499
1500 def test_kill_sigterm(self):
1501 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinc3acbc32010-05-28 16:08:40 +00001502 self._kill(signal.SIGTERM)
Brian Curtineb24d742010-04-12 17:16:38 +00001503
1504 def test_kill_int(self):
1505 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinc3acbc32010-05-28 16:08:40 +00001506 self._kill(100)
Brian Curtineb24d742010-04-12 17:16:38 +00001507
1508 def _kill_with_event(self, event, name):
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001509 tagname = "test_os_%s" % uuid.uuid1()
1510 m = mmap.mmap(-1, 1, tagname)
1511 m[0] = 0
Brian Curtineb24d742010-04-12 17:16:38 +00001512 # Run a script which has console control handling enabled.
1513 proc = subprocess.Popen([sys.executable,
1514 os.path.join(os.path.dirname(__file__),
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001515 "win_console_handler.py"), tagname],
Brian Curtineb24d742010-04-12 17:16:38 +00001516 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
1517 # Let the interpreter startup before we send signals. See #3137.
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001518 count, max = 0, 100
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001519 while count < max and proc.poll() is None:
Brian Curtinf668df52010-10-15 14:21:06 +00001520 if m[0] == 1:
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001521 break
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001522 time.sleep(0.1)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001523 count += 1
1524 else:
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001525 # Forcefully kill the process if we weren't able to signal it.
1526 os.kill(proc.pid, signal.SIGINT)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001527 self.fail("Subprocess didn't finish initialization")
Brian Curtineb24d742010-04-12 17:16:38 +00001528 os.kill(proc.pid, event)
1529 # proc.send_signal(event) could also be done here.
1530 # Allow time for the signal to be passed and the process to exit.
1531 time.sleep(0.5)
1532 if not proc.poll():
1533 # Forcefully kill the process if we weren't able to signal it.
1534 os.kill(proc.pid, signal.SIGINT)
1535 self.fail("subprocess did not stop on {}".format(name))
1536
1537 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
1538 def test_CTRL_C_EVENT(self):
1539 from ctypes import wintypes
1540 import ctypes
1541
1542 # Make a NULL value by creating a pointer with no argument.
1543 NULL = ctypes.POINTER(ctypes.c_int)()
1544 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
1545 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
1546 wintypes.BOOL)
1547 SetConsoleCtrlHandler.restype = wintypes.BOOL
1548
1549 # Calling this with NULL and FALSE causes the calling process to
1550 # handle CTRL+C, rather than ignore it. This property is inherited
1551 # by subprocesses.
1552 SetConsoleCtrlHandler(NULL, 0)
1553
1554 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
1555
1556 def test_CTRL_BREAK_EVENT(self):
1557 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
1558
1559
Brian Curtind40e6f72010-07-08 21:39:08 +00001560@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Brian Curtin3b4499c2010-12-28 14:31:47 +00001561@support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +00001562class Win32SymlinkTests(unittest.TestCase):
1563 filelink = 'filelinktest'
1564 filelink_target = os.path.abspath(__file__)
1565 dirlink = 'dirlinktest'
1566 dirlink_target = os.path.dirname(filelink_target)
1567 missing_link = 'missing link'
1568
1569 def setUp(self):
1570 assert os.path.exists(self.dirlink_target)
1571 assert os.path.exists(self.filelink_target)
1572 assert not os.path.exists(self.dirlink)
1573 assert not os.path.exists(self.filelink)
1574 assert not os.path.exists(self.missing_link)
1575
1576 def tearDown(self):
1577 if os.path.exists(self.filelink):
1578 os.remove(self.filelink)
1579 if os.path.exists(self.dirlink):
1580 os.rmdir(self.dirlink)
1581 if os.path.lexists(self.missing_link):
1582 os.remove(self.missing_link)
1583
1584 def test_directory_link(self):
Jason R. Coombs3a092862013-05-27 23:21:28 -04001585 os.symlink(self.dirlink_target, self.dirlink)
Brian Curtind40e6f72010-07-08 21:39:08 +00001586 self.assertTrue(os.path.exists(self.dirlink))
1587 self.assertTrue(os.path.isdir(self.dirlink))
1588 self.assertTrue(os.path.islink(self.dirlink))
1589 self.check_stat(self.dirlink, self.dirlink_target)
1590
1591 def test_file_link(self):
1592 os.symlink(self.filelink_target, self.filelink)
1593 self.assertTrue(os.path.exists(self.filelink))
1594 self.assertTrue(os.path.isfile(self.filelink))
1595 self.assertTrue(os.path.islink(self.filelink))
1596 self.check_stat(self.filelink, self.filelink_target)
1597
1598 def _create_missing_dir_link(self):
1599 'Create a "directory" link to a non-existent target'
1600 linkname = self.missing_link
1601 if os.path.lexists(linkname):
1602 os.remove(linkname)
1603 target = r'c:\\target does not exist.29r3c740'
1604 assert not os.path.exists(target)
1605 target_is_dir = True
1606 os.symlink(target, linkname, target_is_dir)
1607
1608 def test_remove_directory_link_to_missing_target(self):
1609 self._create_missing_dir_link()
1610 # For compatibility with Unix, os.remove will check the
1611 # directory status and call RemoveDirectory if the symlink
1612 # was created with target_is_dir==True.
1613 os.remove(self.missing_link)
1614
1615 @unittest.skip("currently fails; consider for improvement")
1616 def test_isdir_on_directory_link_to_missing_target(self):
1617 self._create_missing_dir_link()
1618 # consider having isdir return true for directory links
1619 self.assertTrue(os.path.isdir(self.missing_link))
1620
1621 @unittest.skip("currently fails; consider for improvement")
1622 def test_rmdir_on_directory_link_to_missing_target(self):
1623 self._create_missing_dir_link()
1624 # consider allowing rmdir to remove directory links
1625 os.rmdir(self.missing_link)
1626
1627 def check_stat(self, link, target):
1628 self.assertEqual(os.stat(link), os.stat(target))
1629 self.assertNotEqual(os.lstat(link), os.stat(link))
1630
Brian Curtind25aef52011-06-13 15:16:04 -05001631 bytes_link = os.fsencode(link)
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001632 with warnings.catch_warnings():
1633 warnings.simplefilter("ignore", DeprecationWarning)
1634 self.assertEqual(os.stat(bytes_link), os.stat(target))
1635 self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link))
Brian Curtind25aef52011-06-13 15:16:04 -05001636
1637 def test_12084(self):
1638 level1 = os.path.abspath(support.TESTFN)
1639 level2 = os.path.join(level1, "level2")
1640 level3 = os.path.join(level2, "level3")
1641 try:
1642 os.mkdir(level1)
1643 os.mkdir(level2)
1644 os.mkdir(level3)
1645
1646 file1 = os.path.abspath(os.path.join(level1, "file1"))
1647
1648 with open(file1, "w") as f:
1649 f.write("file1")
1650
1651 orig_dir = os.getcwd()
1652 try:
1653 os.chdir(level2)
1654 link = os.path.join(level2, "link")
1655 os.symlink(os.path.relpath(file1), "link")
1656 self.assertIn("link", os.listdir(os.getcwd()))
1657
1658 # Check os.stat calls from the same dir as the link
1659 self.assertEqual(os.stat(file1), os.stat("link"))
1660
1661 # Check os.stat calls from a dir below the link
1662 os.chdir(level1)
1663 self.assertEqual(os.stat(file1),
1664 os.stat(os.path.relpath(link)))
1665
1666 # Check os.stat calls from a dir above the link
1667 os.chdir(level3)
1668 self.assertEqual(os.stat(file1),
1669 os.stat(os.path.relpath(link)))
1670 finally:
1671 os.chdir(orig_dir)
1672 except OSError as err:
1673 self.fail(err)
1674 finally:
1675 os.remove(file1)
1676 shutil.rmtree(level1)
1677
Brian Curtind40e6f72010-07-08 21:39:08 +00001678
Jason R. Coombs3a092862013-05-27 23:21:28 -04001679@support.skip_unless_symlink
1680class NonLocalSymlinkTests(unittest.TestCase):
1681
1682 def setUp(self):
1683 """
1684 Create this structure:
1685
1686 base
1687 \___ some_dir
1688 """
1689 os.makedirs('base/some_dir')
1690
1691 def tearDown(self):
1692 shutil.rmtree('base')
1693
1694 def test_directory_link_nonlocal(self):
1695 """
1696 The symlink target should resolve relative to the link, not relative
1697 to the current directory.
1698
1699 Then, link base/some_link -> base/some_dir and ensure that some_link
1700 is resolved as a directory.
1701
1702 In issue13772, it was discovered that directory detection failed if
1703 the symlink target was not specified relative to the current
1704 directory, which was a defect in the implementation.
1705 """
1706 src = os.path.join('base', 'some_link')
1707 os.symlink('some_dir', src)
1708 assert os.path.isdir(src)
1709
1710
Victor Stinnere8d51452010-08-19 01:05:19 +00001711class FSEncodingTests(unittest.TestCase):
1712 def test_nop(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001713 self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
1714 self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
Benjamin Peterson31191a92010-05-09 03:22:58 +00001715
Victor Stinnere8d51452010-08-19 01:05:19 +00001716 def test_identity(self):
1717 # assert fsdecode(fsencode(x)) == x
1718 for fn in ('unicode\u0141', 'latin\xe9', 'ascii'):
1719 try:
1720 bytesfn = os.fsencode(fn)
1721 except UnicodeEncodeError:
1722 continue
Ezio Melottib3aedd42010-11-20 19:04:17 +00001723 self.assertEqual(os.fsdecode(bytesfn), fn)
Victor Stinnere8d51452010-08-19 01:05:19 +00001724
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00001725
Brett Cannonefb00c02012-02-29 18:31:31 -05001726
1727class DeviceEncodingTests(unittest.TestCase):
1728
1729 def test_bad_fd(self):
1730 # Return None when an fd doesn't actually exist.
1731 self.assertIsNone(os.device_encoding(123456))
1732
Philip Jenveye308b7c2012-02-29 16:16:15 -08001733 @unittest.skipUnless(os.isatty(0) and (sys.platform.startswith('win') or
1734 (hasattr(locale, 'nl_langinfo') and hasattr(locale, 'CODESET'))),
Philip Jenveyd7aff2d2012-02-29 16:21:25 -08001735 'test requires a tty and either Windows or nl_langinfo(CODESET)')
Brett Cannonefb00c02012-02-29 18:31:31 -05001736 def test_device_encoding(self):
1737 encoding = os.device_encoding(0)
1738 self.assertIsNotNone(encoding)
1739 self.assertTrue(codecs.lookup(encoding))
1740
1741
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00001742class PidTests(unittest.TestCase):
1743 @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid")
1744 def test_getppid(self):
1745 p = subprocess.Popen([sys.executable, '-c',
1746 'import os; print(os.getppid())'],
1747 stdout=subprocess.PIPE)
1748 stdout, _ = p.communicate()
1749 # We are the parent of our subprocess
1750 self.assertEqual(int(stdout), os.getpid())
1751
1752
Brian Curtin0151b8e2010-09-24 13:43:43 +00001753# The introduction of this TestCase caused at least two different errors on
1754# *nix buildbots. Temporarily skip this to let the buildbots move along.
1755@unittest.skip("Skip due to platform/environment differences on *NIX buildbots")
Brian Curtine8e4b3b2010-09-23 20:04:14 +00001756@unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin")
1757class LoginTests(unittest.TestCase):
1758 def test_getlogin(self):
1759 user_name = os.getlogin()
1760 self.assertNotEqual(len(user_name), 0)
1761
1762
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001763@unittest.skipUnless(hasattr(os, 'getpriority') and hasattr(os, 'setpriority'),
1764 "needs os.getpriority and os.setpriority")
1765class ProgramPriorityTests(unittest.TestCase):
1766 """Tests for os.getpriority() and os.setpriority()."""
1767
1768 def test_set_get_priority(self):
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001769
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001770 base = os.getpriority(os.PRIO_PROCESS, os.getpid())
1771 os.setpriority(os.PRIO_PROCESS, os.getpid(), base + 1)
1772 try:
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001773 new_prio = os.getpriority(os.PRIO_PROCESS, os.getpid())
1774 if base >= 19 and new_prio <= 19:
1775 raise unittest.SkipTest(
1776 "unable to reliably test setpriority at current nice level of %s" % base)
1777 else:
1778 self.assertEqual(new_prio, base + 1)
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001779 finally:
1780 try:
1781 os.setpriority(os.PRIO_PROCESS, os.getpid(), base)
1782 except OSError as err:
Antoine Pitrou692f0382011-02-26 00:22:25 +00001783 if err.errno != errno.EACCES:
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001784 raise
1785
1786
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001787if threading is not None:
1788 class SendfileTestServer(asyncore.dispatcher, threading.Thread):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001789
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001790 class Handler(asynchat.async_chat):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001791
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001792 def __init__(self, conn):
1793 asynchat.async_chat.__init__(self, conn)
1794 self.in_buffer = []
1795 self.closed = False
1796 self.push(b"220 ready\r\n")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001797
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001798 def handle_read(self):
1799 data = self.recv(4096)
1800 self.in_buffer.append(data)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001801
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001802 def get_data(self):
1803 return b''.join(self.in_buffer)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001804
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001805 def handle_close(self):
1806 self.close()
1807 self.closed = True
1808
1809 def handle_error(self):
1810 raise
1811
1812 def __init__(self, address):
1813 threading.Thread.__init__(self)
1814 asyncore.dispatcher.__init__(self)
1815 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
1816 self.bind(address)
1817 self.listen(5)
1818 self.host, self.port = self.socket.getsockname()[:2]
1819 self.handler_instance = None
1820 self._active = False
1821 self._active_lock = threading.Lock()
1822
1823 # --- public API
1824
1825 @property
1826 def running(self):
1827 return self._active
1828
1829 def start(self):
1830 assert not self.running
1831 self.__flag = threading.Event()
1832 threading.Thread.start(self)
1833 self.__flag.wait()
1834
1835 def stop(self):
1836 assert self.running
1837 self._active = False
1838 self.join()
1839
1840 def wait(self):
1841 # wait for handler connection to be closed, then stop the server
1842 while not getattr(self.handler_instance, "closed", False):
1843 time.sleep(0.001)
1844 self.stop()
1845
1846 # --- internals
1847
1848 def run(self):
1849 self._active = True
1850 self.__flag.set()
1851 while self._active and asyncore.socket_map:
1852 self._active_lock.acquire()
1853 asyncore.loop(timeout=0.001, count=1)
1854 self._active_lock.release()
1855 asyncore.close_all()
1856
1857 def handle_accept(self):
1858 conn, addr = self.accept()
1859 self.handler_instance = self.Handler(conn)
1860
1861 def handle_connect(self):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001862 self.close()
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001863 handle_read = handle_connect
1864
1865 def writable(self):
1866 return 0
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001867
1868 def handle_error(self):
1869 raise
1870
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001871
Giampaolo Rodolà46134642011-02-25 20:01:05 +00001872@unittest.skipUnless(threading is not None, "test needs threading module")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001873@unittest.skipUnless(hasattr(os, 'sendfile'), "test needs os.sendfile()")
1874class TestSendfile(unittest.TestCase):
1875
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001876 DATA = b"12345abcde" * 16 * 1024 # 160 KB
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001877 SUPPORT_HEADERS_TRAILERS = not sys.platform.startswith("linux") and \
Giampaolo Rodolà4bc68572011-02-25 21:46:01 +00001878 not sys.platform.startswith("solaris") and \
1879 not sys.platform.startswith("sunos")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001880
1881 @classmethod
1882 def setUpClass(cls):
1883 with open(support.TESTFN, "wb") as f:
1884 f.write(cls.DATA)
1885
1886 @classmethod
1887 def tearDownClass(cls):
1888 support.unlink(support.TESTFN)
1889
1890 def setUp(self):
1891 self.server = SendfileTestServer((support.HOST, 0))
1892 self.server.start()
1893 self.client = socket.socket()
1894 self.client.connect((self.server.host, self.server.port))
1895 self.client.settimeout(1)
1896 # synchronize by waiting for "220 ready" response
1897 self.client.recv(1024)
1898 self.sockno = self.client.fileno()
1899 self.file = open(support.TESTFN, 'rb')
1900 self.fileno = self.file.fileno()
1901
1902 def tearDown(self):
1903 self.file.close()
1904 self.client.close()
1905 if self.server.running:
1906 self.server.stop()
1907
1908 def sendfile_wrapper(self, sock, file, offset, nbytes, headers=[], trailers=[]):
1909 """A higher level wrapper representing how an application is
1910 supposed to use sendfile().
1911 """
1912 while 1:
1913 try:
1914 if self.SUPPORT_HEADERS_TRAILERS:
1915 return os.sendfile(sock, file, offset, nbytes, headers,
1916 trailers)
1917 else:
1918 return os.sendfile(sock, file, offset, nbytes)
1919 except OSError as err:
1920 if err.errno == errno.ECONNRESET:
1921 # disconnected
1922 raise
1923 elif err.errno in (errno.EAGAIN, errno.EBUSY):
1924 # we have to retry send data
1925 continue
1926 else:
1927 raise
1928
1929 def test_send_whole_file(self):
1930 # normal send
1931 total_sent = 0
1932 offset = 0
1933 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001934 while total_sent < len(self.DATA):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001935 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
1936 if sent == 0:
1937 break
1938 offset += sent
1939 total_sent += sent
1940 self.assertTrue(sent <= nbytes)
1941 self.assertEqual(offset, total_sent)
1942
1943 self.assertEqual(total_sent, len(self.DATA))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001944 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001945 self.client.close()
1946 self.server.wait()
1947 data = self.server.handler_instance.get_data()
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001948 self.assertEqual(len(data), len(self.DATA))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001949 self.assertEqual(data, self.DATA)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001950
1951 def test_send_at_certain_offset(self):
1952 # start sending a file at a certain offset
1953 total_sent = 0
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001954 offset = len(self.DATA) // 2
1955 must_send = len(self.DATA) - offset
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001956 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001957 while total_sent < must_send:
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001958 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
1959 if sent == 0:
1960 break
1961 offset += sent
1962 total_sent += sent
1963 self.assertTrue(sent <= nbytes)
1964
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001965 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001966 self.client.close()
1967 self.server.wait()
1968 data = self.server.handler_instance.get_data()
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001969 expected = self.DATA[len(self.DATA) // 2:]
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001970 self.assertEqual(total_sent, len(expected))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001971 self.assertEqual(len(data), len(expected))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001972 self.assertEqual(data, expected)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001973
1974 def test_offset_overflow(self):
1975 # specify an offset > file size
1976 offset = len(self.DATA) + 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001977 try:
1978 sent = os.sendfile(self.sockno, self.fileno, offset, 4096)
1979 except OSError as e:
1980 # Solaris can raise EINVAL if offset >= file length, ignore.
1981 if e.errno != errno.EINVAL:
1982 raise
1983 else:
1984 self.assertEqual(sent, 0)
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001985 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001986 self.client.close()
1987 self.server.wait()
1988 data = self.server.handler_instance.get_data()
1989 self.assertEqual(data, b'')
1990
1991 def test_invalid_offset(self):
1992 with self.assertRaises(OSError) as cm:
1993 os.sendfile(self.sockno, self.fileno, -1, 4096)
1994 self.assertEqual(cm.exception.errno, errno.EINVAL)
1995
1996 # --- headers / trailers tests
1997
1998 if SUPPORT_HEADERS_TRAILERS:
1999
2000 def test_headers(self):
2001 total_sent = 0
2002 sent = os.sendfile(self.sockno, self.fileno, 0, 4096,
2003 headers=[b"x" * 512])
2004 total_sent += sent
2005 offset = 4096
2006 nbytes = 4096
2007 while 1:
2008 sent = self.sendfile_wrapper(self.sockno, self.fileno,
2009 offset, nbytes)
2010 if sent == 0:
2011 break
2012 total_sent += sent
2013 offset += sent
2014
2015 expected_data = b"x" * 512 + self.DATA
2016 self.assertEqual(total_sent, len(expected_data))
2017 self.client.close()
2018 self.server.wait()
2019 data = self.server.handler_instance.get_data()
2020 self.assertEqual(hash(data), hash(expected_data))
2021
2022 def test_trailers(self):
2023 TESTFN2 = support.TESTFN + "2"
Victor Stinner5e4d6392013-08-15 11:57:02 +02002024 file_data = b"abcdef"
Brett Cannonb6376802011-03-15 17:38:22 -04002025 with open(TESTFN2, 'wb') as f:
Victor Stinner5e4d6392013-08-15 11:57:02 +02002026 f.write(file_data)
Brett Cannonb6376802011-03-15 17:38:22 -04002027 with open(TESTFN2, 'rb')as f:
2028 self.addCleanup(os.remove, TESTFN2)
Victor Stinner5e4d6392013-08-15 11:57:02 +02002029 os.sendfile(self.sockno, f.fileno(), 0, len(file_data),
2030 trailers=[b"1234"])
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002031 self.client.close()
2032 self.server.wait()
2033 data = self.server.handler_instance.get_data()
Victor Stinner5e4d6392013-08-15 11:57:02 +02002034 self.assertEqual(data, b"abcdef1234")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002035
2036 if hasattr(os, "SF_NODISKIO"):
2037 def test_flags(self):
2038 try:
2039 os.sendfile(self.sockno, self.fileno, 0, 4096,
2040 flags=os.SF_NODISKIO)
2041 except OSError as err:
2042 if err.errno not in (errno.EBUSY, errno.EAGAIN):
2043 raise
2044
2045
Larry Hastings9cf065c2012-06-22 16:30:09 -07002046def supports_extended_attributes():
2047 if not hasattr(os, "setxattr"):
2048 return False
2049 try:
2050 with open(support.TESTFN, "wb") as fp:
2051 try:
2052 os.setxattr(fp.fileno(), b"user.test", b"")
2053 except OSError:
2054 return False
2055 finally:
2056 support.unlink(support.TESTFN)
2057 # Kernels < 2.6.39 don't respect setxattr flags.
2058 kernel_version = platform.release()
2059 m = re.match("2.6.(\d{1,2})", kernel_version)
2060 return m is None or int(m.group(1)) >= 39
2061
2062
2063@unittest.skipUnless(supports_extended_attributes(),
2064 "no non-broken extended attribute support")
Benjamin Peterson799bd802011-08-31 22:15:17 -04002065class ExtendedAttributeTests(unittest.TestCase):
2066
2067 def tearDown(self):
2068 support.unlink(support.TESTFN)
2069
Larry Hastings9cf065c2012-06-22 16:30:09 -07002070 def _check_xattrs_str(self, s, getxattr, setxattr, removexattr, listxattr, **kwargs):
Benjamin Peterson799bd802011-08-31 22:15:17 -04002071 fn = support.TESTFN
2072 open(fn, "wb").close()
2073 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002074 getxattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002075 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002076 init_xattr = listxattr(fn)
2077 self.assertIsInstance(init_xattr, list)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002078 setxattr(fn, s("user.test"), b"", **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002079 xattr = set(init_xattr)
2080 xattr.add("user.test")
2081 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002082 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"")
2083 setxattr(fn, s("user.test"), b"hello", os.XATTR_REPLACE, **kwargs)
2084 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"hello")
Benjamin Peterson799bd802011-08-31 22:15:17 -04002085 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002086 setxattr(fn, s("user.test"), b"bye", os.XATTR_CREATE, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002087 self.assertEqual(cm.exception.errno, errno.EEXIST)
2088 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002089 setxattr(fn, s("user.test2"), b"bye", os.XATTR_REPLACE, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002090 self.assertEqual(cm.exception.errno, errno.ENODATA)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002091 setxattr(fn, s("user.test2"), b"foo", os.XATTR_CREATE, **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002092 xattr.add("user.test2")
2093 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002094 removexattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002095 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002096 getxattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002097 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002098 xattr.remove("user.test")
2099 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002100 self.assertEqual(getxattr(fn, s("user.test2"), **kwargs), b"foo")
2101 setxattr(fn, s("user.test"), b"a"*1024, **kwargs)
2102 self.assertEqual(getxattr(fn, s("user.test"), **kwargs), b"a"*1024)
2103 removexattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002104 many = sorted("user.test{}".format(i) for i in range(100))
2105 for thing in many:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002106 setxattr(fn, thing, b"x", **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002107 self.assertEqual(set(listxattr(fn)), set(init_xattr) | set(many))
Benjamin Peterson799bd802011-08-31 22:15:17 -04002108
Larry Hastings9cf065c2012-06-22 16:30:09 -07002109 def _check_xattrs(self, *args, **kwargs):
Benjamin Peterson799bd802011-08-31 22:15:17 -04002110 def make_bytes(s):
2111 return bytes(s, "ascii")
Larry Hastings9cf065c2012-06-22 16:30:09 -07002112 self._check_xattrs_str(str, *args, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002113 support.unlink(support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002114 self._check_xattrs_str(make_bytes, *args, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002115
2116 def test_simple(self):
2117 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
2118 os.listxattr)
2119
2120 def test_lpath(self):
Larry Hastings9cf065c2012-06-22 16:30:09 -07002121 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
2122 os.listxattr, follow_symlinks=False)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002123
2124 def test_fds(self):
2125 def getxattr(path, *args):
2126 with open(path, "rb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002127 return os.getxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002128 def setxattr(path, *args):
2129 with open(path, "wb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002130 os.setxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002131 def removexattr(path, *args):
2132 with open(path, "wb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002133 os.removexattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002134 def listxattr(path, *args):
2135 with open(path, "rb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002136 return os.listxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002137 self._check_xattrs(getxattr, setxattr, removexattr, listxattr)
2138
2139
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002140@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
2141class Win32DeprecatedBytesAPI(unittest.TestCase):
2142 def test_deprecated(self):
2143 import nt
2144 filename = os.fsencode(support.TESTFN)
2145 with warnings.catch_warnings():
2146 warnings.simplefilter("error", DeprecationWarning)
2147 for func, *args in (
2148 (nt._getfullpathname, filename),
2149 (nt._isdir, filename),
2150 (os.access, filename, os.R_OK),
2151 (os.chdir, filename),
2152 (os.chmod, filename, 0o777),
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01002153 (os.getcwdb,),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002154 (os.link, filename, filename),
2155 (os.listdir, filename),
2156 (os.lstat, filename),
2157 (os.mkdir, filename),
2158 (os.open, filename, os.O_RDONLY),
2159 (os.rename, filename, filename),
2160 (os.rmdir, filename),
2161 (os.startfile, filename),
2162 (os.stat, filename),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002163 (os.unlink, filename),
2164 (os.utime, filename),
2165 ):
2166 self.assertRaises(DeprecationWarning, func, *args)
2167
Victor Stinner28216442011-11-16 00:34:44 +01002168 @support.skip_unless_symlink
2169 def test_symlink(self):
2170 filename = os.fsencode(support.TESTFN)
2171 with warnings.catch_warnings():
2172 warnings.simplefilter("error", DeprecationWarning)
2173 self.assertRaises(DeprecationWarning,
2174 os.symlink, filename, filename)
2175
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002176
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002177@unittest.skipUnless(hasattr(os, 'get_terminal_size'), "requires os.get_terminal_size")
2178class TermsizeTests(unittest.TestCase):
2179 def test_does_not_crash(self):
2180 """Check if get_terminal_size() returns a meaningful value.
2181
2182 There's no easy portable way to actually check the size of the
2183 terminal, so let's check if it returns something sensible instead.
2184 """
2185 try:
2186 size = os.get_terminal_size()
2187 except OSError as e:
Antoine Pitrou81a1fa52012-02-09 00:11:00 +01002188 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002189 # Under win32 a generic OSError can be thrown if the
2190 # handle cannot be retrieved
2191 self.skipTest("failed to query terminal size")
2192 raise
2193
Antoine Pitroucfade362012-02-08 23:48:59 +01002194 self.assertGreaterEqual(size.columns, 0)
2195 self.assertGreaterEqual(size.lines, 0)
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002196
2197 def test_stty_match(self):
2198 """Check if stty returns the same results
2199
2200 stty actually tests stdin, so get_terminal_size is invoked on
2201 stdin explicitly. If stty succeeded, then get_terminal_size()
2202 should work too.
2203 """
2204 try:
2205 size = subprocess.check_output(['stty', 'size']).decode().split()
2206 except (FileNotFoundError, subprocess.CalledProcessError):
2207 self.skipTest("stty invocation failed")
2208 expected = (int(size[1]), int(size[0])) # reversed order
2209
Antoine Pitrou81a1fa52012-02-09 00:11:00 +01002210 try:
2211 actual = os.get_terminal_size(sys.__stdin__.fileno())
2212 except OSError as e:
2213 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
2214 # Under win32 a generic OSError can be thrown if the
2215 # handle cannot be retrieved
2216 self.skipTest("failed to query terminal size")
2217 raise
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002218 self.assertEqual(expected, actual)
2219
2220
Victor Stinner292c8352012-10-30 02:17:38 +01002221class OSErrorTests(unittest.TestCase):
2222 def setUp(self):
2223 class Str(str):
2224 pass
2225
Victor Stinnerafe17062012-10-31 22:47:43 +01002226 self.bytes_filenames = []
2227 self.unicode_filenames = []
Victor Stinner292c8352012-10-30 02:17:38 +01002228 if support.TESTFN_UNENCODABLE is not None:
2229 decoded = support.TESTFN_UNENCODABLE
2230 else:
2231 decoded = support.TESTFN
Victor Stinnerafe17062012-10-31 22:47:43 +01002232 self.unicode_filenames.append(decoded)
2233 self.unicode_filenames.append(Str(decoded))
Victor Stinner292c8352012-10-30 02:17:38 +01002234 if support.TESTFN_UNDECODABLE is not None:
2235 encoded = support.TESTFN_UNDECODABLE
2236 else:
2237 encoded = os.fsencode(support.TESTFN)
Victor Stinnerafe17062012-10-31 22:47:43 +01002238 self.bytes_filenames.append(encoded)
2239 self.bytes_filenames.append(memoryview(encoded))
2240
2241 self.filenames = self.bytes_filenames + self.unicode_filenames
Victor Stinner292c8352012-10-30 02:17:38 +01002242
2243 def test_oserror_filename(self):
2244 funcs = [
Victor Stinnerafe17062012-10-31 22:47:43 +01002245 (self.filenames, os.chdir,),
2246 (self.filenames, os.chmod, 0o777),
Victor Stinnerafe17062012-10-31 22:47:43 +01002247 (self.filenames, os.lstat,),
2248 (self.filenames, os.open, os.O_RDONLY),
2249 (self.filenames, os.rmdir,),
2250 (self.filenames, os.stat,),
2251 (self.filenames, os.unlink,),
Victor Stinner292c8352012-10-30 02:17:38 +01002252 ]
2253 if sys.platform == "win32":
2254 funcs.extend((
Victor Stinnerafe17062012-10-31 22:47:43 +01002255 (self.bytes_filenames, os.rename, b"dst"),
2256 (self.bytes_filenames, os.replace, b"dst"),
2257 (self.unicode_filenames, os.rename, "dst"),
2258 (self.unicode_filenames, os.replace, "dst"),
Victor Stinner64e039a2012-11-07 00:10:14 +01002259 # Issue #16414: Don't test undecodable names with listdir()
2260 # because of a Windows bug.
2261 #
2262 # With the ANSI code page 932, os.listdir(b'\xe7') return an
2263 # empty list (instead of failing), whereas os.listdir(b'\xff')
2264 # raises a FileNotFoundError. It looks like a Windows bug:
2265 # b'\xe7' directory does not exist, FindFirstFileA(b'\xe7')
2266 # fails with ERROR_FILE_NOT_FOUND (2), instead of
2267 # ERROR_PATH_NOT_FOUND (3).
2268 (self.unicode_filenames, os.listdir,),
Victor Stinner292c8352012-10-30 02:17:38 +01002269 ))
Victor Stinnerafe17062012-10-31 22:47:43 +01002270 else:
2271 funcs.extend((
Victor Stinner64e039a2012-11-07 00:10:14 +01002272 (self.filenames, os.listdir,),
Victor Stinnerafe17062012-10-31 22:47:43 +01002273 (self.filenames, os.rename, "dst"),
2274 (self.filenames, os.replace, "dst"),
2275 ))
2276 if hasattr(os, "chown"):
2277 funcs.append((self.filenames, os.chown, 0, 0))
2278 if hasattr(os, "lchown"):
2279 funcs.append((self.filenames, os.lchown, 0, 0))
2280 if hasattr(os, "truncate"):
2281 funcs.append((self.filenames, os.truncate, 0))
Victor Stinner292c8352012-10-30 02:17:38 +01002282 if hasattr(os, "chflags"):
Victor Stinneree36c242012-11-13 09:31:51 +01002283 funcs.append((self.filenames, os.chflags, 0))
2284 if hasattr(os, "lchflags"):
2285 funcs.append((self.filenames, os.lchflags, 0))
Victor Stinner292c8352012-10-30 02:17:38 +01002286 if hasattr(os, "chroot"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002287 funcs.append((self.filenames, os.chroot,))
Victor Stinner292c8352012-10-30 02:17:38 +01002288 if hasattr(os, "link"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002289 if sys.platform == "win32":
2290 funcs.append((self.bytes_filenames, os.link, b"dst"))
2291 funcs.append((self.unicode_filenames, os.link, "dst"))
2292 else:
2293 funcs.append((self.filenames, os.link, "dst"))
Victor Stinner292c8352012-10-30 02:17:38 +01002294 if hasattr(os, "listxattr"):
2295 funcs.extend((
Victor Stinnerafe17062012-10-31 22:47:43 +01002296 (self.filenames, os.listxattr,),
2297 (self.filenames, os.getxattr, "user.test"),
2298 (self.filenames, os.setxattr, "user.test", b'user'),
2299 (self.filenames, os.removexattr, "user.test"),
Victor Stinner292c8352012-10-30 02:17:38 +01002300 ))
2301 if hasattr(os, "lchmod"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002302 funcs.append((self.filenames, os.lchmod, 0o777))
Victor Stinner292c8352012-10-30 02:17:38 +01002303 if hasattr(os, "readlink"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002304 if sys.platform == "win32":
2305 funcs.append((self.unicode_filenames, os.readlink,))
2306 else:
2307 funcs.append((self.filenames, os.readlink,))
Victor Stinner292c8352012-10-30 02:17:38 +01002308
Victor Stinnerafe17062012-10-31 22:47:43 +01002309 for filenames, func, *func_args in funcs:
2310 for name in filenames:
Victor Stinner292c8352012-10-30 02:17:38 +01002311 try:
2312 func(name, *func_args)
Victor Stinnerbd54f0e2012-10-31 01:12:55 +01002313 except OSError as err:
Victor Stinner292c8352012-10-30 02:17:38 +01002314 self.assertIs(err.filename, name)
2315 else:
2316 self.fail("No exception thrown by {}".format(func))
2317
Charles-Francois Natali44feda32013-05-20 14:40:46 +02002318class CPUCountTests(unittest.TestCase):
2319 def test_cpu_count(self):
2320 cpus = os.cpu_count()
2321 if cpus is not None:
2322 self.assertIsInstance(cpus, int)
2323 self.assertGreater(cpus, 0)
2324 else:
2325 self.skipTest("Could not determine the number of CPUs")
2326
Victor Stinnerdaf45552013-08-28 00:53:59 +02002327
2328class FDInheritanceTests(unittest.TestCase):
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002329 def test_get_set_inheritable(self):
Victor Stinnerdaf45552013-08-28 00:53:59 +02002330 fd = os.open(__file__, os.O_RDONLY)
2331 self.addCleanup(os.close, fd)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002332 self.assertEqual(os.get_inheritable(fd), False)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002333
Victor Stinnerdaf45552013-08-28 00:53:59 +02002334 os.set_inheritable(fd, True)
2335 self.assertEqual(os.get_inheritable(fd), True)
2336
Victor Stinner4f7a36f2013-09-08 14:14:38 +02002337 @unittest.skipIf(fcntl is None, "need fcntl")
2338 def test_get_inheritable_cloexec(self):
2339 fd = os.open(__file__, os.O_RDONLY)
2340 self.addCleanup(os.close, fd)
2341 self.assertEqual(os.get_inheritable(fd), False)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002342
Victor Stinner4f7a36f2013-09-08 14:14:38 +02002343 # clear FD_CLOEXEC flag
2344 flags = fcntl.fcntl(fd, fcntl.F_GETFD)
2345 flags &= ~fcntl.FD_CLOEXEC
2346 fcntl.fcntl(fd, fcntl.F_SETFD, flags)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002347
Victor Stinner4f7a36f2013-09-08 14:14:38 +02002348 self.assertEqual(os.get_inheritable(fd), True)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002349
Victor Stinner4f7a36f2013-09-08 14:14:38 +02002350 @unittest.skipIf(fcntl is None, "need fcntl")
2351 def test_set_inheritable_cloexec(self):
2352 fd = os.open(__file__, os.O_RDONLY)
2353 self.addCleanup(os.close, fd)
2354 self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
2355 fcntl.FD_CLOEXEC)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002356
Victor Stinner4f7a36f2013-09-08 14:14:38 +02002357 os.set_inheritable(fd, True)
2358 self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
2359 0)
Victor Stinner7ba6b0f2013-09-08 11:47:54 +02002360
Victor Stinnerdaf45552013-08-28 00:53:59 +02002361 def test_open(self):
2362 fd = os.open(__file__, os.O_RDONLY)
2363 self.addCleanup(os.close, fd)
2364 self.assertEqual(os.get_inheritable(fd), False)
2365
2366 @unittest.skipUnless(hasattr(os, 'pipe'), "need os.pipe()")
2367 def test_pipe(self):
2368 rfd, wfd = os.pipe()
2369 self.addCleanup(os.close, rfd)
2370 self.addCleanup(os.close, wfd)
2371 self.assertEqual(os.get_inheritable(rfd), False)
2372 self.assertEqual(os.get_inheritable(wfd), False)
2373
2374 def test_dup(self):
2375 fd1 = os.open(__file__, os.O_RDONLY)
2376 self.addCleanup(os.close, fd1)
2377
2378 fd2 = os.dup(fd1)
2379 self.addCleanup(os.close, fd2)
2380 self.assertEqual(os.get_inheritable(fd2), False)
2381
2382 @unittest.skipUnless(hasattr(os, 'dup2'), "need os.dup2()")
2383 def test_dup2(self):
2384 fd = os.open(__file__, os.O_RDONLY)
2385 self.addCleanup(os.close, fd)
2386
2387 # inheritable by default
2388 fd2 = os.open(__file__, os.O_RDONLY)
2389 try:
2390 os.dup2(fd, fd2)
2391 self.assertEqual(os.get_inheritable(fd2), True)
2392 finally:
2393 os.close(fd2)
2394
2395 # force non-inheritable
2396 fd3 = os.open(__file__, os.O_RDONLY)
2397 try:
2398 os.dup2(fd, fd3, inheritable=False)
2399 self.assertEqual(os.get_inheritable(fd3), False)
2400 finally:
2401 os.close(fd3)
2402
2403 @unittest.skipUnless(hasattr(os, 'openpty'), "need os.openpty()")
2404 def test_openpty(self):
2405 master_fd, slave_fd = os.openpty()
2406 self.addCleanup(os.close, master_fd)
2407 self.addCleanup(os.close, slave_fd)
2408 self.assertEqual(os.get_inheritable(master_fd), False)
2409 self.assertEqual(os.get_inheritable(slave_fd), False)
2410
2411
Antoine Pitrouf26ad712011-07-15 23:00:56 +02002412@support.reap_threads
Fred Drake2e2be372001-09-20 21:33:42 +00002413def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002414 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002415 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002416 StatAttributeTests,
2417 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00002418 WalkTests,
Charles-François Natali7372b062012-02-05 15:15:38 +01002419 FwalkTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00002420 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +00002421 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002422 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +00002423 ExecTests,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00002424 Win32ErrorTests,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002425 TestInvalidFD,
Martin v. Löwis011e8422009-05-05 04:43:17 +00002426 PosixUidGidTests,
Brian Curtineb24d742010-04-12 17:16:38 +00002427 Pep383Tests,
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00002428 Win32KillTests,
Brian Curtind40e6f72010-07-08 21:39:08 +00002429 Win32SymlinkTests,
Jason R. Coombs3a092862013-05-27 23:21:28 -04002430 NonLocalSymlinkTests,
Victor Stinnere8d51452010-08-19 01:05:19 +00002431 FSEncodingTests,
Brett Cannonefb00c02012-02-29 18:31:31 -05002432 DeviceEncodingTests,
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00002433 PidTests,
Brian Curtine8e4b3b2010-09-23 20:04:14 +00002434 LoginTests,
Brian Curtin1b9df392010-11-24 20:24:31 +00002435 LinkTests,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002436 TestSendfile,
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00002437 ProgramPriorityTests,
Benjamin Peterson799bd802011-08-31 22:15:17 -04002438 ExtendedAttributeTests,
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002439 Win32DeprecatedBytesAPI,
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002440 TermsizeTests,
Victor Stinner292c8352012-10-30 02:17:38 +01002441 OSErrorTests,
Andrew Svetlov405faed2012-12-25 12:18:09 +02002442 RemoveDirsTests,
Charles-Francois Natali44feda32013-05-20 14:40:46 +02002443 CPUCountTests,
Victor Stinnerdaf45552013-08-28 00:53:59 +02002444 FDInheritanceTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002445 )
Fred Drake2e2be372001-09-20 21:33:42 +00002446
2447if __name__ == "__main__":
2448 test_main()