blob: 8916305f1c606939caba7e91fa1d2f6b93a52ada [file] [log] [blame]
Fred Drake38c2ef02001-07-17 20:52:51 +00001# As a test suite for the os module, this is woefully inadequate, but this
2# does add tests for a few functions which have been determined to be more
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00003# portable than they had been thought to be.
Fred Drake38c2ef02001-07-17 20:52:51 +00004
5import os
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00006import errno
Fred Drake38c2ef02001-07-17 20:52:51 +00007import unittest
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +00008import warnings
Thomas Wouters477c8d52006-05-27 19:21:47 +00009import sys
Brian Curtineb24d742010-04-12 17:16:38 +000010import signal
11import subprocess
12import time
Martin v. Löwis011e8422009-05-05 04:43:17 +000013import shutil
Benjamin Petersonee8712c2008-05-20 21:35:26 +000014from test import support
Victor Stinnerc2d095f2010-05-17 00:14:53 +000015import contextlib
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +000016import mmap
Benjamin Peterson799bd802011-08-31 22:15:17 -040017import platform
18import re
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +000019import uuid
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000020import asyncore
21import asynchat
22import socket
Charles-François Natali7372b062012-02-05 15:15:38 +010023import itertools
24import stat
Brett Cannonefb00c02012-02-29 18:31:31 -050025import locale
26import codecs
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000027try:
28 import threading
29except ImportError:
30 threading = None
Georg Brandl2daf6ae2012-02-20 19:54:16 +010031from test.script_helper import assert_python_ok
Fred Drake38c2ef02001-07-17 20:52:51 +000032
Victor Stinner034d0aa2012-06-05 01:22:15 +020033with warnings.catch_warnings():
34 warnings.simplefilter("ignore", DeprecationWarning)
35 os.stat_float_times(True)
Victor Stinner1aa54a42012-02-08 04:09:37 +010036st = os.stat(__file__)
37stat_supports_subsecond = (
38 # check if float and int timestamps are different
39 (st.st_atime != st[7])
40 or (st.st_mtime != st[8])
41 or (st.st_ctime != st[9]))
42
Mark Dickinson7cf03892010-04-16 13:45:35 +000043# Detect whether we're on a Linux system that uses the (now outdated
44# and unmaintained) linuxthreads threading library. There's an issue
45# when combining linuxthreads with a failed execv call: see
46# http://bugs.python.org/issue4970.
Victor Stinnerd5c355c2011-04-30 14:53:09 +020047if hasattr(sys, 'thread_info') and sys.thread_info.version:
48 USING_LINUXTHREADS = sys.thread_info.version.startswith("linuxthreads")
49else:
50 USING_LINUXTHREADS = False
Brian Curtineb24d742010-04-12 17:16:38 +000051
Stefan Krahebee49a2013-01-17 15:31:00 +010052# Issue #14110: Some tests fail on FreeBSD if the user is in the wheel group.
53HAVE_WHEEL_GROUP = sys.platform.startswith('freebsd') and os.getgid() == 0
54
Thomas Wouters0e3f5912006-08-11 14:57:12 +000055# Tests creating TESTFN
56class FileTests(unittest.TestCase):
57 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000058 if os.path.exists(support.TESTFN):
59 os.unlink(support.TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000060 tearDown = setUp
61
62 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000063 f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000064 os.close(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000065 self.assertTrue(os.access(support.TESTFN, os.W_OK))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000066
Christian Heimesfdab48e2008-01-20 09:06:41 +000067 def test_closerange(self):
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000068 first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
69 # We must allocate two consecutive file descriptors, otherwise
70 # it will mess up other file descriptors (perhaps even the three
71 # standard ones).
72 second = os.dup(first)
73 try:
74 retries = 0
75 while second != first + 1:
76 os.close(first)
77 retries += 1
78 if retries > 10:
79 # XXX test skipped
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000080 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000081 first, second = second, os.dup(second)
82 finally:
83 os.close(second)
Christian Heimesfdab48e2008-01-20 09:06:41 +000084 # close a fd that is open, and one that isn't
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000085 os.closerange(first, first + 2)
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000086 self.assertRaises(OSError, os.write, first, b"a")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000087
Benjamin Peterson1cc6df92010-06-30 17:39:45 +000088 @support.cpython_only
Hirokazu Yamamoto4c19e6e2008-09-08 23:41:21 +000089 def test_rename(self):
90 path = support.TESTFN
91 old = sys.getrefcount(path)
92 self.assertRaises(TypeError, os.rename, path, 0)
93 new = sys.getrefcount(path)
94 self.assertEqual(old, new)
95
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000096 def test_read(self):
97 with open(support.TESTFN, "w+b") as fobj:
98 fobj.write(b"spam")
99 fobj.flush()
100 fd = fobj.fileno()
101 os.lseek(fd, 0, 0)
102 s = os.read(fd, 4)
103 self.assertEqual(type(s), bytes)
104 self.assertEqual(s, b"spam")
105
106 def test_write(self):
107 # os.write() accepts bytes- and buffer-like objects but not strings
108 fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY)
109 self.assertRaises(TypeError, os.write, fd, "beans")
110 os.write(fd, b"bacon\n")
111 os.write(fd, bytearray(b"eggs\n"))
112 os.write(fd, memoryview(b"spam\n"))
113 os.close(fd)
114 with open(support.TESTFN, "rb") as fobj:
Antoine Pitroud62269f2008-09-15 23:54:52 +0000115 self.assertEqual(fobj.read().splitlines(),
116 [b"bacon", b"eggs", b"spam"])
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000117
Victor Stinnere0daff12011-03-20 23:36:35 +0100118 def write_windows_console(self, *args):
119 retcode = subprocess.call(args,
120 # use a new console to not flood the test output
121 creationflags=subprocess.CREATE_NEW_CONSOLE,
122 # use a shell to hide the console window (SW_HIDE)
123 shell=True)
124 self.assertEqual(retcode, 0)
125
126 @unittest.skipUnless(sys.platform == 'win32',
127 'test specific to the Windows console')
128 def test_write_windows_console(self):
129 # Issue #11395: the Windows console returns an error (12: not enough
130 # space error) on writing into stdout if stdout mode is binary and the
131 # length is greater than 66,000 bytes (or less, depending on heap
132 # usage).
133 code = "print('x' * 100000)"
134 self.write_windows_console(sys.executable, "-c", code)
135 self.write_windows_console(sys.executable, "-u", "-c", code)
136
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000137 def fdopen_helper(self, *args):
138 fd = os.open(support.TESTFN, os.O_RDONLY)
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200139 f = os.fdopen(fd, *args)
140 f.close()
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000141
142 def test_fdopen(self):
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200143 fd = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
144 os.close(fd)
145
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000146 self.fdopen_helper()
147 self.fdopen_helper('r')
148 self.fdopen_helper('r', 100)
149
Antoine Pitrouf3b2d882012-01-30 22:08:52 +0100150 def test_replace(self):
151 TESTFN2 = support.TESTFN + ".2"
152 with open(support.TESTFN, 'w') as f:
153 f.write("1")
154 with open(TESTFN2, 'w') as f:
155 f.write("2")
156 self.addCleanup(os.unlink, TESTFN2)
157 os.replace(support.TESTFN, TESTFN2)
158 self.assertRaises(FileNotFoundError, os.stat, support.TESTFN)
159 with open(TESTFN2, 'r') as f:
160 self.assertEqual(f.read(), "1")
161
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200162
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000163# Test attributes on return values from os.*stat* family.
164class StatAttributeTests(unittest.TestCase):
165 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000166 os.mkdir(support.TESTFN)
167 self.fname = os.path.join(support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000168 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +0000169 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000170 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000171
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000172 def tearDown(self):
173 os.unlink(self.fname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000174 os.rmdir(support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000175
Antoine Pitrou38425292010-09-21 18:19:07 +0000176 def check_stat_attributes(self, fname):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000177 if not hasattr(os, "stat"):
178 return
179
Antoine Pitrou38425292010-09-21 18:19:07 +0000180 result = os.stat(fname)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000181
182 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000183 self.assertEqual(result[stat.ST_SIZE], 3)
184 self.assertEqual(result.st_size, 3)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000185
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000186 # Make sure all the attributes are there
187 members = dir(result)
188 for name in dir(stat):
189 if name[:3] == 'ST_':
190 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000191 if name.endswith("TIME"):
192 def trunc(x): return int(x)
193 else:
194 def trunc(x): return x
Ezio Melottib3aedd42010-11-20 19:04:17 +0000195 self.assertEqual(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000196 result[getattr(stat, name)])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000197 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000198
Larry Hastings6fe20b32012-04-19 15:07:49 -0700199 # Make sure that the st_?time and st_?time_ns fields roughly agree
Larry Hastings76ad59b2012-05-03 00:30:07 -0700200 # (they should always agree up to around tens-of-microseconds)
Larry Hastings6fe20b32012-04-19 15:07:49 -0700201 for name in 'st_atime st_mtime st_ctime'.split():
202 floaty = int(getattr(result, name) * 100000)
203 nanosecondy = getattr(result, name + "_ns") // 10000
Larry Hastings76ad59b2012-05-03 00:30:07 -0700204 self.assertAlmostEqual(floaty, nanosecondy, delta=2)
Larry Hastings6fe20b32012-04-19 15:07:49 -0700205
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000206 try:
207 result[200]
Andrew Svetlov737fb892012-12-18 21:14:22 +0200208 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000209 except IndexError:
210 pass
211
212 # Make sure that assignment fails
213 try:
214 result.st_mode = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200215 self.fail("No exception raised")
Collin Winter42dae6a2007-03-28 21:44:53 +0000216 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000217 pass
218
219 try:
220 result.st_rdev = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200221 self.fail("No exception raised")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000222 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000223 pass
224
225 try:
226 result.parrot = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200227 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000228 except AttributeError:
229 pass
230
231 # Use the stat_result constructor with a too-short tuple.
232 try:
233 result2 = os.stat_result((10,))
Andrew Svetlov737fb892012-12-18 21:14:22 +0200234 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000235 except TypeError:
236 pass
237
Ezio Melotti42da6632011-03-15 05:18:48 +0200238 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000239 try:
240 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
241 except TypeError:
242 pass
243
Antoine Pitrou38425292010-09-21 18:19:07 +0000244 def test_stat_attributes(self):
245 self.check_stat_attributes(self.fname)
246
247 def test_stat_attributes_bytes(self):
248 try:
249 fname = self.fname.encode(sys.getfilesystemencoding())
250 except UnicodeEncodeError:
251 self.skipTest("cannot encode %a for the filesystem" % self.fname)
Victor Stinner1ab6c2d2011-11-15 22:27:41 +0100252 with warnings.catch_warnings():
253 warnings.simplefilter("ignore", DeprecationWarning)
254 self.check_stat_attributes(fname)
Tim Peterse0c446b2001-10-18 21:57:37 +0000255
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000256 def test_statvfs_attributes(self):
257 if not hasattr(os, "statvfs"):
258 return
259
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000260 try:
261 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000262 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000263 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000264 if e.errno == errno.ENOSYS:
265 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000266
267 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000268 self.assertEqual(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000269
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000270 # Make sure all the attributes are there.
271 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
272 'ffree', 'favail', 'flag', 'namemax')
273 for value, member in enumerate(members):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000274 self.assertEqual(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000275
276 # Make sure that assignment really fails
277 try:
278 result.f_bfree = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200279 self.fail("No exception raised")
Collin Winter42dae6a2007-03-28 21:44:53 +0000280 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000281 pass
282
283 try:
284 result.parrot = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200285 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000286 except AttributeError:
287 pass
288
289 # Use the constructor with a too-short tuple.
290 try:
291 result2 = os.statvfs_result((10,))
Andrew Svetlov737fb892012-12-18 21:14:22 +0200292 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000293 except TypeError:
294 pass
295
Ezio Melotti42da6632011-03-15 05:18:48 +0200296 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000297 try:
298 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
299 except TypeError:
300 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000301
Thomas Wouters89f507f2006-12-13 04:49:30 +0000302 def test_utime_dir(self):
303 delta = 1000000
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000304 st = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000305 # round to int, because some systems may support sub-second
306 # time stamps in stat, but not in utime.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000307 os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
308 st2 = os.stat(support.TESTFN)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000309 self.assertEqual(st2.st_mtime, int(st.st_mtime-delta))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000310
Larry Hastings76ad59b2012-05-03 00:30:07 -0700311 def _test_utime(self, filename, attr, utime, delta):
Brian Curtin0277aa32011-11-06 13:50:15 -0600312 # Issue #13327 removed the requirement to pass None as the
Brian Curtin52fbea12011-11-06 13:41:17 -0600313 # second argument. Check that the previous methods of passing
314 # a time tuple or None work in addition to no argument.
Larry Hastings76ad59b2012-05-03 00:30:07 -0700315 st0 = os.stat(filename)
Brian Curtin52fbea12011-11-06 13:41:17 -0600316 # Doesn't set anything new, but sets the time tuple way
Larry Hastings76ad59b2012-05-03 00:30:07 -0700317 utime(filename, (attr(st0, "st_atime"), attr(st0, "st_mtime")))
318 # Setting the time to the time you just read, then reading again,
319 # should always return exactly the same times.
320 st1 = os.stat(filename)
321 self.assertEqual(attr(st0, "st_mtime"), attr(st1, "st_mtime"))
322 self.assertEqual(attr(st0, "st_atime"), attr(st1, "st_atime"))
Brian Curtin52fbea12011-11-06 13:41:17 -0600323 # Set to the current time in the old explicit way.
Larry Hastings76ad59b2012-05-03 00:30:07 -0700324 os.utime(filename, None)
Brian Curtin52fbea12011-11-06 13:41:17 -0600325 st2 = os.stat(support.TESTFN)
Larry Hastings76ad59b2012-05-03 00:30:07 -0700326 # Set to the current time in the new way
327 os.utime(filename)
328 st3 = os.stat(filename)
329 self.assertAlmostEqual(attr(st2, "st_mtime"), attr(st3, "st_mtime"), delta=delta)
330
331 def test_utime(self):
332 def utime(file, times):
333 return os.utime(file, times)
334 self._test_utime(self.fname, getattr, utime, 10)
335 self._test_utime(support.TESTFN, getattr, utime, 10)
336
337
338 def _test_utime_ns(self, set_times_ns, test_dir=True):
339 def getattr_ns(o, attr):
340 return getattr(o, attr + "_ns")
341 ten_s = 10 * 1000 * 1000 * 1000
342 self._test_utime(self.fname, getattr_ns, set_times_ns, ten_s)
343 if test_dir:
344 self._test_utime(support.TESTFN, getattr_ns, set_times_ns, ten_s)
345
346 def test_utime_ns(self):
347 def utime_ns(file, times):
348 return os.utime(file, ns=times)
349 self._test_utime_ns(utime_ns)
350
Larry Hastings9cf065c2012-06-22 16:30:09 -0700351 requires_utime_dir_fd = unittest.skipUnless(
352 os.utime in os.supports_dir_fd,
353 "dir_fd support for utime required for this test.")
354 requires_utime_fd = unittest.skipUnless(
355 os.utime in os.supports_fd,
356 "fd support for utime required for this test.")
357 requires_utime_nofollow_symlinks = unittest.skipUnless(
358 os.utime in os.supports_follow_symlinks,
359 "follow_symlinks support for utime required for this test.")
Larry Hastings76ad59b2012-05-03 00:30:07 -0700360
Larry Hastings9cf065c2012-06-22 16:30:09 -0700361 @requires_utime_nofollow_symlinks
Larry Hastings76ad59b2012-05-03 00:30:07 -0700362 def test_lutimes_ns(self):
363 def lutimes_ns(file, times):
Larry Hastings9cf065c2012-06-22 16:30:09 -0700364 return os.utime(file, ns=times, follow_symlinks=False)
Larry Hastings76ad59b2012-05-03 00:30:07 -0700365 self._test_utime_ns(lutimes_ns)
366
Larry Hastings9cf065c2012-06-22 16:30:09 -0700367 @requires_utime_fd
Larry Hastings76ad59b2012-05-03 00:30:07 -0700368 def test_futimes_ns(self):
369 def futimes_ns(file, times):
370 with open(file, "wb") as f:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700371 os.utime(f.fileno(), ns=times)
Larry Hastings76ad59b2012-05-03 00:30:07 -0700372 self._test_utime_ns(futimes_ns, test_dir=False)
373
374 def _utime_invalid_arguments(self, name, arg):
Larry Hastings9cf065c2012-06-22 16:30:09 -0700375 with self.assertRaises(ValueError):
Larry Hastings76ad59b2012-05-03 00:30:07 -0700376 getattr(os, name)(arg, (5, 5), ns=(5, 5))
377
378 def test_utime_invalid_arguments(self):
379 self._utime_invalid_arguments('utime', self.fname)
380
Brian Curtin52fbea12011-11-06 13:41:17 -0600381
Victor Stinner1aa54a42012-02-08 04:09:37 +0100382 @unittest.skipUnless(stat_supports_subsecond,
383 "os.stat() doesn't has a subsecond resolution")
Victor Stinnera2f7c002012-02-08 03:36:25 +0100384 def _test_utime_subsecond(self, set_time_func):
Victor Stinnerbe557de2012-02-08 03:01:11 +0100385 asec, amsec = 1, 901
386 atime = asec + amsec * 1e-3
Victor Stinnera2f7c002012-02-08 03:36:25 +0100387 msec, mmsec = 2, 901
Victor Stinnerbe557de2012-02-08 03:01:11 +0100388 mtime = msec + mmsec * 1e-3
389 filename = self.fname
Victor Stinnera2f7c002012-02-08 03:36:25 +0100390 os.utime(filename, (0, 0))
391 set_time_func(filename, atime, mtime)
Victor Stinner034d0aa2012-06-05 01:22:15 +0200392 with warnings.catch_warnings():
393 warnings.simplefilter("ignore", DeprecationWarning)
394 os.stat_float_times(True)
Victor Stinnera2f7c002012-02-08 03:36:25 +0100395 st = os.stat(filename)
396 self.assertAlmostEqual(st.st_atime, atime, places=3)
397 self.assertAlmostEqual(st.st_mtime, mtime, places=3)
Victor Stinnerbe557de2012-02-08 03:01:11 +0100398
Victor Stinnera2f7c002012-02-08 03:36:25 +0100399 def test_utime_subsecond(self):
400 def set_time(filename, atime, mtime):
401 os.utime(filename, (atime, mtime))
402 self._test_utime_subsecond(set_time)
403
Larry Hastings9cf065c2012-06-22 16:30:09 -0700404 @requires_utime_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100405 def test_futimes_subsecond(self):
406 def set_time(filename, atime, mtime):
407 with open(filename, "wb") as f:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700408 os.utime(f.fileno(), times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100409 self._test_utime_subsecond(set_time)
410
Larry Hastings9cf065c2012-06-22 16:30:09 -0700411 @requires_utime_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100412 def test_futimens_subsecond(self):
413 def set_time(filename, atime, mtime):
414 with open(filename, "wb") as f:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700415 os.utime(f.fileno(), times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100416 self._test_utime_subsecond(set_time)
417
Larry Hastings9cf065c2012-06-22 16:30:09 -0700418 @requires_utime_dir_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100419 def test_futimesat_subsecond(self):
420 def set_time(filename, atime, mtime):
421 dirname = os.path.dirname(filename)
422 dirfd = os.open(dirname, os.O_RDONLY)
423 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700424 os.utime(os.path.basename(filename), dir_fd=dirfd,
425 times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100426 finally:
427 os.close(dirfd)
428 self._test_utime_subsecond(set_time)
429
Larry Hastings9cf065c2012-06-22 16:30:09 -0700430 @requires_utime_nofollow_symlinks
Victor Stinnera2f7c002012-02-08 03:36:25 +0100431 def test_lutimes_subsecond(self):
432 def set_time(filename, atime, mtime):
Larry Hastings9cf065c2012-06-22 16:30:09 -0700433 os.utime(filename, (atime, mtime), follow_symlinks=False)
Victor Stinnera2f7c002012-02-08 03:36:25 +0100434 self._test_utime_subsecond(set_time)
435
Larry Hastings9cf065c2012-06-22 16:30:09 -0700436 @requires_utime_dir_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100437 def test_utimensat_subsecond(self):
438 def set_time(filename, atime, mtime):
439 dirname = os.path.dirname(filename)
440 dirfd = os.open(dirname, os.O_RDONLY)
441 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700442 os.utime(os.path.basename(filename), dir_fd=dirfd,
443 times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100444 finally:
445 os.close(dirfd)
446 self._test_utime_subsecond(set_time)
Victor Stinnerbe557de2012-02-08 03:01:11 +0100447
Thomas Wouters89f507f2006-12-13 04:49:30 +0000448 # Restrict test to Win32, since there is no guarantee other
449 # systems support centiseconds
450 if sys.platform == 'win32':
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000451 def get_file_system(path):
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000452 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000453 import ctypes
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000454 kernel32 = ctypes.windll.kernel32
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000455 buf = ctypes.create_unicode_buffer("", 100)
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000456 if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000457 return buf.value
458
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000459 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000460 def test_1565150(self):
461 t1 = 1159195039.25
462 os.utime(self.fname, (t1, t1))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000463 self.assertEqual(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000464
Amaury Forgeot d'Arca251a852011-01-03 00:19:11 +0000465 def test_large_time(self):
466 t1 = 5000000000 # some day in 2128
467 os.utime(self.fname, (t1, t1))
468 self.assertEqual(os.stat(self.fname).st_mtime, t1)
469
Guido van Rossumd8faa362007-04-27 19:54:29 +0000470 def test_1686475(self):
471 # Verify that an open file can be stat'ed
472 try:
473 os.stat(r"c:\pagefile.sys")
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200474 except FileNotFoundError:
475 pass # file does not exist; cannot run test
476 except OSError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000477 self.fail("Could not stat pagefile.sys")
478
Richard Oudkerk2240ac12012-07-06 12:05:32 +0100479 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
480 def test_15261(self):
481 # Verify that stat'ing a closed fd does not cause crash
482 r, w = os.pipe()
483 try:
484 os.stat(r) # should not raise error
485 finally:
486 os.close(r)
487 os.close(w)
488 with self.assertRaises(OSError) as ctx:
489 os.stat(r)
490 self.assertEqual(ctx.exception.errno, errno.EBADF)
491
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000492from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000493
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000494class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000495 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000496 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000497
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000498 def setUp(self):
499 self.__save = dict(os.environ)
Victor Stinnerb745a742010-05-18 17:17:23 +0000500 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000501 self.__saveb = dict(os.environb)
Christian Heimes90333392007-11-01 19:08:42 +0000502 for key, value in self._reference().items():
503 os.environ[key] = value
504
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000505 def tearDown(self):
506 os.environ.clear()
507 os.environ.update(self.__save)
Victor Stinnerb745a742010-05-18 17:17:23 +0000508 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000509 os.environb.clear()
510 os.environb.update(self.__saveb)
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000511
Christian Heimes90333392007-11-01 19:08:42 +0000512 def _reference(self):
513 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
514
515 def _empty_mapping(self):
516 os.environ.clear()
517 return os.environ
518
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000519 # Bug 1110478
Ezio Melottic7e139b2012-09-26 20:01:34 +0300520 @unittest.skipUnless(os.path.exists('/bin/sh'), 'requires /bin/sh')
Martin v. Löwis5510f652005-02-17 21:23:20 +0000521 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000522 os.environ.clear()
Ezio Melottic7e139b2012-09-26 20:01:34 +0300523 os.environ.update(HELLO="World")
524 with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
525 value = popen.read().strip()
526 self.assertEqual(value, "World")
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000527
Ezio Melottic7e139b2012-09-26 20:01:34 +0300528 @unittest.skipUnless(os.path.exists('/bin/sh'), 'requires /bin/sh')
Christian Heimes1a13d592007-11-08 14:16:55 +0000529 def test_os_popen_iter(self):
Ezio Melottic7e139b2012-09-26 20:01:34 +0300530 with os.popen(
531 "/bin/sh -c 'echo \"line1\nline2\nline3\"'") as popen:
532 it = iter(popen)
533 self.assertEqual(next(it), "line1\n")
534 self.assertEqual(next(it), "line2\n")
535 self.assertEqual(next(it), "line3\n")
536 self.assertRaises(StopIteration, next, it)
Christian Heimes1a13d592007-11-08 14:16:55 +0000537
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000538 # Verify environ keys and values from the OS are of the
539 # correct str type.
540 def test_keyvalue_types(self):
541 for key, val in os.environ.items():
Ezio Melottib3aedd42010-11-20 19:04:17 +0000542 self.assertEqual(type(key), str)
543 self.assertEqual(type(val), str)
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000544
Christian Heimes90333392007-11-01 19:08:42 +0000545 def test_items(self):
546 for key, value in self._reference().items():
547 self.assertEqual(os.environ.get(key), value)
548
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000549 # Issue 7310
550 def test___repr__(self):
551 """Check that the repr() of os.environ looks like environ({...})."""
552 env = os.environ
Victor Stinner96f0de92010-07-29 00:29:00 +0000553 self.assertEqual(repr(env), 'environ({{{}}})'.format(', '.join(
554 '{!r}: {!r}'.format(key, value)
555 for key, value in env.items())))
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000556
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000557 def test_get_exec_path(self):
558 defpath_list = os.defpath.split(os.pathsep)
559 test_path = ['/monty', '/python', '', '/flying/circus']
560 test_env = {'PATH': os.pathsep.join(test_path)}
561
562 saved_environ = os.environ
563 try:
564 os.environ = dict(test_env)
565 # Test that defaulting to os.environ works.
566 self.assertSequenceEqual(test_path, os.get_exec_path())
567 self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
568 finally:
569 os.environ = saved_environ
570
571 # No PATH environment variable
572 self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
573 # Empty PATH environment variable
574 self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
575 # Supplied PATH environment variable
576 self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
577
Victor Stinnerb745a742010-05-18 17:17:23 +0000578 if os.supports_bytes_environ:
579 # env cannot contain 'PATH' and b'PATH' keys
Victor Stinner38430e22010-08-19 17:10:18 +0000580 try:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000581 # ignore BytesWarning warning
582 with warnings.catch_warnings(record=True):
583 mixed_env = {'PATH': '1', b'PATH': b'2'}
Victor Stinner38430e22010-08-19 17:10:18 +0000584 except BytesWarning:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000585 # mixed_env cannot be created with python -bb
Victor Stinner38430e22010-08-19 17:10:18 +0000586 pass
587 else:
588 self.assertRaises(ValueError, os.get_exec_path, mixed_env)
Victor Stinnerb745a742010-05-18 17:17:23 +0000589
590 # bytes key and/or value
591 self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}),
592 ['abc'])
593 self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}),
594 ['abc'])
595 self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}),
596 ['abc'])
597
598 @unittest.skipUnless(os.supports_bytes_environ,
599 "os.environb required for this test.")
Victor Stinner84ae1182010-05-06 22:05:07 +0000600 def test_environb(self):
601 # os.environ -> os.environb
602 value = 'euro\u20ac'
603 try:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000604 value_bytes = value.encode(sys.getfilesystemencoding(),
605 'surrogateescape')
Victor Stinner84ae1182010-05-06 22:05:07 +0000606 except UnicodeEncodeError:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000607 msg = "U+20AC character is not encodable to %s" % (
608 sys.getfilesystemencoding(),)
Benjamin Peterson932d3f42010-05-06 22:26:31 +0000609 self.skipTest(msg)
Victor Stinner84ae1182010-05-06 22:05:07 +0000610 os.environ['unicode'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000611 self.assertEqual(os.environ['unicode'], value)
612 self.assertEqual(os.environb[b'unicode'], value_bytes)
Victor Stinner84ae1182010-05-06 22:05:07 +0000613
614 # os.environb -> os.environ
615 value = b'\xff'
616 os.environb[b'bytes'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000617 self.assertEqual(os.environb[b'bytes'], value)
Victor Stinner84ae1182010-05-06 22:05:07 +0000618 value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000619 self.assertEqual(os.environ['bytes'], value_str)
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000620
Charles-François Natali2966f102011-11-26 11:32:46 +0100621 # On FreeBSD < 7 and OS X < 10.6, unsetenv() doesn't return a value (issue
622 # #13415).
623 @support.requires_freebsd_version(7)
624 @support.requires_mac_ver(10, 6)
Victor Stinner60b385e2011-11-22 22:01:28 +0100625 def test_unset_error(self):
626 if sys.platform == "win32":
627 # an environment variable is limited to 32,767 characters
628 key = 'x' * 50000
Victor Stinnerb3f82682011-11-22 22:30:19 +0100629 self.assertRaises(ValueError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100630 else:
631 # "=" is not allowed in a variable name
632 key = 'key='
Victor Stinnerb3f82682011-11-22 22:30:19 +0100633 self.assertRaises(OSError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100634
Victor Stinner6d101392013-04-14 16:35:04 +0200635 def test_key_type(self):
636 missing = 'missingkey'
637 self.assertNotIn(missing, os.environ)
638
Victor Stinner839e5ea2013-04-14 16:43:03 +0200639 with self.assertRaises(KeyError) as cm:
Victor Stinner6d101392013-04-14 16:35:04 +0200640 os.environ[missing]
Victor Stinner839e5ea2013-04-14 16:43:03 +0200641 self.assertIs(cm.exception.args[0], missing)
Victor Stinner6d101392013-04-14 16:35:04 +0200642
Victor Stinner839e5ea2013-04-14 16:43:03 +0200643 with self.assertRaises(KeyError) as cm:
Victor Stinner6d101392013-04-14 16:35:04 +0200644 del os.environ[missing]
Victor Stinner839e5ea2013-04-14 16:43:03 +0200645 self.assertIs(cm.exception.args[0], missing)
Victor Stinner6d101392013-04-14 16:35:04 +0200646
Tim Petersc4e09402003-04-25 07:11:48 +0000647class WalkTests(unittest.TestCase):
648 """Tests for os.walk()."""
649
Charles-François Natali7372b062012-02-05 15:15:38 +0100650 def setUp(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000651 import os
652 from os.path import join
653
654 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000655 # TESTFN/
656 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000657 # tmp1
658 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000659 # tmp2
660 # SUB11/ no kids
661 # SUB2/ a file kid and a dirsymlink kid
662 # tmp3
663 # link/ a symlink to TESTFN.2
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200664 # broken_link
Guido van Rossumd8faa362007-04-27 19:54:29 +0000665 # TEST2/
666 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000667 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000668 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000669 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000670 sub2_path = join(walk_path, "SUB2")
671 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000672 tmp2_path = join(sub1_path, "tmp2")
673 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000674 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000675 t2_path = join(support.TESTFN, "TEST2")
676 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200677 link_path = join(sub2_path, "link")
678 broken_link_path = join(sub2_path, "broken_link")
Tim Petersc4e09402003-04-25 07:11:48 +0000679
680 # Create stuff.
681 os.makedirs(sub11_path)
682 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000683 os.makedirs(t2_path)
684 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000685 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000686 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
687 f.close()
Brian Curtin3b4499c2010-12-28 14:31:47 +0000688 if support.can_symlink():
Jason R. Coombs3a092862013-05-27 23:21:28 -0400689 os.symlink(os.path.abspath(t2_path), link_path)
Jason R. Coombsb501b562013-05-27 23:52:43 -0400690 os.symlink('broken', broken_link_path, True)
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200691 sub2_tree = (sub2_path, ["link"], ["broken_link", "tmp3"])
Guido van Rossumd8faa362007-04-27 19:54:29 +0000692 else:
693 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000694
695 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000696 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000697 self.assertEqual(len(all), 4)
698 # We can't know which order SUB1 and SUB2 will appear in.
699 # Not flipped: TESTFN, SUB1, SUB11, SUB2
700 # flipped: TESTFN, SUB2, SUB1, SUB11
701 flipped = all[0][1][0] != "SUB1"
702 all[0][1].sort()
Hynek Schlawackc96f5a02012-05-15 17:55:38 +0200703 all[3 - 2 * flipped][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000704 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000705 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
706 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000707 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000708
709 # Prune the search.
710 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000711 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000712 all.append((root, dirs, files))
713 # Don't descend into SUB1.
714 if 'SUB1' in dirs:
715 # Note that this also mutates the dirs we appended to all!
716 dirs.remove('SUB1')
717 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000718 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Hynek Schlawack39bf90d2012-05-15 18:40:17 +0200719 all[1][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000720 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000721
722 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000723 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000724 self.assertEqual(len(all), 4)
725 # We can't know which order SUB1 and SUB2 will appear in.
726 # Not flipped: SUB11, SUB1, SUB2, TESTFN
727 # flipped: SUB2, SUB11, SUB1, TESTFN
728 flipped = all[3][1][0] != "SUB1"
729 all[3][1].sort()
Hynek Schlawack39bf90d2012-05-15 18:40:17 +0200730 all[2 - 2 * flipped][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000731 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000732 self.assertEqual(all[flipped], (sub11_path, [], []))
733 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000734 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000735
Brian Curtin3b4499c2010-12-28 14:31:47 +0000736 if support.can_symlink():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000737 # Walk, following symlinks.
738 for root, dirs, files in os.walk(walk_path, followlinks=True):
739 if root == link_path:
740 self.assertEqual(dirs, [])
741 self.assertEqual(files, ["tmp4"])
742 break
743 else:
744 self.fail("Didn't follow symlink with followlinks=True")
745
746 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000747 # Tear everything down. This is a decent use for bottom-up on
748 # Windows, which doesn't have a recursive delete command. The
749 # (not so) subtlety is that rmdir will fail unless the dir's
750 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000751 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000752 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000753 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000754 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000755 dirname = os.path.join(root, name)
756 if not os.path.islink(dirname):
757 os.rmdir(dirname)
758 else:
759 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000760 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000761
Charles-François Natali7372b062012-02-05 15:15:38 +0100762
763@unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
764class FwalkTests(WalkTests):
765 """Tests for os.fwalk()."""
766
Larry Hastingsc48fe982012-06-25 04:49:05 -0700767 def _compare_to_walk(self, walk_kwargs, fwalk_kwargs):
768 """
769 compare with walk() results.
770 """
Larry Hastingsb4038062012-07-15 10:57:38 -0700771 walk_kwargs = walk_kwargs.copy()
772 fwalk_kwargs = fwalk_kwargs.copy()
773 for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
774 walk_kwargs.update(topdown=topdown, followlinks=follow_symlinks)
775 fwalk_kwargs.update(topdown=topdown, follow_symlinks=follow_symlinks)
Larry Hastingsc48fe982012-06-25 04:49:05 -0700776
Charles-François Natali7372b062012-02-05 15:15:38 +0100777 expected = {}
Larry Hastingsc48fe982012-06-25 04:49:05 -0700778 for root, dirs, files in os.walk(**walk_kwargs):
Charles-François Natali7372b062012-02-05 15:15:38 +0100779 expected[root] = (set(dirs), set(files))
780
Larry Hastingsc48fe982012-06-25 04:49:05 -0700781 for root, dirs, files, rootfd in os.fwalk(**fwalk_kwargs):
Charles-François Natali7372b062012-02-05 15:15:38 +0100782 self.assertIn(root, expected)
783 self.assertEqual(expected[root], (set(dirs), set(files)))
784
Larry Hastingsc48fe982012-06-25 04:49:05 -0700785 def test_compare_to_walk(self):
786 kwargs = {'top': support.TESTFN}
787 self._compare_to_walk(kwargs, kwargs)
788
Charles-François Natali7372b062012-02-05 15:15:38 +0100789 def test_dir_fd(self):
Larry Hastingsc48fe982012-06-25 04:49:05 -0700790 try:
791 fd = os.open(".", os.O_RDONLY)
792 walk_kwargs = {'top': support.TESTFN}
793 fwalk_kwargs = walk_kwargs.copy()
794 fwalk_kwargs['dir_fd'] = fd
795 self._compare_to_walk(walk_kwargs, fwalk_kwargs)
796 finally:
797 os.close(fd)
798
799 def test_yields_correct_dir_fd(self):
Charles-François Natali7372b062012-02-05 15:15:38 +0100800 # check returned file descriptors
Larry Hastingsb4038062012-07-15 10:57:38 -0700801 for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
802 args = support.TESTFN, topdown, None
803 for root, dirs, files, rootfd in os.fwalk(*args, follow_symlinks=follow_symlinks):
Charles-François Natali7372b062012-02-05 15:15:38 +0100804 # check that the FD is valid
805 os.fstat(rootfd)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700806 # redundant check
807 os.stat(rootfd)
808 # check that listdir() returns consistent information
809 self.assertEqual(set(os.listdir(rootfd)), set(dirs) | set(files))
Charles-François Natali7372b062012-02-05 15:15:38 +0100810
811 def test_fd_leak(self):
812 # Since we're opening a lot of FDs, we must be careful to avoid leaks:
813 # we both check that calling fwalk() a large number of times doesn't
814 # yield EMFILE, and that the minimum allocated FD hasn't changed.
815 minfd = os.dup(1)
816 os.close(minfd)
817 for i in range(256):
818 for x in os.fwalk(support.TESTFN):
819 pass
820 newfd = os.dup(1)
821 self.addCleanup(os.close, newfd)
822 self.assertEqual(newfd, minfd)
823
824 def tearDown(self):
825 # cleanup
826 for root, dirs, files, rootfd in os.fwalk(support.TESTFN, topdown=False):
827 for name in files:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700828 os.unlink(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +0100829 for name in dirs:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700830 st = os.stat(name, dir_fd=rootfd, follow_symlinks=False)
Larry Hastingsb698d8e2012-06-23 16:55:07 -0700831 if stat.S_ISDIR(st.st_mode):
832 os.rmdir(name, dir_fd=rootfd)
833 else:
834 os.unlink(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +0100835 os.rmdir(support.TESTFN)
836
837
Guido van Rossume7ba4952007-06-06 23:52:48 +0000838class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000839 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000840 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000841
842 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000843 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000844 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
845 os.makedirs(path) # Should work
846 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
847 os.makedirs(path)
848
849 # Try paths with a '.' in them
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000850 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000851 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
852 os.makedirs(path)
853 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
854 'dir5', 'dir6')
855 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000856
Terry Reedy5a22b652010-12-02 07:05:56 +0000857 def test_exist_ok_existing_directory(self):
858 path = os.path.join(support.TESTFN, 'dir1')
859 mode = 0o777
860 old_mask = os.umask(0o022)
861 os.makedirs(path, mode)
862 self.assertRaises(OSError, os.makedirs, path, mode)
863 self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
864 self.assertRaises(OSError, os.makedirs, path, 0o776, exist_ok=True)
865 os.makedirs(path, mode=mode, exist_ok=True)
866 os.umask(old_mask)
867
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700868 def test_exist_ok_s_isgid_directory(self):
869 path = os.path.join(support.TESTFN, 'dir1')
870 S_ISGID = stat.S_ISGID
871 mode = 0o777
872 old_mask = os.umask(0o022)
873 try:
874 existing_testfn_mode = stat.S_IMODE(
875 os.lstat(support.TESTFN).st_mode)
Ned Deilyc622f422012-08-08 20:57:24 -0700876 try:
877 os.chmod(support.TESTFN, existing_testfn_mode | S_ISGID)
Ned Deily3a2b97e2012-08-08 21:03:02 -0700878 except PermissionError:
Ned Deilyc622f422012-08-08 20:57:24 -0700879 raise unittest.SkipTest('Cannot set S_ISGID for dir.')
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700880 if (os.lstat(support.TESTFN).st_mode & S_ISGID != S_ISGID):
881 raise unittest.SkipTest('No support for S_ISGID dir mode.')
882 # The os should apply S_ISGID from the parent dir for us, but
883 # this test need not depend on that behavior. Be explicit.
884 os.makedirs(path, mode | S_ISGID)
885 # http://bugs.python.org/issue14992
886 # Should not fail when the bit is already set.
887 os.makedirs(path, mode, exist_ok=True)
888 # remove the bit.
889 os.chmod(path, stat.S_IMODE(os.lstat(path).st_mode) & ~S_ISGID)
890 with self.assertRaises(OSError):
891 # Should fail when the bit is not already set when demanded.
892 os.makedirs(path, mode | S_ISGID, exist_ok=True)
893 finally:
894 os.umask(old_mask)
Terry Reedy5a22b652010-12-02 07:05:56 +0000895
896 def test_exist_ok_existing_regular_file(self):
897 base = support.TESTFN
898 path = os.path.join(support.TESTFN, 'dir1')
899 f = open(path, 'w')
900 f.write('abc')
901 f.close()
902 self.assertRaises(OSError, os.makedirs, path)
903 self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
904 self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
905 os.remove(path)
906
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000907 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000908 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000909 'dir4', 'dir5', 'dir6')
910 # If the tests failed, the bottom-most directory ('../dir6')
911 # may not have been created, so we look for the outermost directory
912 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000913 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000914 path = os.path.dirname(path)
915
916 os.removedirs(path)
917
Andrew Svetlov405faed2012-12-25 12:18:09 +0200918
919class RemoveDirsTests(unittest.TestCase):
920 def setUp(self):
921 os.makedirs(support.TESTFN)
922
923 def tearDown(self):
924 support.rmtree(support.TESTFN)
925
926 def test_remove_all(self):
927 dira = os.path.join(support.TESTFN, 'dira')
928 os.mkdir(dira)
929 dirb = os.path.join(dira, 'dirb')
930 os.mkdir(dirb)
931 os.removedirs(dirb)
932 self.assertFalse(os.path.exists(dirb))
933 self.assertFalse(os.path.exists(dira))
934 self.assertFalse(os.path.exists(support.TESTFN))
935
936 def test_remove_partial(self):
937 dira = os.path.join(support.TESTFN, 'dira')
938 os.mkdir(dira)
939 dirb = os.path.join(dira, 'dirb')
940 os.mkdir(dirb)
941 with open(os.path.join(dira, 'file.txt'), 'w') as f:
942 f.write('text')
943 os.removedirs(dirb)
944 self.assertFalse(os.path.exists(dirb))
945 self.assertTrue(os.path.exists(dira))
946 self.assertTrue(os.path.exists(support.TESTFN))
947
948 def test_remove_nothing(self):
949 dira = os.path.join(support.TESTFN, 'dira')
950 os.mkdir(dira)
951 dirb = os.path.join(dira, 'dirb')
952 os.mkdir(dirb)
953 with open(os.path.join(dirb, 'file.txt'), 'w') as f:
954 f.write('text')
955 with self.assertRaises(OSError):
956 os.removedirs(dirb)
957 self.assertTrue(os.path.exists(dirb))
958 self.assertTrue(os.path.exists(dira))
959 self.assertTrue(os.path.exists(support.TESTFN))
960
961
Guido van Rossume7ba4952007-06-06 23:52:48 +0000962class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000963 def test_devnull(self):
Victor Stinnera6d2c762011-06-30 18:20:11 +0200964 with open(os.devnull, 'wb') as f:
965 f.write(b'hello')
966 f.close()
967 with open(os.devnull, 'rb') as f:
968 self.assertEqual(f.read(), b'')
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000969
Andrew Svetlov405faed2012-12-25 12:18:09 +0200970
Guido van Rossume7ba4952007-06-06 23:52:48 +0000971class URandomTests(unittest.TestCase):
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100972 def test_urandom_length(self):
973 self.assertEqual(len(os.urandom(0)), 0)
974 self.assertEqual(len(os.urandom(1)), 1)
975 self.assertEqual(len(os.urandom(10)), 10)
976 self.assertEqual(len(os.urandom(100)), 100)
977 self.assertEqual(len(os.urandom(1000)), 1000)
978
979 def test_urandom_value(self):
980 data1 = os.urandom(16)
981 data2 = os.urandom(16)
982 self.assertNotEqual(data1, data2)
983
984 def get_urandom_subprocess(self, count):
985 code = '\n'.join((
986 'import os, sys',
987 'data = os.urandom(%s)' % count,
988 'sys.stdout.buffer.write(data)',
989 'sys.stdout.buffer.flush()'))
990 out = assert_python_ok('-c', code)
991 stdout = out[1]
992 self.assertEqual(len(stdout), 16)
993 return stdout
994
995 def test_urandom_subprocess(self):
996 data1 = self.get_urandom_subprocess(16)
997 data2 = self.get_urandom_subprocess(16)
998 self.assertNotEqual(data1, data2)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000999
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001000@contextlib.contextmanager
1001def _execvpe_mockup(defpath=None):
1002 """
1003 Stubs out execv and execve functions when used as context manager.
1004 Records exec calls. The mock execv and execve functions always raise an
1005 exception as they would normally never return.
1006 """
1007 # A list of tuples containing (function name, first arg, args)
1008 # of calls to execv or execve that have been made.
1009 calls = []
1010
1011 def mock_execv(name, *args):
1012 calls.append(('execv', name, args))
1013 raise RuntimeError("execv called")
1014
1015 def mock_execve(name, *args):
1016 calls.append(('execve', name, args))
1017 raise OSError(errno.ENOTDIR, "execve called")
1018
1019 try:
1020 orig_execv = os.execv
1021 orig_execve = os.execve
1022 orig_defpath = os.defpath
1023 os.execv = mock_execv
1024 os.execve = mock_execve
1025 if defpath is not None:
1026 os.defpath = defpath
1027 yield calls
1028 finally:
1029 os.execv = orig_execv
1030 os.execve = orig_execve
1031 os.defpath = orig_defpath
1032
Guido van Rossume7ba4952007-06-06 23:52:48 +00001033class ExecTests(unittest.TestCase):
Mark Dickinson7cf03892010-04-16 13:45:35 +00001034 @unittest.skipIf(USING_LINUXTHREADS,
1035 "avoid triggering a linuxthreads bug: see issue #4970")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001036 def test_execvpe_with_bad_program(self):
Mark Dickinson7cf03892010-04-16 13:45:35 +00001037 self.assertRaises(OSError, os.execvpe, 'no such app-',
1038 ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001039
Thomas Heller6790d602007-08-30 17:15:14 +00001040 def test_execvpe_with_bad_arglist(self):
1041 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
1042
Gregory P. Smith4ae37772010-05-08 18:05:46 +00001043 @unittest.skipUnless(hasattr(os, '_execvpe'),
1044 "No internal os._execvpe function to test.")
Victor Stinnerb745a742010-05-18 17:17:23 +00001045 def _test_internal_execvpe(self, test_type):
1046 program_path = os.sep + 'absolutepath'
1047 if test_type is bytes:
1048 program = b'executable'
1049 fullpath = os.path.join(os.fsencode(program_path), program)
1050 native_fullpath = fullpath
1051 arguments = [b'progname', 'arg1', 'arg2']
1052 else:
1053 program = 'executable'
1054 arguments = ['progname', 'arg1', 'arg2']
1055 fullpath = os.path.join(program_path, program)
1056 if os.name != "nt":
1057 native_fullpath = os.fsencode(fullpath)
1058 else:
1059 native_fullpath = fullpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001060 env = {'spam': 'beans'}
1061
Victor Stinnerb745a742010-05-18 17:17:23 +00001062 # test os._execvpe() with an absolute path
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001063 with _execvpe_mockup() as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +00001064 self.assertRaises(RuntimeError,
1065 os._execvpe, fullpath, arguments)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001066 self.assertEqual(len(calls), 1)
1067 self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))
1068
Victor Stinnerb745a742010-05-18 17:17:23 +00001069 # test os._execvpe() with a relative path:
1070 # os.get_exec_path() returns defpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001071 with _execvpe_mockup(defpath=program_path) as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +00001072 self.assertRaises(OSError,
1073 os._execvpe, program, arguments, env=env)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001074 self.assertEqual(len(calls), 1)
Victor Stinnerb745a742010-05-18 17:17:23 +00001075 self.assertSequenceEqual(calls[0],
1076 ('execve', native_fullpath, (arguments, env)))
1077
1078 # test os._execvpe() with a relative path:
1079 # os.get_exec_path() reads the 'PATH' variable
1080 with _execvpe_mockup() as calls:
1081 env_path = env.copy()
Victor Stinner38430e22010-08-19 17:10:18 +00001082 if test_type is bytes:
1083 env_path[b'PATH'] = program_path
1084 else:
1085 env_path['PATH'] = program_path
Victor Stinnerb745a742010-05-18 17:17:23 +00001086 self.assertRaises(OSError,
1087 os._execvpe, program, arguments, env=env_path)
1088 self.assertEqual(len(calls), 1)
1089 self.assertSequenceEqual(calls[0],
1090 ('execve', native_fullpath, (arguments, env_path)))
1091
1092 def test_internal_execvpe_str(self):
1093 self._test_internal_execvpe(str)
1094 if os.name != "nt":
1095 self._test_internal_execvpe(bytes)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001096
Gregory P. Smith4ae37772010-05-08 18:05:46 +00001097
Thomas Wouters477c8d52006-05-27 19:21:47 +00001098class Win32ErrorTests(unittest.TestCase):
1099 def test_rename(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001100 self.assertRaises(OSError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001101
1102 def test_remove(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001103 self.assertRaises(OSError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001104
1105 def test_chdir(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001106 self.assertRaises(OSError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001107
1108 def test_mkdir(self):
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +00001109 f = open(support.TESTFN, "w")
Benjamin Petersonf91df042009-02-13 02:50:59 +00001110 try:
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001111 self.assertRaises(OSError, os.mkdir, support.TESTFN)
Benjamin Petersonf91df042009-02-13 02:50:59 +00001112 finally:
1113 f.close()
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +00001114 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001115
1116 def test_utime(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001117 self.assertRaises(OSError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001118
Thomas Wouters477c8d52006-05-27 19:21:47 +00001119 def test_chmod(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001120 self.assertRaises(OSError, os.chmod, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001121
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001122class TestInvalidFD(unittest.TestCase):
Benjamin Peterson05e782f2009-01-19 15:15:02 +00001123 singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001124 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
1125 #singles.append("close")
1126 #We omit close because it doesn'r raise an exception on some platforms
1127 def get_single(f):
1128 def helper(self):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001129 if hasattr(os, f):
1130 self.check(getattr(os, f))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001131 return helper
1132 for f in singles:
1133 locals()["test_"+f] = get_single(f)
1134
Benjamin Peterson7522c742009-01-19 21:00:09 +00001135 def check(self, f, *args):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001136 try:
1137 f(support.make_bad_fd(), *args)
1138 except OSError as e:
1139 self.assertEqual(e.errno, errno.EBADF)
1140 else:
1141 self.fail("%r didn't raise a OSError with a bad file descriptor"
1142 % f)
Benjamin Peterson7522c742009-01-19 21:00:09 +00001143
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001144 def test_isatty(self):
1145 if hasattr(os, "isatty"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001146 self.assertEqual(os.isatty(support.make_bad_fd()), False)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001147
1148 def test_closerange(self):
1149 if hasattr(os, "closerange"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001150 fd = support.make_bad_fd()
R. David Murray630cc482009-07-22 15:20:27 +00001151 # Make sure none of the descriptors we are about to close are
1152 # currently valid (issue 6542).
1153 for i in range(10):
1154 try: os.fstat(fd+i)
1155 except OSError:
1156 pass
1157 else:
1158 break
1159 if i < 2:
1160 raise unittest.SkipTest(
1161 "Unable to acquire a range of invalid file descriptors")
1162 self.assertEqual(os.closerange(fd, fd + i-1), None)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001163
1164 def test_dup2(self):
1165 if hasattr(os, "dup2"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001166 self.check(os.dup2, 20)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001167
1168 def test_fchmod(self):
1169 if hasattr(os, "fchmod"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001170 self.check(os.fchmod, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001171
1172 def test_fchown(self):
1173 if hasattr(os, "fchown"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001174 self.check(os.fchown, -1, -1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001175
1176 def test_fpathconf(self):
1177 if hasattr(os, "fpathconf"):
Georg Brandl306336b2012-06-24 12:55:33 +02001178 self.check(os.pathconf, "PC_NAME_MAX")
Benjamin Peterson7522c742009-01-19 21:00:09 +00001179 self.check(os.fpathconf, "PC_NAME_MAX")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001180
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001181 def test_ftruncate(self):
1182 if hasattr(os, "ftruncate"):
Georg Brandl306336b2012-06-24 12:55:33 +02001183 self.check(os.truncate, 0)
Benjamin Peterson7522c742009-01-19 21:00:09 +00001184 self.check(os.ftruncate, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001185
1186 def test_lseek(self):
1187 if hasattr(os, "lseek"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001188 self.check(os.lseek, 0, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001189
1190 def test_read(self):
1191 if hasattr(os, "read"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001192 self.check(os.read, 1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001193
1194 def test_tcsetpgrpt(self):
1195 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001196 self.check(os.tcsetpgrp, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001197
1198 def test_write(self):
1199 if hasattr(os, "write"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001200 self.check(os.write, b" ")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001201
Brian Curtin1b9df392010-11-24 20:24:31 +00001202
1203class LinkTests(unittest.TestCase):
1204 def setUp(self):
1205 self.file1 = support.TESTFN
1206 self.file2 = os.path.join(support.TESTFN + "2")
1207
Brian Curtinc0abc4e2010-11-30 23:46:54 +00001208 def tearDown(self):
Brian Curtin1b9df392010-11-24 20:24:31 +00001209 for file in (self.file1, self.file2):
1210 if os.path.exists(file):
1211 os.unlink(file)
1212
Brian Curtin1b9df392010-11-24 20:24:31 +00001213 def _test_link(self, file1, file2):
1214 with open(file1, "w") as f1:
1215 f1.write("test")
1216
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001217 with warnings.catch_warnings():
1218 warnings.simplefilter("ignore", DeprecationWarning)
1219 os.link(file1, file2)
Brian Curtin1b9df392010-11-24 20:24:31 +00001220 with open(file1, "r") as f1, open(file2, "r") as f2:
1221 self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
1222
1223 def test_link(self):
1224 self._test_link(self.file1, self.file2)
1225
1226 def test_link_bytes(self):
1227 self._test_link(bytes(self.file1, sys.getfilesystemencoding()),
1228 bytes(self.file2, sys.getfilesystemencoding()))
1229
Brian Curtinf498b752010-11-30 15:54:04 +00001230 def test_unicode_name(self):
Brian Curtin43f0c272010-11-30 15:40:04 +00001231 try:
Brian Curtinf498b752010-11-30 15:54:04 +00001232 os.fsencode("\xf1")
Brian Curtin43f0c272010-11-30 15:40:04 +00001233 except UnicodeError:
1234 raise unittest.SkipTest("Unable to encode for this platform.")
1235
Brian Curtinf498b752010-11-30 15:54:04 +00001236 self.file1 += "\xf1"
Brian Curtinfc889c42010-11-28 23:59:46 +00001237 self.file2 = self.file1 + "2"
1238 self._test_link(self.file1, self.file2)
1239
Thomas Wouters477c8d52006-05-27 19:21:47 +00001240if sys.platform != 'win32':
1241 class Win32ErrorTests(unittest.TestCase):
1242 pass
1243
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001244 class PosixUidGidTests(unittest.TestCase):
1245 if hasattr(os, 'setuid'):
1246 def test_setuid(self):
1247 if os.getuid() != 0:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001248 self.assertRaises(OSError, os.setuid, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001249 self.assertRaises(OverflowError, os.setuid, 1<<32)
1250
1251 if hasattr(os, 'setgid'):
1252 def test_setgid(self):
Stefan Krahebee49a2013-01-17 15:31:00 +01001253 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001254 self.assertRaises(OSError, os.setgid, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001255 self.assertRaises(OverflowError, os.setgid, 1<<32)
1256
1257 if hasattr(os, 'seteuid'):
1258 def test_seteuid(self):
1259 if os.getuid() != 0:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001260 self.assertRaises(OSError, os.seteuid, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001261 self.assertRaises(OverflowError, os.seteuid, 1<<32)
1262
1263 if hasattr(os, 'setegid'):
1264 def test_setegid(self):
Stefan Krahebee49a2013-01-17 15:31:00 +01001265 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001266 self.assertRaises(OSError, os.setegid, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001267 self.assertRaises(OverflowError, os.setegid, 1<<32)
1268
1269 if hasattr(os, 'setreuid'):
1270 def test_setreuid(self):
1271 if os.getuid() != 0:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001272 self.assertRaises(OSError, os.setreuid, 0, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001273 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
1274 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001275
1276 def test_setreuid_neg1(self):
1277 # Needs to accept -1. We run this in a subprocess to avoid
1278 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001279 subprocess.check_call([
1280 sys.executable, '-c',
1281 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001282
1283 if hasattr(os, 'setregid'):
1284 def test_setregid(self):
Stefan Krahebee49a2013-01-17 15:31:00 +01001285 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001286 self.assertRaises(OSError, os.setregid, 0, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001287 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
1288 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001289
1290 def test_setregid_neg1(self):
1291 # Needs to accept -1. We run this in a subprocess to avoid
1292 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001293 subprocess.check_call([
1294 sys.executable, '-c',
1295 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Martin v. Löwis011e8422009-05-05 04:43:17 +00001296
1297 class Pep383Tests(unittest.TestCase):
Martin v. Löwis011e8422009-05-05 04:43:17 +00001298 def setUp(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001299 if support.TESTFN_UNENCODABLE:
1300 self.dir = support.TESTFN_UNENCODABLE
Victor Stinner8b219b22012-11-06 23:23:43 +01001301 elif support.TESTFN_NONASCII:
1302 self.dir = support.TESTFN_NONASCII
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001303 else:
1304 self.dir = support.TESTFN
1305 self.bdir = os.fsencode(self.dir)
1306
1307 bytesfn = []
1308 def add_filename(fn):
1309 try:
1310 fn = os.fsencode(fn)
1311 except UnicodeEncodeError:
1312 return
1313 bytesfn.append(fn)
1314 add_filename(support.TESTFN_UNICODE)
1315 if support.TESTFN_UNENCODABLE:
1316 add_filename(support.TESTFN_UNENCODABLE)
Victor Stinner8b219b22012-11-06 23:23:43 +01001317 if support.TESTFN_NONASCII:
1318 add_filename(support.TESTFN_NONASCII)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001319 if not bytesfn:
1320 self.skipTest("couldn't create any non-ascii filename")
1321
1322 self.unicodefn = set()
Martin v. Löwis011e8422009-05-05 04:43:17 +00001323 os.mkdir(self.dir)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001324 try:
1325 for fn in bytesfn:
Victor Stinnerbf816222011-06-30 23:25:47 +02001326 support.create_empty_file(os.path.join(self.bdir, fn))
Victor Stinnere8d51452010-08-19 01:05:19 +00001327 fn = os.fsdecode(fn)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001328 if fn in self.unicodefn:
1329 raise ValueError("duplicate filename")
1330 self.unicodefn.add(fn)
1331 except:
1332 shutil.rmtree(self.dir)
1333 raise
Martin v. Löwis011e8422009-05-05 04:43:17 +00001334
1335 def tearDown(self):
1336 shutil.rmtree(self.dir)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001337
1338 def test_listdir(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001339 expected = self.unicodefn
1340 found = set(os.listdir(self.dir))
Ezio Melottib3aedd42010-11-20 19:04:17 +00001341 self.assertEqual(found, expected)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001342 # test listdir without arguments
1343 current_directory = os.getcwd()
1344 try:
1345 os.chdir(os.sep)
1346 self.assertEqual(set(os.listdir()), set(os.listdir(os.sep)))
1347 finally:
1348 os.chdir(current_directory)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001349
1350 def test_open(self):
1351 for fn in self.unicodefn:
Victor Stinnera6d2c762011-06-30 18:20:11 +02001352 f = open(os.path.join(self.dir, fn), 'rb')
Martin v. Löwis011e8422009-05-05 04:43:17 +00001353 f.close()
1354
Victor Stinnere4110dc2013-01-01 23:05:55 +01001355 @unittest.skipUnless(hasattr(os, 'statvfs'),
1356 "need os.statvfs()")
1357 def test_statvfs(self):
1358 # issue #9645
1359 for fn in self.unicodefn:
1360 # should not fail with file not found error
1361 fullname = os.path.join(self.dir, fn)
1362 os.statvfs(fullname)
1363
Martin v. Löwis011e8422009-05-05 04:43:17 +00001364 def test_stat(self):
1365 for fn in self.unicodefn:
1366 os.stat(os.path.join(self.dir, fn))
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001367else:
1368 class PosixUidGidTests(unittest.TestCase):
1369 pass
Martin v. Löwis011e8422009-05-05 04:43:17 +00001370 class Pep383Tests(unittest.TestCase):
1371 pass
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001372
Brian Curtineb24d742010-04-12 17:16:38 +00001373@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
1374class Win32KillTests(unittest.TestCase):
Brian Curtinc3acbc32010-05-28 16:08:40 +00001375 def _kill(self, sig):
1376 # Start sys.executable as a subprocess and communicate from the
1377 # subprocess to the parent that the interpreter is ready. When it
1378 # becomes ready, send *sig* via os.kill to the subprocess and check
1379 # that the return code is equal to *sig*.
1380 import ctypes
1381 from ctypes import wintypes
1382 import msvcrt
1383
1384 # Since we can't access the contents of the process' stdout until the
1385 # process has exited, use PeekNamedPipe to see what's inside stdout
1386 # without waiting. This is done so we can tell that the interpreter
1387 # is started and running at a point where it could handle a signal.
1388 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
1389 PeekNamedPipe.restype = wintypes.BOOL
1390 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
1391 ctypes.POINTER(ctypes.c_char), # stdout buf
1392 wintypes.DWORD, # Buffer size
1393 ctypes.POINTER(wintypes.DWORD), # bytes read
1394 ctypes.POINTER(wintypes.DWORD), # bytes avail
1395 ctypes.POINTER(wintypes.DWORD)) # bytes left
1396 msg = "running"
1397 proc = subprocess.Popen([sys.executable, "-c",
1398 "import sys;"
1399 "sys.stdout.write('{}');"
1400 "sys.stdout.flush();"
1401 "input()".format(msg)],
1402 stdout=subprocess.PIPE,
1403 stderr=subprocess.PIPE,
1404 stdin=subprocess.PIPE)
Brian Curtin43ec5772010-11-05 15:17:11 +00001405 self.addCleanup(proc.stdout.close)
1406 self.addCleanup(proc.stderr.close)
1407 self.addCleanup(proc.stdin.close)
Brian Curtinc3acbc32010-05-28 16:08:40 +00001408
1409 count, max = 0, 100
1410 while count < max and proc.poll() is None:
1411 # Create a string buffer to store the result of stdout from the pipe
1412 buf = ctypes.create_string_buffer(len(msg))
1413 # Obtain the text currently in proc.stdout
1414 # Bytes read/avail/left are left as NULL and unused
1415 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
1416 buf, ctypes.sizeof(buf), None, None, None)
1417 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
1418 if buf.value:
1419 self.assertEqual(msg, buf.value.decode())
1420 break
1421 time.sleep(0.1)
1422 count += 1
1423 else:
1424 self.fail("Did not receive communication from the subprocess")
1425
Brian Curtineb24d742010-04-12 17:16:38 +00001426 os.kill(proc.pid, sig)
1427 self.assertEqual(proc.wait(), sig)
1428
1429 def test_kill_sigterm(self):
1430 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinc3acbc32010-05-28 16:08:40 +00001431 self._kill(signal.SIGTERM)
Brian Curtineb24d742010-04-12 17:16:38 +00001432
1433 def test_kill_int(self):
1434 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinc3acbc32010-05-28 16:08:40 +00001435 self._kill(100)
Brian Curtineb24d742010-04-12 17:16:38 +00001436
1437 def _kill_with_event(self, event, name):
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001438 tagname = "test_os_%s" % uuid.uuid1()
1439 m = mmap.mmap(-1, 1, tagname)
1440 m[0] = 0
Brian Curtineb24d742010-04-12 17:16:38 +00001441 # Run a script which has console control handling enabled.
1442 proc = subprocess.Popen([sys.executable,
1443 os.path.join(os.path.dirname(__file__),
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001444 "win_console_handler.py"), tagname],
Brian Curtineb24d742010-04-12 17:16:38 +00001445 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
1446 # Let the interpreter startup before we send signals. See #3137.
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001447 count, max = 0, 100
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001448 while count < max and proc.poll() is None:
Brian Curtinf668df52010-10-15 14:21:06 +00001449 if m[0] == 1:
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001450 break
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001451 time.sleep(0.1)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001452 count += 1
1453 else:
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001454 # Forcefully kill the process if we weren't able to signal it.
1455 os.kill(proc.pid, signal.SIGINT)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001456 self.fail("Subprocess didn't finish initialization")
Brian Curtineb24d742010-04-12 17:16:38 +00001457 os.kill(proc.pid, event)
1458 # proc.send_signal(event) could also be done here.
1459 # Allow time for the signal to be passed and the process to exit.
1460 time.sleep(0.5)
1461 if not proc.poll():
1462 # Forcefully kill the process if we weren't able to signal it.
1463 os.kill(proc.pid, signal.SIGINT)
1464 self.fail("subprocess did not stop on {}".format(name))
1465
1466 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
1467 def test_CTRL_C_EVENT(self):
1468 from ctypes import wintypes
1469 import ctypes
1470
1471 # Make a NULL value by creating a pointer with no argument.
1472 NULL = ctypes.POINTER(ctypes.c_int)()
1473 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
1474 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
1475 wintypes.BOOL)
1476 SetConsoleCtrlHandler.restype = wintypes.BOOL
1477
1478 # Calling this with NULL and FALSE causes the calling process to
1479 # handle CTRL+C, rather than ignore it. This property is inherited
1480 # by subprocesses.
1481 SetConsoleCtrlHandler(NULL, 0)
1482
1483 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
1484
1485 def test_CTRL_BREAK_EVENT(self):
1486 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
1487
1488
Brian Curtind40e6f72010-07-08 21:39:08 +00001489@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Brian Curtin3b4499c2010-12-28 14:31:47 +00001490@support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +00001491class Win32SymlinkTests(unittest.TestCase):
1492 filelink = 'filelinktest'
1493 filelink_target = os.path.abspath(__file__)
1494 dirlink = 'dirlinktest'
1495 dirlink_target = os.path.dirname(filelink_target)
1496 missing_link = 'missing link'
1497
1498 def setUp(self):
1499 assert os.path.exists(self.dirlink_target)
1500 assert os.path.exists(self.filelink_target)
1501 assert not os.path.exists(self.dirlink)
1502 assert not os.path.exists(self.filelink)
1503 assert not os.path.exists(self.missing_link)
1504
1505 def tearDown(self):
1506 if os.path.exists(self.filelink):
1507 os.remove(self.filelink)
1508 if os.path.exists(self.dirlink):
1509 os.rmdir(self.dirlink)
1510 if os.path.lexists(self.missing_link):
1511 os.remove(self.missing_link)
1512
1513 def test_directory_link(self):
Jason R. Coombs3a092862013-05-27 23:21:28 -04001514 os.symlink(self.dirlink_target, self.dirlink)
Brian Curtind40e6f72010-07-08 21:39:08 +00001515 self.assertTrue(os.path.exists(self.dirlink))
1516 self.assertTrue(os.path.isdir(self.dirlink))
1517 self.assertTrue(os.path.islink(self.dirlink))
1518 self.check_stat(self.dirlink, self.dirlink_target)
1519
1520 def test_file_link(self):
1521 os.symlink(self.filelink_target, self.filelink)
1522 self.assertTrue(os.path.exists(self.filelink))
1523 self.assertTrue(os.path.isfile(self.filelink))
1524 self.assertTrue(os.path.islink(self.filelink))
1525 self.check_stat(self.filelink, self.filelink_target)
1526
1527 def _create_missing_dir_link(self):
1528 'Create a "directory" link to a non-existent target'
1529 linkname = self.missing_link
1530 if os.path.lexists(linkname):
1531 os.remove(linkname)
1532 target = r'c:\\target does not exist.29r3c740'
1533 assert not os.path.exists(target)
1534 target_is_dir = True
1535 os.symlink(target, linkname, target_is_dir)
1536
1537 def test_remove_directory_link_to_missing_target(self):
1538 self._create_missing_dir_link()
1539 # For compatibility with Unix, os.remove will check the
1540 # directory status and call RemoveDirectory if the symlink
1541 # was created with target_is_dir==True.
1542 os.remove(self.missing_link)
1543
1544 @unittest.skip("currently fails; consider for improvement")
1545 def test_isdir_on_directory_link_to_missing_target(self):
1546 self._create_missing_dir_link()
1547 # consider having isdir return true for directory links
1548 self.assertTrue(os.path.isdir(self.missing_link))
1549
1550 @unittest.skip("currently fails; consider for improvement")
1551 def test_rmdir_on_directory_link_to_missing_target(self):
1552 self._create_missing_dir_link()
1553 # consider allowing rmdir to remove directory links
1554 os.rmdir(self.missing_link)
1555
1556 def check_stat(self, link, target):
1557 self.assertEqual(os.stat(link), os.stat(target))
1558 self.assertNotEqual(os.lstat(link), os.stat(link))
1559
Brian Curtind25aef52011-06-13 15:16:04 -05001560 bytes_link = os.fsencode(link)
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001561 with warnings.catch_warnings():
1562 warnings.simplefilter("ignore", DeprecationWarning)
1563 self.assertEqual(os.stat(bytes_link), os.stat(target))
1564 self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link))
Brian Curtind25aef52011-06-13 15:16:04 -05001565
1566 def test_12084(self):
1567 level1 = os.path.abspath(support.TESTFN)
1568 level2 = os.path.join(level1, "level2")
1569 level3 = os.path.join(level2, "level3")
1570 try:
1571 os.mkdir(level1)
1572 os.mkdir(level2)
1573 os.mkdir(level3)
1574
1575 file1 = os.path.abspath(os.path.join(level1, "file1"))
1576
1577 with open(file1, "w") as f:
1578 f.write("file1")
1579
1580 orig_dir = os.getcwd()
1581 try:
1582 os.chdir(level2)
1583 link = os.path.join(level2, "link")
1584 os.symlink(os.path.relpath(file1), "link")
1585 self.assertIn("link", os.listdir(os.getcwd()))
1586
1587 # Check os.stat calls from the same dir as the link
1588 self.assertEqual(os.stat(file1), os.stat("link"))
1589
1590 # Check os.stat calls from a dir below the link
1591 os.chdir(level1)
1592 self.assertEqual(os.stat(file1),
1593 os.stat(os.path.relpath(link)))
1594
1595 # Check os.stat calls from a dir above the link
1596 os.chdir(level3)
1597 self.assertEqual(os.stat(file1),
1598 os.stat(os.path.relpath(link)))
1599 finally:
1600 os.chdir(orig_dir)
1601 except OSError as err:
1602 self.fail(err)
1603 finally:
1604 os.remove(file1)
1605 shutil.rmtree(level1)
1606
Brian Curtind40e6f72010-07-08 21:39:08 +00001607
Jason R. Coombs3a092862013-05-27 23:21:28 -04001608@support.skip_unless_symlink
1609class NonLocalSymlinkTests(unittest.TestCase):
1610
1611 def setUp(self):
1612 """
1613 Create this structure:
1614
1615 base
1616 \___ some_dir
1617 """
1618 os.makedirs('base/some_dir')
1619
1620 def tearDown(self):
1621 shutil.rmtree('base')
1622
1623 def test_directory_link_nonlocal(self):
1624 """
1625 The symlink target should resolve relative to the link, not relative
1626 to the current directory.
1627
1628 Then, link base/some_link -> base/some_dir and ensure that some_link
1629 is resolved as a directory.
1630
1631 In issue13772, it was discovered that directory detection failed if
1632 the symlink target was not specified relative to the current
1633 directory, which was a defect in the implementation.
1634 """
1635 src = os.path.join('base', 'some_link')
1636 os.symlink('some_dir', src)
1637 assert os.path.isdir(src)
1638
1639
Victor Stinnere8d51452010-08-19 01:05:19 +00001640class FSEncodingTests(unittest.TestCase):
1641 def test_nop(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001642 self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
1643 self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
Benjamin Peterson31191a92010-05-09 03:22:58 +00001644
Victor Stinnere8d51452010-08-19 01:05:19 +00001645 def test_identity(self):
1646 # assert fsdecode(fsencode(x)) == x
1647 for fn in ('unicode\u0141', 'latin\xe9', 'ascii'):
1648 try:
1649 bytesfn = os.fsencode(fn)
1650 except UnicodeEncodeError:
1651 continue
Ezio Melottib3aedd42010-11-20 19:04:17 +00001652 self.assertEqual(os.fsdecode(bytesfn), fn)
Victor Stinnere8d51452010-08-19 01:05:19 +00001653
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00001654
Brett Cannonefb00c02012-02-29 18:31:31 -05001655
1656class DeviceEncodingTests(unittest.TestCase):
1657
1658 def test_bad_fd(self):
1659 # Return None when an fd doesn't actually exist.
1660 self.assertIsNone(os.device_encoding(123456))
1661
Philip Jenveye308b7c2012-02-29 16:16:15 -08001662 @unittest.skipUnless(os.isatty(0) and (sys.platform.startswith('win') or
1663 (hasattr(locale, 'nl_langinfo') and hasattr(locale, 'CODESET'))),
Philip Jenveyd7aff2d2012-02-29 16:21:25 -08001664 'test requires a tty and either Windows or nl_langinfo(CODESET)')
Brett Cannonefb00c02012-02-29 18:31:31 -05001665 def test_device_encoding(self):
1666 encoding = os.device_encoding(0)
1667 self.assertIsNotNone(encoding)
1668 self.assertTrue(codecs.lookup(encoding))
1669
1670
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00001671class PidTests(unittest.TestCase):
1672 @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid")
1673 def test_getppid(self):
1674 p = subprocess.Popen([sys.executable, '-c',
1675 'import os; print(os.getppid())'],
1676 stdout=subprocess.PIPE)
1677 stdout, _ = p.communicate()
1678 # We are the parent of our subprocess
1679 self.assertEqual(int(stdout), os.getpid())
1680
1681
Brian Curtin0151b8e2010-09-24 13:43:43 +00001682# The introduction of this TestCase caused at least two different errors on
1683# *nix buildbots. Temporarily skip this to let the buildbots move along.
1684@unittest.skip("Skip due to platform/environment differences on *NIX buildbots")
Brian Curtine8e4b3b2010-09-23 20:04:14 +00001685@unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin")
1686class LoginTests(unittest.TestCase):
1687 def test_getlogin(self):
1688 user_name = os.getlogin()
1689 self.assertNotEqual(len(user_name), 0)
1690
1691
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001692@unittest.skipUnless(hasattr(os, 'getpriority') and hasattr(os, 'setpriority'),
1693 "needs os.getpriority and os.setpriority")
1694class ProgramPriorityTests(unittest.TestCase):
1695 """Tests for os.getpriority() and os.setpriority()."""
1696
1697 def test_set_get_priority(self):
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001698
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001699 base = os.getpriority(os.PRIO_PROCESS, os.getpid())
1700 os.setpriority(os.PRIO_PROCESS, os.getpid(), base + 1)
1701 try:
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001702 new_prio = os.getpriority(os.PRIO_PROCESS, os.getpid())
1703 if base >= 19 and new_prio <= 19:
1704 raise unittest.SkipTest(
1705 "unable to reliably test setpriority at current nice level of %s" % base)
1706 else:
1707 self.assertEqual(new_prio, base + 1)
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001708 finally:
1709 try:
1710 os.setpriority(os.PRIO_PROCESS, os.getpid(), base)
1711 except OSError as err:
Antoine Pitrou692f0382011-02-26 00:22:25 +00001712 if err.errno != errno.EACCES:
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001713 raise
1714
1715
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001716if threading is not None:
1717 class SendfileTestServer(asyncore.dispatcher, threading.Thread):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001718
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001719 class Handler(asynchat.async_chat):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001720
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001721 def __init__(self, conn):
1722 asynchat.async_chat.__init__(self, conn)
1723 self.in_buffer = []
1724 self.closed = False
1725 self.push(b"220 ready\r\n")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001726
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001727 def handle_read(self):
1728 data = self.recv(4096)
1729 self.in_buffer.append(data)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001730
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001731 def get_data(self):
1732 return b''.join(self.in_buffer)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001733
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001734 def handle_close(self):
1735 self.close()
1736 self.closed = True
1737
1738 def handle_error(self):
1739 raise
1740
1741 def __init__(self, address):
1742 threading.Thread.__init__(self)
1743 asyncore.dispatcher.__init__(self)
1744 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
1745 self.bind(address)
1746 self.listen(5)
1747 self.host, self.port = self.socket.getsockname()[:2]
1748 self.handler_instance = None
1749 self._active = False
1750 self._active_lock = threading.Lock()
1751
1752 # --- public API
1753
1754 @property
1755 def running(self):
1756 return self._active
1757
1758 def start(self):
1759 assert not self.running
1760 self.__flag = threading.Event()
1761 threading.Thread.start(self)
1762 self.__flag.wait()
1763
1764 def stop(self):
1765 assert self.running
1766 self._active = False
1767 self.join()
1768
1769 def wait(self):
1770 # wait for handler connection to be closed, then stop the server
1771 while not getattr(self.handler_instance, "closed", False):
1772 time.sleep(0.001)
1773 self.stop()
1774
1775 # --- internals
1776
1777 def run(self):
1778 self._active = True
1779 self.__flag.set()
1780 while self._active and asyncore.socket_map:
1781 self._active_lock.acquire()
1782 asyncore.loop(timeout=0.001, count=1)
1783 self._active_lock.release()
1784 asyncore.close_all()
1785
1786 def handle_accept(self):
1787 conn, addr = self.accept()
1788 self.handler_instance = self.Handler(conn)
1789
1790 def handle_connect(self):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001791 self.close()
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001792 handle_read = handle_connect
1793
1794 def writable(self):
1795 return 0
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001796
1797 def handle_error(self):
1798 raise
1799
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001800
Giampaolo Rodolà46134642011-02-25 20:01:05 +00001801@unittest.skipUnless(threading is not None, "test needs threading module")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001802@unittest.skipUnless(hasattr(os, 'sendfile'), "test needs os.sendfile()")
1803class TestSendfile(unittest.TestCase):
1804
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001805 DATA = b"12345abcde" * 16 * 1024 # 160 KB
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001806 SUPPORT_HEADERS_TRAILERS = not sys.platform.startswith("linux") and \
Giampaolo Rodolà4bc68572011-02-25 21:46:01 +00001807 not sys.platform.startswith("solaris") and \
1808 not sys.platform.startswith("sunos")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001809
1810 @classmethod
1811 def setUpClass(cls):
1812 with open(support.TESTFN, "wb") as f:
1813 f.write(cls.DATA)
1814
1815 @classmethod
1816 def tearDownClass(cls):
1817 support.unlink(support.TESTFN)
1818
1819 def setUp(self):
1820 self.server = SendfileTestServer((support.HOST, 0))
1821 self.server.start()
1822 self.client = socket.socket()
1823 self.client.connect((self.server.host, self.server.port))
1824 self.client.settimeout(1)
1825 # synchronize by waiting for "220 ready" response
1826 self.client.recv(1024)
1827 self.sockno = self.client.fileno()
1828 self.file = open(support.TESTFN, 'rb')
1829 self.fileno = self.file.fileno()
1830
1831 def tearDown(self):
1832 self.file.close()
1833 self.client.close()
1834 if self.server.running:
1835 self.server.stop()
1836
1837 def sendfile_wrapper(self, sock, file, offset, nbytes, headers=[], trailers=[]):
1838 """A higher level wrapper representing how an application is
1839 supposed to use sendfile().
1840 """
1841 while 1:
1842 try:
1843 if self.SUPPORT_HEADERS_TRAILERS:
1844 return os.sendfile(sock, file, offset, nbytes, headers,
1845 trailers)
1846 else:
1847 return os.sendfile(sock, file, offset, nbytes)
1848 except OSError as err:
1849 if err.errno == errno.ECONNRESET:
1850 # disconnected
1851 raise
1852 elif err.errno in (errno.EAGAIN, errno.EBUSY):
1853 # we have to retry send data
1854 continue
1855 else:
1856 raise
1857
1858 def test_send_whole_file(self):
1859 # normal send
1860 total_sent = 0
1861 offset = 0
1862 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001863 while total_sent < len(self.DATA):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001864 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
1865 if sent == 0:
1866 break
1867 offset += sent
1868 total_sent += sent
1869 self.assertTrue(sent <= nbytes)
1870 self.assertEqual(offset, total_sent)
1871
1872 self.assertEqual(total_sent, len(self.DATA))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001873 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001874 self.client.close()
1875 self.server.wait()
1876 data = self.server.handler_instance.get_data()
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001877 self.assertEqual(len(data), len(self.DATA))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001878 self.assertEqual(data, self.DATA)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001879
1880 def test_send_at_certain_offset(self):
1881 # start sending a file at a certain offset
1882 total_sent = 0
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001883 offset = len(self.DATA) // 2
1884 must_send = len(self.DATA) - offset
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001885 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001886 while total_sent < must_send:
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001887 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
1888 if sent == 0:
1889 break
1890 offset += sent
1891 total_sent += sent
1892 self.assertTrue(sent <= nbytes)
1893
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001894 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001895 self.client.close()
1896 self.server.wait()
1897 data = self.server.handler_instance.get_data()
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001898 expected = self.DATA[len(self.DATA) // 2:]
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001899 self.assertEqual(total_sent, len(expected))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001900 self.assertEqual(len(data), len(expected))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001901 self.assertEqual(data, expected)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001902
1903 def test_offset_overflow(self):
1904 # specify an offset > file size
1905 offset = len(self.DATA) + 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001906 try:
1907 sent = os.sendfile(self.sockno, self.fileno, offset, 4096)
1908 except OSError as e:
1909 # Solaris can raise EINVAL if offset >= file length, ignore.
1910 if e.errno != errno.EINVAL:
1911 raise
1912 else:
1913 self.assertEqual(sent, 0)
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001914 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001915 self.client.close()
1916 self.server.wait()
1917 data = self.server.handler_instance.get_data()
1918 self.assertEqual(data, b'')
1919
1920 def test_invalid_offset(self):
1921 with self.assertRaises(OSError) as cm:
1922 os.sendfile(self.sockno, self.fileno, -1, 4096)
1923 self.assertEqual(cm.exception.errno, errno.EINVAL)
1924
1925 # --- headers / trailers tests
1926
1927 if SUPPORT_HEADERS_TRAILERS:
1928
1929 def test_headers(self):
1930 total_sent = 0
1931 sent = os.sendfile(self.sockno, self.fileno, 0, 4096,
1932 headers=[b"x" * 512])
1933 total_sent += sent
1934 offset = 4096
1935 nbytes = 4096
1936 while 1:
1937 sent = self.sendfile_wrapper(self.sockno, self.fileno,
1938 offset, nbytes)
1939 if sent == 0:
1940 break
1941 total_sent += sent
1942 offset += sent
1943
1944 expected_data = b"x" * 512 + self.DATA
1945 self.assertEqual(total_sent, len(expected_data))
1946 self.client.close()
1947 self.server.wait()
1948 data = self.server.handler_instance.get_data()
1949 self.assertEqual(hash(data), hash(expected_data))
1950
1951 def test_trailers(self):
1952 TESTFN2 = support.TESTFN + "2"
Brett Cannonb6376802011-03-15 17:38:22 -04001953 with open(TESTFN2, 'wb') as f:
1954 f.write(b"abcde")
1955 with open(TESTFN2, 'rb')as f:
1956 self.addCleanup(os.remove, TESTFN2)
1957 os.sendfile(self.sockno, f.fileno(), 0, 4096,
1958 trailers=[b"12345"])
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001959 self.client.close()
1960 self.server.wait()
1961 data = self.server.handler_instance.get_data()
1962 self.assertEqual(data, b"abcde12345")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001963
1964 if hasattr(os, "SF_NODISKIO"):
1965 def test_flags(self):
1966 try:
1967 os.sendfile(self.sockno, self.fileno, 0, 4096,
1968 flags=os.SF_NODISKIO)
1969 except OSError as err:
1970 if err.errno not in (errno.EBUSY, errno.EAGAIN):
1971 raise
1972
1973
Larry Hastings9cf065c2012-06-22 16:30:09 -07001974def supports_extended_attributes():
1975 if not hasattr(os, "setxattr"):
1976 return False
1977 try:
1978 with open(support.TESTFN, "wb") as fp:
1979 try:
1980 os.setxattr(fp.fileno(), b"user.test", b"")
1981 except OSError:
1982 return False
1983 finally:
1984 support.unlink(support.TESTFN)
1985 # Kernels < 2.6.39 don't respect setxattr flags.
1986 kernel_version = platform.release()
1987 m = re.match("2.6.(\d{1,2})", kernel_version)
1988 return m is None or int(m.group(1)) >= 39
1989
1990
1991@unittest.skipUnless(supports_extended_attributes(),
1992 "no non-broken extended attribute support")
Benjamin Peterson799bd802011-08-31 22:15:17 -04001993class ExtendedAttributeTests(unittest.TestCase):
1994
1995 def tearDown(self):
1996 support.unlink(support.TESTFN)
1997
Larry Hastings9cf065c2012-06-22 16:30:09 -07001998 def _check_xattrs_str(self, s, getxattr, setxattr, removexattr, listxattr, **kwargs):
Benjamin Peterson799bd802011-08-31 22:15:17 -04001999 fn = support.TESTFN
2000 open(fn, "wb").close()
2001 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002002 getxattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002003 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002004 init_xattr = listxattr(fn)
2005 self.assertIsInstance(init_xattr, list)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002006 setxattr(fn, s("user.test"), b"", **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002007 xattr = set(init_xattr)
2008 xattr.add("user.test")
2009 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002010 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"")
2011 setxattr(fn, s("user.test"), b"hello", os.XATTR_REPLACE, **kwargs)
2012 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"hello")
Benjamin Peterson799bd802011-08-31 22:15:17 -04002013 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002014 setxattr(fn, s("user.test"), b"bye", os.XATTR_CREATE, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002015 self.assertEqual(cm.exception.errno, errno.EEXIST)
2016 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002017 setxattr(fn, s("user.test2"), b"bye", os.XATTR_REPLACE, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002018 self.assertEqual(cm.exception.errno, errno.ENODATA)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002019 setxattr(fn, s("user.test2"), b"foo", os.XATTR_CREATE, **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002020 xattr.add("user.test2")
2021 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002022 removexattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002023 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002024 getxattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002025 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002026 xattr.remove("user.test")
2027 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002028 self.assertEqual(getxattr(fn, s("user.test2"), **kwargs), b"foo")
2029 setxattr(fn, s("user.test"), b"a"*1024, **kwargs)
2030 self.assertEqual(getxattr(fn, s("user.test"), **kwargs), b"a"*1024)
2031 removexattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002032 many = sorted("user.test{}".format(i) for i in range(100))
2033 for thing in many:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002034 setxattr(fn, thing, b"x", **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002035 self.assertEqual(set(listxattr(fn)), set(init_xattr) | set(many))
Benjamin Peterson799bd802011-08-31 22:15:17 -04002036
Larry Hastings9cf065c2012-06-22 16:30:09 -07002037 def _check_xattrs(self, *args, **kwargs):
Benjamin Peterson799bd802011-08-31 22:15:17 -04002038 def make_bytes(s):
2039 return bytes(s, "ascii")
Larry Hastings9cf065c2012-06-22 16:30:09 -07002040 self._check_xattrs_str(str, *args, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002041 support.unlink(support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002042 self._check_xattrs_str(make_bytes, *args, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002043
2044 def test_simple(self):
2045 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
2046 os.listxattr)
2047
2048 def test_lpath(self):
Larry Hastings9cf065c2012-06-22 16:30:09 -07002049 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
2050 os.listxattr, follow_symlinks=False)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002051
2052 def test_fds(self):
2053 def getxattr(path, *args):
2054 with open(path, "rb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002055 return os.getxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002056 def setxattr(path, *args):
2057 with open(path, "wb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002058 os.setxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002059 def removexattr(path, *args):
2060 with open(path, "wb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002061 os.removexattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002062 def listxattr(path, *args):
2063 with open(path, "rb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002064 return os.listxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002065 self._check_xattrs(getxattr, setxattr, removexattr, listxattr)
2066
2067
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002068@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
2069class Win32DeprecatedBytesAPI(unittest.TestCase):
2070 def test_deprecated(self):
2071 import nt
2072 filename = os.fsencode(support.TESTFN)
2073 with warnings.catch_warnings():
2074 warnings.simplefilter("error", DeprecationWarning)
2075 for func, *args in (
2076 (nt._getfullpathname, filename),
2077 (nt._isdir, filename),
2078 (os.access, filename, os.R_OK),
2079 (os.chdir, filename),
2080 (os.chmod, filename, 0o777),
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01002081 (os.getcwdb,),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002082 (os.link, filename, filename),
2083 (os.listdir, filename),
2084 (os.lstat, filename),
2085 (os.mkdir, filename),
2086 (os.open, filename, os.O_RDONLY),
2087 (os.rename, filename, filename),
2088 (os.rmdir, filename),
2089 (os.startfile, filename),
2090 (os.stat, filename),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002091 (os.unlink, filename),
2092 (os.utime, filename),
2093 ):
2094 self.assertRaises(DeprecationWarning, func, *args)
2095
Victor Stinner28216442011-11-16 00:34:44 +01002096 @support.skip_unless_symlink
2097 def test_symlink(self):
2098 filename = os.fsencode(support.TESTFN)
2099 with warnings.catch_warnings():
2100 warnings.simplefilter("error", DeprecationWarning)
2101 self.assertRaises(DeprecationWarning,
2102 os.symlink, filename, filename)
2103
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002104
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002105@unittest.skipUnless(hasattr(os, 'get_terminal_size'), "requires os.get_terminal_size")
2106class TermsizeTests(unittest.TestCase):
2107 def test_does_not_crash(self):
2108 """Check if get_terminal_size() returns a meaningful value.
2109
2110 There's no easy portable way to actually check the size of the
2111 terminal, so let's check if it returns something sensible instead.
2112 """
2113 try:
2114 size = os.get_terminal_size()
2115 except OSError as e:
Antoine Pitrou81a1fa52012-02-09 00:11:00 +01002116 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002117 # Under win32 a generic OSError can be thrown if the
2118 # handle cannot be retrieved
2119 self.skipTest("failed to query terminal size")
2120 raise
2121
Antoine Pitroucfade362012-02-08 23:48:59 +01002122 self.assertGreaterEqual(size.columns, 0)
2123 self.assertGreaterEqual(size.lines, 0)
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002124
2125 def test_stty_match(self):
2126 """Check if stty returns the same results
2127
2128 stty actually tests stdin, so get_terminal_size is invoked on
2129 stdin explicitly. If stty succeeded, then get_terminal_size()
2130 should work too.
2131 """
2132 try:
2133 size = subprocess.check_output(['stty', 'size']).decode().split()
2134 except (FileNotFoundError, subprocess.CalledProcessError):
2135 self.skipTest("stty invocation failed")
2136 expected = (int(size[1]), int(size[0])) # reversed order
2137
Antoine Pitrou81a1fa52012-02-09 00:11:00 +01002138 try:
2139 actual = os.get_terminal_size(sys.__stdin__.fileno())
2140 except OSError as e:
2141 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
2142 # Under win32 a generic OSError can be thrown if the
2143 # handle cannot be retrieved
2144 self.skipTest("failed to query terminal size")
2145 raise
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002146 self.assertEqual(expected, actual)
2147
2148
Victor Stinner292c8352012-10-30 02:17:38 +01002149class OSErrorTests(unittest.TestCase):
2150 def setUp(self):
2151 class Str(str):
2152 pass
2153
Victor Stinnerafe17062012-10-31 22:47:43 +01002154 self.bytes_filenames = []
2155 self.unicode_filenames = []
Victor Stinner292c8352012-10-30 02:17:38 +01002156 if support.TESTFN_UNENCODABLE is not None:
2157 decoded = support.TESTFN_UNENCODABLE
2158 else:
2159 decoded = support.TESTFN
Victor Stinnerafe17062012-10-31 22:47:43 +01002160 self.unicode_filenames.append(decoded)
2161 self.unicode_filenames.append(Str(decoded))
Victor Stinner292c8352012-10-30 02:17:38 +01002162 if support.TESTFN_UNDECODABLE is not None:
2163 encoded = support.TESTFN_UNDECODABLE
2164 else:
2165 encoded = os.fsencode(support.TESTFN)
Victor Stinnerafe17062012-10-31 22:47:43 +01002166 self.bytes_filenames.append(encoded)
2167 self.bytes_filenames.append(memoryview(encoded))
2168
2169 self.filenames = self.bytes_filenames + self.unicode_filenames
Victor Stinner292c8352012-10-30 02:17:38 +01002170
2171 def test_oserror_filename(self):
2172 funcs = [
Victor Stinnerafe17062012-10-31 22:47:43 +01002173 (self.filenames, os.chdir,),
2174 (self.filenames, os.chmod, 0o777),
Victor Stinnerafe17062012-10-31 22:47:43 +01002175 (self.filenames, os.lstat,),
2176 (self.filenames, os.open, os.O_RDONLY),
2177 (self.filenames, os.rmdir,),
2178 (self.filenames, os.stat,),
2179 (self.filenames, os.unlink,),
Victor Stinner292c8352012-10-30 02:17:38 +01002180 ]
2181 if sys.platform == "win32":
2182 funcs.extend((
Victor Stinnerafe17062012-10-31 22:47:43 +01002183 (self.bytes_filenames, os.rename, b"dst"),
2184 (self.bytes_filenames, os.replace, b"dst"),
2185 (self.unicode_filenames, os.rename, "dst"),
2186 (self.unicode_filenames, os.replace, "dst"),
Victor Stinner64e039a2012-11-07 00:10:14 +01002187 # Issue #16414: Don't test undecodable names with listdir()
2188 # because of a Windows bug.
2189 #
2190 # With the ANSI code page 932, os.listdir(b'\xe7') return an
2191 # empty list (instead of failing), whereas os.listdir(b'\xff')
2192 # raises a FileNotFoundError. It looks like a Windows bug:
2193 # b'\xe7' directory does not exist, FindFirstFileA(b'\xe7')
2194 # fails with ERROR_FILE_NOT_FOUND (2), instead of
2195 # ERROR_PATH_NOT_FOUND (3).
2196 (self.unicode_filenames, os.listdir,),
Victor Stinner292c8352012-10-30 02:17:38 +01002197 ))
Victor Stinnerafe17062012-10-31 22:47:43 +01002198 else:
2199 funcs.extend((
Victor Stinner64e039a2012-11-07 00:10:14 +01002200 (self.filenames, os.listdir,),
Victor Stinnerafe17062012-10-31 22:47:43 +01002201 (self.filenames, os.rename, "dst"),
2202 (self.filenames, os.replace, "dst"),
2203 ))
2204 if hasattr(os, "chown"):
2205 funcs.append((self.filenames, os.chown, 0, 0))
2206 if hasattr(os, "lchown"):
2207 funcs.append((self.filenames, os.lchown, 0, 0))
2208 if hasattr(os, "truncate"):
2209 funcs.append((self.filenames, os.truncate, 0))
Victor Stinner292c8352012-10-30 02:17:38 +01002210 if hasattr(os, "chflags"):
Victor Stinneree36c242012-11-13 09:31:51 +01002211 funcs.append((self.filenames, os.chflags, 0))
2212 if hasattr(os, "lchflags"):
2213 funcs.append((self.filenames, os.lchflags, 0))
Victor Stinner292c8352012-10-30 02:17:38 +01002214 if hasattr(os, "chroot"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002215 funcs.append((self.filenames, os.chroot,))
Victor Stinner292c8352012-10-30 02:17:38 +01002216 if hasattr(os, "link"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002217 if sys.platform == "win32":
2218 funcs.append((self.bytes_filenames, os.link, b"dst"))
2219 funcs.append((self.unicode_filenames, os.link, "dst"))
2220 else:
2221 funcs.append((self.filenames, os.link, "dst"))
Victor Stinner292c8352012-10-30 02:17:38 +01002222 if hasattr(os, "listxattr"):
2223 funcs.extend((
Victor Stinnerafe17062012-10-31 22:47:43 +01002224 (self.filenames, os.listxattr,),
2225 (self.filenames, os.getxattr, "user.test"),
2226 (self.filenames, os.setxattr, "user.test", b'user'),
2227 (self.filenames, os.removexattr, "user.test"),
Victor Stinner292c8352012-10-30 02:17:38 +01002228 ))
2229 if hasattr(os, "lchmod"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002230 funcs.append((self.filenames, os.lchmod, 0o777))
Victor Stinner292c8352012-10-30 02:17:38 +01002231 if hasattr(os, "readlink"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002232 if sys.platform == "win32":
2233 funcs.append((self.unicode_filenames, os.readlink,))
2234 else:
2235 funcs.append((self.filenames, os.readlink,))
Victor Stinner292c8352012-10-30 02:17:38 +01002236
Victor Stinnerafe17062012-10-31 22:47:43 +01002237 for filenames, func, *func_args in funcs:
2238 for name in filenames:
Victor Stinner292c8352012-10-30 02:17:38 +01002239 try:
2240 func(name, *func_args)
Victor Stinnerbd54f0e2012-10-31 01:12:55 +01002241 except OSError as err:
Victor Stinner292c8352012-10-30 02:17:38 +01002242 self.assertIs(err.filename, name)
2243 else:
2244 self.fail("No exception thrown by {}".format(func))
2245
Charles-Francois Natali44feda32013-05-20 14:40:46 +02002246class CPUCountTests(unittest.TestCase):
2247 def test_cpu_count(self):
2248 cpus = os.cpu_count()
2249 if cpus is not None:
2250 self.assertIsInstance(cpus, int)
2251 self.assertGreater(cpus, 0)
2252 else:
2253 self.skipTest("Could not determine the number of CPUs")
2254
Antoine Pitrouf26ad712011-07-15 23:00:56 +02002255@support.reap_threads
Fred Drake2e2be372001-09-20 21:33:42 +00002256def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002257 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002258 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002259 StatAttributeTests,
2260 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00002261 WalkTests,
Charles-François Natali7372b062012-02-05 15:15:38 +01002262 FwalkTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00002263 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +00002264 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002265 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +00002266 ExecTests,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00002267 Win32ErrorTests,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002268 TestInvalidFD,
Martin v. Löwis011e8422009-05-05 04:43:17 +00002269 PosixUidGidTests,
Brian Curtineb24d742010-04-12 17:16:38 +00002270 Pep383Tests,
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00002271 Win32KillTests,
Brian Curtind40e6f72010-07-08 21:39:08 +00002272 Win32SymlinkTests,
Jason R. Coombs3a092862013-05-27 23:21:28 -04002273 NonLocalSymlinkTests,
Victor Stinnere8d51452010-08-19 01:05:19 +00002274 FSEncodingTests,
Brett Cannonefb00c02012-02-29 18:31:31 -05002275 DeviceEncodingTests,
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00002276 PidTests,
Brian Curtine8e4b3b2010-09-23 20:04:14 +00002277 LoginTests,
Brian Curtin1b9df392010-11-24 20:24:31 +00002278 LinkTests,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002279 TestSendfile,
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00002280 ProgramPriorityTests,
Benjamin Peterson799bd802011-08-31 22:15:17 -04002281 ExtendedAttributeTests,
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002282 Win32DeprecatedBytesAPI,
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002283 TermsizeTests,
Victor Stinner292c8352012-10-30 02:17:38 +01002284 OSErrorTests,
Andrew Svetlov405faed2012-12-25 12:18:09 +02002285 RemoveDirsTests,
Charles-Francois Natali44feda32013-05-20 14:40:46 +02002286 CPUCountTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002287 )
Fred Drake2e2be372001-09-20 21:33:42 +00002288
2289if __name__ == "__main__":
2290 test_main()