blob: 65d3c3bf6e3f7841aeac53cc1aa4c4b0c96b99f1 [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():
Antoine Pitrou5311c1d2012-01-24 08:59:28 +0100689 if os.name == 'nt':
690 def symlink_to_dir(src, dest):
691 os.symlink(src, dest, True)
692 else:
693 symlink_to_dir = os.symlink
694 symlink_to_dir(os.path.abspath(t2_path), link_path)
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200695 symlink_to_dir('broken', broken_link_path)
696 sub2_tree = (sub2_path, ["link"], ["broken_link", "tmp3"])
Guido van Rossumd8faa362007-04-27 19:54:29 +0000697 else:
698 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000699
700 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000701 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000702 self.assertEqual(len(all), 4)
703 # We can't know which order SUB1 and SUB2 will appear in.
704 # Not flipped: TESTFN, SUB1, SUB11, SUB2
705 # flipped: TESTFN, SUB2, SUB1, SUB11
706 flipped = all[0][1][0] != "SUB1"
707 all[0][1].sort()
Hynek Schlawackc96f5a02012-05-15 17:55:38 +0200708 all[3 - 2 * flipped][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000709 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000710 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
711 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000712 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000713
714 # Prune the search.
715 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000716 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000717 all.append((root, dirs, files))
718 # Don't descend into SUB1.
719 if 'SUB1' in dirs:
720 # Note that this also mutates the dirs we appended to all!
721 dirs.remove('SUB1')
722 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000723 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Hynek Schlawack39bf90d2012-05-15 18:40:17 +0200724 all[1][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000725 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000726
727 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000728 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000729 self.assertEqual(len(all), 4)
730 # We can't know which order SUB1 and SUB2 will appear in.
731 # Not flipped: SUB11, SUB1, SUB2, TESTFN
732 # flipped: SUB2, SUB11, SUB1, TESTFN
733 flipped = all[3][1][0] != "SUB1"
734 all[3][1].sort()
Hynek Schlawack39bf90d2012-05-15 18:40:17 +0200735 all[2 - 2 * flipped][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000736 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000737 self.assertEqual(all[flipped], (sub11_path, [], []))
738 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000739 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000740
Brian Curtin3b4499c2010-12-28 14:31:47 +0000741 if support.can_symlink():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000742 # Walk, following symlinks.
743 for root, dirs, files in os.walk(walk_path, followlinks=True):
744 if root == link_path:
745 self.assertEqual(dirs, [])
746 self.assertEqual(files, ["tmp4"])
747 break
748 else:
749 self.fail("Didn't follow symlink with followlinks=True")
750
751 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000752 # Tear everything down. This is a decent use for bottom-up on
753 # Windows, which doesn't have a recursive delete command. The
754 # (not so) subtlety is that rmdir will fail unless the dir's
755 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000756 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000757 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000758 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000759 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000760 dirname = os.path.join(root, name)
761 if not os.path.islink(dirname):
762 os.rmdir(dirname)
763 else:
764 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000765 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000766
Charles-François Natali7372b062012-02-05 15:15:38 +0100767
768@unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
769class FwalkTests(WalkTests):
770 """Tests for os.fwalk()."""
771
Larry Hastingsc48fe982012-06-25 04:49:05 -0700772 def _compare_to_walk(self, walk_kwargs, fwalk_kwargs):
773 """
774 compare with walk() results.
775 """
Larry Hastingsb4038062012-07-15 10:57:38 -0700776 walk_kwargs = walk_kwargs.copy()
777 fwalk_kwargs = fwalk_kwargs.copy()
778 for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
779 walk_kwargs.update(topdown=topdown, followlinks=follow_symlinks)
780 fwalk_kwargs.update(topdown=topdown, follow_symlinks=follow_symlinks)
Larry Hastingsc48fe982012-06-25 04:49:05 -0700781
Charles-François Natali7372b062012-02-05 15:15:38 +0100782 expected = {}
Larry Hastingsc48fe982012-06-25 04:49:05 -0700783 for root, dirs, files in os.walk(**walk_kwargs):
Charles-François Natali7372b062012-02-05 15:15:38 +0100784 expected[root] = (set(dirs), set(files))
785
Larry Hastingsc48fe982012-06-25 04:49:05 -0700786 for root, dirs, files, rootfd in os.fwalk(**fwalk_kwargs):
Charles-François Natali7372b062012-02-05 15:15:38 +0100787 self.assertIn(root, expected)
788 self.assertEqual(expected[root], (set(dirs), set(files)))
789
Larry Hastingsc48fe982012-06-25 04:49:05 -0700790 def test_compare_to_walk(self):
791 kwargs = {'top': support.TESTFN}
792 self._compare_to_walk(kwargs, kwargs)
793
Charles-François Natali7372b062012-02-05 15:15:38 +0100794 def test_dir_fd(self):
Larry Hastingsc48fe982012-06-25 04:49:05 -0700795 try:
796 fd = os.open(".", os.O_RDONLY)
797 walk_kwargs = {'top': support.TESTFN}
798 fwalk_kwargs = walk_kwargs.copy()
799 fwalk_kwargs['dir_fd'] = fd
800 self._compare_to_walk(walk_kwargs, fwalk_kwargs)
801 finally:
802 os.close(fd)
803
804 def test_yields_correct_dir_fd(self):
Charles-François Natali7372b062012-02-05 15:15:38 +0100805 # check returned file descriptors
Larry Hastingsb4038062012-07-15 10:57:38 -0700806 for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
807 args = support.TESTFN, topdown, None
808 for root, dirs, files, rootfd in os.fwalk(*args, follow_symlinks=follow_symlinks):
Charles-François Natali7372b062012-02-05 15:15:38 +0100809 # check that the FD is valid
810 os.fstat(rootfd)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700811 # redundant check
812 os.stat(rootfd)
813 # check that listdir() returns consistent information
814 self.assertEqual(set(os.listdir(rootfd)), set(dirs) | set(files))
Charles-François Natali7372b062012-02-05 15:15:38 +0100815
816 def test_fd_leak(self):
817 # Since we're opening a lot of FDs, we must be careful to avoid leaks:
818 # we both check that calling fwalk() a large number of times doesn't
819 # yield EMFILE, and that the minimum allocated FD hasn't changed.
820 minfd = os.dup(1)
821 os.close(minfd)
822 for i in range(256):
823 for x in os.fwalk(support.TESTFN):
824 pass
825 newfd = os.dup(1)
826 self.addCleanup(os.close, newfd)
827 self.assertEqual(newfd, minfd)
828
829 def tearDown(self):
830 # cleanup
831 for root, dirs, files, rootfd in os.fwalk(support.TESTFN, topdown=False):
832 for name in files:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700833 os.unlink(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +0100834 for name in dirs:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700835 st = os.stat(name, dir_fd=rootfd, follow_symlinks=False)
Larry Hastingsb698d8e2012-06-23 16:55:07 -0700836 if stat.S_ISDIR(st.st_mode):
837 os.rmdir(name, dir_fd=rootfd)
838 else:
839 os.unlink(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +0100840 os.rmdir(support.TESTFN)
841
842
Guido van Rossume7ba4952007-06-06 23:52:48 +0000843class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000844 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000845 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000846
847 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000848 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000849 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
850 os.makedirs(path) # Should work
851 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
852 os.makedirs(path)
853
854 # Try paths with a '.' in them
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000855 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000856 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
857 os.makedirs(path)
858 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
859 'dir5', 'dir6')
860 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000861
Terry Reedy5a22b652010-12-02 07:05:56 +0000862 def test_exist_ok_existing_directory(self):
863 path = os.path.join(support.TESTFN, 'dir1')
864 mode = 0o777
865 old_mask = os.umask(0o022)
866 os.makedirs(path, mode)
867 self.assertRaises(OSError, os.makedirs, path, mode)
868 self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
869 self.assertRaises(OSError, os.makedirs, path, 0o776, exist_ok=True)
870 os.makedirs(path, mode=mode, exist_ok=True)
871 os.umask(old_mask)
872
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700873 def test_exist_ok_s_isgid_directory(self):
874 path = os.path.join(support.TESTFN, 'dir1')
875 S_ISGID = stat.S_ISGID
876 mode = 0o777
877 old_mask = os.umask(0o022)
878 try:
879 existing_testfn_mode = stat.S_IMODE(
880 os.lstat(support.TESTFN).st_mode)
Ned Deilyc622f422012-08-08 20:57:24 -0700881 try:
882 os.chmod(support.TESTFN, existing_testfn_mode | S_ISGID)
Ned Deily3a2b97e2012-08-08 21:03:02 -0700883 except PermissionError:
Ned Deilyc622f422012-08-08 20:57:24 -0700884 raise unittest.SkipTest('Cannot set S_ISGID for dir.')
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700885 if (os.lstat(support.TESTFN).st_mode & S_ISGID != S_ISGID):
886 raise unittest.SkipTest('No support for S_ISGID dir mode.')
887 # The os should apply S_ISGID from the parent dir for us, but
888 # this test need not depend on that behavior. Be explicit.
889 os.makedirs(path, mode | S_ISGID)
890 # http://bugs.python.org/issue14992
891 # Should not fail when the bit is already set.
892 os.makedirs(path, mode, exist_ok=True)
893 # remove the bit.
894 os.chmod(path, stat.S_IMODE(os.lstat(path).st_mode) & ~S_ISGID)
895 with self.assertRaises(OSError):
896 # Should fail when the bit is not already set when demanded.
897 os.makedirs(path, mode | S_ISGID, exist_ok=True)
898 finally:
899 os.umask(old_mask)
Terry Reedy5a22b652010-12-02 07:05:56 +0000900
901 def test_exist_ok_existing_regular_file(self):
902 base = support.TESTFN
903 path = os.path.join(support.TESTFN, 'dir1')
904 f = open(path, 'w')
905 f.write('abc')
906 f.close()
907 self.assertRaises(OSError, os.makedirs, path)
908 self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
909 self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
910 os.remove(path)
911
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000912 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000913 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000914 'dir4', 'dir5', 'dir6')
915 # If the tests failed, the bottom-most directory ('../dir6')
916 # may not have been created, so we look for the outermost directory
917 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000918 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000919 path = os.path.dirname(path)
920
921 os.removedirs(path)
922
Andrew Svetlov405faed2012-12-25 12:18:09 +0200923
924class RemoveDirsTests(unittest.TestCase):
925 def setUp(self):
926 os.makedirs(support.TESTFN)
927
928 def tearDown(self):
929 support.rmtree(support.TESTFN)
930
931 def test_remove_all(self):
932 dira = os.path.join(support.TESTFN, 'dira')
933 os.mkdir(dira)
934 dirb = os.path.join(dira, 'dirb')
935 os.mkdir(dirb)
936 os.removedirs(dirb)
937 self.assertFalse(os.path.exists(dirb))
938 self.assertFalse(os.path.exists(dira))
939 self.assertFalse(os.path.exists(support.TESTFN))
940
941 def test_remove_partial(self):
942 dira = os.path.join(support.TESTFN, 'dira')
943 os.mkdir(dira)
944 dirb = os.path.join(dira, 'dirb')
945 os.mkdir(dirb)
946 with open(os.path.join(dira, 'file.txt'), 'w') as f:
947 f.write('text')
948 os.removedirs(dirb)
949 self.assertFalse(os.path.exists(dirb))
950 self.assertTrue(os.path.exists(dira))
951 self.assertTrue(os.path.exists(support.TESTFN))
952
953 def test_remove_nothing(self):
954 dira = os.path.join(support.TESTFN, 'dira')
955 os.mkdir(dira)
956 dirb = os.path.join(dira, 'dirb')
957 os.mkdir(dirb)
958 with open(os.path.join(dirb, 'file.txt'), 'w') as f:
959 f.write('text')
960 with self.assertRaises(OSError):
961 os.removedirs(dirb)
962 self.assertTrue(os.path.exists(dirb))
963 self.assertTrue(os.path.exists(dira))
964 self.assertTrue(os.path.exists(support.TESTFN))
965
966
Guido van Rossume7ba4952007-06-06 23:52:48 +0000967class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000968 def test_devnull(self):
Victor Stinnera6d2c762011-06-30 18:20:11 +0200969 with open(os.devnull, 'wb') as f:
970 f.write(b'hello')
971 f.close()
972 with open(os.devnull, 'rb') as f:
973 self.assertEqual(f.read(), b'')
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000974
Andrew Svetlov405faed2012-12-25 12:18:09 +0200975
Guido van Rossume7ba4952007-06-06 23:52:48 +0000976class URandomTests(unittest.TestCase):
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100977 def test_urandom_length(self):
978 self.assertEqual(len(os.urandom(0)), 0)
979 self.assertEqual(len(os.urandom(1)), 1)
980 self.assertEqual(len(os.urandom(10)), 10)
981 self.assertEqual(len(os.urandom(100)), 100)
982 self.assertEqual(len(os.urandom(1000)), 1000)
983
984 def test_urandom_value(self):
985 data1 = os.urandom(16)
986 data2 = os.urandom(16)
987 self.assertNotEqual(data1, data2)
988
989 def get_urandom_subprocess(self, count):
990 code = '\n'.join((
991 'import os, sys',
992 'data = os.urandom(%s)' % count,
993 'sys.stdout.buffer.write(data)',
994 'sys.stdout.buffer.flush()'))
995 out = assert_python_ok('-c', code)
996 stdout = out[1]
997 self.assertEqual(len(stdout), 16)
998 return stdout
999
1000 def test_urandom_subprocess(self):
1001 data1 = self.get_urandom_subprocess(16)
1002 data2 = self.get_urandom_subprocess(16)
1003 self.assertNotEqual(data1, data2)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +00001004
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001005@contextlib.contextmanager
1006def _execvpe_mockup(defpath=None):
1007 """
1008 Stubs out execv and execve functions when used as context manager.
1009 Records exec calls. The mock execv and execve functions always raise an
1010 exception as they would normally never return.
1011 """
1012 # A list of tuples containing (function name, first arg, args)
1013 # of calls to execv or execve that have been made.
1014 calls = []
1015
1016 def mock_execv(name, *args):
1017 calls.append(('execv', name, args))
1018 raise RuntimeError("execv called")
1019
1020 def mock_execve(name, *args):
1021 calls.append(('execve', name, args))
1022 raise OSError(errno.ENOTDIR, "execve called")
1023
1024 try:
1025 orig_execv = os.execv
1026 orig_execve = os.execve
1027 orig_defpath = os.defpath
1028 os.execv = mock_execv
1029 os.execve = mock_execve
1030 if defpath is not None:
1031 os.defpath = defpath
1032 yield calls
1033 finally:
1034 os.execv = orig_execv
1035 os.execve = orig_execve
1036 os.defpath = orig_defpath
1037
Guido van Rossume7ba4952007-06-06 23:52:48 +00001038class ExecTests(unittest.TestCase):
Mark Dickinson7cf03892010-04-16 13:45:35 +00001039 @unittest.skipIf(USING_LINUXTHREADS,
1040 "avoid triggering a linuxthreads bug: see issue #4970")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001041 def test_execvpe_with_bad_program(self):
Mark Dickinson7cf03892010-04-16 13:45:35 +00001042 self.assertRaises(OSError, os.execvpe, 'no such app-',
1043 ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001044
Thomas Heller6790d602007-08-30 17:15:14 +00001045 def test_execvpe_with_bad_arglist(self):
1046 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
1047
Gregory P. Smith4ae37772010-05-08 18:05:46 +00001048 @unittest.skipUnless(hasattr(os, '_execvpe'),
1049 "No internal os._execvpe function to test.")
Victor Stinnerb745a742010-05-18 17:17:23 +00001050 def _test_internal_execvpe(self, test_type):
1051 program_path = os.sep + 'absolutepath'
1052 if test_type is bytes:
1053 program = b'executable'
1054 fullpath = os.path.join(os.fsencode(program_path), program)
1055 native_fullpath = fullpath
1056 arguments = [b'progname', 'arg1', 'arg2']
1057 else:
1058 program = 'executable'
1059 arguments = ['progname', 'arg1', 'arg2']
1060 fullpath = os.path.join(program_path, program)
1061 if os.name != "nt":
1062 native_fullpath = os.fsencode(fullpath)
1063 else:
1064 native_fullpath = fullpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001065 env = {'spam': 'beans'}
1066
Victor Stinnerb745a742010-05-18 17:17:23 +00001067 # test os._execvpe() with an absolute path
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001068 with _execvpe_mockup() as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +00001069 self.assertRaises(RuntimeError,
1070 os._execvpe, fullpath, arguments)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001071 self.assertEqual(len(calls), 1)
1072 self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))
1073
Victor Stinnerb745a742010-05-18 17:17:23 +00001074 # test os._execvpe() with a relative path:
1075 # os.get_exec_path() returns defpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001076 with _execvpe_mockup(defpath=program_path) as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +00001077 self.assertRaises(OSError,
1078 os._execvpe, program, arguments, env=env)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001079 self.assertEqual(len(calls), 1)
Victor Stinnerb745a742010-05-18 17:17:23 +00001080 self.assertSequenceEqual(calls[0],
1081 ('execve', native_fullpath, (arguments, env)))
1082
1083 # test os._execvpe() with a relative path:
1084 # os.get_exec_path() reads the 'PATH' variable
1085 with _execvpe_mockup() as calls:
1086 env_path = env.copy()
Victor Stinner38430e22010-08-19 17:10:18 +00001087 if test_type is bytes:
1088 env_path[b'PATH'] = program_path
1089 else:
1090 env_path['PATH'] = program_path
Victor Stinnerb745a742010-05-18 17:17:23 +00001091 self.assertRaises(OSError,
1092 os._execvpe, program, arguments, env=env_path)
1093 self.assertEqual(len(calls), 1)
1094 self.assertSequenceEqual(calls[0],
1095 ('execve', native_fullpath, (arguments, env_path)))
1096
1097 def test_internal_execvpe_str(self):
1098 self._test_internal_execvpe(str)
1099 if os.name != "nt":
1100 self._test_internal_execvpe(bytes)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001101
Gregory P. Smith4ae37772010-05-08 18:05:46 +00001102
Thomas Wouters477c8d52006-05-27 19:21:47 +00001103class Win32ErrorTests(unittest.TestCase):
1104 def test_rename(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001105 self.assertRaises(OSError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001106
1107 def test_remove(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001108 self.assertRaises(OSError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001109
1110 def test_chdir(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001111 self.assertRaises(OSError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001112
1113 def test_mkdir(self):
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +00001114 f = open(support.TESTFN, "w")
Benjamin Petersonf91df042009-02-13 02:50:59 +00001115 try:
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001116 self.assertRaises(OSError, os.mkdir, support.TESTFN)
Benjamin Petersonf91df042009-02-13 02:50:59 +00001117 finally:
1118 f.close()
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +00001119 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001120
1121 def test_utime(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001122 self.assertRaises(OSError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001123
Thomas Wouters477c8d52006-05-27 19:21:47 +00001124 def test_chmod(self):
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001125 self.assertRaises(OSError, os.chmod, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001126
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001127class TestInvalidFD(unittest.TestCase):
Benjamin Peterson05e782f2009-01-19 15:15:02 +00001128 singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001129 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
1130 #singles.append("close")
1131 #We omit close because it doesn'r raise an exception on some platforms
1132 def get_single(f):
1133 def helper(self):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001134 if hasattr(os, f):
1135 self.check(getattr(os, f))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001136 return helper
1137 for f in singles:
1138 locals()["test_"+f] = get_single(f)
1139
Benjamin Peterson7522c742009-01-19 21:00:09 +00001140 def check(self, f, *args):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001141 try:
1142 f(support.make_bad_fd(), *args)
1143 except OSError as e:
1144 self.assertEqual(e.errno, errno.EBADF)
1145 else:
1146 self.fail("%r didn't raise a OSError with a bad file descriptor"
1147 % f)
Benjamin Peterson7522c742009-01-19 21:00:09 +00001148
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001149 def test_isatty(self):
1150 if hasattr(os, "isatty"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001151 self.assertEqual(os.isatty(support.make_bad_fd()), False)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001152
1153 def test_closerange(self):
1154 if hasattr(os, "closerange"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001155 fd = support.make_bad_fd()
R. David Murray630cc482009-07-22 15:20:27 +00001156 # Make sure none of the descriptors we are about to close are
1157 # currently valid (issue 6542).
1158 for i in range(10):
1159 try: os.fstat(fd+i)
1160 except OSError:
1161 pass
1162 else:
1163 break
1164 if i < 2:
1165 raise unittest.SkipTest(
1166 "Unable to acquire a range of invalid file descriptors")
1167 self.assertEqual(os.closerange(fd, fd + i-1), None)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001168
1169 def test_dup2(self):
1170 if hasattr(os, "dup2"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001171 self.check(os.dup2, 20)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001172
1173 def test_fchmod(self):
1174 if hasattr(os, "fchmod"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001175 self.check(os.fchmod, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001176
1177 def test_fchown(self):
1178 if hasattr(os, "fchown"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001179 self.check(os.fchown, -1, -1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001180
1181 def test_fpathconf(self):
1182 if hasattr(os, "fpathconf"):
Georg Brandl306336b2012-06-24 12:55:33 +02001183 self.check(os.pathconf, "PC_NAME_MAX")
Benjamin Peterson7522c742009-01-19 21:00:09 +00001184 self.check(os.fpathconf, "PC_NAME_MAX")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001185
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001186 def test_ftruncate(self):
1187 if hasattr(os, "ftruncate"):
Georg Brandl306336b2012-06-24 12:55:33 +02001188 self.check(os.truncate, 0)
Benjamin Peterson7522c742009-01-19 21:00:09 +00001189 self.check(os.ftruncate, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001190
1191 def test_lseek(self):
1192 if hasattr(os, "lseek"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001193 self.check(os.lseek, 0, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001194
1195 def test_read(self):
1196 if hasattr(os, "read"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001197 self.check(os.read, 1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001198
1199 def test_tcsetpgrpt(self):
1200 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001201 self.check(os.tcsetpgrp, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001202
1203 def test_write(self):
1204 if hasattr(os, "write"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001205 self.check(os.write, b" ")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001206
Brian Curtin1b9df392010-11-24 20:24:31 +00001207
1208class LinkTests(unittest.TestCase):
1209 def setUp(self):
1210 self.file1 = support.TESTFN
1211 self.file2 = os.path.join(support.TESTFN + "2")
1212
Brian Curtinc0abc4e2010-11-30 23:46:54 +00001213 def tearDown(self):
Brian Curtin1b9df392010-11-24 20:24:31 +00001214 for file in (self.file1, self.file2):
1215 if os.path.exists(file):
1216 os.unlink(file)
1217
Brian Curtin1b9df392010-11-24 20:24:31 +00001218 def _test_link(self, file1, file2):
1219 with open(file1, "w") as f1:
1220 f1.write("test")
1221
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001222 with warnings.catch_warnings():
1223 warnings.simplefilter("ignore", DeprecationWarning)
1224 os.link(file1, file2)
Brian Curtin1b9df392010-11-24 20:24:31 +00001225 with open(file1, "r") as f1, open(file2, "r") as f2:
1226 self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
1227
1228 def test_link(self):
1229 self._test_link(self.file1, self.file2)
1230
1231 def test_link_bytes(self):
1232 self._test_link(bytes(self.file1, sys.getfilesystemencoding()),
1233 bytes(self.file2, sys.getfilesystemencoding()))
1234
Brian Curtinf498b752010-11-30 15:54:04 +00001235 def test_unicode_name(self):
Brian Curtin43f0c272010-11-30 15:40:04 +00001236 try:
Brian Curtinf498b752010-11-30 15:54:04 +00001237 os.fsencode("\xf1")
Brian Curtin43f0c272010-11-30 15:40:04 +00001238 except UnicodeError:
1239 raise unittest.SkipTest("Unable to encode for this platform.")
1240
Brian Curtinf498b752010-11-30 15:54:04 +00001241 self.file1 += "\xf1"
Brian Curtinfc889c42010-11-28 23:59:46 +00001242 self.file2 = self.file1 + "2"
1243 self._test_link(self.file1, self.file2)
1244
Thomas Wouters477c8d52006-05-27 19:21:47 +00001245if sys.platform != 'win32':
1246 class Win32ErrorTests(unittest.TestCase):
1247 pass
1248
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001249 class PosixUidGidTests(unittest.TestCase):
1250 if hasattr(os, 'setuid'):
1251 def test_setuid(self):
1252 if os.getuid() != 0:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001253 self.assertRaises(OSError, os.setuid, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001254 self.assertRaises(OverflowError, os.setuid, 1<<32)
1255
1256 if hasattr(os, 'setgid'):
1257 def test_setgid(self):
Stefan Krahebee49a2013-01-17 15:31:00 +01001258 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001259 self.assertRaises(OSError, os.setgid, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001260 self.assertRaises(OverflowError, os.setgid, 1<<32)
1261
1262 if hasattr(os, 'seteuid'):
1263 def test_seteuid(self):
1264 if os.getuid() != 0:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001265 self.assertRaises(OSError, os.seteuid, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001266 self.assertRaises(OverflowError, os.seteuid, 1<<32)
1267
1268 if hasattr(os, 'setegid'):
1269 def test_setegid(self):
Stefan Krahebee49a2013-01-17 15:31:00 +01001270 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001271 self.assertRaises(OSError, os.setegid, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001272 self.assertRaises(OverflowError, os.setegid, 1<<32)
1273
1274 if hasattr(os, 'setreuid'):
1275 def test_setreuid(self):
1276 if os.getuid() != 0:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001277 self.assertRaises(OSError, os.setreuid, 0, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001278 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
1279 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001280
1281 def test_setreuid_neg1(self):
1282 # Needs to accept -1. We run this in a subprocess to avoid
1283 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001284 subprocess.check_call([
1285 sys.executable, '-c',
1286 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001287
1288 if hasattr(os, 'setregid'):
1289 def test_setregid(self):
Stefan Krahebee49a2013-01-17 15:31:00 +01001290 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
Andrew Svetlov8b33dd82012-12-24 19:58:48 +02001291 self.assertRaises(OSError, os.setregid, 0, 0)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001292 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
1293 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001294
1295 def test_setregid_neg1(self):
1296 # Needs to accept -1. We run this in a subprocess to avoid
1297 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001298 subprocess.check_call([
1299 sys.executable, '-c',
1300 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Martin v. Löwis011e8422009-05-05 04:43:17 +00001301
1302 class Pep383Tests(unittest.TestCase):
Martin v. Löwis011e8422009-05-05 04:43:17 +00001303 def setUp(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001304 if support.TESTFN_UNENCODABLE:
1305 self.dir = support.TESTFN_UNENCODABLE
Victor Stinner8b219b22012-11-06 23:23:43 +01001306 elif support.TESTFN_NONASCII:
1307 self.dir = support.TESTFN_NONASCII
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001308 else:
1309 self.dir = support.TESTFN
1310 self.bdir = os.fsencode(self.dir)
1311
1312 bytesfn = []
1313 def add_filename(fn):
1314 try:
1315 fn = os.fsencode(fn)
1316 except UnicodeEncodeError:
1317 return
1318 bytesfn.append(fn)
1319 add_filename(support.TESTFN_UNICODE)
1320 if support.TESTFN_UNENCODABLE:
1321 add_filename(support.TESTFN_UNENCODABLE)
Victor Stinner8b219b22012-11-06 23:23:43 +01001322 if support.TESTFN_NONASCII:
1323 add_filename(support.TESTFN_NONASCII)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001324 if not bytesfn:
1325 self.skipTest("couldn't create any non-ascii filename")
1326
1327 self.unicodefn = set()
Martin v. Löwis011e8422009-05-05 04:43:17 +00001328 os.mkdir(self.dir)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001329 try:
1330 for fn in bytesfn:
Victor Stinnerbf816222011-06-30 23:25:47 +02001331 support.create_empty_file(os.path.join(self.bdir, fn))
Victor Stinnere8d51452010-08-19 01:05:19 +00001332 fn = os.fsdecode(fn)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001333 if fn in self.unicodefn:
1334 raise ValueError("duplicate filename")
1335 self.unicodefn.add(fn)
1336 except:
1337 shutil.rmtree(self.dir)
1338 raise
Martin v. Löwis011e8422009-05-05 04:43:17 +00001339
1340 def tearDown(self):
1341 shutil.rmtree(self.dir)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001342
1343 def test_listdir(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001344 expected = self.unicodefn
1345 found = set(os.listdir(self.dir))
Ezio Melottib3aedd42010-11-20 19:04:17 +00001346 self.assertEqual(found, expected)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001347 # test listdir without arguments
1348 current_directory = os.getcwd()
1349 try:
1350 os.chdir(os.sep)
1351 self.assertEqual(set(os.listdir()), set(os.listdir(os.sep)))
1352 finally:
1353 os.chdir(current_directory)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001354
1355 def test_open(self):
1356 for fn in self.unicodefn:
Victor Stinnera6d2c762011-06-30 18:20:11 +02001357 f = open(os.path.join(self.dir, fn), 'rb')
Martin v. Löwis011e8422009-05-05 04:43:17 +00001358 f.close()
1359
Victor Stinnere4110dc2013-01-01 23:05:55 +01001360 @unittest.skipUnless(hasattr(os, 'statvfs'),
1361 "need os.statvfs()")
1362 def test_statvfs(self):
1363 # issue #9645
1364 for fn in self.unicodefn:
1365 # should not fail with file not found error
1366 fullname = os.path.join(self.dir, fn)
1367 os.statvfs(fullname)
1368
Martin v. Löwis011e8422009-05-05 04:43:17 +00001369 def test_stat(self):
1370 for fn in self.unicodefn:
1371 os.stat(os.path.join(self.dir, fn))
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001372else:
1373 class PosixUidGidTests(unittest.TestCase):
1374 pass
Martin v. Löwis011e8422009-05-05 04:43:17 +00001375 class Pep383Tests(unittest.TestCase):
1376 pass
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001377
Brian Curtineb24d742010-04-12 17:16:38 +00001378@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
1379class Win32KillTests(unittest.TestCase):
Brian Curtinc3acbc32010-05-28 16:08:40 +00001380 def _kill(self, sig):
1381 # Start sys.executable as a subprocess and communicate from the
1382 # subprocess to the parent that the interpreter is ready. When it
1383 # becomes ready, send *sig* via os.kill to the subprocess and check
1384 # that the return code is equal to *sig*.
1385 import ctypes
1386 from ctypes import wintypes
1387 import msvcrt
1388
1389 # Since we can't access the contents of the process' stdout until the
1390 # process has exited, use PeekNamedPipe to see what's inside stdout
1391 # without waiting. This is done so we can tell that the interpreter
1392 # is started and running at a point where it could handle a signal.
1393 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
1394 PeekNamedPipe.restype = wintypes.BOOL
1395 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
1396 ctypes.POINTER(ctypes.c_char), # stdout buf
1397 wintypes.DWORD, # Buffer size
1398 ctypes.POINTER(wintypes.DWORD), # bytes read
1399 ctypes.POINTER(wintypes.DWORD), # bytes avail
1400 ctypes.POINTER(wintypes.DWORD)) # bytes left
1401 msg = "running"
1402 proc = subprocess.Popen([sys.executable, "-c",
1403 "import sys;"
1404 "sys.stdout.write('{}');"
1405 "sys.stdout.flush();"
1406 "input()".format(msg)],
1407 stdout=subprocess.PIPE,
1408 stderr=subprocess.PIPE,
1409 stdin=subprocess.PIPE)
Brian Curtin43ec5772010-11-05 15:17:11 +00001410 self.addCleanup(proc.stdout.close)
1411 self.addCleanup(proc.stderr.close)
1412 self.addCleanup(proc.stdin.close)
Brian Curtinc3acbc32010-05-28 16:08:40 +00001413
1414 count, max = 0, 100
1415 while count < max and proc.poll() is None:
1416 # Create a string buffer to store the result of stdout from the pipe
1417 buf = ctypes.create_string_buffer(len(msg))
1418 # Obtain the text currently in proc.stdout
1419 # Bytes read/avail/left are left as NULL and unused
1420 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
1421 buf, ctypes.sizeof(buf), None, None, None)
1422 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
1423 if buf.value:
1424 self.assertEqual(msg, buf.value.decode())
1425 break
1426 time.sleep(0.1)
1427 count += 1
1428 else:
1429 self.fail("Did not receive communication from the subprocess")
1430
Brian Curtineb24d742010-04-12 17:16:38 +00001431 os.kill(proc.pid, sig)
1432 self.assertEqual(proc.wait(), sig)
1433
1434 def test_kill_sigterm(self):
1435 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinc3acbc32010-05-28 16:08:40 +00001436 self._kill(signal.SIGTERM)
Brian Curtineb24d742010-04-12 17:16:38 +00001437
1438 def test_kill_int(self):
1439 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinc3acbc32010-05-28 16:08:40 +00001440 self._kill(100)
Brian Curtineb24d742010-04-12 17:16:38 +00001441
1442 def _kill_with_event(self, event, name):
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001443 tagname = "test_os_%s" % uuid.uuid1()
1444 m = mmap.mmap(-1, 1, tagname)
1445 m[0] = 0
Brian Curtineb24d742010-04-12 17:16:38 +00001446 # Run a script which has console control handling enabled.
1447 proc = subprocess.Popen([sys.executable,
1448 os.path.join(os.path.dirname(__file__),
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001449 "win_console_handler.py"), tagname],
Brian Curtineb24d742010-04-12 17:16:38 +00001450 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
1451 # Let the interpreter startup before we send signals. See #3137.
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001452 count, max = 0, 100
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001453 while count < max and proc.poll() is None:
Brian Curtinf668df52010-10-15 14:21:06 +00001454 if m[0] == 1:
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001455 break
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001456 time.sleep(0.1)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001457 count += 1
1458 else:
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001459 # Forcefully kill the process if we weren't able to signal it.
1460 os.kill(proc.pid, signal.SIGINT)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001461 self.fail("Subprocess didn't finish initialization")
Brian Curtineb24d742010-04-12 17:16:38 +00001462 os.kill(proc.pid, event)
1463 # proc.send_signal(event) could also be done here.
1464 # Allow time for the signal to be passed and the process to exit.
1465 time.sleep(0.5)
1466 if not proc.poll():
1467 # Forcefully kill the process if we weren't able to signal it.
1468 os.kill(proc.pid, signal.SIGINT)
1469 self.fail("subprocess did not stop on {}".format(name))
1470
1471 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
1472 def test_CTRL_C_EVENT(self):
1473 from ctypes import wintypes
1474 import ctypes
1475
1476 # Make a NULL value by creating a pointer with no argument.
1477 NULL = ctypes.POINTER(ctypes.c_int)()
1478 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
1479 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
1480 wintypes.BOOL)
1481 SetConsoleCtrlHandler.restype = wintypes.BOOL
1482
1483 # Calling this with NULL and FALSE causes the calling process to
1484 # handle CTRL+C, rather than ignore it. This property is inherited
1485 # by subprocesses.
1486 SetConsoleCtrlHandler(NULL, 0)
1487
1488 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
1489
1490 def test_CTRL_BREAK_EVENT(self):
1491 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
1492
1493
Brian Curtind40e6f72010-07-08 21:39:08 +00001494@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Brian Curtin3b4499c2010-12-28 14:31:47 +00001495@support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +00001496class Win32SymlinkTests(unittest.TestCase):
1497 filelink = 'filelinktest'
1498 filelink_target = os.path.abspath(__file__)
1499 dirlink = 'dirlinktest'
1500 dirlink_target = os.path.dirname(filelink_target)
1501 missing_link = 'missing link'
1502
1503 def setUp(self):
1504 assert os.path.exists(self.dirlink_target)
1505 assert os.path.exists(self.filelink_target)
1506 assert not os.path.exists(self.dirlink)
1507 assert not os.path.exists(self.filelink)
1508 assert not os.path.exists(self.missing_link)
1509
1510 def tearDown(self):
1511 if os.path.exists(self.filelink):
1512 os.remove(self.filelink)
1513 if os.path.exists(self.dirlink):
1514 os.rmdir(self.dirlink)
1515 if os.path.lexists(self.missing_link):
1516 os.remove(self.missing_link)
1517
1518 def test_directory_link(self):
Antoine Pitrou5311c1d2012-01-24 08:59:28 +01001519 os.symlink(self.dirlink_target, self.dirlink, True)
Brian Curtind40e6f72010-07-08 21:39:08 +00001520 self.assertTrue(os.path.exists(self.dirlink))
1521 self.assertTrue(os.path.isdir(self.dirlink))
1522 self.assertTrue(os.path.islink(self.dirlink))
1523 self.check_stat(self.dirlink, self.dirlink_target)
1524
1525 def test_file_link(self):
1526 os.symlink(self.filelink_target, self.filelink)
1527 self.assertTrue(os.path.exists(self.filelink))
1528 self.assertTrue(os.path.isfile(self.filelink))
1529 self.assertTrue(os.path.islink(self.filelink))
1530 self.check_stat(self.filelink, self.filelink_target)
1531
1532 def _create_missing_dir_link(self):
1533 'Create a "directory" link to a non-existent target'
1534 linkname = self.missing_link
1535 if os.path.lexists(linkname):
1536 os.remove(linkname)
1537 target = r'c:\\target does not exist.29r3c740'
1538 assert not os.path.exists(target)
1539 target_is_dir = True
1540 os.symlink(target, linkname, target_is_dir)
1541
1542 def test_remove_directory_link_to_missing_target(self):
1543 self._create_missing_dir_link()
1544 # For compatibility with Unix, os.remove will check the
1545 # directory status and call RemoveDirectory if the symlink
1546 # was created with target_is_dir==True.
1547 os.remove(self.missing_link)
1548
1549 @unittest.skip("currently fails; consider for improvement")
1550 def test_isdir_on_directory_link_to_missing_target(self):
1551 self._create_missing_dir_link()
1552 # consider having isdir return true for directory links
1553 self.assertTrue(os.path.isdir(self.missing_link))
1554
1555 @unittest.skip("currently fails; consider for improvement")
1556 def test_rmdir_on_directory_link_to_missing_target(self):
1557 self._create_missing_dir_link()
1558 # consider allowing rmdir to remove directory links
1559 os.rmdir(self.missing_link)
1560
1561 def check_stat(self, link, target):
1562 self.assertEqual(os.stat(link), os.stat(target))
1563 self.assertNotEqual(os.lstat(link), os.stat(link))
1564
Brian Curtind25aef52011-06-13 15:16:04 -05001565 bytes_link = os.fsencode(link)
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001566 with warnings.catch_warnings():
1567 warnings.simplefilter("ignore", DeprecationWarning)
1568 self.assertEqual(os.stat(bytes_link), os.stat(target))
1569 self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link))
Brian Curtind25aef52011-06-13 15:16:04 -05001570
1571 def test_12084(self):
1572 level1 = os.path.abspath(support.TESTFN)
1573 level2 = os.path.join(level1, "level2")
1574 level3 = os.path.join(level2, "level3")
1575 try:
1576 os.mkdir(level1)
1577 os.mkdir(level2)
1578 os.mkdir(level3)
1579
1580 file1 = os.path.abspath(os.path.join(level1, "file1"))
1581
1582 with open(file1, "w") as f:
1583 f.write("file1")
1584
1585 orig_dir = os.getcwd()
1586 try:
1587 os.chdir(level2)
1588 link = os.path.join(level2, "link")
1589 os.symlink(os.path.relpath(file1), "link")
1590 self.assertIn("link", os.listdir(os.getcwd()))
1591
1592 # Check os.stat calls from the same dir as the link
1593 self.assertEqual(os.stat(file1), os.stat("link"))
1594
1595 # Check os.stat calls from a dir below the link
1596 os.chdir(level1)
1597 self.assertEqual(os.stat(file1),
1598 os.stat(os.path.relpath(link)))
1599
1600 # Check os.stat calls from a dir above the link
1601 os.chdir(level3)
1602 self.assertEqual(os.stat(file1),
1603 os.stat(os.path.relpath(link)))
1604 finally:
1605 os.chdir(orig_dir)
1606 except OSError as err:
1607 self.fail(err)
1608 finally:
1609 os.remove(file1)
1610 shutil.rmtree(level1)
1611
Brian Curtind40e6f72010-07-08 21:39:08 +00001612
Victor Stinnere8d51452010-08-19 01:05:19 +00001613class FSEncodingTests(unittest.TestCase):
1614 def test_nop(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001615 self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
1616 self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
Benjamin Peterson31191a92010-05-09 03:22:58 +00001617
Victor Stinnere8d51452010-08-19 01:05:19 +00001618 def test_identity(self):
1619 # assert fsdecode(fsencode(x)) == x
1620 for fn in ('unicode\u0141', 'latin\xe9', 'ascii'):
1621 try:
1622 bytesfn = os.fsencode(fn)
1623 except UnicodeEncodeError:
1624 continue
Ezio Melottib3aedd42010-11-20 19:04:17 +00001625 self.assertEqual(os.fsdecode(bytesfn), fn)
Victor Stinnere8d51452010-08-19 01:05:19 +00001626
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00001627
Brett Cannonefb00c02012-02-29 18:31:31 -05001628
1629class DeviceEncodingTests(unittest.TestCase):
1630
1631 def test_bad_fd(self):
1632 # Return None when an fd doesn't actually exist.
1633 self.assertIsNone(os.device_encoding(123456))
1634
Philip Jenveye308b7c2012-02-29 16:16:15 -08001635 @unittest.skipUnless(os.isatty(0) and (sys.platform.startswith('win') or
1636 (hasattr(locale, 'nl_langinfo') and hasattr(locale, 'CODESET'))),
Philip Jenveyd7aff2d2012-02-29 16:21:25 -08001637 'test requires a tty and either Windows or nl_langinfo(CODESET)')
Brett Cannonefb00c02012-02-29 18:31:31 -05001638 def test_device_encoding(self):
1639 encoding = os.device_encoding(0)
1640 self.assertIsNotNone(encoding)
1641 self.assertTrue(codecs.lookup(encoding))
1642
1643
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00001644class PidTests(unittest.TestCase):
1645 @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid")
1646 def test_getppid(self):
1647 p = subprocess.Popen([sys.executable, '-c',
1648 'import os; print(os.getppid())'],
1649 stdout=subprocess.PIPE)
1650 stdout, _ = p.communicate()
1651 # We are the parent of our subprocess
1652 self.assertEqual(int(stdout), os.getpid())
1653
1654
Brian Curtin0151b8e2010-09-24 13:43:43 +00001655# The introduction of this TestCase caused at least two different errors on
1656# *nix buildbots. Temporarily skip this to let the buildbots move along.
1657@unittest.skip("Skip due to platform/environment differences on *NIX buildbots")
Brian Curtine8e4b3b2010-09-23 20:04:14 +00001658@unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin")
1659class LoginTests(unittest.TestCase):
1660 def test_getlogin(self):
1661 user_name = os.getlogin()
1662 self.assertNotEqual(len(user_name), 0)
1663
1664
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001665@unittest.skipUnless(hasattr(os, 'getpriority') and hasattr(os, 'setpriority'),
1666 "needs os.getpriority and os.setpriority")
1667class ProgramPriorityTests(unittest.TestCase):
1668 """Tests for os.getpriority() and os.setpriority()."""
1669
1670 def test_set_get_priority(self):
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001671
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001672 base = os.getpriority(os.PRIO_PROCESS, os.getpid())
1673 os.setpriority(os.PRIO_PROCESS, os.getpid(), base + 1)
1674 try:
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001675 new_prio = os.getpriority(os.PRIO_PROCESS, os.getpid())
1676 if base >= 19 and new_prio <= 19:
1677 raise unittest.SkipTest(
1678 "unable to reliably test setpriority at current nice level of %s" % base)
1679 else:
1680 self.assertEqual(new_prio, base + 1)
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001681 finally:
1682 try:
1683 os.setpriority(os.PRIO_PROCESS, os.getpid(), base)
1684 except OSError as err:
Antoine Pitrou692f0382011-02-26 00:22:25 +00001685 if err.errno != errno.EACCES:
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001686 raise
1687
1688
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001689if threading is not None:
1690 class SendfileTestServer(asyncore.dispatcher, threading.Thread):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001691
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001692 class Handler(asynchat.async_chat):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001693
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001694 def __init__(self, conn):
1695 asynchat.async_chat.__init__(self, conn)
1696 self.in_buffer = []
1697 self.closed = False
1698 self.push(b"220 ready\r\n")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001699
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001700 def handle_read(self):
1701 data = self.recv(4096)
1702 self.in_buffer.append(data)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001703
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001704 def get_data(self):
1705 return b''.join(self.in_buffer)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001706
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001707 def handle_close(self):
1708 self.close()
1709 self.closed = True
1710
1711 def handle_error(self):
1712 raise
1713
1714 def __init__(self, address):
1715 threading.Thread.__init__(self)
1716 asyncore.dispatcher.__init__(self)
1717 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
1718 self.bind(address)
1719 self.listen(5)
1720 self.host, self.port = self.socket.getsockname()[:2]
1721 self.handler_instance = None
1722 self._active = False
1723 self._active_lock = threading.Lock()
1724
1725 # --- public API
1726
1727 @property
1728 def running(self):
1729 return self._active
1730
1731 def start(self):
1732 assert not self.running
1733 self.__flag = threading.Event()
1734 threading.Thread.start(self)
1735 self.__flag.wait()
1736
1737 def stop(self):
1738 assert self.running
1739 self._active = False
1740 self.join()
1741
1742 def wait(self):
1743 # wait for handler connection to be closed, then stop the server
1744 while not getattr(self.handler_instance, "closed", False):
1745 time.sleep(0.001)
1746 self.stop()
1747
1748 # --- internals
1749
1750 def run(self):
1751 self._active = True
1752 self.__flag.set()
1753 while self._active and asyncore.socket_map:
1754 self._active_lock.acquire()
1755 asyncore.loop(timeout=0.001, count=1)
1756 self._active_lock.release()
1757 asyncore.close_all()
1758
1759 def handle_accept(self):
1760 conn, addr = self.accept()
1761 self.handler_instance = self.Handler(conn)
1762
1763 def handle_connect(self):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001764 self.close()
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001765 handle_read = handle_connect
1766
1767 def writable(self):
1768 return 0
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001769
1770 def handle_error(self):
1771 raise
1772
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001773
Giampaolo Rodolà46134642011-02-25 20:01:05 +00001774@unittest.skipUnless(threading is not None, "test needs threading module")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001775@unittest.skipUnless(hasattr(os, 'sendfile'), "test needs os.sendfile()")
1776class TestSendfile(unittest.TestCase):
1777
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001778 DATA = b"12345abcde" * 16 * 1024 # 160 KB
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001779 SUPPORT_HEADERS_TRAILERS = not sys.platform.startswith("linux") and \
Giampaolo Rodolà4bc68572011-02-25 21:46:01 +00001780 not sys.platform.startswith("solaris") and \
1781 not sys.platform.startswith("sunos")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001782
1783 @classmethod
1784 def setUpClass(cls):
1785 with open(support.TESTFN, "wb") as f:
1786 f.write(cls.DATA)
1787
1788 @classmethod
1789 def tearDownClass(cls):
1790 support.unlink(support.TESTFN)
1791
1792 def setUp(self):
1793 self.server = SendfileTestServer((support.HOST, 0))
1794 self.server.start()
1795 self.client = socket.socket()
1796 self.client.connect((self.server.host, self.server.port))
1797 self.client.settimeout(1)
1798 # synchronize by waiting for "220 ready" response
1799 self.client.recv(1024)
1800 self.sockno = self.client.fileno()
1801 self.file = open(support.TESTFN, 'rb')
1802 self.fileno = self.file.fileno()
1803
1804 def tearDown(self):
1805 self.file.close()
1806 self.client.close()
1807 if self.server.running:
1808 self.server.stop()
1809
1810 def sendfile_wrapper(self, sock, file, offset, nbytes, headers=[], trailers=[]):
1811 """A higher level wrapper representing how an application is
1812 supposed to use sendfile().
1813 """
1814 while 1:
1815 try:
1816 if self.SUPPORT_HEADERS_TRAILERS:
1817 return os.sendfile(sock, file, offset, nbytes, headers,
1818 trailers)
1819 else:
1820 return os.sendfile(sock, file, offset, nbytes)
1821 except OSError as err:
1822 if err.errno == errno.ECONNRESET:
1823 # disconnected
1824 raise
1825 elif err.errno in (errno.EAGAIN, errno.EBUSY):
1826 # we have to retry send data
1827 continue
1828 else:
1829 raise
1830
1831 def test_send_whole_file(self):
1832 # normal send
1833 total_sent = 0
1834 offset = 0
1835 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001836 while total_sent < len(self.DATA):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001837 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
1838 if sent == 0:
1839 break
1840 offset += sent
1841 total_sent += sent
1842 self.assertTrue(sent <= nbytes)
1843 self.assertEqual(offset, total_sent)
1844
1845 self.assertEqual(total_sent, len(self.DATA))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001846 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001847 self.client.close()
1848 self.server.wait()
1849 data = self.server.handler_instance.get_data()
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001850 self.assertEqual(len(data), len(self.DATA))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001851 self.assertEqual(data, self.DATA)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001852
1853 def test_send_at_certain_offset(self):
1854 # start sending a file at a certain offset
1855 total_sent = 0
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001856 offset = len(self.DATA) // 2
1857 must_send = len(self.DATA) - offset
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001858 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001859 while total_sent < must_send:
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001860 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
1861 if sent == 0:
1862 break
1863 offset += sent
1864 total_sent += sent
1865 self.assertTrue(sent <= nbytes)
1866
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001867 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001868 self.client.close()
1869 self.server.wait()
1870 data = self.server.handler_instance.get_data()
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001871 expected = self.DATA[len(self.DATA) // 2:]
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001872 self.assertEqual(total_sent, len(expected))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001873 self.assertEqual(len(data), len(expected))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001874 self.assertEqual(data, expected)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001875
1876 def test_offset_overflow(self):
1877 # specify an offset > file size
1878 offset = len(self.DATA) + 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001879 try:
1880 sent = os.sendfile(self.sockno, self.fileno, offset, 4096)
1881 except OSError as e:
1882 # Solaris can raise EINVAL if offset >= file length, ignore.
1883 if e.errno != errno.EINVAL:
1884 raise
1885 else:
1886 self.assertEqual(sent, 0)
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001887 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001888 self.client.close()
1889 self.server.wait()
1890 data = self.server.handler_instance.get_data()
1891 self.assertEqual(data, b'')
1892
1893 def test_invalid_offset(self):
1894 with self.assertRaises(OSError) as cm:
1895 os.sendfile(self.sockno, self.fileno, -1, 4096)
1896 self.assertEqual(cm.exception.errno, errno.EINVAL)
1897
1898 # --- headers / trailers tests
1899
1900 if SUPPORT_HEADERS_TRAILERS:
1901
1902 def test_headers(self):
1903 total_sent = 0
1904 sent = os.sendfile(self.sockno, self.fileno, 0, 4096,
1905 headers=[b"x" * 512])
1906 total_sent += sent
1907 offset = 4096
1908 nbytes = 4096
1909 while 1:
1910 sent = self.sendfile_wrapper(self.sockno, self.fileno,
1911 offset, nbytes)
1912 if sent == 0:
1913 break
1914 total_sent += sent
1915 offset += sent
1916
1917 expected_data = b"x" * 512 + self.DATA
1918 self.assertEqual(total_sent, len(expected_data))
1919 self.client.close()
1920 self.server.wait()
1921 data = self.server.handler_instance.get_data()
1922 self.assertEqual(hash(data), hash(expected_data))
1923
1924 def test_trailers(self):
1925 TESTFN2 = support.TESTFN + "2"
Brett Cannonb6376802011-03-15 17:38:22 -04001926 with open(TESTFN2, 'wb') as f:
1927 f.write(b"abcde")
1928 with open(TESTFN2, 'rb')as f:
1929 self.addCleanup(os.remove, TESTFN2)
1930 os.sendfile(self.sockno, f.fileno(), 0, 4096,
1931 trailers=[b"12345"])
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001932 self.client.close()
1933 self.server.wait()
1934 data = self.server.handler_instance.get_data()
1935 self.assertEqual(data, b"abcde12345")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001936
1937 if hasattr(os, "SF_NODISKIO"):
1938 def test_flags(self):
1939 try:
1940 os.sendfile(self.sockno, self.fileno, 0, 4096,
1941 flags=os.SF_NODISKIO)
1942 except OSError as err:
1943 if err.errno not in (errno.EBUSY, errno.EAGAIN):
1944 raise
1945
1946
Larry Hastings9cf065c2012-06-22 16:30:09 -07001947def supports_extended_attributes():
1948 if not hasattr(os, "setxattr"):
1949 return False
1950 try:
1951 with open(support.TESTFN, "wb") as fp:
1952 try:
1953 os.setxattr(fp.fileno(), b"user.test", b"")
1954 except OSError:
1955 return False
1956 finally:
1957 support.unlink(support.TESTFN)
1958 # Kernels < 2.6.39 don't respect setxattr flags.
1959 kernel_version = platform.release()
1960 m = re.match("2.6.(\d{1,2})", kernel_version)
1961 return m is None or int(m.group(1)) >= 39
1962
1963
1964@unittest.skipUnless(supports_extended_attributes(),
1965 "no non-broken extended attribute support")
Benjamin Peterson799bd802011-08-31 22:15:17 -04001966class ExtendedAttributeTests(unittest.TestCase):
1967
1968 def tearDown(self):
1969 support.unlink(support.TESTFN)
1970
Larry Hastings9cf065c2012-06-22 16:30:09 -07001971 def _check_xattrs_str(self, s, getxattr, setxattr, removexattr, listxattr, **kwargs):
Benjamin Peterson799bd802011-08-31 22:15:17 -04001972 fn = support.TESTFN
1973 open(fn, "wb").close()
1974 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001975 getxattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001976 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02001977 init_xattr = listxattr(fn)
1978 self.assertIsInstance(init_xattr, list)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001979 setxattr(fn, s("user.test"), b"", **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02001980 xattr = set(init_xattr)
1981 xattr.add("user.test")
1982 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001983 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"")
1984 setxattr(fn, s("user.test"), b"hello", os.XATTR_REPLACE, **kwargs)
1985 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"hello")
Benjamin Peterson799bd802011-08-31 22:15:17 -04001986 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001987 setxattr(fn, s("user.test"), b"bye", os.XATTR_CREATE, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001988 self.assertEqual(cm.exception.errno, errno.EEXIST)
1989 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001990 setxattr(fn, s("user.test2"), b"bye", os.XATTR_REPLACE, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001991 self.assertEqual(cm.exception.errno, errno.ENODATA)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001992 setxattr(fn, s("user.test2"), b"foo", os.XATTR_CREATE, **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02001993 xattr.add("user.test2")
1994 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001995 removexattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001996 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001997 getxattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001998 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02001999 xattr.remove("user.test")
2000 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002001 self.assertEqual(getxattr(fn, s("user.test2"), **kwargs), b"foo")
2002 setxattr(fn, s("user.test"), b"a"*1024, **kwargs)
2003 self.assertEqual(getxattr(fn, s("user.test"), **kwargs), b"a"*1024)
2004 removexattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002005 many = sorted("user.test{}".format(i) for i in range(100))
2006 for thing in many:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002007 setxattr(fn, thing, b"x", **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002008 self.assertEqual(set(listxattr(fn)), set(init_xattr) | set(many))
Benjamin Peterson799bd802011-08-31 22:15:17 -04002009
Larry Hastings9cf065c2012-06-22 16:30:09 -07002010 def _check_xattrs(self, *args, **kwargs):
Benjamin Peterson799bd802011-08-31 22:15:17 -04002011 def make_bytes(s):
2012 return bytes(s, "ascii")
Larry Hastings9cf065c2012-06-22 16:30:09 -07002013 self._check_xattrs_str(str, *args, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002014 support.unlink(support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002015 self._check_xattrs_str(make_bytes, *args, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002016
2017 def test_simple(self):
2018 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
2019 os.listxattr)
2020
2021 def test_lpath(self):
Larry Hastings9cf065c2012-06-22 16:30:09 -07002022 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
2023 os.listxattr, follow_symlinks=False)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002024
2025 def test_fds(self):
2026 def getxattr(path, *args):
2027 with open(path, "rb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002028 return os.getxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002029 def setxattr(path, *args):
2030 with open(path, "wb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002031 os.setxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002032 def removexattr(path, *args):
2033 with open(path, "wb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002034 os.removexattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002035 def listxattr(path, *args):
2036 with open(path, "rb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002037 return os.listxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002038 self._check_xattrs(getxattr, setxattr, removexattr, listxattr)
2039
2040
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002041@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
2042class Win32DeprecatedBytesAPI(unittest.TestCase):
2043 def test_deprecated(self):
2044 import nt
2045 filename = os.fsencode(support.TESTFN)
2046 with warnings.catch_warnings():
2047 warnings.simplefilter("error", DeprecationWarning)
2048 for func, *args in (
2049 (nt._getfullpathname, filename),
2050 (nt._isdir, filename),
2051 (os.access, filename, os.R_OK),
2052 (os.chdir, filename),
2053 (os.chmod, filename, 0o777),
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01002054 (os.getcwdb,),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002055 (os.link, filename, filename),
2056 (os.listdir, filename),
2057 (os.lstat, filename),
2058 (os.mkdir, filename),
2059 (os.open, filename, os.O_RDONLY),
2060 (os.rename, filename, filename),
2061 (os.rmdir, filename),
2062 (os.startfile, filename),
2063 (os.stat, filename),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002064 (os.unlink, filename),
2065 (os.utime, filename),
2066 ):
2067 self.assertRaises(DeprecationWarning, func, *args)
2068
Victor Stinner28216442011-11-16 00:34:44 +01002069 @support.skip_unless_symlink
2070 def test_symlink(self):
2071 filename = os.fsencode(support.TESTFN)
2072 with warnings.catch_warnings():
2073 warnings.simplefilter("error", DeprecationWarning)
2074 self.assertRaises(DeprecationWarning,
2075 os.symlink, filename, filename)
2076
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002077
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002078@unittest.skipUnless(hasattr(os, 'get_terminal_size'), "requires os.get_terminal_size")
2079class TermsizeTests(unittest.TestCase):
2080 def test_does_not_crash(self):
2081 """Check if get_terminal_size() returns a meaningful value.
2082
2083 There's no easy portable way to actually check the size of the
2084 terminal, so let's check if it returns something sensible instead.
2085 """
2086 try:
2087 size = os.get_terminal_size()
2088 except OSError as e:
Antoine Pitrou81a1fa52012-02-09 00:11:00 +01002089 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002090 # Under win32 a generic OSError can be thrown if the
2091 # handle cannot be retrieved
2092 self.skipTest("failed to query terminal size")
2093 raise
2094
Antoine Pitroucfade362012-02-08 23:48:59 +01002095 self.assertGreaterEqual(size.columns, 0)
2096 self.assertGreaterEqual(size.lines, 0)
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002097
2098 def test_stty_match(self):
2099 """Check if stty returns the same results
2100
2101 stty actually tests stdin, so get_terminal_size is invoked on
2102 stdin explicitly. If stty succeeded, then get_terminal_size()
2103 should work too.
2104 """
2105 try:
2106 size = subprocess.check_output(['stty', 'size']).decode().split()
2107 except (FileNotFoundError, subprocess.CalledProcessError):
2108 self.skipTest("stty invocation failed")
2109 expected = (int(size[1]), int(size[0])) # reversed order
2110
Antoine Pitrou81a1fa52012-02-09 00:11:00 +01002111 try:
2112 actual = os.get_terminal_size(sys.__stdin__.fileno())
2113 except OSError as e:
2114 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
2115 # Under win32 a generic OSError can be thrown if the
2116 # handle cannot be retrieved
2117 self.skipTest("failed to query terminal size")
2118 raise
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002119 self.assertEqual(expected, actual)
2120
2121
Victor Stinner292c8352012-10-30 02:17:38 +01002122class OSErrorTests(unittest.TestCase):
2123 def setUp(self):
2124 class Str(str):
2125 pass
2126
Victor Stinnerafe17062012-10-31 22:47:43 +01002127 self.bytes_filenames = []
2128 self.unicode_filenames = []
Victor Stinner292c8352012-10-30 02:17:38 +01002129 if support.TESTFN_UNENCODABLE is not None:
2130 decoded = support.TESTFN_UNENCODABLE
2131 else:
2132 decoded = support.TESTFN
Victor Stinnerafe17062012-10-31 22:47:43 +01002133 self.unicode_filenames.append(decoded)
2134 self.unicode_filenames.append(Str(decoded))
Victor Stinner292c8352012-10-30 02:17:38 +01002135 if support.TESTFN_UNDECODABLE is not None:
2136 encoded = support.TESTFN_UNDECODABLE
2137 else:
2138 encoded = os.fsencode(support.TESTFN)
Victor Stinnerafe17062012-10-31 22:47:43 +01002139 self.bytes_filenames.append(encoded)
2140 self.bytes_filenames.append(memoryview(encoded))
2141
2142 self.filenames = self.bytes_filenames + self.unicode_filenames
Victor Stinner292c8352012-10-30 02:17:38 +01002143
2144 def test_oserror_filename(self):
2145 funcs = [
Victor Stinnerafe17062012-10-31 22:47:43 +01002146 (self.filenames, os.chdir,),
2147 (self.filenames, os.chmod, 0o777),
Victor Stinnerafe17062012-10-31 22:47:43 +01002148 (self.filenames, os.lstat,),
2149 (self.filenames, os.open, os.O_RDONLY),
2150 (self.filenames, os.rmdir,),
2151 (self.filenames, os.stat,),
2152 (self.filenames, os.unlink,),
Victor Stinner292c8352012-10-30 02:17:38 +01002153 ]
2154 if sys.platform == "win32":
2155 funcs.extend((
Victor Stinnerafe17062012-10-31 22:47:43 +01002156 (self.bytes_filenames, os.rename, b"dst"),
2157 (self.bytes_filenames, os.replace, b"dst"),
2158 (self.unicode_filenames, os.rename, "dst"),
2159 (self.unicode_filenames, os.replace, "dst"),
Victor Stinner64e039a2012-11-07 00:10:14 +01002160 # Issue #16414: Don't test undecodable names with listdir()
2161 # because of a Windows bug.
2162 #
2163 # With the ANSI code page 932, os.listdir(b'\xe7') return an
2164 # empty list (instead of failing), whereas os.listdir(b'\xff')
2165 # raises a FileNotFoundError. It looks like a Windows bug:
2166 # b'\xe7' directory does not exist, FindFirstFileA(b'\xe7')
2167 # fails with ERROR_FILE_NOT_FOUND (2), instead of
2168 # ERROR_PATH_NOT_FOUND (3).
2169 (self.unicode_filenames, os.listdir,),
Victor Stinner292c8352012-10-30 02:17:38 +01002170 ))
Victor Stinnerafe17062012-10-31 22:47:43 +01002171 else:
2172 funcs.extend((
Victor Stinner64e039a2012-11-07 00:10:14 +01002173 (self.filenames, os.listdir,),
Victor Stinnerafe17062012-10-31 22:47:43 +01002174 (self.filenames, os.rename, "dst"),
2175 (self.filenames, os.replace, "dst"),
2176 ))
2177 if hasattr(os, "chown"):
2178 funcs.append((self.filenames, os.chown, 0, 0))
2179 if hasattr(os, "lchown"):
2180 funcs.append((self.filenames, os.lchown, 0, 0))
2181 if hasattr(os, "truncate"):
2182 funcs.append((self.filenames, os.truncate, 0))
Victor Stinner292c8352012-10-30 02:17:38 +01002183 if hasattr(os, "chflags"):
Victor Stinneree36c242012-11-13 09:31:51 +01002184 funcs.append((self.filenames, os.chflags, 0))
2185 if hasattr(os, "lchflags"):
2186 funcs.append((self.filenames, os.lchflags, 0))
Victor Stinner292c8352012-10-30 02:17:38 +01002187 if hasattr(os, "chroot"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002188 funcs.append((self.filenames, os.chroot,))
Victor Stinner292c8352012-10-30 02:17:38 +01002189 if hasattr(os, "link"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002190 if sys.platform == "win32":
2191 funcs.append((self.bytes_filenames, os.link, b"dst"))
2192 funcs.append((self.unicode_filenames, os.link, "dst"))
2193 else:
2194 funcs.append((self.filenames, os.link, "dst"))
Victor Stinner292c8352012-10-30 02:17:38 +01002195 if hasattr(os, "listxattr"):
2196 funcs.extend((
Victor Stinnerafe17062012-10-31 22:47:43 +01002197 (self.filenames, os.listxattr,),
2198 (self.filenames, os.getxattr, "user.test"),
2199 (self.filenames, os.setxattr, "user.test", b'user'),
2200 (self.filenames, os.removexattr, "user.test"),
Victor Stinner292c8352012-10-30 02:17:38 +01002201 ))
2202 if hasattr(os, "lchmod"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002203 funcs.append((self.filenames, os.lchmod, 0o777))
Victor Stinner292c8352012-10-30 02:17:38 +01002204 if hasattr(os, "readlink"):
Victor Stinnerafe17062012-10-31 22:47:43 +01002205 if sys.platform == "win32":
2206 funcs.append((self.unicode_filenames, os.readlink,))
2207 else:
2208 funcs.append((self.filenames, os.readlink,))
Victor Stinner292c8352012-10-30 02:17:38 +01002209
Victor Stinnerafe17062012-10-31 22:47:43 +01002210 for filenames, func, *func_args in funcs:
2211 for name in filenames:
Victor Stinner292c8352012-10-30 02:17:38 +01002212 try:
2213 func(name, *func_args)
Victor Stinnerbd54f0e2012-10-31 01:12:55 +01002214 except OSError as err:
Victor Stinner292c8352012-10-30 02:17:38 +01002215 self.assertIs(err.filename, name)
2216 else:
2217 self.fail("No exception thrown by {}".format(func))
2218
Charles-Francois Natali44feda32013-05-20 14:40:46 +02002219class CPUCountTests(unittest.TestCase):
2220 def test_cpu_count(self):
2221 cpus = os.cpu_count()
2222 if cpus is not None:
2223 self.assertIsInstance(cpus, int)
2224 self.assertGreater(cpus, 0)
2225 else:
2226 self.skipTest("Could not determine the number of CPUs")
2227
Antoine Pitrouf26ad712011-07-15 23:00:56 +02002228@support.reap_threads
Fred Drake2e2be372001-09-20 21:33:42 +00002229def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002230 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002231 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002232 StatAttributeTests,
2233 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00002234 WalkTests,
Charles-François Natali7372b062012-02-05 15:15:38 +01002235 FwalkTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00002236 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +00002237 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002238 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +00002239 ExecTests,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00002240 Win32ErrorTests,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002241 TestInvalidFD,
Martin v. Löwis011e8422009-05-05 04:43:17 +00002242 PosixUidGidTests,
Brian Curtineb24d742010-04-12 17:16:38 +00002243 Pep383Tests,
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00002244 Win32KillTests,
Brian Curtind40e6f72010-07-08 21:39:08 +00002245 Win32SymlinkTests,
Victor Stinnere8d51452010-08-19 01:05:19 +00002246 FSEncodingTests,
Brett Cannonefb00c02012-02-29 18:31:31 -05002247 DeviceEncodingTests,
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00002248 PidTests,
Brian Curtine8e4b3b2010-09-23 20:04:14 +00002249 LoginTests,
Brian Curtin1b9df392010-11-24 20:24:31 +00002250 LinkTests,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002251 TestSendfile,
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00002252 ProgramPriorityTests,
Benjamin Peterson799bd802011-08-31 22:15:17 -04002253 ExtendedAttributeTests,
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002254 Win32DeprecatedBytesAPI,
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002255 TermsizeTests,
Victor Stinner292c8352012-10-30 02:17:38 +01002256 OSErrorTests,
Andrew Svetlov405faed2012-12-25 12:18:09 +02002257 RemoveDirsTests,
Charles-Francois Natali44feda32013-05-20 14:40:46 +02002258 CPUCountTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002259 )
Fred Drake2e2be372001-09-20 21:33:42 +00002260
2261if __name__ == "__main__":
2262 test_main()