blob: d2424d786559e072a62d52eefba59d5724699b5c [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
Antoine Pitrouec34ab52013-08-16 20:44:38 +020031try:
32 import resource
33except ImportError:
34 resource = None
35
Georg Brandl2daf6ae2012-02-20 19:54:16 +010036from test.script_helper import assert_python_ok
Fred Drake38c2ef02001-07-17 20:52:51 +000037
Victor Stinner034d0aa2012-06-05 01:22:15 +020038with warnings.catch_warnings():
39 warnings.simplefilter("ignore", DeprecationWarning)
40 os.stat_float_times(True)
Victor Stinner1aa54a42012-02-08 04:09:37 +010041st = os.stat(__file__)
42stat_supports_subsecond = (
43 # check if float and int timestamps are different
44 (st.st_atime != st[7])
45 or (st.st_mtime != st[8])
46 or (st.st_ctime != st[9]))
47
Mark Dickinson7cf03892010-04-16 13:45:35 +000048# Detect whether we're on a Linux system that uses the (now outdated
49# and unmaintained) linuxthreads threading library. There's an issue
50# when combining linuxthreads with a failed execv call: see
51# http://bugs.python.org/issue4970.
Victor Stinnerd5c355c2011-04-30 14:53:09 +020052if hasattr(sys, 'thread_info') and sys.thread_info.version:
53 USING_LINUXTHREADS = sys.thread_info.version.startswith("linuxthreads")
54else:
55 USING_LINUXTHREADS = False
Brian Curtineb24d742010-04-12 17:16:38 +000056
Stefan Krahebee49a2013-01-17 15:31:00 +010057# Issue #14110: Some tests fail on FreeBSD if the user is in the wheel group.
58HAVE_WHEEL_GROUP = sys.platform.startswith('freebsd') and os.getgid() == 0
59
Thomas Wouters0e3f5912006-08-11 14:57:12 +000060# Tests creating TESTFN
61class FileTests(unittest.TestCase):
62 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000063 if os.path.exists(support.TESTFN):
64 os.unlink(support.TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000065 tearDown = setUp
66
67 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000068 f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000069 os.close(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000070 self.assertTrue(os.access(support.TESTFN, os.W_OK))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000071
Christian Heimesfdab48e2008-01-20 09:06:41 +000072 def test_closerange(self):
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000073 first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
74 # We must allocate two consecutive file descriptors, otherwise
75 # it will mess up other file descriptors (perhaps even the three
76 # standard ones).
77 second = os.dup(first)
78 try:
79 retries = 0
80 while second != first + 1:
81 os.close(first)
82 retries += 1
83 if retries > 10:
84 # XXX test skipped
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000085 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000086 first, second = second, os.dup(second)
87 finally:
88 os.close(second)
Christian Heimesfdab48e2008-01-20 09:06:41 +000089 # close a fd that is open, and one that isn't
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000090 os.closerange(first, first + 2)
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000091 self.assertRaises(OSError, os.write, first, b"a")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000092
Benjamin Peterson1cc6df92010-06-30 17:39:45 +000093 @support.cpython_only
Hirokazu Yamamoto4c19e6e2008-09-08 23:41:21 +000094 def test_rename(self):
95 path = support.TESTFN
96 old = sys.getrefcount(path)
97 self.assertRaises(TypeError, os.rename, path, 0)
98 new = sys.getrefcount(path)
99 self.assertEqual(old, new)
100
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000101 def test_read(self):
102 with open(support.TESTFN, "w+b") as fobj:
103 fobj.write(b"spam")
104 fobj.flush()
105 fd = fobj.fileno()
106 os.lseek(fd, 0, 0)
107 s = os.read(fd, 4)
108 self.assertEqual(type(s), bytes)
109 self.assertEqual(s, b"spam")
110
111 def test_write(self):
112 # os.write() accepts bytes- and buffer-like objects but not strings
113 fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY)
114 self.assertRaises(TypeError, os.write, fd, "beans")
115 os.write(fd, b"bacon\n")
116 os.write(fd, bytearray(b"eggs\n"))
117 os.write(fd, memoryview(b"spam\n"))
118 os.close(fd)
119 with open(support.TESTFN, "rb") as fobj:
Antoine Pitroud62269f2008-09-15 23:54:52 +0000120 self.assertEqual(fobj.read().splitlines(),
121 [b"bacon", b"eggs", b"spam"])
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000122
Victor Stinnere0daff12011-03-20 23:36:35 +0100123 def write_windows_console(self, *args):
124 retcode = subprocess.call(args,
125 # use a new console to not flood the test output
126 creationflags=subprocess.CREATE_NEW_CONSOLE,
127 # use a shell to hide the console window (SW_HIDE)
128 shell=True)
129 self.assertEqual(retcode, 0)
130
131 @unittest.skipUnless(sys.platform == 'win32',
132 'test specific to the Windows console')
133 def test_write_windows_console(self):
134 # Issue #11395: the Windows console returns an error (12: not enough
135 # space error) on writing into stdout if stdout mode is binary and the
136 # length is greater than 66,000 bytes (or less, depending on heap
137 # usage).
138 code = "print('x' * 100000)"
139 self.write_windows_console(sys.executable, "-c", code)
140 self.write_windows_console(sys.executable, "-u", "-c", code)
141
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000142 def fdopen_helper(self, *args):
143 fd = os.open(support.TESTFN, os.O_RDONLY)
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200144 f = os.fdopen(fd, *args)
145 f.close()
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000146
147 def test_fdopen(self):
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200148 fd = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
149 os.close(fd)
150
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000151 self.fdopen_helper()
152 self.fdopen_helper('r')
153 self.fdopen_helper('r', 100)
154
Antoine Pitrouf3b2d882012-01-30 22:08:52 +0100155 def test_replace(self):
156 TESTFN2 = support.TESTFN + ".2"
157 with open(support.TESTFN, 'w') as f:
158 f.write("1")
159 with open(TESTFN2, 'w') as f:
160 f.write("2")
161 self.addCleanup(os.unlink, TESTFN2)
162 os.replace(support.TESTFN, TESTFN2)
163 self.assertRaises(FileNotFoundError, os.stat, support.TESTFN)
164 with open(TESTFN2, 'r') as f:
165 self.assertEqual(f.read(), "1")
166
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200167
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000168# Test attributes on return values from os.*stat* family.
169class StatAttributeTests(unittest.TestCase):
170 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000171 os.mkdir(support.TESTFN)
172 self.fname = os.path.join(support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000173 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +0000174 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000175 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000176
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000177 def tearDown(self):
178 os.unlink(self.fname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000179 os.rmdir(support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000180
Antoine Pitrou38425292010-09-21 18:19:07 +0000181 def check_stat_attributes(self, fname):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000182 if not hasattr(os, "stat"):
183 return
184
Antoine Pitrou38425292010-09-21 18:19:07 +0000185 result = os.stat(fname)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000186
187 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000188 self.assertEqual(result[stat.ST_SIZE], 3)
189 self.assertEqual(result.st_size, 3)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000190
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000191 # Make sure all the attributes are there
192 members = dir(result)
193 for name in dir(stat):
194 if name[:3] == 'ST_':
195 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000196 if name.endswith("TIME"):
197 def trunc(x): return int(x)
198 else:
199 def trunc(x): return x
Ezio Melottib3aedd42010-11-20 19:04:17 +0000200 self.assertEqual(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000201 result[getattr(stat, name)])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000202 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000203
Larry Hastings6fe20b32012-04-19 15:07:49 -0700204 # Make sure that the st_?time and st_?time_ns fields roughly agree
Larry Hastings76ad59b2012-05-03 00:30:07 -0700205 # (they should always agree up to around tens-of-microseconds)
Larry Hastings6fe20b32012-04-19 15:07:49 -0700206 for name in 'st_atime st_mtime st_ctime'.split():
207 floaty = int(getattr(result, name) * 100000)
208 nanosecondy = getattr(result, name + "_ns") // 10000
Larry Hastings76ad59b2012-05-03 00:30:07 -0700209 self.assertAlmostEqual(floaty, nanosecondy, delta=2)
Larry Hastings6fe20b32012-04-19 15:07:49 -0700210
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000211 try:
212 result[200]
Andrew Svetlov737fb892012-12-18 21:14:22 +0200213 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000214 except IndexError:
215 pass
216
217 # Make sure that assignment fails
218 try:
219 result.st_mode = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200220 self.fail("No exception raised")
Collin Winter42dae6a2007-03-28 21:44:53 +0000221 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000222 pass
223
224 try:
225 result.st_rdev = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200226 self.fail("No exception raised")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000227 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000228 pass
229
230 try:
231 result.parrot = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200232 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000233 except AttributeError:
234 pass
235
236 # Use the stat_result constructor with a too-short tuple.
237 try:
238 result2 = os.stat_result((10,))
Andrew Svetlov737fb892012-12-18 21:14:22 +0200239 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000240 except TypeError:
241 pass
242
Ezio Melotti42da6632011-03-15 05:18:48 +0200243 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000244 try:
245 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
246 except TypeError:
247 pass
248
Antoine Pitrou38425292010-09-21 18:19:07 +0000249 def test_stat_attributes(self):
250 self.check_stat_attributes(self.fname)
251
252 def test_stat_attributes_bytes(self):
253 try:
254 fname = self.fname.encode(sys.getfilesystemencoding())
255 except UnicodeEncodeError:
256 self.skipTest("cannot encode %a for the filesystem" % self.fname)
Victor Stinner1ab6c2d2011-11-15 22:27:41 +0100257 with warnings.catch_warnings():
258 warnings.simplefilter("ignore", DeprecationWarning)
259 self.check_stat_attributes(fname)
Tim Peterse0c446b2001-10-18 21:57:37 +0000260
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000261 def test_statvfs_attributes(self):
262 if not hasattr(os, "statvfs"):
263 return
264
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000265 try:
266 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000267 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000268 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000269 if e.errno == errno.ENOSYS:
270 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000271
272 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000273 self.assertEqual(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000274
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000275 # Make sure all the attributes are there.
276 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
277 'ffree', 'favail', 'flag', 'namemax')
278 for value, member in enumerate(members):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000279 self.assertEqual(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000280
281 # Make sure that assignment really fails
282 try:
283 result.f_bfree = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200284 self.fail("No exception raised")
Collin Winter42dae6a2007-03-28 21:44:53 +0000285 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000286 pass
287
288 try:
289 result.parrot = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200290 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000291 except AttributeError:
292 pass
293
294 # Use the constructor with a too-short tuple.
295 try:
296 result2 = os.statvfs_result((10,))
Andrew Svetlov737fb892012-12-18 21:14:22 +0200297 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000298 except TypeError:
299 pass
300
Ezio Melotti42da6632011-03-15 05:18:48 +0200301 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000302 try:
303 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
304 except TypeError:
305 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000306
Thomas Wouters89f507f2006-12-13 04:49:30 +0000307 def test_utime_dir(self):
308 delta = 1000000
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000309 st = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000310 # round to int, because some systems may support sub-second
311 # time stamps in stat, but not in utime.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000312 os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
313 st2 = os.stat(support.TESTFN)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000314 self.assertEqual(st2.st_mtime, int(st.st_mtime-delta))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000315
Larry Hastings76ad59b2012-05-03 00:30:07 -0700316 def _test_utime(self, filename, attr, utime, delta):
Brian Curtin0277aa32011-11-06 13:50:15 -0600317 # Issue #13327 removed the requirement to pass None as the
Brian Curtin52fbea12011-11-06 13:41:17 -0600318 # second argument. Check that the previous methods of passing
319 # a time tuple or None work in addition to no argument.
Larry Hastings76ad59b2012-05-03 00:30:07 -0700320 st0 = os.stat(filename)
Brian Curtin52fbea12011-11-06 13:41:17 -0600321 # Doesn't set anything new, but sets the time tuple way
Larry Hastings76ad59b2012-05-03 00:30:07 -0700322 utime(filename, (attr(st0, "st_atime"), attr(st0, "st_mtime")))
323 # Setting the time to the time you just read, then reading again,
324 # should always return exactly the same times.
325 st1 = os.stat(filename)
326 self.assertEqual(attr(st0, "st_mtime"), attr(st1, "st_mtime"))
327 self.assertEqual(attr(st0, "st_atime"), attr(st1, "st_atime"))
Brian Curtin52fbea12011-11-06 13:41:17 -0600328 # Set to the current time in the old explicit way.
Larry Hastings76ad59b2012-05-03 00:30:07 -0700329 os.utime(filename, None)
Brian Curtin52fbea12011-11-06 13:41:17 -0600330 st2 = os.stat(support.TESTFN)
Larry Hastings76ad59b2012-05-03 00:30:07 -0700331 # Set to the current time in the new way
332 os.utime(filename)
333 st3 = os.stat(filename)
334 self.assertAlmostEqual(attr(st2, "st_mtime"), attr(st3, "st_mtime"), delta=delta)
335
336 def test_utime(self):
337 def utime(file, times):
338 return os.utime(file, times)
339 self._test_utime(self.fname, getattr, utime, 10)
340 self._test_utime(support.TESTFN, getattr, utime, 10)
341
342
343 def _test_utime_ns(self, set_times_ns, test_dir=True):
344 def getattr_ns(o, attr):
345 return getattr(o, attr + "_ns")
346 ten_s = 10 * 1000 * 1000 * 1000
347 self._test_utime(self.fname, getattr_ns, set_times_ns, ten_s)
348 if test_dir:
349 self._test_utime(support.TESTFN, getattr_ns, set_times_ns, ten_s)
350
351 def test_utime_ns(self):
352 def utime_ns(file, times):
353 return os.utime(file, ns=times)
354 self._test_utime_ns(utime_ns)
355
Larry Hastings9cf065c2012-06-22 16:30:09 -0700356 requires_utime_dir_fd = unittest.skipUnless(
357 os.utime in os.supports_dir_fd,
358 "dir_fd support for utime required for this test.")
359 requires_utime_fd = unittest.skipUnless(
360 os.utime in os.supports_fd,
361 "fd support for utime required for this test.")
362 requires_utime_nofollow_symlinks = unittest.skipUnless(
363 os.utime in os.supports_follow_symlinks,
364 "follow_symlinks support for utime required for this test.")
Larry Hastings76ad59b2012-05-03 00:30:07 -0700365
Larry Hastings9cf065c2012-06-22 16:30:09 -0700366 @requires_utime_nofollow_symlinks
Larry Hastings76ad59b2012-05-03 00:30:07 -0700367 def test_lutimes_ns(self):
368 def lutimes_ns(file, times):
Larry Hastings9cf065c2012-06-22 16:30:09 -0700369 return os.utime(file, ns=times, follow_symlinks=False)
Larry Hastings76ad59b2012-05-03 00:30:07 -0700370 self._test_utime_ns(lutimes_ns)
371
Larry Hastings9cf065c2012-06-22 16:30:09 -0700372 @requires_utime_fd
Larry Hastings76ad59b2012-05-03 00:30:07 -0700373 def test_futimes_ns(self):
374 def futimes_ns(file, times):
375 with open(file, "wb") as f:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700376 os.utime(f.fileno(), ns=times)
Larry Hastings76ad59b2012-05-03 00:30:07 -0700377 self._test_utime_ns(futimes_ns, test_dir=False)
378
379 def _utime_invalid_arguments(self, name, arg):
Larry Hastings9cf065c2012-06-22 16:30:09 -0700380 with self.assertRaises(ValueError):
Larry Hastings76ad59b2012-05-03 00:30:07 -0700381 getattr(os, name)(arg, (5, 5), ns=(5, 5))
382
383 def test_utime_invalid_arguments(self):
384 self._utime_invalid_arguments('utime', self.fname)
385
Brian Curtin52fbea12011-11-06 13:41:17 -0600386
Victor Stinner1aa54a42012-02-08 04:09:37 +0100387 @unittest.skipUnless(stat_supports_subsecond,
388 "os.stat() doesn't has a subsecond resolution")
Victor Stinnera2f7c002012-02-08 03:36:25 +0100389 def _test_utime_subsecond(self, set_time_func):
Victor Stinnerbe557de2012-02-08 03:01:11 +0100390 asec, amsec = 1, 901
391 atime = asec + amsec * 1e-3
Victor Stinnera2f7c002012-02-08 03:36:25 +0100392 msec, mmsec = 2, 901
Victor Stinnerbe557de2012-02-08 03:01:11 +0100393 mtime = msec + mmsec * 1e-3
394 filename = self.fname
Victor Stinnera2f7c002012-02-08 03:36:25 +0100395 os.utime(filename, (0, 0))
396 set_time_func(filename, atime, mtime)
Victor Stinner034d0aa2012-06-05 01:22:15 +0200397 with warnings.catch_warnings():
398 warnings.simplefilter("ignore", DeprecationWarning)
399 os.stat_float_times(True)
Victor Stinnera2f7c002012-02-08 03:36:25 +0100400 st = os.stat(filename)
401 self.assertAlmostEqual(st.st_atime, atime, places=3)
402 self.assertAlmostEqual(st.st_mtime, mtime, places=3)
Victor Stinnerbe557de2012-02-08 03:01:11 +0100403
Victor Stinnera2f7c002012-02-08 03:36:25 +0100404 def test_utime_subsecond(self):
405 def set_time(filename, atime, mtime):
406 os.utime(filename, (atime, mtime))
407 self._test_utime_subsecond(set_time)
408
Larry Hastings9cf065c2012-06-22 16:30:09 -0700409 @requires_utime_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100410 def test_futimes_subsecond(self):
411 def set_time(filename, atime, mtime):
412 with open(filename, "wb") as f:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700413 os.utime(f.fileno(), times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100414 self._test_utime_subsecond(set_time)
415
Larry Hastings9cf065c2012-06-22 16:30:09 -0700416 @requires_utime_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100417 def test_futimens_subsecond(self):
418 def set_time(filename, atime, mtime):
419 with open(filename, "wb") as f:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700420 os.utime(f.fileno(), times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100421 self._test_utime_subsecond(set_time)
422
Larry Hastings9cf065c2012-06-22 16:30:09 -0700423 @requires_utime_dir_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100424 def test_futimesat_subsecond(self):
425 def set_time(filename, atime, mtime):
426 dirname = os.path.dirname(filename)
427 dirfd = os.open(dirname, os.O_RDONLY)
428 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700429 os.utime(os.path.basename(filename), dir_fd=dirfd,
430 times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100431 finally:
432 os.close(dirfd)
433 self._test_utime_subsecond(set_time)
434
Larry Hastings9cf065c2012-06-22 16:30:09 -0700435 @requires_utime_nofollow_symlinks
Victor Stinnera2f7c002012-02-08 03:36:25 +0100436 def test_lutimes_subsecond(self):
437 def set_time(filename, atime, mtime):
Larry Hastings9cf065c2012-06-22 16:30:09 -0700438 os.utime(filename, (atime, mtime), follow_symlinks=False)
Victor Stinnera2f7c002012-02-08 03:36:25 +0100439 self._test_utime_subsecond(set_time)
440
Larry Hastings9cf065c2012-06-22 16:30:09 -0700441 @requires_utime_dir_fd
Victor Stinnera2f7c002012-02-08 03:36:25 +0100442 def test_utimensat_subsecond(self):
443 def set_time(filename, atime, mtime):
444 dirname = os.path.dirname(filename)
445 dirfd = os.open(dirname, os.O_RDONLY)
446 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700447 os.utime(os.path.basename(filename), dir_fd=dirfd,
448 times=(atime, mtime))
Victor Stinnera2f7c002012-02-08 03:36:25 +0100449 finally:
450 os.close(dirfd)
451 self._test_utime_subsecond(set_time)
Victor Stinnerbe557de2012-02-08 03:01:11 +0100452
Thomas Wouters89f507f2006-12-13 04:49:30 +0000453 # Restrict test to Win32, since there is no guarantee other
454 # systems support centiseconds
455 if sys.platform == 'win32':
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000456 def get_file_system(path):
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000457 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000458 import ctypes
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000459 kernel32 = ctypes.windll.kernel32
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000460 buf = ctypes.create_unicode_buffer("", 100)
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000461 if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000462 return buf.value
463
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000464 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000465 def test_1565150(self):
466 t1 = 1159195039.25
467 os.utime(self.fname, (t1, t1))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000468 self.assertEqual(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000469
Amaury Forgeot d'Arca251a852011-01-03 00:19:11 +0000470 def test_large_time(self):
471 t1 = 5000000000 # some day in 2128
472 os.utime(self.fname, (t1, t1))
473 self.assertEqual(os.stat(self.fname).st_mtime, t1)
474
Guido van Rossumd8faa362007-04-27 19:54:29 +0000475 def test_1686475(self):
476 # Verify that an open file can be stat'ed
477 try:
478 os.stat(r"c:\pagefile.sys")
479 except WindowsError as e:
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000480 if e.errno == 2: # file does not exist; cannot run test
Guido van Rossumd8faa362007-04-27 19:54:29 +0000481 return
482 self.fail("Could not stat pagefile.sys")
483
Richard Oudkerk2240ac12012-07-06 12:05:32 +0100484 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
485 def test_15261(self):
486 # Verify that stat'ing a closed fd does not cause crash
487 r, w = os.pipe()
488 try:
489 os.stat(r) # should not raise error
490 finally:
491 os.close(r)
492 os.close(w)
493 with self.assertRaises(OSError) as ctx:
494 os.stat(r)
495 self.assertEqual(ctx.exception.errno, errno.EBADF)
496
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000497from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000498
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000499class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000500 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000501 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000502
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000503 def setUp(self):
504 self.__save = dict(os.environ)
Victor Stinnerb745a742010-05-18 17:17:23 +0000505 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000506 self.__saveb = dict(os.environb)
Christian Heimes90333392007-11-01 19:08:42 +0000507 for key, value in self._reference().items():
508 os.environ[key] = value
509
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000510 def tearDown(self):
511 os.environ.clear()
512 os.environ.update(self.__save)
Victor Stinnerb745a742010-05-18 17:17:23 +0000513 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000514 os.environb.clear()
515 os.environb.update(self.__saveb)
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000516
Christian Heimes90333392007-11-01 19:08:42 +0000517 def _reference(self):
518 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
519
520 def _empty_mapping(self):
521 os.environ.clear()
522 return os.environ
523
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000524 # Bug 1110478
Ezio Melottic7e139b2012-09-26 20:01:34 +0300525 @unittest.skipUnless(os.path.exists('/bin/sh'), 'requires /bin/sh')
Martin v. Löwis5510f652005-02-17 21:23:20 +0000526 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000527 os.environ.clear()
Ezio Melottic7e139b2012-09-26 20:01:34 +0300528 os.environ.update(HELLO="World")
529 with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
530 value = popen.read().strip()
531 self.assertEqual(value, "World")
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000532
Ezio Melottic7e139b2012-09-26 20:01:34 +0300533 @unittest.skipUnless(os.path.exists('/bin/sh'), 'requires /bin/sh')
Christian Heimes1a13d592007-11-08 14:16:55 +0000534 def test_os_popen_iter(self):
Ezio Melottic7e139b2012-09-26 20:01:34 +0300535 with os.popen(
536 "/bin/sh -c 'echo \"line1\nline2\nline3\"'") as popen:
537 it = iter(popen)
538 self.assertEqual(next(it), "line1\n")
539 self.assertEqual(next(it), "line2\n")
540 self.assertEqual(next(it), "line3\n")
541 self.assertRaises(StopIteration, next, it)
Christian Heimes1a13d592007-11-08 14:16:55 +0000542
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000543 # Verify environ keys and values from the OS are of the
544 # correct str type.
545 def test_keyvalue_types(self):
546 for key, val in os.environ.items():
Ezio Melottib3aedd42010-11-20 19:04:17 +0000547 self.assertEqual(type(key), str)
548 self.assertEqual(type(val), str)
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000549
Christian Heimes90333392007-11-01 19:08:42 +0000550 def test_items(self):
551 for key, value in self._reference().items():
552 self.assertEqual(os.environ.get(key), value)
553
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000554 # Issue 7310
555 def test___repr__(self):
556 """Check that the repr() of os.environ looks like environ({...})."""
557 env = os.environ
Victor Stinner96f0de92010-07-29 00:29:00 +0000558 self.assertEqual(repr(env), 'environ({{{}}})'.format(', '.join(
559 '{!r}: {!r}'.format(key, value)
560 for key, value in env.items())))
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000561
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000562 def test_get_exec_path(self):
563 defpath_list = os.defpath.split(os.pathsep)
564 test_path = ['/monty', '/python', '', '/flying/circus']
565 test_env = {'PATH': os.pathsep.join(test_path)}
566
567 saved_environ = os.environ
568 try:
569 os.environ = dict(test_env)
570 # Test that defaulting to os.environ works.
571 self.assertSequenceEqual(test_path, os.get_exec_path())
572 self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
573 finally:
574 os.environ = saved_environ
575
576 # No PATH environment variable
577 self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
578 # Empty PATH environment variable
579 self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
580 # Supplied PATH environment variable
581 self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
582
Victor Stinnerb745a742010-05-18 17:17:23 +0000583 if os.supports_bytes_environ:
584 # env cannot contain 'PATH' and b'PATH' keys
Victor Stinner38430e22010-08-19 17:10:18 +0000585 try:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000586 # ignore BytesWarning warning
587 with warnings.catch_warnings(record=True):
588 mixed_env = {'PATH': '1', b'PATH': b'2'}
Victor Stinner38430e22010-08-19 17:10:18 +0000589 except BytesWarning:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000590 # mixed_env cannot be created with python -bb
Victor Stinner38430e22010-08-19 17:10:18 +0000591 pass
592 else:
593 self.assertRaises(ValueError, os.get_exec_path, mixed_env)
Victor Stinnerb745a742010-05-18 17:17:23 +0000594
595 # bytes key and/or value
596 self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}),
597 ['abc'])
598 self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}),
599 ['abc'])
600 self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}),
601 ['abc'])
602
603 @unittest.skipUnless(os.supports_bytes_environ,
604 "os.environb required for this test.")
Victor Stinner84ae1182010-05-06 22:05:07 +0000605 def test_environb(self):
606 # os.environ -> os.environb
607 value = 'euro\u20ac'
608 try:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000609 value_bytes = value.encode(sys.getfilesystemencoding(),
610 'surrogateescape')
Victor Stinner84ae1182010-05-06 22:05:07 +0000611 except UnicodeEncodeError:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000612 msg = "U+20AC character is not encodable to %s" % (
613 sys.getfilesystemencoding(),)
Benjamin Peterson932d3f42010-05-06 22:26:31 +0000614 self.skipTest(msg)
Victor Stinner84ae1182010-05-06 22:05:07 +0000615 os.environ['unicode'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000616 self.assertEqual(os.environ['unicode'], value)
617 self.assertEqual(os.environb[b'unicode'], value_bytes)
Victor Stinner84ae1182010-05-06 22:05:07 +0000618
619 # os.environb -> os.environ
620 value = b'\xff'
621 os.environb[b'bytes'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000622 self.assertEqual(os.environb[b'bytes'], value)
Victor Stinner84ae1182010-05-06 22:05:07 +0000623 value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000624 self.assertEqual(os.environ['bytes'], value_str)
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000625
Charles-François Natali2966f102011-11-26 11:32:46 +0100626 # On FreeBSD < 7 and OS X < 10.6, unsetenv() doesn't return a value (issue
627 # #13415).
628 @support.requires_freebsd_version(7)
629 @support.requires_mac_ver(10, 6)
Victor Stinner60b385e2011-11-22 22:01:28 +0100630 def test_unset_error(self):
631 if sys.platform == "win32":
632 # an environment variable is limited to 32,767 characters
633 key = 'x' * 50000
Victor Stinnerb3f82682011-11-22 22:30:19 +0100634 self.assertRaises(ValueError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100635 else:
636 # "=" is not allowed in a variable name
637 key = 'key='
Victor Stinnerb3f82682011-11-22 22:30:19 +0100638 self.assertRaises(OSError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100639
Victor Stinner6d101392013-04-14 16:35:04 +0200640 def test_key_type(self):
641 missing = 'missingkey'
642 self.assertNotIn(missing, os.environ)
643
Victor Stinner839e5ea2013-04-14 16:43:03 +0200644 with self.assertRaises(KeyError) as cm:
Victor Stinner6d101392013-04-14 16:35:04 +0200645 os.environ[missing]
Victor Stinner839e5ea2013-04-14 16:43:03 +0200646 self.assertIs(cm.exception.args[0], missing)
Victor Stinner0c2dd0c2013-08-23 19:19:15 +0200647 self.assertTrue(cm.exception.__suppress_context__)
Victor Stinner6d101392013-04-14 16:35:04 +0200648
Victor Stinner839e5ea2013-04-14 16:43:03 +0200649 with self.assertRaises(KeyError) as cm:
Victor Stinner6d101392013-04-14 16:35:04 +0200650 del os.environ[missing]
Victor Stinner839e5ea2013-04-14 16:43:03 +0200651 self.assertIs(cm.exception.args[0], missing)
Victor Stinner0c2dd0c2013-08-23 19:19:15 +0200652 self.assertTrue(cm.exception.__suppress_context__)
653
Victor Stinner6d101392013-04-14 16:35:04 +0200654
Tim Petersc4e09402003-04-25 07:11:48 +0000655class WalkTests(unittest.TestCase):
656 """Tests for os.walk()."""
657
Charles-François Natali7372b062012-02-05 15:15:38 +0100658 def setUp(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000659 import os
660 from os.path import join
661
662 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000663 # TESTFN/
664 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000665 # tmp1
666 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000667 # tmp2
668 # SUB11/ no kids
669 # SUB2/ a file kid and a dirsymlink kid
670 # tmp3
671 # link/ a symlink to TESTFN.2
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200672 # broken_link
Guido van Rossumd8faa362007-04-27 19:54:29 +0000673 # TEST2/
674 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000675 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000676 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000677 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000678 sub2_path = join(walk_path, "SUB2")
679 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000680 tmp2_path = join(sub1_path, "tmp2")
681 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000682 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000683 t2_path = join(support.TESTFN, "TEST2")
684 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200685 link_path = join(sub2_path, "link")
686 broken_link_path = join(sub2_path, "broken_link")
Tim Petersc4e09402003-04-25 07:11:48 +0000687
688 # Create stuff.
689 os.makedirs(sub11_path)
690 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000691 os.makedirs(t2_path)
692 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000693 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000694 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
695 f.close()
Brian Curtin3b4499c2010-12-28 14:31:47 +0000696 if support.can_symlink():
Jason R. Coombs3a092862013-05-27 23:21:28 -0400697 os.symlink(os.path.abspath(t2_path), link_path)
Jason R. Coombsb501b562013-05-27 23:52:43 -0400698 os.symlink('broken', broken_link_path, True)
Hynek Schlawack66bfcc12012-05-15 16:32:21 +0200699 sub2_tree = (sub2_path, ["link"], ["broken_link", "tmp3"])
Guido van Rossumd8faa362007-04-27 19:54:29 +0000700 else:
701 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000702
703 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000704 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000705 self.assertEqual(len(all), 4)
706 # We can't know which order SUB1 and SUB2 will appear in.
707 # Not flipped: TESTFN, SUB1, SUB11, SUB2
708 # flipped: TESTFN, SUB2, SUB1, SUB11
709 flipped = all[0][1][0] != "SUB1"
710 all[0][1].sort()
Hynek Schlawackc96f5a02012-05-15 17:55:38 +0200711 all[3 - 2 * flipped][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000712 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000713 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
714 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000715 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000716
717 # Prune the search.
718 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000719 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000720 all.append((root, dirs, files))
721 # Don't descend into SUB1.
722 if 'SUB1' in dirs:
723 # Note that this also mutates the dirs we appended to all!
724 dirs.remove('SUB1')
725 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000726 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Hynek Schlawack39bf90d2012-05-15 18:40:17 +0200727 all[1][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000728 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000729
730 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000731 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000732 self.assertEqual(len(all), 4)
733 # We can't know which order SUB1 and SUB2 will appear in.
734 # Not flipped: SUB11, SUB1, SUB2, TESTFN
735 # flipped: SUB2, SUB11, SUB1, TESTFN
736 flipped = all[3][1][0] != "SUB1"
737 all[3][1].sort()
Hynek Schlawack39bf90d2012-05-15 18:40:17 +0200738 all[2 - 2 * flipped][-1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000739 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000740 self.assertEqual(all[flipped], (sub11_path, [], []))
741 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000742 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000743
Brian Curtin3b4499c2010-12-28 14:31:47 +0000744 if support.can_symlink():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000745 # Walk, following symlinks.
746 for root, dirs, files in os.walk(walk_path, followlinks=True):
747 if root == link_path:
748 self.assertEqual(dirs, [])
749 self.assertEqual(files, ["tmp4"])
750 break
751 else:
752 self.fail("Didn't follow symlink with followlinks=True")
753
754 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000755 # Tear everything down. This is a decent use for bottom-up on
756 # Windows, which doesn't have a recursive delete command. The
757 # (not so) subtlety is that rmdir will fail unless the dir's
758 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000759 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000760 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000761 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000762 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000763 dirname = os.path.join(root, name)
764 if not os.path.islink(dirname):
765 os.rmdir(dirname)
766 else:
767 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000768 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000769
Charles-François Natali7372b062012-02-05 15:15:38 +0100770
771@unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
772class FwalkTests(WalkTests):
773 """Tests for os.fwalk()."""
774
Larry Hastingsc48fe982012-06-25 04:49:05 -0700775 def _compare_to_walk(self, walk_kwargs, fwalk_kwargs):
776 """
777 compare with walk() results.
778 """
Larry Hastingsb4038062012-07-15 10:57:38 -0700779 walk_kwargs = walk_kwargs.copy()
780 fwalk_kwargs = fwalk_kwargs.copy()
781 for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
782 walk_kwargs.update(topdown=topdown, followlinks=follow_symlinks)
783 fwalk_kwargs.update(topdown=topdown, follow_symlinks=follow_symlinks)
Larry Hastingsc48fe982012-06-25 04:49:05 -0700784
Charles-François Natali7372b062012-02-05 15:15:38 +0100785 expected = {}
Larry Hastingsc48fe982012-06-25 04:49:05 -0700786 for root, dirs, files in os.walk(**walk_kwargs):
Charles-François Natali7372b062012-02-05 15:15:38 +0100787 expected[root] = (set(dirs), set(files))
788
Larry Hastingsc48fe982012-06-25 04:49:05 -0700789 for root, dirs, files, rootfd in os.fwalk(**fwalk_kwargs):
Charles-François Natali7372b062012-02-05 15:15:38 +0100790 self.assertIn(root, expected)
791 self.assertEqual(expected[root], (set(dirs), set(files)))
792
Larry Hastingsc48fe982012-06-25 04:49:05 -0700793 def test_compare_to_walk(self):
794 kwargs = {'top': support.TESTFN}
795 self._compare_to_walk(kwargs, kwargs)
796
Charles-François Natali7372b062012-02-05 15:15:38 +0100797 def test_dir_fd(self):
Larry Hastingsc48fe982012-06-25 04:49:05 -0700798 try:
799 fd = os.open(".", os.O_RDONLY)
800 walk_kwargs = {'top': support.TESTFN}
801 fwalk_kwargs = walk_kwargs.copy()
802 fwalk_kwargs['dir_fd'] = fd
803 self._compare_to_walk(walk_kwargs, fwalk_kwargs)
804 finally:
805 os.close(fd)
806
807 def test_yields_correct_dir_fd(self):
Charles-François Natali7372b062012-02-05 15:15:38 +0100808 # check returned file descriptors
Larry Hastingsb4038062012-07-15 10:57:38 -0700809 for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
810 args = support.TESTFN, topdown, None
811 for root, dirs, files, rootfd in os.fwalk(*args, follow_symlinks=follow_symlinks):
Charles-François Natali7372b062012-02-05 15:15:38 +0100812 # check that the FD is valid
813 os.fstat(rootfd)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700814 # redundant check
815 os.stat(rootfd)
816 # check that listdir() returns consistent information
817 self.assertEqual(set(os.listdir(rootfd)), set(dirs) | set(files))
Charles-François Natali7372b062012-02-05 15:15:38 +0100818
819 def test_fd_leak(self):
820 # Since we're opening a lot of FDs, we must be careful to avoid leaks:
821 # we both check that calling fwalk() a large number of times doesn't
822 # yield EMFILE, and that the minimum allocated FD hasn't changed.
823 minfd = os.dup(1)
824 os.close(minfd)
825 for i in range(256):
826 for x in os.fwalk(support.TESTFN):
827 pass
828 newfd = os.dup(1)
829 self.addCleanup(os.close, newfd)
830 self.assertEqual(newfd, minfd)
831
832 def tearDown(self):
833 # cleanup
834 for root, dirs, files, rootfd in os.fwalk(support.TESTFN, topdown=False):
835 for name in files:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700836 os.unlink(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +0100837 for name in dirs:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700838 st = os.stat(name, dir_fd=rootfd, follow_symlinks=False)
Larry Hastingsb698d8e2012-06-23 16:55:07 -0700839 if stat.S_ISDIR(st.st_mode):
840 os.rmdir(name, dir_fd=rootfd)
841 else:
842 os.unlink(name, dir_fd=rootfd)
Charles-François Natali7372b062012-02-05 15:15:38 +0100843 os.rmdir(support.TESTFN)
844
845
Guido van Rossume7ba4952007-06-06 23:52:48 +0000846class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000847 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000848 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000849
850 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000851 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000852 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
853 os.makedirs(path) # Should work
854 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
855 os.makedirs(path)
856
857 # Try paths with a '.' in them
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000858 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000859 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
860 os.makedirs(path)
861 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
862 'dir5', 'dir6')
863 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000864
Terry Reedy5a22b652010-12-02 07:05:56 +0000865 def test_exist_ok_existing_directory(self):
866 path = os.path.join(support.TESTFN, 'dir1')
867 mode = 0o777
868 old_mask = os.umask(0o022)
869 os.makedirs(path, mode)
870 self.assertRaises(OSError, os.makedirs, path, mode)
871 self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
872 self.assertRaises(OSError, os.makedirs, path, 0o776, exist_ok=True)
873 os.makedirs(path, mode=mode, exist_ok=True)
874 os.umask(old_mask)
875
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700876 def test_exist_ok_s_isgid_directory(self):
877 path = os.path.join(support.TESTFN, 'dir1')
878 S_ISGID = stat.S_ISGID
879 mode = 0o777
880 old_mask = os.umask(0o022)
881 try:
882 existing_testfn_mode = stat.S_IMODE(
883 os.lstat(support.TESTFN).st_mode)
Ned Deilyc622f422012-08-08 20:57:24 -0700884 try:
885 os.chmod(support.TESTFN, existing_testfn_mode | S_ISGID)
Ned Deily3a2b97e2012-08-08 21:03:02 -0700886 except PermissionError:
Ned Deilyc622f422012-08-08 20:57:24 -0700887 raise unittest.SkipTest('Cannot set S_ISGID for dir.')
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700888 if (os.lstat(support.TESTFN).st_mode & S_ISGID != S_ISGID):
889 raise unittest.SkipTest('No support for S_ISGID dir mode.')
890 # The os should apply S_ISGID from the parent dir for us, but
891 # this test need not depend on that behavior. Be explicit.
892 os.makedirs(path, mode | S_ISGID)
893 # http://bugs.python.org/issue14992
894 # Should not fail when the bit is already set.
895 os.makedirs(path, mode, exist_ok=True)
896 # remove the bit.
897 os.chmod(path, stat.S_IMODE(os.lstat(path).st_mode) & ~S_ISGID)
898 with self.assertRaises(OSError):
899 # Should fail when the bit is not already set when demanded.
900 os.makedirs(path, mode | S_ISGID, exist_ok=True)
901 finally:
902 os.umask(old_mask)
Terry Reedy5a22b652010-12-02 07:05:56 +0000903
904 def test_exist_ok_existing_regular_file(self):
905 base = support.TESTFN
906 path = os.path.join(support.TESTFN, 'dir1')
907 f = open(path, 'w')
908 f.write('abc')
909 f.close()
910 self.assertRaises(OSError, os.makedirs, path)
911 self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
912 self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
913 os.remove(path)
914
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000915 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000916 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000917 'dir4', 'dir5', 'dir6')
918 # If the tests failed, the bottom-most directory ('../dir6')
919 # may not have been created, so we look for the outermost directory
920 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000921 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000922 path = os.path.dirname(path)
923
924 os.removedirs(path)
925
Andrew Svetlov405faed2012-12-25 12:18:09 +0200926
927class RemoveDirsTests(unittest.TestCase):
928 def setUp(self):
929 os.makedirs(support.TESTFN)
930
931 def tearDown(self):
932 support.rmtree(support.TESTFN)
933
934 def test_remove_all(self):
935 dira = os.path.join(support.TESTFN, 'dira')
936 os.mkdir(dira)
937 dirb = os.path.join(dira, 'dirb')
938 os.mkdir(dirb)
939 os.removedirs(dirb)
940 self.assertFalse(os.path.exists(dirb))
941 self.assertFalse(os.path.exists(dira))
942 self.assertFalse(os.path.exists(support.TESTFN))
943
944 def test_remove_partial(self):
945 dira = os.path.join(support.TESTFN, 'dira')
946 os.mkdir(dira)
947 dirb = os.path.join(dira, 'dirb')
948 os.mkdir(dirb)
949 with open(os.path.join(dira, 'file.txt'), 'w') as f:
950 f.write('text')
951 os.removedirs(dirb)
952 self.assertFalse(os.path.exists(dirb))
953 self.assertTrue(os.path.exists(dira))
954 self.assertTrue(os.path.exists(support.TESTFN))
955
956 def test_remove_nothing(self):
957 dira = os.path.join(support.TESTFN, 'dira')
958 os.mkdir(dira)
959 dirb = os.path.join(dira, 'dirb')
960 os.mkdir(dirb)
961 with open(os.path.join(dirb, 'file.txt'), 'w') as f:
962 f.write('text')
963 with self.assertRaises(OSError):
964 os.removedirs(dirb)
965 self.assertTrue(os.path.exists(dirb))
966 self.assertTrue(os.path.exists(dira))
967 self.assertTrue(os.path.exists(support.TESTFN))
968
969
Guido van Rossume7ba4952007-06-06 23:52:48 +0000970class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000971 def test_devnull(self):
Victor Stinnera6d2c762011-06-30 18:20:11 +0200972 with open(os.devnull, 'wb') as f:
973 f.write(b'hello')
974 f.close()
975 with open(os.devnull, 'rb') as f:
976 self.assertEqual(f.read(), b'')
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000977
Andrew Svetlov405faed2012-12-25 12:18:09 +0200978
Guido van Rossume7ba4952007-06-06 23:52:48 +0000979class URandomTests(unittest.TestCase):
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100980 def test_urandom_length(self):
981 self.assertEqual(len(os.urandom(0)), 0)
982 self.assertEqual(len(os.urandom(1)), 1)
983 self.assertEqual(len(os.urandom(10)), 10)
984 self.assertEqual(len(os.urandom(100)), 100)
985 self.assertEqual(len(os.urandom(1000)), 1000)
986
987 def test_urandom_value(self):
988 data1 = os.urandom(16)
989 data2 = os.urandom(16)
990 self.assertNotEqual(data1, data2)
991
992 def get_urandom_subprocess(self, count):
993 code = '\n'.join((
994 'import os, sys',
995 'data = os.urandom(%s)' % count,
996 'sys.stdout.buffer.write(data)',
997 'sys.stdout.buffer.flush()'))
998 out = assert_python_ok('-c', code)
999 stdout = out[1]
1000 self.assertEqual(len(stdout), 16)
1001 return stdout
1002
1003 def test_urandom_subprocess(self):
1004 data1 = self.get_urandom_subprocess(16)
1005 data2 = self.get_urandom_subprocess(16)
1006 self.assertNotEqual(data1, data2)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +00001007
Antoine Pitrouec34ab52013-08-16 20:44:38 +02001008 @unittest.skipUnless(resource, "test requires the resource module")
1009 def test_urandom_failure(self):
Antoine Pitroueba25ba2013-08-24 20:52:27 +02001010 # Check urandom() failing when it is not able to open /dev/random.
1011 # We spawn a new process to make the test more robust (if getrlimit()
1012 # failed to restore the file descriptor limit after this, the whole
1013 # test suite would crash; this actually happened on the OS X Tiger
1014 # buildbot).
1015 code = """if 1:
1016 import errno
1017 import os
1018 import resource
1019
1020 soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
1021 resource.setrlimit(resource.RLIMIT_NOFILE, (1, hard_limit))
1022 try:
Antoine Pitrouec34ab52013-08-16 20:44:38 +02001023 os.urandom(16)
Antoine Pitroueba25ba2013-08-24 20:52:27 +02001024 except OSError as e:
1025 assert e.errno == errno.EMFILE, e.errno
1026 else:
1027 raise AssertionError("OSError not raised")
1028 """
1029 assert_python_ok('-c', code)
Antoine Pitrouec34ab52013-08-16 20:44:38 +02001030
1031
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001032@contextlib.contextmanager
1033def _execvpe_mockup(defpath=None):
1034 """
1035 Stubs out execv and execve functions when used as context manager.
1036 Records exec calls. The mock execv and execve functions always raise an
1037 exception as they would normally never return.
1038 """
1039 # A list of tuples containing (function name, first arg, args)
1040 # of calls to execv or execve that have been made.
1041 calls = []
1042
1043 def mock_execv(name, *args):
1044 calls.append(('execv', name, args))
1045 raise RuntimeError("execv called")
1046
1047 def mock_execve(name, *args):
1048 calls.append(('execve', name, args))
1049 raise OSError(errno.ENOTDIR, "execve called")
1050
1051 try:
1052 orig_execv = os.execv
1053 orig_execve = os.execve
1054 orig_defpath = os.defpath
1055 os.execv = mock_execv
1056 os.execve = mock_execve
1057 if defpath is not None:
1058 os.defpath = defpath
1059 yield calls
1060 finally:
1061 os.execv = orig_execv
1062 os.execve = orig_execve
1063 os.defpath = orig_defpath
1064
Guido van Rossume7ba4952007-06-06 23:52:48 +00001065class ExecTests(unittest.TestCase):
Mark Dickinson7cf03892010-04-16 13:45:35 +00001066 @unittest.skipIf(USING_LINUXTHREADS,
1067 "avoid triggering a linuxthreads bug: see issue #4970")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001068 def test_execvpe_with_bad_program(self):
Mark Dickinson7cf03892010-04-16 13:45:35 +00001069 self.assertRaises(OSError, os.execvpe, 'no such app-',
1070 ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001071
Thomas Heller6790d602007-08-30 17:15:14 +00001072 def test_execvpe_with_bad_arglist(self):
1073 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
1074
Gregory P. Smith4ae37772010-05-08 18:05:46 +00001075 @unittest.skipUnless(hasattr(os, '_execvpe'),
1076 "No internal os._execvpe function to test.")
Victor Stinnerb745a742010-05-18 17:17:23 +00001077 def _test_internal_execvpe(self, test_type):
1078 program_path = os.sep + 'absolutepath'
1079 if test_type is bytes:
1080 program = b'executable'
1081 fullpath = os.path.join(os.fsencode(program_path), program)
1082 native_fullpath = fullpath
1083 arguments = [b'progname', 'arg1', 'arg2']
1084 else:
1085 program = 'executable'
1086 arguments = ['progname', 'arg1', 'arg2']
1087 fullpath = os.path.join(program_path, program)
1088 if os.name != "nt":
1089 native_fullpath = os.fsencode(fullpath)
1090 else:
1091 native_fullpath = fullpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001092 env = {'spam': 'beans'}
1093
Victor Stinnerb745a742010-05-18 17:17:23 +00001094 # test os._execvpe() with an absolute path
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001095 with _execvpe_mockup() as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +00001096 self.assertRaises(RuntimeError,
1097 os._execvpe, fullpath, arguments)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001098 self.assertEqual(len(calls), 1)
1099 self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))
1100
Victor Stinnerb745a742010-05-18 17:17:23 +00001101 # test os._execvpe() with a relative path:
1102 # os.get_exec_path() returns defpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001103 with _execvpe_mockup(defpath=program_path) as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +00001104 self.assertRaises(OSError,
1105 os._execvpe, program, arguments, env=env)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001106 self.assertEqual(len(calls), 1)
Victor Stinnerb745a742010-05-18 17:17:23 +00001107 self.assertSequenceEqual(calls[0],
1108 ('execve', native_fullpath, (arguments, env)))
1109
1110 # test os._execvpe() with a relative path:
1111 # os.get_exec_path() reads the 'PATH' variable
1112 with _execvpe_mockup() as calls:
1113 env_path = env.copy()
Victor Stinner38430e22010-08-19 17:10:18 +00001114 if test_type is bytes:
1115 env_path[b'PATH'] = program_path
1116 else:
1117 env_path['PATH'] = program_path
Victor Stinnerb745a742010-05-18 17:17:23 +00001118 self.assertRaises(OSError,
1119 os._execvpe, program, arguments, env=env_path)
1120 self.assertEqual(len(calls), 1)
1121 self.assertSequenceEqual(calls[0],
1122 ('execve', native_fullpath, (arguments, env_path)))
1123
1124 def test_internal_execvpe_str(self):
1125 self._test_internal_execvpe(str)
1126 if os.name != "nt":
1127 self._test_internal_execvpe(bytes)
Victor Stinnerc2d095f2010-05-17 00:14:53 +00001128
Gregory P. Smith4ae37772010-05-08 18:05:46 +00001129
Thomas Wouters477c8d52006-05-27 19:21:47 +00001130class Win32ErrorTests(unittest.TestCase):
1131 def test_rename(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001132 self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001133
1134 def test_remove(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001135 self.assertRaises(WindowsError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001136
1137 def test_chdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001138 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001139
1140 def test_mkdir(self):
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +00001141 f = open(support.TESTFN, "w")
Benjamin Petersonf91df042009-02-13 02:50:59 +00001142 try:
1143 self.assertRaises(WindowsError, os.mkdir, support.TESTFN)
1144 finally:
1145 f.close()
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +00001146 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001147
1148 def test_utime(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001149 self.assertRaises(WindowsError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001150
Thomas Wouters477c8d52006-05-27 19:21:47 +00001151 def test_chmod(self):
Benjamin Petersonf91df042009-02-13 02:50:59 +00001152 self.assertRaises(WindowsError, os.chmod, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001153
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001154class TestInvalidFD(unittest.TestCase):
Benjamin Peterson05e782f2009-01-19 15:15:02 +00001155 singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001156 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
1157 #singles.append("close")
1158 #We omit close because it doesn'r raise an exception on some platforms
1159 def get_single(f):
1160 def helper(self):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001161 if hasattr(os, f):
1162 self.check(getattr(os, f))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001163 return helper
1164 for f in singles:
1165 locals()["test_"+f] = get_single(f)
1166
Benjamin Peterson7522c742009-01-19 21:00:09 +00001167 def check(self, f, *args):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001168 try:
1169 f(support.make_bad_fd(), *args)
1170 except OSError as e:
1171 self.assertEqual(e.errno, errno.EBADF)
1172 else:
1173 self.fail("%r didn't raise a OSError with a bad file descriptor"
1174 % f)
Benjamin Peterson7522c742009-01-19 21:00:09 +00001175
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001176 def test_isatty(self):
1177 if hasattr(os, "isatty"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001178 self.assertEqual(os.isatty(support.make_bad_fd()), False)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001179
1180 def test_closerange(self):
1181 if hasattr(os, "closerange"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001182 fd = support.make_bad_fd()
R. David Murray630cc482009-07-22 15:20:27 +00001183 # Make sure none of the descriptors we are about to close are
1184 # currently valid (issue 6542).
1185 for i in range(10):
1186 try: os.fstat(fd+i)
1187 except OSError:
1188 pass
1189 else:
1190 break
1191 if i < 2:
1192 raise unittest.SkipTest(
1193 "Unable to acquire a range of invalid file descriptors")
1194 self.assertEqual(os.closerange(fd, fd + i-1), None)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001195
1196 def test_dup2(self):
1197 if hasattr(os, "dup2"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001198 self.check(os.dup2, 20)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001199
1200 def test_fchmod(self):
1201 if hasattr(os, "fchmod"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001202 self.check(os.fchmod, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001203
1204 def test_fchown(self):
1205 if hasattr(os, "fchown"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001206 self.check(os.fchown, -1, -1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001207
1208 def test_fpathconf(self):
1209 if hasattr(os, "fpathconf"):
Georg Brandl306336b2012-06-24 12:55:33 +02001210 self.check(os.pathconf, "PC_NAME_MAX")
Benjamin Peterson7522c742009-01-19 21:00:09 +00001211 self.check(os.fpathconf, "PC_NAME_MAX")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001212
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001213 def test_ftruncate(self):
1214 if hasattr(os, "ftruncate"):
Georg Brandl306336b2012-06-24 12:55:33 +02001215 self.check(os.truncate, 0)
Benjamin Peterson7522c742009-01-19 21:00:09 +00001216 self.check(os.ftruncate, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001217
1218 def test_lseek(self):
1219 if hasattr(os, "lseek"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001220 self.check(os.lseek, 0, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001221
1222 def test_read(self):
1223 if hasattr(os, "read"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001224 self.check(os.read, 1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001225
1226 def test_tcsetpgrpt(self):
1227 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001228 self.check(os.tcsetpgrp, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001229
1230 def test_write(self):
1231 if hasattr(os, "write"):
Benjamin Peterson7522c742009-01-19 21:00:09 +00001232 self.check(os.write, b" ")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001233
Brian Curtin1b9df392010-11-24 20:24:31 +00001234
1235class LinkTests(unittest.TestCase):
1236 def setUp(self):
1237 self.file1 = support.TESTFN
1238 self.file2 = os.path.join(support.TESTFN + "2")
1239
Brian Curtinc0abc4e2010-11-30 23:46:54 +00001240 def tearDown(self):
Brian Curtin1b9df392010-11-24 20:24:31 +00001241 for file in (self.file1, self.file2):
1242 if os.path.exists(file):
1243 os.unlink(file)
1244
Brian Curtin1b9df392010-11-24 20:24:31 +00001245 def _test_link(self, file1, file2):
1246 with open(file1, "w") as f1:
1247 f1.write("test")
1248
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001249 with warnings.catch_warnings():
1250 warnings.simplefilter("ignore", DeprecationWarning)
1251 os.link(file1, file2)
Brian Curtin1b9df392010-11-24 20:24:31 +00001252 with open(file1, "r") as f1, open(file2, "r") as f2:
1253 self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
1254
1255 def test_link(self):
1256 self._test_link(self.file1, self.file2)
1257
1258 def test_link_bytes(self):
1259 self._test_link(bytes(self.file1, sys.getfilesystemencoding()),
1260 bytes(self.file2, sys.getfilesystemencoding()))
1261
Brian Curtinf498b752010-11-30 15:54:04 +00001262 def test_unicode_name(self):
Brian Curtin43f0c272010-11-30 15:40:04 +00001263 try:
Brian Curtinf498b752010-11-30 15:54:04 +00001264 os.fsencode("\xf1")
Brian Curtin43f0c272010-11-30 15:40:04 +00001265 except UnicodeError:
1266 raise unittest.SkipTest("Unable to encode for this platform.")
1267
Brian Curtinf498b752010-11-30 15:54:04 +00001268 self.file1 += "\xf1"
Brian Curtinfc889c42010-11-28 23:59:46 +00001269 self.file2 = self.file1 + "2"
1270 self._test_link(self.file1, self.file2)
1271
Thomas Wouters477c8d52006-05-27 19:21:47 +00001272if sys.platform != 'win32':
1273 class Win32ErrorTests(unittest.TestCase):
1274 pass
1275
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001276 class PosixUidGidTests(unittest.TestCase):
1277 if hasattr(os, 'setuid'):
1278 def test_setuid(self):
1279 if os.getuid() != 0:
1280 self.assertRaises(os.error, os.setuid, 0)
1281 self.assertRaises(OverflowError, os.setuid, 1<<32)
1282
1283 if hasattr(os, 'setgid'):
1284 def test_setgid(self):
Stefan Krahebee49a2013-01-17 15:31:00 +01001285 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001286 self.assertRaises(os.error, os.setgid, 0)
1287 self.assertRaises(OverflowError, os.setgid, 1<<32)
1288
1289 if hasattr(os, 'seteuid'):
1290 def test_seteuid(self):
1291 if os.getuid() != 0:
1292 self.assertRaises(os.error, os.seteuid, 0)
1293 self.assertRaises(OverflowError, os.seteuid, 1<<32)
1294
1295 if hasattr(os, 'setegid'):
1296 def test_setegid(self):
Stefan Krahebee49a2013-01-17 15:31:00 +01001297 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001298 self.assertRaises(os.error, os.setegid, 0)
1299 self.assertRaises(OverflowError, os.setegid, 1<<32)
1300
1301 if hasattr(os, 'setreuid'):
1302 def test_setreuid(self):
1303 if os.getuid() != 0:
1304 self.assertRaises(os.error, os.setreuid, 0, 0)
1305 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
1306 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001307
1308 def test_setreuid_neg1(self):
1309 # Needs to accept -1. We run this in a subprocess to avoid
1310 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001311 subprocess.check_call([
1312 sys.executable, '-c',
1313 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001314
1315 if hasattr(os, 'setregid'):
1316 def test_setregid(self):
Stefan Krahebee49a2013-01-17 15:31:00 +01001317 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001318 self.assertRaises(os.error, os.setregid, 0, 0)
1319 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
1320 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001321
1322 def test_setregid_neg1(self):
1323 # Needs to accept -1. We run this in a subprocess to avoid
1324 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001325 subprocess.check_call([
1326 sys.executable, '-c',
1327 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Martin v. Löwis011e8422009-05-05 04:43:17 +00001328
1329 class Pep383Tests(unittest.TestCase):
Martin v. Löwis011e8422009-05-05 04:43:17 +00001330 def setUp(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001331 if support.TESTFN_UNENCODABLE:
1332 self.dir = support.TESTFN_UNENCODABLE
Victor Stinnere667e982012-11-12 01:23:15 +01001333 elif support.TESTFN_NONASCII:
1334 self.dir = support.TESTFN_NONASCII
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001335 else:
1336 self.dir = support.TESTFN
1337 self.bdir = os.fsencode(self.dir)
1338
1339 bytesfn = []
1340 def add_filename(fn):
1341 try:
1342 fn = os.fsencode(fn)
1343 except UnicodeEncodeError:
1344 return
1345 bytesfn.append(fn)
1346 add_filename(support.TESTFN_UNICODE)
1347 if support.TESTFN_UNENCODABLE:
1348 add_filename(support.TESTFN_UNENCODABLE)
Victor Stinnere667e982012-11-12 01:23:15 +01001349 if support.TESTFN_NONASCII:
1350 add_filename(support.TESTFN_NONASCII)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001351 if not bytesfn:
1352 self.skipTest("couldn't create any non-ascii filename")
1353
1354 self.unicodefn = set()
Martin v. Löwis011e8422009-05-05 04:43:17 +00001355 os.mkdir(self.dir)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001356 try:
1357 for fn in bytesfn:
Victor Stinnerbf816222011-06-30 23:25:47 +02001358 support.create_empty_file(os.path.join(self.bdir, fn))
Victor Stinnere8d51452010-08-19 01:05:19 +00001359 fn = os.fsdecode(fn)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001360 if fn in self.unicodefn:
1361 raise ValueError("duplicate filename")
1362 self.unicodefn.add(fn)
1363 except:
1364 shutil.rmtree(self.dir)
1365 raise
Martin v. Löwis011e8422009-05-05 04:43:17 +00001366
1367 def tearDown(self):
1368 shutil.rmtree(self.dir)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001369
1370 def test_listdir(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001371 expected = self.unicodefn
1372 found = set(os.listdir(self.dir))
Ezio Melottib3aedd42010-11-20 19:04:17 +00001373 self.assertEqual(found, expected)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001374 # test listdir without arguments
1375 current_directory = os.getcwd()
1376 try:
1377 os.chdir(os.sep)
1378 self.assertEqual(set(os.listdir()), set(os.listdir(os.sep)))
1379 finally:
1380 os.chdir(current_directory)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001381
1382 def test_open(self):
1383 for fn in self.unicodefn:
Victor Stinnera6d2c762011-06-30 18:20:11 +02001384 f = open(os.path.join(self.dir, fn), 'rb')
Martin v. Löwis011e8422009-05-05 04:43:17 +00001385 f.close()
1386
Victor Stinnere4110dc2013-01-01 23:05:55 +01001387 @unittest.skipUnless(hasattr(os, 'statvfs'),
1388 "need os.statvfs()")
1389 def test_statvfs(self):
1390 # issue #9645
1391 for fn in self.unicodefn:
1392 # should not fail with file not found error
1393 fullname = os.path.join(self.dir, fn)
1394 os.statvfs(fullname)
1395
Martin v. Löwis011e8422009-05-05 04:43:17 +00001396 def test_stat(self):
1397 for fn in self.unicodefn:
1398 os.stat(os.path.join(self.dir, fn))
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001399else:
1400 class PosixUidGidTests(unittest.TestCase):
1401 pass
Martin v. Löwis011e8422009-05-05 04:43:17 +00001402 class Pep383Tests(unittest.TestCase):
1403 pass
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001404
Brian Curtineb24d742010-04-12 17:16:38 +00001405@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
1406class Win32KillTests(unittest.TestCase):
Brian Curtinc3acbc32010-05-28 16:08:40 +00001407 def _kill(self, sig):
1408 # Start sys.executable as a subprocess and communicate from the
1409 # subprocess to the parent that the interpreter is ready. When it
1410 # becomes ready, send *sig* via os.kill to the subprocess and check
1411 # that the return code is equal to *sig*.
1412 import ctypes
1413 from ctypes import wintypes
1414 import msvcrt
1415
1416 # Since we can't access the contents of the process' stdout until the
1417 # process has exited, use PeekNamedPipe to see what's inside stdout
1418 # without waiting. This is done so we can tell that the interpreter
1419 # is started and running at a point where it could handle a signal.
1420 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
1421 PeekNamedPipe.restype = wintypes.BOOL
1422 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
1423 ctypes.POINTER(ctypes.c_char), # stdout buf
1424 wintypes.DWORD, # Buffer size
1425 ctypes.POINTER(wintypes.DWORD), # bytes read
1426 ctypes.POINTER(wintypes.DWORD), # bytes avail
1427 ctypes.POINTER(wintypes.DWORD)) # bytes left
1428 msg = "running"
1429 proc = subprocess.Popen([sys.executable, "-c",
1430 "import sys;"
1431 "sys.stdout.write('{}');"
1432 "sys.stdout.flush();"
1433 "input()".format(msg)],
1434 stdout=subprocess.PIPE,
1435 stderr=subprocess.PIPE,
1436 stdin=subprocess.PIPE)
Brian Curtin43ec5772010-11-05 15:17:11 +00001437 self.addCleanup(proc.stdout.close)
1438 self.addCleanup(proc.stderr.close)
1439 self.addCleanup(proc.stdin.close)
Brian Curtinc3acbc32010-05-28 16:08:40 +00001440
1441 count, max = 0, 100
1442 while count < max and proc.poll() is None:
1443 # Create a string buffer to store the result of stdout from the pipe
1444 buf = ctypes.create_string_buffer(len(msg))
1445 # Obtain the text currently in proc.stdout
1446 # Bytes read/avail/left are left as NULL and unused
1447 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
1448 buf, ctypes.sizeof(buf), None, None, None)
1449 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
1450 if buf.value:
1451 self.assertEqual(msg, buf.value.decode())
1452 break
1453 time.sleep(0.1)
1454 count += 1
1455 else:
1456 self.fail("Did not receive communication from the subprocess")
1457
Brian Curtineb24d742010-04-12 17:16:38 +00001458 os.kill(proc.pid, sig)
1459 self.assertEqual(proc.wait(), sig)
1460
1461 def test_kill_sigterm(self):
1462 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinc3acbc32010-05-28 16:08:40 +00001463 self._kill(signal.SIGTERM)
Brian Curtineb24d742010-04-12 17:16:38 +00001464
1465 def test_kill_int(self):
1466 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinc3acbc32010-05-28 16:08:40 +00001467 self._kill(100)
Brian Curtineb24d742010-04-12 17:16:38 +00001468
1469 def _kill_with_event(self, event, name):
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001470 tagname = "test_os_%s" % uuid.uuid1()
1471 m = mmap.mmap(-1, 1, tagname)
1472 m[0] = 0
Brian Curtineb24d742010-04-12 17:16:38 +00001473 # Run a script which has console control handling enabled.
1474 proc = subprocess.Popen([sys.executable,
1475 os.path.join(os.path.dirname(__file__),
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001476 "win_console_handler.py"), tagname],
Brian Curtineb24d742010-04-12 17:16:38 +00001477 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
1478 # Let the interpreter startup before we send signals. See #3137.
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001479 count, max = 0, 100
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001480 while count < max and proc.poll() is None:
Brian Curtinf668df52010-10-15 14:21:06 +00001481 if m[0] == 1:
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001482 break
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001483 time.sleep(0.1)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001484 count += 1
1485 else:
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001486 # Forcefully kill the process if we weren't able to signal it.
1487 os.kill(proc.pid, signal.SIGINT)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001488 self.fail("Subprocess didn't finish initialization")
Brian Curtineb24d742010-04-12 17:16:38 +00001489 os.kill(proc.pid, event)
1490 # proc.send_signal(event) could also be done here.
1491 # Allow time for the signal to be passed and the process to exit.
1492 time.sleep(0.5)
1493 if not proc.poll():
1494 # Forcefully kill the process if we weren't able to signal it.
1495 os.kill(proc.pid, signal.SIGINT)
1496 self.fail("subprocess did not stop on {}".format(name))
1497
1498 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
1499 def test_CTRL_C_EVENT(self):
1500 from ctypes import wintypes
1501 import ctypes
1502
1503 # Make a NULL value by creating a pointer with no argument.
1504 NULL = ctypes.POINTER(ctypes.c_int)()
1505 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
1506 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
1507 wintypes.BOOL)
1508 SetConsoleCtrlHandler.restype = wintypes.BOOL
1509
1510 # Calling this with NULL and FALSE causes the calling process to
1511 # handle CTRL+C, rather than ignore it. This property is inherited
1512 # by subprocesses.
1513 SetConsoleCtrlHandler(NULL, 0)
1514
1515 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
1516
1517 def test_CTRL_BREAK_EVENT(self):
1518 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
1519
1520
Brian Curtind40e6f72010-07-08 21:39:08 +00001521@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Brian Curtin3b4499c2010-12-28 14:31:47 +00001522@support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +00001523class Win32SymlinkTests(unittest.TestCase):
1524 filelink = 'filelinktest'
1525 filelink_target = os.path.abspath(__file__)
1526 dirlink = 'dirlinktest'
1527 dirlink_target = os.path.dirname(filelink_target)
1528 missing_link = 'missing link'
1529
1530 def setUp(self):
1531 assert os.path.exists(self.dirlink_target)
1532 assert os.path.exists(self.filelink_target)
1533 assert not os.path.exists(self.dirlink)
1534 assert not os.path.exists(self.filelink)
1535 assert not os.path.exists(self.missing_link)
1536
1537 def tearDown(self):
1538 if os.path.exists(self.filelink):
1539 os.remove(self.filelink)
1540 if os.path.exists(self.dirlink):
1541 os.rmdir(self.dirlink)
1542 if os.path.lexists(self.missing_link):
1543 os.remove(self.missing_link)
1544
1545 def test_directory_link(self):
Jason R. Coombs3a092862013-05-27 23:21:28 -04001546 os.symlink(self.dirlink_target, self.dirlink)
Brian Curtind40e6f72010-07-08 21:39:08 +00001547 self.assertTrue(os.path.exists(self.dirlink))
1548 self.assertTrue(os.path.isdir(self.dirlink))
1549 self.assertTrue(os.path.islink(self.dirlink))
1550 self.check_stat(self.dirlink, self.dirlink_target)
1551
1552 def test_file_link(self):
1553 os.symlink(self.filelink_target, self.filelink)
1554 self.assertTrue(os.path.exists(self.filelink))
1555 self.assertTrue(os.path.isfile(self.filelink))
1556 self.assertTrue(os.path.islink(self.filelink))
1557 self.check_stat(self.filelink, self.filelink_target)
1558
1559 def _create_missing_dir_link(self):
1560 'Create a "directory" link to a non-existent target'
1561 linkname = self.missing_link
1562 if os.path.lexists(linkname):
1563 os.remove(linkname)
1564 target = r'c:\\target does not exist.29r3c740'
1565 assert not os.path.exists(target)
1566 target_is_dir = True
1567 os.symlink(target, linkname, target_is_dir)
1568
1569 def test_remove_directory_link_to_missing_target(self):
1570 self._create_missing_dir_link()
1571 # For compatibility with Unix, os.remove will check the
1572 # directory status and call RemoveDirectory if the symlink
1573 # was created with target_is_dir==True.
1574 os.remove(self.missing_link)
1575
1576 @unittest.skip("currently fails; consider for improvement")
1577 def test_isdir_on_directory_link_to_missing_target(self):
1578 self._create_missing_dir_link()
1579 # consider having isdir return true for directory links
1580 self.assertTrue(os.path.isdir(self.missing_link))
1581
1582 @unittest.skip("currently fails; consider for improvement")
1583 def test_rmdir_on_directory_link_to_missing_target(self):
1584 self._create_missing_dir_link()
1585 # consider allowing rmdir to remove directory links
1586 os.rmdir(self.missing_link)
1587
1588 def check_stat(self, link, target):
1589 self.assertEqual(os.stat(link), os.stat(target))
1590 self.assertNotEqual(os.lstat(link), os.stat(link))
1591
Brian Curtind25aef52011-06-13 15:16:04 -05001592 bytes_link = os.fsencode(link)
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001593 with warnings.catch_warnings():
1594 warnings.simplefilter("ignore", DeprecationWarning)
1595 self.assertEqual(os.stat(bytes_link), os.stat(target))
1596 self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link))
Brian Curtind25aef52011-06-13 15:16:04 -05001597
1598 def test_12084(self):
1599 level1 = os.path.abspath(support.TESTFN)
1600 level2 = os.path.join(level1, "level2")
1601 level3 = os.path.join(level2, "level3")
1602 try:
1603 os.mkdir(level1)
1604 os.mkdir(level2)
1605 os.mkdir(level3)
1606
1607 file1 = os.path.abspath(os.path.join(level1, "file1"))
1608
1609 with open(file1, "w") as f:
1610 f.write("file1")
1611
1612 orig_dir = os.getcwd()
1613 try:
1614 os.chdir(level2)
1615 link = os.path.join(level2, "link")
1616 os.symlink(os.path.relpath(file1), "link")
1617 self.assertIn("link", os.listdir(os.getcwd()))
1618
1619 # Check os.stat calls from the same dir as the link
1620 self.assertEqual(os.stat(file1), os.stat("link"))
1621
1622 # Check os.stat calls from a dir below the link
1623 os.chdir(level1)
1624 self.assertEqual(os.stat(file1),
1625 os.stat(os.path.relpath(link)))
1626
1627 # Check os.stat calls from a dir above the link
1628 os.chdir(level3)
1629 self.assertEqual(os.stat(file1),
1630 os.stat(os.path.relpath(link)))
1631 finally:
1632 os.chdir(orig_dir)
1633 except OSError as err:
1634 self.fail(err)
1635 finally:
1636 os.remove(file1)
1637 shutil.rmtree(level1)
1638
Brian Curtind40e6f72010-07-08 21:39:08 +00001639
Jason R. Coombs3a092862013-05-27 23:21:28 -04001640@support.skip_unless_symlink
1641class NonLocalSymlinkTests(unittest.TestCase):
1642
1643 def setUp(self):
1644 """
1645 Create this structure:
1646
1647 base
1648 \___ some_dir
1649 """
1650 os.makedirs('base/some_dir')
1651
1652 def tearDown(self):
1653 shutil.rmtree('base')
1654
1655 def test_directory_link_nonlocal(self):
1656 """
1657 The symlink target should resolve relative to the link, not relative
1658 to the current directory.
1659
1660 Then, link base/some_link -> base/some_dir and ensure that some_link
1661 is resolved as a directory.
1662
1663 In issue13772, it was discovered that directory detection failed if
1664 the symlink target was not specified relative to the current
1665 directory, which was a defect in the implementation.
1666 """
1667 src = os.path.join('base', 'some_link')
1668 os.symlink('some_dir', src)
1669 assert os.path.isdir(src)
1670
1671
Victor Stinnere8d51452010-08-19 01:05:19 +00001672class FSEncodingTests(unittest.TestCase):
1673 def test_nop(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001674 self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
1675 self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
Benjamin Peterson31191a92010-05-09 03:22:58 +00001676
Victor Stinnere8d51452010-08-19 01:05:19 +00001677 def test_identity(self):
1678 # assert fsdecode(fsencode(x)) == x
1679 for fn in ('unicode\u0141', 'latin\xe9', 'ascii'):
1680 try:
1681 bytesfn = os.fsencode(fn)
1682 except UnicodeEncodeError:
1683 continue
Ezio Melottib3aedd42010-11-20 19:04:17 +00001684 self.assertEqual(os.fsdecode(bytesfn), fn)
Victor Stinnere8d51452010-08-19 01:05:19 +00001685
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00001686
Brett Cannonefb00c02012-02-29 18:31:31 -05001687
1688class DeviceEncodingTests(unittest.TestCase):
1689
1690 def test_bad_fd(self):
1691 # Return None when an fd doesn't actually exist.
1692 self.assertIsNone(os.device_encoding(123456))
1693
Philip Jenveye308b7c2012-02-29 16:16:15 -08001694 @unittest.skipUnless(os.isatty(0) and (sys.platform.startswith('win') or
1695 (hasattr(locale, 'nl_langinfo') and hasattr(locale, 'CODESET'))),
Philip Jenveyd7aff2d2012-02-29 16:21:25 -08001696 'test requires a tty and either Windows or nl_langinfo(CODESET)')
Brett Cannonefb00c02012-02-29 18:31:31 -05001697 def test_device_encoding(self):
1698 encoding = os.device_encoding(0)
1699 self.assertIsNotNone(encoding)
1700 self.assertTrue(codecs.lookup(encoding))
1701
1702
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00001703class PidTests(unittest.TestCase):
1704 @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid")
1705 def test_getppid(self):
1706 p = subprocess.Popen([sys.executable, '-c',
1707 'import os; print(os.getppid())'],
1708 stdout=subprocess.PIPE)
1709 stdout, _ = p.communicate()
1710 # We are the parent of our subprocess
1711 self.assertEqual(int(stdout), os.getpid())
1712
1713
Brian Curtin0151b8e2010-09-24 13:43:43 +00001714# The introduction of this TestCase caused at least two different errors on
1715# *nix buildbots. Temporarily skip this to let the buildbots move along.
1716@unittest.skip("Skip due to platform/environment differences on *NIX buildbots")
Brian Curtine8e4b3b2010-09-23 20:04:14 +00001717@unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin")
1718class LoginTests(unittest.TestCase):
1719 def test_getlogin(self):
1720 user_name = os.getlogin()
1721 self.assertNotEqual(len(user_name), 0)
1722
1723
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001724@unittest.skipUnless(hasattr(os, 'getpriority') and hasattr(os, 'setpriority'),
1725 "needs os.getpriority and os.setpriority")
1726class ProgramPriorityTests(unittest.TestCase):
1727 """Tests for os.getpriority() and os.setpriority()."""
1728
1729 def test_set_get_priority(self):
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001730
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001731 base = os.getpriority(os.PRIO_PROCESS, os.getpid())
1732 os.setpriority(os.PRIO_PROCESS, os.getpid(), base + 1)
1733 try:
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001734 new_prio = os.getpriority(os.PRIO_PROCESS, os.getpid())
1735 if base >= 19 and new_prio <= 19:
1736 raise unittest.SkipTest(
1737 "unable to reliably test setpriority at current nice level of %s" % base)
1738 else:
1739 self.assertEqual(new_prio, base + 1)
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001740 finally:
1741 try:
1742 os.setpriority(os.PRIO_PROCESS, os.getpid(), base)
1743 except OSError as err:
Antoine Pitrou692f0382011-02-26 00:22:25 +00001744 if err.errno != errno.EACCES:
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001745 raise
1746
1747
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001748if threading is not None:
1749 class SendfileTestServer(asyncore.dispatcher, threading.Thread):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001750
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001751 class Handler(asynchat.async_chat):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001752
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001753 def __init__(self, conn):
1754 asynchat.async_chat.__init__(self, conn)
1755 self.in_buffer = []
1756 self.closed = False
1757 self.push(b"220 ready\r\n")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001758
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001759 def handle_read(self):
1760 data = self.recv(4096)
1761 self.in_buffer.append(data)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001762
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001763 def get_data(self):
1764 return b''.join(self.in_buffer)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001765
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001766 def handle_close(self):
1767 self.close()
1768 self.closed = True
1769
1770 def handle_error(self):
1771 raise
1772
1773 def __init__(self, address):
1774 threading.Thread.__init__(self)
1775 asyncore.dispatcher.__init__(self)
1776 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
1777 self.bind(address)
1778 self.listen(5)
1779 self.host, self.port = self.socket.getsockname()[:2]
1780 self.handler_instance = None
1781 self._active = False
1782 self._active_lock = threading.Lock()
1783
1784 # --- public API
1785
1786 @property
1787 def running(self):
1788 return self._active
1789
1790 def start(self):
1791 assert not self.running
1792 self.__flag = threading.Event()
1793 threading.Thread.start(self)
1794 self.__flag.wait()
1795
1796 def stop(self):
1797 assert self.running
1798 self._active = False
1799 self.join()
1800
1801 def wait(self):
1802 # wait for handler connection to be closed, then stop the server
1803 while not getattr(self.handler_instance, "closed", False):
1804 time.sleep(0.001)
1805 self.stop()
1806
1807 # --- internals
1808
1809 def run(self):
1810 self._active = True
1811 self.__flag.set()
1812 while self._active and asyncore.socket_map:
1813 self._active_lock.acquire()
1814 asyncore.loop(timeout=0.001, count=1)
1815 self._active_lock.release()
1816 asyncore.close_all()
1817
1818 def handle_accept(self):
1819 conn, addr = self.accept()
1820 self.handler_instance = self.Handler(conn)
1821
1822 def handle_connect(self):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001823 self.close()
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001824 handle_read = handle_connect
1825
1826 def writable(self):
1827 return 0
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001828
1829 def handle_error(self):
1830 raise
1831
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001832
Giampaolo Rodolà46134642011-02-25 20:01:05 +00001833@unittest.skipUnless(threading is not None, "test needs threading module")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001834@unittest.skipUnless(hasattr(os, 'sendfile'), "test needs os.sendfile()")
1835class TestSendfile(unittest.TestCase):
1836
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001837 DATA = b"12345abcde" * 16 * 1024 # 160 KB
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001838 SUPPORT_HEADERS_TRAILERS = not sys.platform.startswith("linux") and \
Giampaolo Rodolà4bc68572011-02-25 21:46:01 +00001839 not sys.platform.startswith("solaris") and \
1840 not sys.platform.startswith("sunos")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001841
1842 @classmethod
1843 def setUpClass(cls):
1844 with open(support.TESTFN, "wb") as f:
1845 f.write(cls.DATA)
1846
1847 @classmethod
1848 def tearDownClass(cls):
1849 support.unlink(support.TESTFN)
1850
1851 def setUp(self):
1852 self.server = SendfileTestServer((support.HOST, 0))
1853 self.server.start()
1854 self.client = socket.socket()
1855 self.client.connect((self.server.host, self.server.port))
1856 self.client.settimeout(1)
1857 # synchronize by waiting for "220 ready" response
1858 self.client.recv(1024)
1859 self.sockno = self.client.fileno()
1860 self.file = open(support.TESTFN, 'rb')
1861 self.fileno = self.file.fileno()
1862
1863 def tearDown(self):
1864 self.file.close()
1865 self.client.close()
1866 if self.server.running:
1867 self.server.stop()
1868
1869 def sendfile_wrapper(self, sock, file, offset, nbytes, headers=[], trailers=[]):
1870 """A higher level wrapper representing how an application is
1871 supposed to use sendfile().
1872 """
1873 while 1:
1874 try:
1875 if self.SUPPORT_HEADERS_TRAILERS:
1876 return os.sendfile(sock, file, offset, nbytes, headers,
1877 trailers)
1878 else:
1879 return os.sendfile(sock, file, offset, nbytes)
1880 except OSError as err:
1881 if err.errno == errno.ECONNRESET:
1882 # disconnected
1883 raise
1884 elif err.errno in (errno.EAGAIN, errno.EBUSY):
1885 # we have to retry send data
1886 continue
1887 else:
1888 raise
1889
1890 def test_send_whole_file(self):
1891 # normal send
1892 total_sent = 0
1893 offset = 0
1894 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001895 while total_sent < len(self.DATA):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001896 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
1897 if sent == 0:
1898 break
1899 offset += sent
1900 total_sent += sent
1901 self.assertTrue(sent <= nbytes)
1902 self.assertEqual(offset, total_sent)
1903
1904 self.assertEqual(total_sent, len(self.DATA))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001905 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001906 self.client.close()
1907 self.server.wait()
1908 data = self.server.handler_instance.get_data()
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001909 self.assertEqual(len(data), len(self.DATA))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001910 self.assertEqual(data, self.DATA)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001911
1912 def test_send_at_certain_offset(self):
1913 # start sending a file at a certain offset
1914 total_sent = 0
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001915 offset = len(self.DATA) // 2
1916 must_send = len(self.DATA) - offset
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001917 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001918 while total_sent < must_send:
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001919 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
1920 if sent == 0:
1921 break
1922 offset += sent
1923 total_sent += sent
1924 self.assertTrue(sent <= nbytes)
1925
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001926 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001927 self.client.close()
1928 self.server.wait()
1929 data = self.server.handler_instance.get_data()
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001930 expected = self.DATA[len(self.DATA) // 2:]
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001931 self.assertEqual(total_sent, len(expected))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001932 self.assertEqual(len(data), len(expected))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001933 self.assertEqual(data, expected)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001934
1935 def test_offset_overflow(self):
1936 # specify an offset > file size
1937 offset = len(self.DATA) + 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001938 try:
1939 sent = os.sendfile(self.sockno, self.fileno, offset, 4096)
1940 except OSError as e:
1941 # Solaris can raise EINVAL if offset >= file length, ignore.
1942 if e.errno != errno.EINVAL:
1943 raise
1944 else:
1945 self.assertEqual(sent, 0)
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001946 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001947 self.client.close()
1948 self.server.wait()
1949 data = self.server.handler_instance.get_data()
1950 self.assertEqual(data, b'')
1951
1952 def test_invalid_offset(self):
1953 with self.assertRaises(OSError) as cm:
1954 os.sendfile(self.sockno, self.fileno, -1, 4096)
1955 self.assertEqual(cm.exception.errno, errno.EINVAL)
1956
1957 # --- headers / trailers tests
1958
1959 if SUPPORT_HEADERS_TRAILERS:
1960
1961 def test_headers(self):
1962 total_sent = 0
1963 sent = os.sendfile(self.sockno, self.fileno, 0, 4096,
1964 headers=[b"x" * 512])
1965 total_sent += sent
1966 offset = 4096
1967 nbytes = 4096
1968 while 1:
1969 sent = self.sendfile_wrapper(self.sockno, self.fileno,
1970 offset, nbytes)
1971 if sent == 0:
1972 break
1973 total_sent += sent
1974 offset += sent
1975
1976 expected_data = b"x" * 512 + self.DATA
1977 self.assertEqual(total_sent, len(expected_data))
1978 self.client.close()
1979 self.server.wait()
1980 data = self.server.handler_instance.get_data()
1981 self.assertEqual(hash(data), hash(expected_data))
1982
1983 def test_trailers(self):
1984 TESTFN2 = support.TESTFN + "2"
Victor Stinner5e4d6392013-08-15 11:57:02 +02001985 file_data = b"abcdef"
Brett Cannonb6376802011-03-15 17:38:22 -04001986 with open(TESTFN2, 'wb') as f:
Victor Stinner5e4d6392013-08-15 11:57:02 +02001987 f.write(file_data)
Brett Cannonb6376802011-03-15 17:38:22 -04001988 with open(TESTFN2, 'rb')as f:
1989 self.addCleanup(os.remove, TESTFN2)
Victor Stinner5e4d6392013-08-15 11:57:02 +02001990 os.sendfile(self.sockno, f.fileno(), 0, len(file_data),
1991 trailers=[b"1234"])
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001992 self.client.close()
1993 self.server.wait()
1994 data = self.server.handler_instance.get_data()
Victor Stinner5e4d6392013-08-15 11:57:02 +02001995 self.assertEqual(data, b"abcdef1234")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001996
1997 if hasattr(os, "SF_NODISKIO"):
1998 def test_flags(self):
1999 try:
2000 os.sendfile(self.sockno, self.fileno, 0, 4096,
2001 flags=os.SF_NODISKIO)
2002 except OSError as err:
2003 if err.errno not in (errno.EBUSY, errno.EAGAIN):
2004 raise
2005
2006
Larry Hastings9cf065c2012-06-22 16:30:09 -07002007def supports_extended_attributes():
2008 if not hasattr(os, "setxattr"):
2009 return False
2010 try:
2011 with open(support.TESTFN, "wb") as fp:
2012 try:
2013 os.setxattr(fp.fileno(), b"user.test", b"")
2014 except OSError:
2015 return False
2016 finally:
2017 support.unlink(support.TESTFN)
2018 # Kernels < 2.6.39 don't respect setxattr flags.
2019 kernel_version = platform.release()
2020 m = re.match("2.6.(\d{1,2})", kernel_version)
2021 return m is None or int(m.group(1)) >= 39
2022
2023
2024@unittest.skipUnless(supports_extended_attributes(),
2025 "no non-broken extended attribute support")
Benjamin Peterson799bd802011-08-31 22:15:17 -04002026class ExtendedAttributeTests(unittest.TestCase):
2027
2028 def tearDown(self):
2029 support.unlink(support.TESTFN)
2030
Larry Hastings9cf065c2012-06-22 16:30:09 -07002031 def _check_xattrs_str(self, s, getxattr, setxattr, removexattr, listxattr, **kwargs):
Benjamin Peterson799bd802011-08-31 22:15:17 -04002032 fn = support.TESTFN
2033 open(fn, "wb").close()
2034 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002035 getxattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002036 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002037 init_xattr = listxattr(fn)
2038 self.assertIsInstance(init_xattr, list)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002039 setxattr(fn, s("user.test"), b"", **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002040 xattr = set(init_xattr)
2041 xattr.add("user.test")
2042 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002043 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"")
2044 setxattr(fn, s("user.test"), b"hello", os.XATTR_REPLACE, **kwargs)
2045 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"hello")
Benjamin Peterson799bd802011-08-31 22:15:17 -04002046 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002047 setxattr(fn, s("user.test"), b"bye", os.XATTR_CREATE, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002048 self.assertEqual(cm.exception.errno, errno.EEXIST)
2049 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002050 setxattr(fn, s("user.test2"), b"bye", os.XATTR_REPLACE, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002051 self.assertEqual(cm.exception.errno, errno.ENODATA)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002052 setxattr(fn, s("user.test2"), b"foo", os.XATTR_CREATE, **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002053 xattr.add("user.test2")
2054 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002055 removexattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002056 with self.assertRaises(OSError) as cm:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002057 getxattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002058 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002059 xattr.remove("user.test")
2060 self.assertEqual(set(listxattr(fn)), xattr)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002061 self.assertEqual(getxattr(fn, s("user.test2"), **kwargs), b"foo")
2062 setxattr(fn, s("user.test"), b"a"*1024, **kwargs)
2063 self.assertEqual(getxattr(fn, s("user.test"), **kwargs), b"a"*1024)
2064 removexattr(fn, s("user.test"), **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002065 many = sorted("user.test{}".format(i) for i in range(100))
2066 for thing in many:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002067 setxattr(fn, thing, b"x", **kwargs)
Victor Stinnerf12e5062011-10-16 22:12:03 +02002068 self.assertEqual(set(listxattr(fn)), set(init_xattr) | set(many))
Benjamin Peterson799bd802011-08-31 22:15:17 -04002069
Larry Hastings9cf065c2012-06-22 16:30:09 -07002070 def _check_xattrs(self, *args, **kwargs):
Benjamin Peterson799bd802011-08-31 22:15:17 -04002071 def make_bytes(s):
2072 return bytes(s, "ascii")
Larry Hastings9cf065c2012-06-22 16:30:09 -07002073 self._check_xattrs_str(str, *args, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002074 support.unlink(support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002075 self._check_xattrs_str(make_bytes, *args, **kwargs)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002076
2077 def test_simple(self):
2078 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
2079 os.listxattr)
2080
2081 def test_lpath(self):
Larry Hastings9cf065c2012-06-22 16:30:09 -07002082 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
2083 os.listxattr, follow_symlinks=False)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002084
2085 def test_fds(self):
2086 def getxattr(path, *args):
2087 with open(path, "rb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002088 return os.getxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002089 def setxattr(path, *args):
2090 with open(path, "wb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002091 os.setxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002092 def removexattr(path, *args):
2093 with open(path, "wb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002094 os.removexattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002095 def listxattr(path, *args):
2096 with open(path, "rb") as fp:
Larry Hastings9cf065c2012-06-22 16:30:09 -07002097 return os.listxattr(fp.fileno(), *args)
Benjamin Peterson799bd802011-08-31 22:15:17 -04002098 self._check_xattrs(getxattr, setxattr, removexattr, listxattr)
2099
2100
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002101@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
2102class Win32DeprecatedBytesAPI(unittest.TestCase):
2103 def test_deprecated(self):
2104 import nt
2105 filename = os.fsencode(support.TESTFN)
2106 with warnings.catch_warnings():
2107 warnings.simplefilter("error", DeprecationWarning)
2108 for func, *args in (
2109 (nt._getfullpathname, filename),
2110 (nt._isdir, filename),
2111 (os.access, filename, os.R_OK),
2112 (os.chdir, filename),
2113 (os.chmod, filename, 0o777),
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01002114 (os.getcwdb,),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002115 (os.link, filename, filename),
2116 (os.listdir, filename),
2117 (os.lstat, filename),
2118 (os.mkdir, filename),
2119 (os.open, filename, os.O_RDONLY),
2120 (os.rename, filename, filename),
2121 (os.rmdir, filename),
2122 (os.startfile, filename),
2123 (os.stat, filename),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002124 (os.unlink, filename),
2125 (os.utime, filename),
2126 ):
2127 self.assertRaises(DeprecationWarning, func, *args)
2128
Victor Stinner28216442011-11-16 00:34:44 +01002129 @support.skip_unless_symlink
2130 def test_symlink(self):
2131 filename = os.fsencode(support.TESTFN)
2132 with warnings.catch_warnings():
2133 warnings.simplefilter("error", DeprecationWarning)
2134 self.assertRaises(DeprecationWarning,
2135 os.symlink, filename, filename)
2136
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002137
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002138@unittest.skipUnless(hasattr(os, 'get_terminal_size'), "requires os.get_terminal_size")
2139class TermsizeTests(unittest.TestCase):
2140 def test_does_not_crash(self):
2141 """Check if get_terminal_size() returns a meaningful value.
2142
2143 There's no easy portable way to actually check the size of the
2144 terminal, so let's check if it returns something sensible instead.
2145 """
2146 try:
2147 size = os.get_terminal_size()
2148 except OSError as e:
Antoine Pitrou81a1fa52012-02-09 00:11:00 +01002149 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002150 # Under win32 a generic OSError can be thrown if the
2151 # handle cannot be retrieved
2152 self.skipTest("failed to query terminal size")
2153 raise
2154
Antoine Pitroucfade362012-02-08 23:48:59 +01002155 self.assertGreaterEqual(size.columns, 0)
2156 self.assertGreaterEqual(size.lines, 0)
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002157
2158 def test_stty_match(self):
2159 """Check if stty returns the same results
2160
2161 stty actually tests stdin, so get_terminal_size is invoked on
2162 stdin explicitly. If stty succeeded, then get_terminal_size()
2163 should work too.
2164 """
2165 try:
2166 size = subprocess.check_output(['stty', 'size']).decode().split()
2167 except (FileNotFoundError, subprocess.CalledProcessError):
2168 self.skipTest("stty invocation failed")
2169 expected = (int(size[1]), int(size[0])) # reversed order
2170
Antoine Pitrou81a1fa52012-02-09 00:11:00 +01002171 try:
2172 actual = os.get_terminal_size(sys.__stdin__.fileno())
2173 except OSError as e:
2174 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
2175 # Under win32 a generic OSError can be thrown if the
2176 # handle cannot be retrieved
2177 self.skipTest("failed to query terminal size")
2178 raise
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002179 self.assertEqual(expected, actual)
2180
2181
Antoine Pitrouf26ad712011-07-15 23:00:56 +02002182@support.reap_threads
Fred Drake2e2be372001-09-20 21:33:42 +00002183def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002184 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002185 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002186 StatAttributeTests,
2187 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00002188 WalkTests,
Charles-François Natali7372b062012-02-05 15:15:38 +01002189 FwalkTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00002190 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +00002191 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002192 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +00002193 ExecTests,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00002194 Win32ErrorTests,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002195 TestInvalidFD,
Martin v. Löwis011e8422009-05-05 04:43:17 +00002196 PosixUidGidTests,
Brian Curtineb24d742010-04-12 17:16:38 +00002197 Pep383Tests,
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00002198 Win32KillTests,
Brian Curtind40e6f72010-07-08 21:39:08 +00002199 Win32SymlinkTests,
Jason R. Coombs3a092862013-05-27 23:21:28 -04002200 NonLocalSymlinkTests,
Victor Stinnere8d51452010-08-19 01:05:19 +00002201 FSEncodingTests,
Brett Cannonefb00c02012-02-29 18:31:31 -05002202 DeviceEncodingTests,
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00002203 PidTests,
Brian Curtine8e4b3b2010-09-23 20:04:14 +00002204 LoginTests,
Brian Curtin1b9df392010-11-24 20:24:31 +00002205 LinkTests,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00002206 TestSendfile,
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00002207 ProgramPriorityTests,
Benjamin Peterson799bd802011-08-31 22:15:17 -04002208 ExtendedAttributeTests,
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01002209 Win32DeprecatedBytesAPI,
Antoine Pitroubcf2b592012-02-08 23:28:36 +01002210 TermsizeTests,
Andrew Svetlov405faed2012-12-25 12:18:09 +02002211 RemoveDirsTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002212 )
Fred Drake2e2be372001-09-20 21:33:42 +00002213
2214if __name__ == "__main__":
2215 test_main()