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