blob: 184c9ae31f70d77f094d42eaddab6c5acaef46d3 [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")
474 except WindowsError as e:
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000475 if e.errno == 2: # file does not exist; cannot run test
Guido van Rossumd8faa362007-04-27 19:54:29 +0000476 return
477 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
Tim Petersc4e09402003-04-25 07:11:48 +0000635class WalkTests(unittest.TestCase):
636 """Tests for os.walk()."""
637
Charles-François Natali7372b062012-02-05 15:15:38 +0100638 def setUp(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000639 import os
640 from os.path import join
641
642 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000643 # TESTFN/
644 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000645 # tmp1
646 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000647 # tmp2
648 # SUB11/ no kids
649 # SUB2/ a file kid and a dirsymlink kid
650 # tmp3
651 # link/ a symlink to TESTFN.2
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200652 # broken_link
Guido van Rossumd8faa362007-04-27 19:54:29 +0000653 # TEST2/
654 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000655 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000656 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000657 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000658 sub2_path = join(walk_path, "SUB2")
659 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000660 tmp2_path = join(sub1_path, "tmp2")
661 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000662 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000663 t2_path = join(support.TESTFN, "TEST2")
664 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200665 link_path = join(sub2_path, "link")
666 broken_link_path = join(sub2_path, "broken_link")
Tim Petersc4e09402003-04-25 07:11:48 +0000667
668 # Create stuff.
669 os.makedirs(sub11_path)
670 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000671 os.makedirs(t2_path)
672 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000673 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000674 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
675 f.close()
Brian Curtin3b4499c2010-12-28 14:31:47 +0000676 if support.can_symlink():
Antoine Pitrou5311c1d2012-01-24 08:59:28 +0100677 if os.name == 'nt':
678 def symlink_to_dir(src, dest):
679 os.symlink(src, dest, True)
680 else:
681 symlink_to_dir = os.symlink
682 symlink_to_dir(os.path.abspath(t2_path), link_path)
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200683 symlink_to_dir('broken', broken_link_path)
684 sub2_tree = (sub2_path, ["link"], ["broken_link", "tmp3"])
Guido van Rossumd8faa362007-04-27 19:54:29 +0000685 else:
686 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000687
688 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000689 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000690 self.assertEqual(len(all), 4)
691 # We can't know which order SUB1 and SUB2 will appear in.
692 # Not flipped: TESTFN, SUB1, SUB11, SUB2
693 # flipped: TESTFN, SUB2, SUB1, SUB11
694 flipped = all[0][1][0] != "SUB1"
695 all[0][1].sort()
Hynek Schlawackc96f5a02012-05-15 17:55:38 +0200696 all[3 - 2 * flipped][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000697 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000698 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
699 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000700 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000701
702 # Prune the search.
703 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000704 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000705 all.append((root, dirs, files))
706 # Don't descend into SUB1.
707 if 'SUB1' in dirs:
708 # Note that this also mutates the dirs we appended to all!
709 dirs.remove('SUB1')
710 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000711 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Hynek Schlawack39bf90d2012-05-15 18:40:17 +0200712 all[1][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000713 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000714
715 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000716 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000717 self.assertEqual(len(all), 4)
718 # We can't know which order SUB1 and SUB2 will appear in.
719 # Not flipped: SUB11, SUB1, SUB2, TESTFN
720 # flipped: SUB2, SUB11, SUB1, TESTFN
721 flipped = all[3][1][0] != "SUB1"
722 all[3][1].sort()
Hynek Schlawack39bf90d2012-05-15 18:40:17 +0200723 all[2 - 2 * flipped][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000724 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000725 self.assertEqual(all[flipped], (sub11_path, [], []))
726 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000727 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000728
Brian Curtin3b4499c2010-12-28 14:31:47 +0000729 if support.can_symlink():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000730 # Walk, following symlinks.
731 for root, dirs, files in os.walk(walk_path, followlinks=True):
732 if root == link_path:
733 self.assertEqual(dirs, [])
734 self.assertEqual(files, ["tmp4"])
735 break
736 else:
737 self.fail("Didn't follow symlink with followlinks=True")
738
739 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000740 # Tear everything down. This is a decent use for bottom-up on
741 # Windows, which doesn't have a recursive delete command. The
742 # (not so) subtlety is that rmdir will fail unless the dir's
743 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000744 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000745 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000746 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000747 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000748 dirname = os.path.join(root, name)
749 if not os.path.islink(dirname):
750 os.rmdir(dirname)
751 else:
752 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000753 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000754
Charles-François Natali7372b062012-02-05 15:15:38 +0100755
756@unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
757class FwalkTests(WalkTests):
758 """Tests for os.fwalk()."""
759
Larry Hastingsc48fe982012-06-25 04:49:05 -0700760 def _compare_to_walk(self, walk_kwargs, fwalk_kwargs):
761 """
762 compare with walk() results.
763 """
Larry Hastingsb4038062012-07-15 10:57:38 -0700764 walk_kwargs = walk_kwargs.copy()
765 fwalk_kwargs = fwalk_kwargs.copy()
766 for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
767 walk_kwargs.update(topdown=topdown, followlinks=follow_symlinks)
768 fwalk_kwargs.update(topdown=topdown, follow_symlinks=follow_symlinks)
Larry Hastingsc48fe982012-06-25 04:49:05 -0700769
Charles-François Natali7372b062012-02-05 15:15:38 +0100770 expected = {}
Larry Hastingsc48fe982012-06-25 04:49:05 -0700771 for root, dirs, files in os.walk(**walk_kwargs):
Charles-François Natali7372b062012-02-05 15:15:38 +0100772 expected[root] = (set(dirs), set(files))
773
Larry Hastingsc48fe982012-06-25 04:49:05 -0700774 for root, dirs, files, rootfd in os.fwalk(**fwalk_kwargs):
Charles-François Natali7372b062012-02-05 15:15:38 +0100775 self.assertIn(root, expected)
776 self.assertEqual(expected[root], (set(dirs), set(files)))
777
Larry Hastingsc48fe982012-06-25 04:49:05 -0700778 def test_compare_to_walk(self):
779 kwargs = {'top': support.TESTFN}
780 self._compare_to_walk(kwargs, kwargs)
781
Charles-François Natali7372b062012-02-05 15:15:38 +0100782 def test_dir_fd(self):
Larry Hastingsc48fe982012-06-25 04:49:05 -0700783 try:
784 fd = os.open(".", os.O_RDONLY)
785 walk_kwargs = {'top': support.TESTFN}
786 fwalk_kwargs = walk_kwargs.copy()
787 fwalk_kwargs['dir_fd'] = fd
788 self._compare_to_walk(walk_kwargs, fwalk_kwargs)
789 finally:
790 os.close(fd)
791
792 def test_yields_correct_dir_fd(self):
Charles-François Natali7372b062012-02-05 15:15:38 +0100793 # check returned file descriptors
Larry Hastingsb4038062012-07-15 10:57:38 -0700794 for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
795 args = support.TESTFN, topdown, None
796 for root, dirs, files, rootfd in os.fwalk(*args, follow_symlinks=follow_symlinks):
Charles-François Natali7372b062012-02-05 15:15:38 +0100797 # check that the FD is valid
798 os.fstat(rootfd)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700799 # redundant check
800 os.stat(rootfd)
801 # check that listdir() returns consistent information
802 self.assertEqual(set(os.listdir(rootfd)), set(dirs) | set(files))
Charles-François Natali7372b062012-02-05 15:15:38 +0100803
804 def test_fd_leak(self):
805 # Since we're opening a lot of FDs, we must be careful to avoid leaks:
806 # we both check that calling fwalk() a large number of times doesn't
807 # yield EMFILE, and that the minimum allocated FD hasn't changed.
808 minfd = os.dup(1)
809 os.close(minfd)
810 for i in range(256):
811 for x in os.fwalk(support.TESTFN):
812 pass
813 newfd = os.dup(1)
814 self.addCleanup(os.close, newfd)
815 self.assertEqual(newfd, minfd)
816
817 def tearDown(self):
818 # cleanup
819 for root, dirs, files, rootfd in os.fwalk(support.TESTFN, topdown=False):
820 for name in files:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700821 os.unlink(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +0100822 for name in dirs:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700823 st = os.stat(name, dir_fd=rootfd, follow_symlinks=False)
Larry Hastingsb698d8e2012-06-23 16:55:07 -0700824 if stat.S_ISDIR(st.st_mode):
825 os.rmdir(name, dir_fd=rootfd)
826 else:
827 os.unlink(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +0100828 os.rmdir(support.TESTFN)
829
830
Guido van Rossume7ba4952007-06-06 23:52:48 +0000831class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000832 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000833 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000834
835 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000836 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000837 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
838 os.makedirs(path) # Should work
839 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
840 os.makedirs(path)
841
842 # Try paths with a '.' in them
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000843 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000844 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
845 os.makedirs(path)
846 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
847 'dir5', 'dir6')
848 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000849
Terry Reedy5a22b652010-12-02 07:05:56 +0000850 def test_exist_ok_existing_directory(self):
851 path = os.path.join(support.TESTFN, 'dir1')
852 mode = 0o777
853 old_mask = os.umask(0o022)
854 os.makedirs(path, mode)
855 self.assertRaises(OSError, os.makedirs, path, mode)
856 self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
857 self.assertRaises(OSError, os.makedirs, path, 0o776, exist_ok=True)
858 os.makedirs(path, mode=mode, exist_ok=True)
859 os.umask(old_mask)
860
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700861 def test_exist_ok_s_isgid_directory(self):
862 path = os.path.join(support.TESTFN, 'dir1')
863 S_ISGID = stat.S_ISGID
864 mode = 0o777
865 old_mask = os.umask(0o022)
866 try:
867 existing_testfn_mode = stat.S_IMODE(
868 os.lstat(support.TESTFN).st_mode)
Ned Deilyc622f422012-08-08 20:57:24 -0700869 try:
870 os.chmod(support.TESTFN, existing_testfn_mode | S_ISGID)
Ned Deily3a2b97e2012-08-08 21:03:02 -0700871 except PermissionError:
Ned Deilyc622f422012-08-08 20:57:24 -0700872 raise unittest.SkipTest('Cannot set S_ISGID for dir.')
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700873 if (os.lstat(support.TESTFN).st_mode & S_ISGID != S_ISGID):
874 raise unittest.SkipTest('No support for S_ISGID dir mode.')
875 # The os should apply S_ISGID from the parent dir for us, but
876 # this test need not depend on that behavior. Be explicit.
877 os.makedirs(path, mode | S_ISGID)
878 # http://bugs.python.org/issue14992
879 # Should not fail when the bit is already set.
880 os.makedirs(path, mode, exist_ok=True)
881 # remove the bit.
882 os.chmod(path, stat.S_IMODE(os.lstat(path).st_mode) & ~S_ISGID)
883 with self.assertRaises(OSError):
884 # Should fail when the bit is not already set when demanded.
885 os.makedirs(path, mode | S_ISGID, exist_ok=True)
886 finally:
887 os.umask(old_mask)
Terry Reedy5a22b652010-12-02 07:05:56 +0000888
889 def test_exist_ok_existing_regular_file(self):
890 base = support.TESTFN
891 path = os.path.join(support.TESTFN, 'dir1')
892 f = open(path, 'w')
893 f.write('abc')
894 f.close()
895 self.assertRaises(OSError, os.makedirs, path)
896 self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
897 self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
898 os.remove(path)
899
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000900 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000901 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000902 'dir4', 'dir5', 'dir6')
903 # If the tests failed, the bottom-most directory ('../dir6')
904 # may not have been created, so we look for the outermost directory
905 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000906 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000907 path = os.path.dirname(path)
908
909 os.removedirs(path)
910
Andrew Svetlov405faed2012-12-25 12:18:09 +0200911
912class RemoveDirsTests(unittest.TestCase):
913 def setUp(self):
914 os.makedirs(support.TESTFN)
915
916 def tearDown(self):
917 support.rmtree(support.TESTFN)
918
919 def test_remove_all(self):
920 dira = os.path.join(support.TESTFN, 'dira')
921 os.mkdir(dira)
922 dirb = os.path.join(dira, 'dirb')
923 os.mkdir(dirb)
924 os.removedirs(dirb)
925 self.assertFalse(os.path.exists(dirb))
926 self.assertFalse(os.path.exists(dira))
927 self.assertFalse(os.path.exists(support.TESTFN))
928
929 def test_remove_partial(self):
930 dira = os.path.join(support.TESTFN, 'dira')
931 os.mkdir(dira)
932 dirb = os.path.join(dira, 'dirb')
933 os.mkdir(dirb)
934 with open(os.path.join(dira, 'file.txt'), 'w') as f:
935 f.write('text')
936 os.removedirs(dirb)
937 self.assertFalse(os.path.exists(dirb))
938 self.assertTrue(os.path.exists(dira))
939 self.assertTrue(os.path.exists(support.TESTFN))
940
941 def test_remove_nothing(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(dirb, 'file.txt'), 'w') as f:
947 f.write('text')
948 with self.assertRaises(OSError):
949 os.removedirs(dirb)
950 self.assertTrue(os.path.exists(dirb))
951 self.assertTrue(os.path.exists(dira))
952 self.assertTrue(os.path.exists(support.TESTFN))
953
954
Guido van Rossume7ba4952007-06-06 23:52:48 +0000955class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000956 def test_devnull(self):
Victor Stinnera6d2c762011-06-30 18:20:11 +0200957 with open(os.devnull, 'wb') as f:
958 f.write(b'hello')
959 f.close()
960 with open(os.devnull, 'rb') as f:
961 self.assertEqual(f.read(), b'')
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000962
Andrew Svetlov405faed2012-12-25 12:18:09 +0200963
Guido van Rossume7ba4952007-06-06 23:52:48 +0000964class URandomTests(unittest.TestCase):
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100965 def test_urandom_length(self):
966 self.assertEqual(len(os.urandom(0)), 0)
967 self.assertEqual(len(os.urandom(1)), 1)
968 self.assertEqual(len(os.urandom(10)), 10)
969 self.assertEqual(len(os.urandom(100)), 100)
970 self.assertEqual(len(os.urandom(1000)), 1000)
971
972 def test_urandom_value(self):
973 data1 = os.urandom(16)
974 data2 = os.urandom(16)
975 self.assertNotEqual(data1, data2)
976
977 def get_urandom_subprocess(self, count):
978 code = '\n'.join((
979 'import os, sys',
980 'data = os.urandom(%s)' % count,
981 'sys.stdout.buffer.write(data)',
982 'sys.stdout.buffer.flush()'))
983 out = assert_python_ok('-c', code)
984 stdout = out[1]
985 self.assertEqual(len(stdout), 16)
986 return stdout
987
988 def test_urandom_subprocess(self):
989 data1 = self.get_urandom_subprocess(16)
990 data2 = self.get_urandom_subprocess(16)
991 self.assertNotEqual(data1, data2)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000992
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000993@contextlib.contextmanager
994def _execvpe_mockup(defpath=None):
995 """
996 Stubs out execv and execve functions when used as context manager.
997 Records exec calls. The mock execv and execve functions always raise an
998 exception as they would normally never return.
999 """
1000 # A list of tuples containing (function name, first arg, args)
1001 # of calls to execv or execve that have been made.
1002 calls = []
1003
1004 def mock_execv(name, *args):
1005 calls.append(('execv', name, args))
1006 raise RuntimeError("execv called")
1007
1008 def mock_execve(name, *args):
1009 calls.append(('execve', name, args))
1010 raise OSError(errno.ENOTDIR, "execve called")
1011
1012 try:
1013 orig_execv = os.execv
1014 orig_execve = os.execve
1015 orig_defpath = os.defpath
1016 os.execv = mock_execv
1017 os.execve = mock_execve
1018 if defpath is not None:
1019 os.defpath = defpath
1020 yield calls
1021 finally:
1022 os.execv = orig_execv
1023 os.execve = orig_execve
1024 os.defpath = orig_defpath
1025
Guido van Rossume7ba4952007-06-06 23:52:48 +00001026class ExecTests(unittest.TestCase):
Mark Dickinson7cf03892010-04-16 13:45:35 +00001027 @unittest.skipIf(USING_LINUXTHREADS,
1028 "avoid triggering a linuxthreads bug: see issue #4970")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001029 def test_execvpe_with_bad_program(self):
Mark Dickinson7cf03892010-04-16 13:45:35 +00001030 self.assertRaises(OSError, os.execvpe, 'no such app-',
1031 ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001032
Thomas Heller6790d602007-08-30 17:15:14 +00001033 def test_execvpe_with_bad_arglist(self):
1034 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
1035
Gregory P. Smith4ae37772010-05-08 18:05:46 +00001036 @unittest.skipUnless(hasattr(os, '_execvpe'),
1037 "No internal os._execvpe function to test.")
Victor Stinnerb745a742010-05-18 17:17:23 +00001038 def _test_internal_execvpe(self, test_type):
1039 program_path = os.sep + 'absolutepath'
1040 if test_type is bytes:
1041 program = b'executable'
1042 fullpath = os.path.join(os.fsencode(program_path), program)
1043 native_fullpath = fullpath
1044 arguments = [b'progname', 'arg1', 'arg2']
1045 else:
1046 program = 'executable'
1047 arguments = ['progname', 'arg1', 'arg2']
1048 fullpath = os.path.join(program_path, program)
1049 if os.name != "nt":
1050 native_fullpath = os.fsencode(fullpath)
1051 else:
1052 native_fullpath = fullpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001053 env = {'spam': 'beans'}
1054
Victor Stinnerb745a742010-05-18 17:17:23 +00001055 # test os._execvpe() with an absolute path
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001056 with _execvpe_mockup() as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +00001057 self.assertRaises(RuntimeError,
1058 os._execvpe, fullpath, arguments)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001059 self.assertEqual(len(calls), 1)
1060 self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))
1061
Victor Stinnerb745a742010-05-18 17:17:23 +00001062 # test os._execvpe() with a relative path:
1063 # os.get_exec_path() returns defpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001064 with _execvpe_mockup(defpath=program_path) as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +00001065 self.assertRaises(OSError,
1066 os._execvpe, program, arguments, env=env)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001067 self.assertEqual(len(calls), 1)
Victor Stinnerb745a742010-05-18 17:17:23 +00001068 self.assertSequenceEqual(calls[0],
1069 ('execve', native_fullpath, (arguments, env)))
1070
1071 # test os._execvpe() with a relative path:
1072 # os.get_exec_path() reads the 'PATH' variable
1073 with _execvpe_mockup() as calls:
1074 env_path = env.copy()
Victor Stinner38430e22010-08-19 17:10:18 +00001075 if test_type is bytes:
1076 env_path[b'PATH'] = program_path
1077 else:
1078 env_path['PATH'] = program_path
Victor Stinnerb745a742010-05-18 17:17:23 +00001079 self.assertRaises(OSError,
1080 os._execvpe, program, arguments, env=env_path)
1081 self.assertEqual(len(calls), 1)
1082 self.assertSequenceEqual(calls[0],
1083 ('execve', native_fullpath, (arguments, env_path)))
1084
1085 def test_internal_execvpe_str(self):
1086 self._test_internal_execvpe(str)
1087 if os.name != "nt":
1088 self._test_internal_execvpe(bytes)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001089
Gregory P. Smith4ae37772010-05-08 18:05:46 +00001090
Thomas Wouters477c8d52006-05-27 19:21:47 +00001091class Win32ErrorTests(unittest.TestCase):
1092 def test_rename(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001093 self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001094
1095 def test_remove(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001096 self.assertRaises(WindowsError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001097
1098 def test_chdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001099 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001100
1101 def test_mkdir(self):
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +00001102 f = open(support.TESTFN, "w")
Benjamin Petersonf91df042009-02-13 02:50:59 +00001103 try:
1104 self.assertRaises(WindowsError, os.mkdir, support.TESTFN)
1105 finally:
1106 f.close()
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +00001107 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001108
1109 def test_utime(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001110 self.assertRaises(WindowsError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001111
Thomas Wouters477c8d52006-05-27 19:21:47 +00001112 def test_chmod(self):
Benjamin Petersonf91df042009-02-13 02:50:59 +00001113 self.assertRaises(WindowsError, os.chmod, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001114
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001115class TestInvalidFD(unittest.TestCase):
Benjamin Peterson05e782f2009-01-19 15:15:02 +00001116 singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001117 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
1118 #singles.append("close")
1119 #We omit close because it doesn'r raise an exception on some platforms
1120 def get_single(f):
1121 def helper(self):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001122 if hasattr(os, f):
1123 self.check(getattr(os, f))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001124 return helper
1125 for f in singles:
1126 locals()["test_"+f] = get_single(f)
1127
Benjamin Peterson7522c742009-01-19 21:00:09 +00001128 def check(self, f, *args):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001129 try:
1130 f(support.make_bad_fd(), *args)
1131 except OSError as e:
1132 self.assertEqual(e.errno, errno.EBADF)
1133 else:
1134 self.fail("%r didn't raise a OSError with a bad file descriptor"
1135 % f)
Benjamin Peterson7522c742009-01-19 21:00:09 +00001136
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001137 def test_isatty(self):
1138 if hasattr(os, "isatty"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001139 self.assertEqual(os.isatty(support.make_bad_fd()), False)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001140
1141 def test_closerange(self):
1142 if hasattr(os, "closerange"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001143 fd = support.make_bad_fd()
R. David Murray630cc482009-07-22 15:20:27 +00001144 # Make sure none of the descriptors we are about to close are
1145 # currently valid (issue 6542).
1146 for i in range(10):
1147 try: os.fstat(fd+i)
1148 except OSError:
1149 pass
1150 else:
1151 break
1152 if i < 2:
1153 raise unittest.SkipTest(
1154 "Unable to acquire a range of invalid file descriptors")
1155 self.assertEqual(os.closerange(fd, fd + i-1), None)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001156
1157 def test_dup2(self):
1158 if hasattr(os, "dup2"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001159 self.check(os.dup2, 20)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001160
1161 def test_fchmod(self):
1162 if hasattr(os, "fchmod"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001163 self.check(os.fchmod, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001164
1165 def test_fchown(self):
1166 if hasattr(os, "fchown"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001167 self.check(os.fchown, -1, -1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001168
1169 def test_fpathconf(self):
1170 if hasattr(os, "fpathconf"):
Georg Brandl306336b2012-06-24 12:55:33 +02001171 self.check(os.pathconf, "PC_NAME_MAX")
Benjamin Peterson7522c742009-01-19 21:00:09 +00001172 self.check(os.fpathconf, "PC_NAME_MAX")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001173
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001174 def test_ftruncate(self):
1175 if hasattr(os, "ftruncate"):
Georg Brandl306336b2012-06-24 12:55:33 +02001176 self.check(os.truncate, 0)
Benjamin Peterson7522c742009-01-19 21:00:09 +00001177 self.check(os.ftruncate, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001178
1179 def test_lseek(self):
1180 if hasattr(os, "lseek"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001181 self.check(os.lseek, 0, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001182
1183 def test_read(self):
1184 if hasattr(os, "read"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001185 self.check(os.read, 1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001186
1187 def test_tcsetpgrpt(self):
1188 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001189 self.check(os.tcsetpgrp, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001190
1191 def test_write(self):
1192 if hasattr(os, "write"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001193 self.check(os.write, b" ")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001194
Brian Curtin1b9df392010-11-24 20:24:31 +00001195
1196class LinkTests(unittest.TestCase):
1197 def setUp(self):
1198 self.file1 = support.TESTFN
1199 self.file2 = os.path.join(support.TESTFN + "2")
1200
Brian Curtinc0abc4e2010-11-30 23:46:54 +00001201 def tearDown(self):
Brian Curtin1b9df392010-11-24 20:24:31 +00001202 for file in (self.file1, self.file2):
1203 if os.path.exists(file):
1204 os.unlink(file)
1205
Brian Curtin1b9df392010-11-24 20:24:31 +00001206 def _test_link(self, file1, file2):
1207 with open(file1, "w") as f1:
1208 f1.write("test")
1209
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001210 with warnings.catch_warnings():
1211 warnings.simplefilter("ignore", DeprecationWarning)
1212 os.link(file1, file2)
Brian Curtin1b9df392010-11-24 20:24:31 +00001213 with open(file1, "r") as f1, open(file2, "r") as f2:
1214 self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
1215
1216 def test_link(self):
1217 self._test_link(self.file1, self.file2)
1218
1219 def test_link_bytes(self):
1220 self._test_link(bytes(self.file1, sys.getfilesystemencoding()),
1221 bytes(self.file2, sys.getfilesystemencoding()))
1222
Brian Curtinf498b752010-11-30 15:54:04 +00001223 def test_unicode_name(self):
Brian Curtin43f0c272010-11-30 15:40:04 +00001224 try:
Brian Curtinf498b752010-11-30 15:54:04 +00001225 os.fsencode("\xf1")
Brian Curtin43f0c272010-11-30 15:40:04 +00001226 except UnicodeError:
1227 raise unittest.SkipTest("Unable to encode for this platform.")
1228
Brian Curtinf498b752010-11-30 15:54:04 +00001229 self.file1 += "\xf1"
Brian Curtinfc889c42010-11-28 23:59:46 +00001230 self.file2 = self.file1 + "2"
1231 self._test_link(self.file1, self.file2)
1232
Thomas Wouters477c8d52006-05-27 19:21:47 +00001233if sys.platform != 'win32':
1234 class Win32ErrorTests(unittest.TestCase):
1235 pass
1236
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001237 class PosixUidGidTests(unittest.TestCase):
1238 if hasattr(os, 'setuid'):
1239 def test_setuid(self):
1240 if os.getuid() != 0:
1241 self.assertRaises(os.error, os.setuid, 0)
1242 self.assertRaises(OverflowError, os.setuid, 1<<32)
1243
1244 if hasattr(os, 'setgid'):
1245 def test_setgid(self):
Stefan Krahebee49a2013-01-17 15:31:00 +01001246 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001247 self.assertRaises(os.error, os.setgid, 0)
1248 self.assertRaises(OverflowError, os.setgid, 1<<32)
1249
1250 if hasattr(os, 'seteuid'):
1251 def test_seteuid(self):
1252 if os.getuid() != 0:
1253 self.assertRaises(os.error, os.seteuid, 0)
1254 self.assertRaises(OverflowError, os.seteuid, 1<<32)
1255
1256 if hasattr(os, 'setegid'):
1257 def test_setegid(self):
Stefan Krahebee49a2013-01-17 15:31:00 +01001258 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001259 self.assertRaises(os.error, os.setegid, 0)
1260 self.assertRaises(OverflowError, os.setegid, 1<<32)
1261
1262 if hasattr(os, 'setreuid'):
1263 def test_setreuid(self):
1264 if os.getuid() != 0:
1265 self.assertRaises(os.error, os.setreuid, 0, 0)
1266 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
1267 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001268
1269 def test_setreuid_neg1(self):
1270 # Needs to accept -1. We run this in a subprocess to avoid
1271 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001272 subprocess.check_call([
1273 sys.executable, '-c',
1274 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001275
1276 if hasattr(os, 'setregid'):
1277 def test_setregid(self):
Stefan Krahebee49a2013-01-17 15:31:00 +01001278 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001279 self.assertRaises(os.error, os.setregid, 0, 0)
1280 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
1281 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001282
1283 def test_setregid_neg1(self):
1284 # Needs to accept -1. We run this in a subprocess to avoid
1285 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001286 subprocess.check_call([
1287 sys.executable, '-c',
1288 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Martin v. Löwis011e8422009-05-05 04:43:17 +00001289
1290 class Pep383Tests(unittest.TestCase):
Martin v. Löwis011e8422009-05-05 04:43:17 +00001291 def setUp(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001292 if support.TESTFN_UNENCODABLE:
1293 self.dir = support.TESTFN_UNENCODABLE
Victor Stinnere667e982012-11-12 01:23:15 +01001294 elif support.TESTFN_NONASCII:
1295 self.dir = support.TESTFN_NONASCII
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001296 else:
1297 self.dir = support.TESTFN
1298 self.bdir = os.fsencode(self.dir)
1299
1300 bytesfn = []
1301 def add_filename(fn):
1302 try:
1303 fn = os.fsencode(fn)
1304 except UnicodeEncodeError:
1305 return
1306 bytesfn.append(fn)
1307 add_filename(support.TESTFN_UNICODE)
1308 if support.TESTFN_UNENCODABLE:
1309 add_filename(support.TESTFN_UNENCODABLE)
Victor Stinnere667e982012-11-12 01:23:15 +01001310 if support.TESTFN_NONASCII:
1311 add_filename(support.TESTFN_NONASCII)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001312 if not bytesfn:
1313 self.skipTest("couldn't create any non-ascii filename")
1314
1315 self.unicodefn = set()
Martin v. Löwis011e8422009-05-05 04:43:17 +00001316 os.mkdir(self.dir)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001317 try:
1318 for fn in bytesfn:
Victor Stinnerbf816222011-06-30 23:25:47 +02001319 support.create_empty_file(os.path.join(self.bdir, fn))
Victor Stinnere8d51452010-08-19 01:05:19 +00001320 fn = os.fsdecode(fn)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001321 if fn in self.unicodefn:
1322 raise ValueError("duplicate filename")
1323 self.unicodefn.add(fn)
1324 except:
1325 shutil.rmtree(self.dir)
1326 raise
Martin v. Löwis011e8422009-05-05 04:43:17 +00001327
1328 def tearDown(self):
1329 shutil.rmtree(self.dir)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001330
1331 def test_listdir(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001332 expected = self.unicodefn
1333 found = set(os.listdir(self.dir))
Ezio Melottib3aedd42010-11-20 19:04:17 +00001334 self.assertEqual(found, expected)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001335 # test listdir without arguments
1336 current_directory = os.getcwd()
1337 try:
1338 os.chdir(os.sep)
1339 self.assertEqual(set(os.listdir()), set(os.listdir(os.sep)))
1340 finally:
1341 os.chdir(current_directory)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001342
1343 def test_open(self):
1344 for fn in self.unicodefn:
Victor Stinnera6d2c762011-06-30 18:20:11 +02001345 f = open(os.path.join(self.dir, fn), 'rb')
Martin v. Löwis011e8422009-05-05 04:43:17 +00001346 f.close()
1347
Victor Stinnere4110dc2013-01-01 23:05:55 +01001348 @unittest.skipUnless(hasattr(os, 'statvfs'),
1349 "need os.statvfs()")
1350 def test_statvfs(self):
1351 # issue #9645
1352 for fn in self.unicodefn:
1353 # should not fail with file not found error
1354 fullname = os.path.join(self.dir, fn)
1355 os.statvfs(fullname)
1356
Martin v. Löwis011e8422009-05-05 04:43:17 +00001357 def test_stat(self):
1358 for fn in self.unicodefn:
1359 os.stat(os.path.join(self.dir, fn))
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001360else:
1361 class PosixUidGidTests(unittest.TestCase):
1362 pass
Martin v. Löwis011e8422009-05-05 04:43:17 +00001363 class Pep383Tests(unittest.TestCase):
1364 pass
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001365
Brian Curtineb24d742010-04-12 17:16:38 +00001366@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
1367class Win32KillTests(unittest.TestCase):
Brian Curtinc3acbc32010-05-28 16:08:40 +00001368 def _kill(self, sig):
1369 # Start sys.executable as a subprocess and communicate from the
1370 # subprocess to the parent that the interpreter is ready. When it
1371 # becomes ready, send *sig* via os.kill to the subprocess and check
1372 # that the return code is equal to *sig*.
1373 import ctypes
1374 from ctypes import wintypes
1375 import msvcrt
1376
1377 # Since we can't access the contents of the process' stdout until the
1378 # process has exited, use PeekNamedPipe to see what's inside stdout
1379 # without waiting. This is done so we can tell that the interpreter
1380 # is started and running at a point where it could handle a signal.
1381 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
1382 PeekNamedPipe.restype = wintypes.BOOL
1383 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
1384 ctypes.POINTER(ctypes.c_char), # stdout buf
1385 wintypes.DWORD, # Buffer size
1386 ctypes.POINTER(wintypes.DWORD), # bytes read
1387 ctypes.POINTER(wintypes.DWORD), # bytes avail
1388 ctypes.POINTER(wintypes.DWORD)) # bytes left
1389 msg = "running"
1390 proc = subprocess.Popen([sys.executable, "-c",
1391 "import sys;"
1392 "sys.stdout.write('{}');"
1393 "sys.stdout.flush();"
1394 "input()".format(msg)],
1395 stdout=subprocess.PIPE,
1396 stderr=subprocess.PIPE,
1397 stdin=subprocess.PIPE)
Brian Curtin43ec5772010-11-05 15:17:11 +00001398 self.addCleanup(proc.stdout.close)
1399 self.addCleanup(proc.stderr.close)
1400 self.addCleanup(proc.stdin.close)
Brian Curtinc3acbc32010-05-28 16:08:40 +00001401
1402 count, max = 0, 100
1403 while count < max and proc.poll() is None:
1404 # Create a string buffer to store the result of stdout from the pipe
1405 buf = ctypes.create_string_buffer(len(msg))
1406 # Obtain the text currently in proc.stdout
1407 # Bytes read/avail/left are left as NULL and unused
1408 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
1409 buf, ctypes.sizeof(buf), None, None, None)
1410 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
1411 if buf.value:
1412 self.assertEqual(msg, buf.value.decode())
1413 break
1414 time.sleep(0.1)
1415 count += 1
1416 else:
1417 self.fail("Did not receive communication from the subprocess")
1418
Brian Curtineb24d742010-04-12 17:16:38 +00001419 os.kill(proc.pid, sig)
1420 self.assertEqual(proc.wait(), sig)
1421
1422 def test_kill_sigterm(self):
1423 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinc3acbc32010-05-28 16:08:40 +00001424 self._kill(signal.SIGTERM)
Brian Curtineb24d742010-04-12 17:16:38 +00001425
1426 def test_kill_int(self):
1427 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinc3acbc32010-05-28 16:08:40 +00001428 self._kill(100)
Brian Curtineb24d742010-04-12 17:16:38 +00001429
1430 def _kill_with_event(self, event, name):
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001431 tagname = "test_os_%s" % uuid.uuid1()
1432 m = mmap.mmap(-1, 1, tagname)
1433 m[0] = 0
Brian Curtineb24d742010-04-12 17:16:38 +00001434 # Run a script which has console control handling enabled.
1435 proc = subprocess.Popen([sys.executable,
1436 os.path.join(os.path.dirname(__file__),
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001437 "win_console_handler.py"), tagname],
Brian Curtineb24d742010-04-12 17:16:38 +00001438 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
1439 # Let the interpreter startup before we send signals. See #3137.
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001440 count, max = 0, 100
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001441 while count < max and proc.poll() is None:
Brian Curtinf668df52010-10-15 14:21:06 +00001442 if m[0] == 1:
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001443 break
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001444 time.sleep(0.1)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001445 count += 1
1446 else:
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001447 # Forcefully kill the process if we weren't able to signal it.
1448 os.kill(proc.pid, signal.SIGINT)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001449 self.fail("Subprocess didn't finish initialization")
Brian Curtineb24d742010-04-12 17:16:38 +00001450 os.kill(proc.pid, event)
1451 # proc.send_signal(event) could also be done here.
1452 # Allow time for the signal to be passed and the process to exit.
1453 time.sleep(0.5)
1454 if not proc.poll():
1455 # Forcefully kill the process if we weren't able to signal it.
1456 os.kill(proc.pid, signal.SIGINT)
1457 self.fail("subprocess did not stop on {}".format(name))
1458
1459 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
1460 def test_CTRL_C_EVENT(self):
1461 from ctypes import wintypes
1462 import ctypes
1463
1464 # Make a NULL value by creating a pointer with no argument.
1465 NULL = ctypes.POINTER(ctypes.c_int)()
1466 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
1467 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
1468 wintypes.BOOL)
1469 SetConsoleCtrlHandler.restype = wintypes.BOOL
1470
1471 # Calling this with NULL and FALSE causes the calling process to
1472 # handle CTRL+C, rather than ignore it. This property is inherited
1473 # by subprocesses.
1474 SetConsoleCtrlHandler(NULL, 0)
1475
1476 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
1477
1478 def test_CTRL_BREAK_EVENT(self):
1479 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
1480
1481
Brian Curtind40e6f72010-07-08 21:39:08 +00001482@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Brian Curtin3b4499c2010-12-28 14:31:47 +00001483@support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +00001484class Win32SymlinkTests(unittest.TestCase):
1485 filelink = 'filelinktest'
1486 filelink_target = os.path.abspath(__file__)
1487 dirlink = 'dirlinktest'
1488 dirlink_target = os.path.dirname(filelink_target)
1489 missing_link = 'missing link'
1490
1491 def setUp(self):
1492 assert os.path.exists(self.dirlink_target)
1493 assert os.path.exists(self.filelink_target)
1494 assert not os.path.exists(self.dirlink)
1495 assert not os.path.exists(self.filelink)
1496 assert not os.path.exists(self.missing_link)
1497
1498 def tearDown(self):
1499 if os.path.exists(self.filelink):
1500 os.remove(self.filelink)
1501 if os.path.exists(self.dirlink):
1502 os.rmdir(self.dirlink)
1503 if os.path.lexists(self.missing_link):
1504 os.remove(self.missing_link)
1505
1506 def test_directory_link(self):
Antoine Pitrou5311c1d2012-01-24 08:59:28 +01001507 os.symlink(self.dirlink_target, self.dirlink, True)
Brian Curtind40e6f72010-07-08 21:39:08 +00001508 self.assertTrue(os.path.exists(self.dirlink))
1509 self.assertTrue(os.path.isdir(self.dirlink))
1510 self.assertTrue(os.path.islink(self.dirlink))
1511 self.check_stat(self.dirlink, self.dirlink_target)
1512
1513 def test_file_link(self):
1514 os.symlink(self.filelink_target, self.filelink)
1515 self.assertTrue(os.path.exists(self.filelink))
1516 self.assertTrue(os.path.isfile(self.filelink))
1517 self.assertTrue(os.path.islink(self.filelink))
1518 self.check_stat(self.filelink, self.filelink_target)
1519
1520 def _create_missing_dir_link(self):
1521 'Create a "directory" link to a non-existent target'
1522 linkname = self.missing_link
1523 if os.path.lexists(linkname):
1524 os.remove(linkname)
1525 target = r'c:\\target does not exist.29r3c740'
1526 assert not os.path.exists(target)
1527 target_is_dir = True
1528 os.symlink(target, linkname, target_is_dir)
1529
1530 def test_remove_directory_link_to_missing_target(self):
1531 self._create_missing_dir_link()
1532 # For compatibility with Unix, os.remove will check the
1533 # directory status and call RemoveDirectory if the symlink
1534 # was created with target_is_dir==True.
1535 os.remove(self.missing_link)
1536
1537 @unittest.skip("currently fails; consider for improvement")
1538 def test_isdir_on_directory_link_to_missing_target(self):
1539 self._create_missing_dir_link()
1540 # consider having isdir return true for directory links
1541 self.assertTrue(os.path.isdir(self.missing_link))
1542
1543 @unittest.skip("currently fails; consider for improvement")
1544 def test_rmdir_on_directory_link_to_missing_target(self):
1545 self._create_missing_dir_link()
1546 # consider allowing rmdir to remove directory links
1547 os.rmdir(self.missing_link)
1548
1549 def check_stat(self, link, target):
1550 self.assertEqual(os.stat(link), os.stat(target))
1551 self.assertNotEqual(os.lstat(link), os.stat(link))
1552
Brian Curtind25aef52011-06-13 15:16:04 -05001553 bytes_link = os.fsencode(link)
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001554 with warnings.catch_warnings():
1555 warnings.simplefilter("ignore", DeprecationWarning)
1556 self.assertEqual(os.stat(bytes_link), os.stat(target))
1557 self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link))
Brian Curtind25aef52011-06-13 15:16:04 -05001558
1559 def test_12084(self):
1560 level1 = os.path.abspath(support.TESTFN)
1561 level2 = os.path.join(level1, "level2")
1562 level3 = os.path.join(level2, "level3")
1563 try:
1564 os.mkdir(level1)
1565 os.mkdir(level2)
1566 os.mkdir(level3)
1567
1568 file1 = os.path.abspath(os.path.join(level1, "file1"))
1569
1570 with open(file1, "w") as f:
1571 f.write("file1")
1572
1573 orig_dir = os.getcwd()
1574 try:
1575 os.chdir(level2)
1576 link = os.path.join(level2, "link")
1577 os.symlink(os.path.relpath(file1), "link")
1578 self.assertIn("link", os.listdir(os.getcwd()))
1579
1580 # Check os.stat calls from the same dir as the link
1581 self.assertEqual(os.stat(file1), os.stat("link"))
1582
1583 # Check os.stat calls from a dir below the link
1584 os.chdir(level1)
1585 self.assertEqual(os.stat(file1),
1586 os.stat(os.path.relpath(link)))
1587
1588 # Check os.stat calls from a dir above the link
1589 os.chdir(level3)
1590 self.assertEqual(os.stat(file1),
1591 os.stat(os.path.relpath(link)))
1592 finally:
1593 os.chdir(orig_dir)
1594 except OSError as err:
1595 self.fail(err)
1596 finally:
1597 os.remove(file1)
1598 shutil.rmtree(level1)
1599
Brian Curtind40e6f72010-07-08 21:39:08 +00001600
Victor Stinnere8d51452010-08-19 01:05:19 +00001601class FSEncodingTests(unittest.TestCase):
1602 def test_nop(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001603 self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
1604 self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
Benjamin Peterson31191a92010-05-09 03:22:58 +00001605
Victor Stinnere8d51452010-08-19 01:05:19 +00001606 def test_identity(self):
1607 # assert fsdecode(fsencode(x)) == x
1608 for fn in ('unicode\u0141', 'latin\xe9', 'ascii'):
1609 try:
1610 bytesfn = os.fsencode(fn)
1611 except UnicodeEncodeError:
1612 continue
Ezio Melottib3aedd42010-11-20 19:04:17 +00001613 self.assertEqual(os.fsdecode(bytesfn), fn)
Victor Stinnere8d51452010-08-19 01:05:19 +00001614
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00001615
Brett Cannonefb00c02012-02-29 18:31:31 -05001616
1617class DeviceEncodingTests(unittest.TestCase):
1618
1619 def test_bad_fd(self):
1620 # Return None when an fd doesn't actually exist.
1621 self.assertIsNone(os.device_encoding(123456))
1622
Philip Jenveye308b7c2012-02-29 16:16:15 -08001623 @unittest.skipUnless(os.isatty(0) and (sys.platform.startswith('win') or
1624 (hasattr(locale, 'nl_langinfo') and hasattr(locale, 'CODESET'))),
Philip Jenveyd7aff2d2012-02-29 16:21:25 -08001625 'test requires a tty and either Windows or nl_langinfo(CODESET)')
Brett Cannonefb00c02012-02-29 18:31:31 -05001626 def test_device_encoding(self):
1627 encoding = os.device_encoding(0)
1628 self.assertIsNotNone(encoding)
1629 self.assertTrue(codecs.lookup(encoding))
1630
1631
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00001632class PidTests(unittest.TestCase):
1633 @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid")
1634 def test_getppid(self):
1635 p = subprocess.Popen([sys.executable, '-c',
1636 'import os; print(os.getppid())'],
1637 stdout=subprocess.PIPE)
1638 stdout, _ = p.communicate()
1639 # We are the parent of our subprocess
1640 self.assertEqual(int(stdout), os.getpid())
1641
1642
Brian Curtin0151b8e2010-09-24 13:43:43 +00001643# The introduction of this TestCase caused at least two different errors on
1644# *nix buildbots. Temporarily skip this to let the buildbots move along.
1645@unittest.skip("Skip due to platform/environment differences on *NIX buildbots")
Brian Curtine8e4b3b2010-09-23 20:04:14 +00001646@unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin")
1647class LoginTests(unittest.TestCase):
1648 def test_getlogin(self):
1649 user_name = os.getlogin()
1650 self.assertNotEqual(len(user_name), 0)
1651
1652
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001653@unittest.skipUnless(hasattr(os, 'getpriority') and hasattr(os, 'setpriority'),
1654 "needs os.getpriority and os.setpriority")
1655class ProgramPriorityTests(unittest.TestCase):
1656 """Tests for os.getpriority() and os.setpriority()."""
1657
1658 def test_set_get_priority(self):
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001659
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001660 base = os.getpriority(os.PRIO_PROCESS, os.getpid())
1661 os.setpriority(os.PRIO_PROCESS, os.getpid(), base + 1)
1662 try:
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001663 new_prio = os.getpriority(os.PRIO_PROCESS, os.getpid())
1664 if base >= 19 and new_prio <= 19:
1665 raise unittest.SkipTest(
1666 "unable to reliably test setpriority at current nice level of %s" % base)
1667 else:
1668 self.assertEqual(new_prio, base + 1)
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001669 finally:
1670 try:
1671 os.setpriority(os.PRIO_PROCESS, os.getpid(), base)
1672 except OSError as err:
Antoine Pitrou692f0382011-02-26 00:22:25 +00001673 if err.errno != errno.EACCES:
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001674 raise
1675
1676
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001677if threading is not None:
1678 class SendfileTestServer(asyncore.dispatcher, threading.Thread):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001679
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001680 class Handler(asynchat.async_chat):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001681
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001682 def __init__(self, conn):
1683 asynchat.async_chat.__init__(self, conn)
1684 self.in_buffer = []
1685 self.closed = False
1686 self.push(b"220 ready\r\n")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001687
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001688 def handle_read(self):
1689 data = self.recv(4096)
1690 self.in_buffer.append(data)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001691
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001692 def get_data(self):
1693 return b''.join(self.in_buffer)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001694
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001695 def handle_close(self):
1696 self.close()
1697 self.closed = True
1698
1699 def handle_error(self):
1700 raise
1701
1702 def __init__(self, address):
1703 threading.Thread.__init__(self)
1704 asyncore.dispatcher.__init__(self)
1705 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
1706 self.bind(address)
1707 self.listen(5)
1708 self.host, self.port = self.socket.getsockname()[:2]
1709 self.handler_instance = None
1710 self._active = False
1711 self._active_lock = threading.Lock()
1712
1713 # --- public API
1714
1715 @property
1716 def running(self):
1717 return self._active
1718
1719 def start(self):
1720 assert not self.running
1721 self.__flag = threading.Event()
1722 threading.Thread.start(self)
1723 self.__flag.wait()
1724
1725 def stop(self):
1726 assert self.running
1727 self._active = False
1728 self.join()
1729
1730 def wait(self):
1731 # wait for handler connection to be closed, then stop the server
1732 while not getattr(self.handler_instance, "closed", False):
1733 time.sleep(0.001)
1734 self.stop()
1735
1736 # --- internals
1737
1738 def run(self):
1739 self._active = True
1740 self.__flag.set()
1741 while self._active and asyncore.socket_map:
1742 self._active_lock.acquire()
1743 asyncore.loop(timeout=0.001, count=1)
1744 self._active_lock.release()
1745 asyncore.close_all()
1746
1747 def handle_accept(self):
1748 conn, addr = self.accept()
1749 self.handler_instance = self.Handler(conn)
1750
1751 def handle_connect(self):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001752 self.close()
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001753 handle_read = handle_connect
1754
1755 def writable(self):
1756 return 0
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001757
1758 def handle_error(self):
1759 raise
1760
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001761
Giampaolo Rodolà46134642011-02-25 20:01:05 +00001762@unittest.skipUnless(threading is not None, "test needs threading module")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001763@unittest.skipUnless(hasattr(os, 'sendfile'), "test needs os.sendfile()")
1764class TestSendfile(unittest.TestCase):
1765
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001766 DATA = b"12345abcde" * 16 * 1024 # 160 KB
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001767 SUPPORT_HEADERS_TRAILERS = not sys.platform.startswith("linux") and \
Giampaolo Rodolà4bc68572011-02-25 21:46:01 +00001768 not sys.platform.startswith("solaris") and \
1769 not sys.platform.startswith("sunos")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001770
1771 @classmethod
1772 def setUpClass(cls):
1773 with open(support.TESTFN, "wb") as f:
1774 f.write(cls.DATA)
1775
1776 @classmethod
1777 def tearDownClass(cls):
1778 support.unlink(support.TESTFN)
1779
1780 def setUp(self):
1781 self.server = SendfileTestServer((support.HOST, 0))
1782 self.server.start()
1783 self.client = socket.socket()
1784 self.client.connect((self.server.host, self.server.port))
1785 self.client.settimeout(1)
1786 # synchronize by waiting for "220 ready" response
1787 self.client.recv(1024)
1788 self.sockno = self.client.fileno()
1789 self.file = open(support.TESTFN, 'rb')
1790 self.fileno = self.file.fileno()
1791
1792 def tearDown(self):
1793 self.file.close()
1794 self.client.close()
1795 if self.server.running:
1796 self.server.stop()
1797
1798 def sendfile_wrapper(self, sock, file, offset, nbytes, headers=[], trailers=[]):
1799 """A higher level wrapper representing how an application is
1800 supposed to use sendfile().
1801 """
1802 while 1:
1803 try:
1804 if self.SUPPORT_HEADERS_TRAILERS:
1805 return os.sendfile(sock, file, offset, nbytes, headers,
1806 trailers)
1807 else:
1808 return os.sendfile(sock, file, offset, nbytes)
1809 except OSError as err:
1810 if err.errno == errno.ECONNRESET:
1811 # disconnected
1812 raise
1813 elif err.errno in (errno.EAGAIN, errno.EBUSY):
1814 # we have to retry send data
1815 continue
1816 else:
1817 raise
1818
1819 def test_send_whole_file(self):
1820 # normal send
1821 total_sent = 0
1822 offset = 0
1823 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001824 while total_sent < len(self.DATA):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001825 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
1826 if sent == 0:
1827 break
1828 offset += sent
1829 total_sent += sent
1830 self.assertTrue(sent <= nbytes)
1831 self.assertEqual(offset, total_sent)
1832
1833 self.assertEqual(total_sent, len(self.DATA))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001834 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001835 self.client.close()
1836 self.server.wait()
1837 data = self.server.handler_instance.get_data()
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001838 self.assertEqual(len(data), len(self.DATA))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001839 self.assertEqual(data, self.DATA)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001840
1841 def test_send_at_certain_offset(self):
1842 # start sending a file at a certain offset
1843 total_sent = 0
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001844 offset = len(self.DATA) // 2
1845 must_send = len(self.DATA) - offset
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001846 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001847 while total_sent < must_send:
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001848 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
1849 if sent == 0:
1850 break
1851 offset += sent
1852 total_sent += sent
1853 self.assertTrue(sent <= nbytes)
1854
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001855 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001856 self.client.close()
1857 self.server.wait()
1858 data = self.server.handler_instance.get_data()
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001859 expected = self.DATA[len(self.DATA) // 2:]
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001860 self.assertEqual(total_sent, len(expected))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001861 self.assertEqual(len(data), len(expected))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001862 self.assertEqual(data, expected)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001863
1864 def test_offset_overflow(self):
1865 # specify an offset > file size
1866 offset = len(self.DATA) + 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001867 try:
1868 sent = os.sendfile(self.sockno, self.fileno, offset, 4096)
1869 except OSError as e:
1870 # Solaris can raise EINVAL if offset >= file length, ignore.
1871 if e.errno != errno.EINVAL:
1872 raise
1873 else:
1874 self.assertEqual(sent, 0)
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001875 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001876 self.client.close()
1877 self.server.wait()
1878 data = self.server.handler_instance.get_data()
1879 self.assertEqual(data, b'')
1880
1881 def test_invalid_offset(self):
1882 with self.assertRaises(OSError) as cm:
1883 os.sendfile(self.sockno, self.fileno, -1, 4096)
1884 self.assertEqual(cm.exception.errno, errno.EINVAL)
1885
1886 # --- headers / trailers tests
1887
1888 if SUPPORT_HEADERS_TRAILERS:
1889
1890 def test_headers(self):
1891 total_sent = 0
1892 sent = os.sendfile(self.sockno, self.fileno, 0, 4096,
1893 headers=[b"x" * 512])
1894 total_sent += sent
1895 offset = 4096
1896 nbytes = 4096
1897 while 1:
1898 sent = self.sendfile_wrapper(self.sockno, self.fileno,
1899 offset, nbytes)
1900 if sent == 0:
1901 break
1902 total_sent += sent
1903 offset += sent
1904
1905 expected_data = b"x" * 512 + self.DATA
1906 self.assertEqual(total_sent, len(expected_data))
1907 self.client.close()
1908 self.server.wait()
1909 data = self.server.handler_instance.get_data()
1910 self.assertEqual(hash(data), hash(expected_data))
1911
1912 def test_trailers(self):
1913 TESTFN2 = support.TESTFN + "2"
Brett Cannonb6376802011-03-15 17:38:22 -04001914 with open(TESTFN2, 'wb') as f:
1915 f.write(b"abcde")
1916 with open(TESTFN2, 'rb')as f:
1917 self.addCleanup(os.remove, TESTFN2)
1918 os.sendfile(self.sockno, f.fileno(), 0, 4096,
1919 trailers=[b"12345"])
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001920 self.client.close()
1921 self.server.wait()
1922 data = self.server.handler_instance.get_data()
1923 self.assertEqual(data, b"abcde12345")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001924
1925 if hasattr(os, "SF_NODISKIO"):
1926 def test_flags(self):
1927 try:
1928 os.sendfile(self.sockno, self.fileno, 0, 4096,
1929 flags=os.SF_NODISKIO)
1930 except OSError as err:
1931 if err.errno not in (errno.EBUSY, errno.EAGAIN):
1932 raise
1933
1934
Larry Hastings9cf065c2012-06-22 16:30:09 -07001935def supports_extended_attributes():
1936 if not hasattr(os, "setxattr"):
1937 return False
1938 try:
1939 with open(support.TESTFN, "wb") as fp:
1940 try:
1941 os.setxattr(fp.fileno(), b"user.test", b"")
1942 except OSError:
1943 return False
1944 finally:
1945 support.unlink(support.TESTFN)
1946 # Kernels < 2.6.39 don't respect setxattr flags.
1947 kernel_version = platform.release()
1948 m = re.match("2.6.(\d{1,2})", kernel_version)
1949 return m is None or int(m.group(1)) >= 39
1950
1951
1952@unittest.skipUnless(supports_extended_attributes(),
1953 "no non-broken extended attribute support")
Benjamin Peterson799bd802011-08-31 22:15:17 -04001954class ExtendedAttributeTests(unittest.TestCase):
1955
1956 def tearDown(self):
1957 support.unlink(support.TESTFN)
1958
Larry Hastings9cf065c2012-06-22 16:30:09 -07001959 def _check_xattrs_str(self, s, getxattr, setxattr, removexattr, listxattr, **kwargs):
Benjamin Peterson799bd802011-08-31 22:15:17 -04001960 fn = support.TESTFN
1961 open(fn, "wb").close()
1962 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001963 getxattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001964 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02001965 init_xattr = listxattr(fn)
1966 self.assertIsInstance(init_xattr, list)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001967 setxattr(fn, s("user.test"), b"", **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02001968 xattr = set(init_xattr)
1969 xattr.add("user.test")
1970 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001971 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"")
1972 setxattr(fn, s("user.test"), b"hello", os.XATTR_REPLACE, **kwargs)
1973 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"hello")
Benjamin Peterson799bd802011-08-31 22:15:17 -04001974 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001975 setxattr(fn, s("user.test"), b"bye", os.XATTR_CREATE, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001976 self.assertEqual(cm.exception.errno, errno.EEXIST)
1977 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001978 setxattr(fn, s("user.test2"), b"bye", os.XATTR_REPLACE, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001979 self.assertEqual(cm.exception.errno, errno.ENODATA)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001980 setxattr(fn, s("user.test2"), b"foo", os.XATTR_CREATE, **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02001981 xattr.add("user.test2")
1982 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001983 removexattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001984 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001985 getxattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001986 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02001987 xattr.remove("user.test")
1988 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001989 self.assertEqual(getxattr(fn, s("user.test2"), **kwargs), b"foo")
1990 setxattr(fn, s("user.test"), b"a"*1024, **kwargs)
1991 self.assertEqual(getxattr(fn, s("user.test"), **kwargs), b"a"*1024)
1992 removexattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001993 many = sorted("user.test{}".format(i) for i in range(100))
1994 for thing in many:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001995 setxattr(fn, thing, b"x", **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02001996 self.assertEqual(set(listxattr(fn)), set(init_xattr) | set(many))
Benjamin Peterson799bd802011-08-31 22:15:17 -04001997
Larry Hastings9cf065c2012-06-22 16:30:09 -07001998 def _check_xattrs(self, *args, **kwargs):
Benjamin Peterson799bd802011-08-31 22:15:17 -04001999 def make_bytes(s):
2000 return bytes(s, "ascii")
Larry Hastings9cf065c2012-06-22 16:30:09 -07002001 self._check_xattrs_str(str, *args, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002002 support.unlink(support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002003 self._check_xattrs_str(make_bytes, *args, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002004
2005 def test_simple(self):
2006 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
2007 os.listxattr)
2008
2009 def test_lpath(self):
Larry Hastings9cf065c2012-06-22 16:30:09 -07002010 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
2011 os.listxattr, follow_symlinks=False)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002012
2013 def test_fds(self):
2014 def getxattr(path, *args):
2015 with open(path, "rb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002016 return os.getxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002017 def setxattr(path, *args):
2018 with open(path, "wb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002019 os.setxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002020 def removexattr(path, *args):
2021 with open(path, "wb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002022 os.removexattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002023 def listxattr(path, *args):
2024 with open(path, "rb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002025 return os.listxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002026 self._check_xattrs(getxattr, setxattr, removexattr, listxattr)
2027
2028
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002029@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
2030class Win32DeprecatedBytesAPI(unittest.TestCase):
2031 def test_deprecated(self):
2032 import nt
2033 filename = os.fsencode(support.TESTFN)
2034 with warnings.catch_warnings():
2035 warnings.simplefilter("error", DeprecationWarning)
2036 for func, *args in (
2037 (nt._getfullpathname, filename),
2038 (nt._isdir, filename),
2039 (os.access, filename, os.R_OK),
2040 (os.chdir, filename),
2041 (os.chmod, filename, 0o777),
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01002042 (os.getcwdb,),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002043 (os.link, filename, filename),
2044 (os.listdir, filename),
2045 (os.lstat, filename),
2046 (os.mkdir, filename),
2047 (os.open, filename, os.O_RDONLY),
2048 (os.rename, filename, filename),
2049 (os.rmdir, filename),
2050 (os.startfile, filename),
2051 (os.stat, filename),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002052 (os.unlink, filename),
2053 (os.utime, filename),
2054 ):
2055 self.assertRaises(DeprecationWarning, func, *args)
2056
Victor Stinner28216442011-11-16 00:34:44 +01002057 @support.skip_unless_symlink
2058 def test_symlink(self):
2059 filename = os.fsencode(support.TESTFN)
2060 with warnings.catch_warnings():
2061 warnings.simplefilter("error", DeprecationWarning)
2062 self.assertRaises(DeprecationWarning,
2063 os.symlink, filename, filename)
2064
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002065
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002066@unittest.skipUnless(hasattr(os, 'get_terminal_size'), "requires os.get_terminal_size")
2067class TermsizeTests(unittest.TestCase):
2068 def test_does_not_crash(self):
2069 """Check if get_terminal_size() returns a meaningful value.
2070
2071 There's no easy portable way to actually check the size of the
2072 terminal, so let's check if it returns something sensible instead.
2073 """
2074 try:
2075 size = os.get_terminal_size()
2076 except OSError as e:
Antoine Pitrou81a1fa52012-02-09 00:11:00 +01002077 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002078 # Under win32 a generic OSError can be thrown if the
2079 # handle cannot be retrieved
2080 self.skipTest("failed to query terminal size")
2081 raise
2082
Antoine Pitroucfade362012-02-08 23:48:59 +01002083 self.assertGreaterEqual(size.columns, 0)
2084 self.assertGreaterEqual(size.lines, 0)
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002085
2086 def test_stty_match(self):
2087 """Check if stty returns the same results
2088
2089 stty actually tests stdin, so get_terminal_size is invoked on
2090 stdin explicitly. If stty succeeded, then get_terminal_size()
2091 should work too.
2092 """
2093 try:
2094 size = subprocess.check_output(['stty', 'size']).decode().split()
2095 except (FileNotFoundError, subprocess.CalledProcessError):
2096 self.skipTest("stty invocation failed")
2097 expected = (int(size[1]), int(size[0])) # reversed order
2098
Antoine Pitrou81a1fa52012-02-09 00:11:00 +01002099 try:
2100 actual = os.get_terminal_size(sys.__stdin__.fileno())
2101 except OSError as e:
2102 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
2103 # Under win32 a generic OSError can be thrown if the
2104 # handle cannot be retrieved
2105 self.skipTest("failed to query terminal size")
2106 raise
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002107 self.assertEqual(expected, actual)
2108
2109
Antoine Pitrouf26ad712011-07-15 23:00:56 +02002110@support.reap_threads
Fred Drake2e2be372001-09-20 21:33:42 +00002111def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002112 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002113 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002114 StatAttributeTests,
2115 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00002116 WalkTests,
Charles-François Natali7372b062012-02-05 15:15:38 +01002117 FwalkTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00002118 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +00002119 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002120 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +00002121 ExecTests,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00002122 Win32ErrorTests,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002123 TestInvalidFD,
Martin v. Löwis011e8422009-05-05 04:43:17 +00002124 PosixUidGidTests,
Brian Curtineb24d742010-04-12 17:16:38 +00002125 Pep383Tests,
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00002126 Win32KillTests,
Brian Curtind40e6f72010-07-08 21:39:08 +00002127 Win32SymlinkTests,
Victor Stinnere8d51452010-08-19 01:05:19 +00002128 FSEncodingTests,
Brett Cannonefb00c02012-02-29 18:31:31 -05002129 DeviceEncodingTests,
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00002130 PidTests,
Brian Curtine8e4b3b2010-09-23 20:04:14 +00002131 LoginTests,
Brian Curtin1b9df392010-11-24 20:24:31 +00002132 LinkTests,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002133 TestSendfile,
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00002134 ProgramPriorityTests,
Benjamin Peterson799bd802011-08-31 22:15:17 -04002135 ExtendedAttributeTests,
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002136 Win32DeprecatedBytesAPI,
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002137 TermsizeTests,
Andrew Svetlov405faed2012-12-25 12:18:09 +02002138 RemoveDirsTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002139 )
Fred Drake2e2be372001-09-20 21:33:42 +00002140
2141if __name__ == "__main__":
2142 test_main()