blob: 7d8712a999372c86c8ef20f72f9056d7b9651d0e [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
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000025try:
26 import threading
27except ImportError:
28 threading = None
Fred Drake38c2ef02001-07-17 20:52:51 +000029
Mark Dickinson7cf03892010-04-16 13:45:35 +000030# Detect whether we're on a Linux system that uses the (now outdated
31# and unmaintained) linuxthreads threading library. There's an issue
32# when combining linuxthreads with a failed execv call: see
33# http://bugs.python.org/issue4970.
Victor Stinnerd5c355c2011-04-30 14:53:09 +020034if hasattr(sys, 'thread_info') and sys.thread_info.version:
35 USING_LINUXTHREADS = sys.thread_info.version.startswith("linuxthreads")
36else:
37 USING_LINUXTHREADS = False
Brian Curtineb24d742010-04-12 17:16:38 +000038
Thomas Wouters0e3f5912006-08-11 14:57:12 +000039# Tests creating TESTFN
40class FileTests(unittest.TestCase):
41 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000042 if os.path.exists(support.TESTFN):
43 os.unlink(support.TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000044 tearDown = setUp
45
46 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000047 f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000048 os.close(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000049 self.assertTrue(os.access(support.TESTFN, os.W_OK))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000050
Christian Heimesfdab48e2008-01-20 09:06:41 +000051 def test_closerange(self):
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000052 first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
53 # We must allocate two consecutive file descriptors, otherwise
54 # it will mess up other file descriptors (perhaps even the three
55 # standard ones).
56 second = os.dup(first)
57 try:
58 retries = 0
59 while second != first + 1:
60 os.close(first)
61 retries += 1
62 if retries > 10:
63 # XXX test skipped
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000064 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000065 first, second = second, os.dup(second)
66 finally:
67 os.close(second)
Christian Heimesfdab48e2008-01-20 09:06:41 +000068 # close a fd that is open, and one that isn't
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000069 os.closerange(first, first + 2)
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000070 self.assertRaises(OSError, os.write, first, b"a")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000071
Benjamin Peterson1cc6df92010-06-30 17:39:45 +000072 @support.cpython_only
Hirokazu Yamamoto4c19e6e2008-09-08 23:41:21 +000073 def test_rename(self):
74 path = support.TESTFN
75 old = sys.getrefcount(path)
76 self.assertRaises(TypeError, os.rename, path, 0)
77 new = sys.getrefcount(path)
78 self.assertEqual(old, new)
79
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000080 def test_read(self):
81 with open(support.TESTFN, "w+b") as fobj:
82 fobj.write(b"spam")
83 fobj.flush()
84 fd = fobj.fileno()
85 os.lseek(fd, 0, 0)
86 s = os.read(fd, 4)
87 self.assertEqual(type(s), bytes)
88 self.assertEqual(s, b"spam")
89
90 def test_write(self):
91 # os.write() accepts bytes- and buffer-like objects but not strings
92 fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY)
93 self.assertRaises(TypeError, os.write, fd, "beans")
94 os.write(fd, b"bacon\n")
95 os.write(fd, bytearray(b"eggs\n"))
96 os.write(fd, memoryview(b"spam\n"))
97 os.close(fd)
98 with open(support.TESTFN, "rb") as fobj:
Antoine Pitroud62269f2008-09-15 23:54:52 +000099 self.assertEqual(fobj.read().splitlines(),
100 [b"bacon", b"eggs", b"spam"])
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000101
Victor Stinnere0daff12011-03-20 23:36:35 +0100102 def write_windows_console(self, *args):
103 retcode = subprocess.call(args,
104 # use a new console to not flood the test output
105 creationflags=subprocess.CREATE_NEW_CONSOLE,
106 # use a shell to hide the console window (SW_HIDE)
107 shell=True)
108 self.assertEqual(retcode, 0)
109
110 @unittest.skipUnless(sys.platform == 'win32',
111 'test specific to the Windows console')
112 def test_write_windows_console(self):
113 # Issue #11395: the Windows console returns an error (12: not enough
114 # space error) on writing into stdout if stdout mode is binary and the
115 # length is greater than 66,000 bytes (or less, depending on heap
116 # usage).
117 code = "print('x' * 100000)"
118 self.write_windows_console(sys.executable, "-c", code)
119 self.write_windows_console(sys.executable, "-u", "-c", code)
120
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000121 def fdopen_helper(self, *args):
122 fd = os.open(support.TESTFN, os.O_RDONLY)
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200123 f = os.fdopen(fd, *args)
124 f.close()
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000125
126 def test_fdopen(self):
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200127 fd = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
128 os.close(fd)
129
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000130 self.fdopen_helper()
131 self.fdopen_helper('r')
132 self.fdopen_helper('r', 100)
133
Antoine Pitrouf3b2d882012-01-30 22:08:52 +0100134 def test_replace(self):
135 TESTFN2 = support.TESTFN + ".2"
136 with open(support.TESTFN, 'w') as f:
137 f.write("1")
138 with open(TESTFN2, 'w') as f:
139 f.write("2")
140 self.addCleanup(os.unlink, TESTFN2)
141 os.replace(support.TESTFN, TESTFN2)
142 self.assertRaises(FileNotFoundError, os.stat, support.TESTFN)
143 with open(TESTFN2, 'r') as f:
144 self.assertEqual(f.read(), "1")
145
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200146
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000147# Test attributes on return values from os.*stat* family.
148class StatAttributeTests(unittest.TestCase):
149 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000150 os.mkdir(support.TESTFN)
151 self.fname = os.path.join(support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000152 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +0000153 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000154 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000155
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000156 def tearDown(self):
157 os.unlink(self.fname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000158 os.rmdir(support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000159
Antoine Pitrou38425292010-09-21 18:19:07 +0000160 def check_stat_attributes(self, fname):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000161 if not hasattr(os, "stat"):
162 return
163
Antoine Pitrou38425292010-09-21 18:19:07 +0000164 result = os.stat(fname)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000165
166 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000167 self.assertEqual(result[stat.ST_SIZE], 3)
168 self.assertEqual(result.st_size, 3)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000169
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000170 # Make sure all the attributes are there
171 members = dir(result)
172 for name in dir(stat):
173 if name[:3] == 'ST_':
174 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000175 if name.endswith("TIME"):
176 def trunc(x): return int(x)
177 else:
178 def trunc(x): return x
Ezio Melottib3aedd42010-11-20 19:04:17 +0000179 self.assertEqual(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000180 result[getattr(stat, name)])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000181 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000182
183 try:
184 result[200]
185 self.fail("No exception thrown")
186 except IndexError:
187 pass
188
189 # Make sure that assignment fails
190 try:
191 result.st_mode = 1
192 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000193 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000194 pass
195
196 try:
197 result.st_rdev = 1
198 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000199 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000200 pass
201
202 try:
203 result.parrot = 1
204 self.fail("No exception thrown")
205 except AttributeError:
206 pass
207
208 # Use the stat_result constructor with a too-short tuple.
209 try:
210 result2 = os.stat_result((10,))
211 self.fail("No exception thrown")
212 except TypeError:
213 pass
214
Ezio Melotti42da6632011-03-15 05:18:48 +0200215 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000216 try:
217 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
218 except TypeError:
219 pass
220
Antoine Pitrou38425292010-09-21 18:19:07 +0000221 def test_stat_attributes(self):
222 self.check_stat_attributes(self.fname)
223
224 def test_stat_attributes_bytes(self):
225 try:
226 fname = self.fname.encode(sys.getfilesystemencoding())
227 except UnicodeEncodeError:
228 self.skipTest("cannot encode %a for the filesystem" % self.fname)
Victor Stinner1ab6c2d2011-11-15 22:27:41 +0100229 with warnings.catch_warnings():
230 warnings.simplefilter("ignore", DeprecationWarning)
231 self.check_stat_attributes(fname)
Tim Peterse0c446b2001-10-18 21:57:37 +0000232
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000233 def test_statvfs_attributes(self):
234 if not hasattr(os, "statvfs"):
235 return
236
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000237 try:
238 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000239 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000240 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000241 if e.errno == errno.ENOSYS:
242 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000243
244 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000245 self.assertEqual(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000246
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000247 # Make sure all the attributes are there.
248 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
249 'ffree', 'favail', 'flag', 'namemax')
250 for value, member in enumerate(members):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000251 self.assertEqual(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000252
253 # Make sure that assignment really fails
254 try:
255 result.f_bfree = 1
256 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000257 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000258 pass
259
260 try:
261 result.parrot = 1
262 self.fail("No exception thrown")
263 except AttributeError:
264 pass
265
266 # Use the constructor with a too-short tuple.
267 try:
268 result2 = os.statvfs_result((10,))
269 self.fail("No exception thrown")
270 except TypeError:
271 pass
272
Ezio Melotti42da6632011-03-15 05:18:48 +0200273 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000274 try:
275 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
276 except TypeError:
277 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000278
Thomas Wouters89f507f2006-12-13 04:49:30 +0000279 def test_utime_dir(self):
280 delta = 1000000
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000281 st = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000282 # round to int, because some systems may support sub-second
283 # time stamps in stat, but not in utime.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000284 os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
285 st2 = os.stat(support.TESTFN)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000286 self.assertEqual(st2.st_mtime, int(st.st_mtime-delta))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000287
Brian Curtin52fbea12011-11-06 13:41:17 -0600288 def test_utime_noargs(self):
Brian Curtin0277aa32011-11-06 13:50:15 -0600289 # Issue #13327 removed the requirement to pass None as the
Brian Curtin52fbea12011-11-06 13:41:17 -0600290 # second argument. Check that the previous methods of passing
291 # a time tuple or None work in addition to no argument.
292 st = os.stat(support.TESTFN)
293 # Doesn't set anything new, but sets the time tuple way
294 os.utime(support.TESTFN, (st.st_atime, st.st_mtime))
295 # Set to the current time in the old explicit way.
296 os.utime(support.TESTFN, None)
297 st1 = os.stat(support.TESTFN)
298 # Set to the current time in the new way
299 os.utime(support.TESTFN)
300 st2 = os.stat(support.TESTFN)
301 self.assertAlmostEqual(st1.st_mtime, st2.st_mtime, delta=10)
302
Victor Stinnerbe557de2012-02-08 03:01:11 +0100303 def test_utime_subsecond(self):
304 asec, amsec = 1, 901
305 atime = asec + amsec * 1e-3
306 msec, mmsec = 5, 901
307 mtime = msec + mmsec * 1e-3
308 filename = self.fname
309 dirname = os.path.dirname(filename)
310 for func in ('utime', 'futimes', 'futimens', 'lutimes', 'utimensat'):
311 if not hasattr(os, func):
312 continue
313 os.utime(filename, (0, 0))
314 if func == 'utime':
315 os.utime(filename, (atime, mtime))
316 elif func == 'futimes':
317 with open(filename, "wb") as f:
318 os.futimes(f.fileno(), (atime, mtime))
319 os.utime(filename, (atime, mtime))
320 elif func == 'futimens':
321 with open(filename, "wb") as f:
322 os.futimens(f.fileno(),
323 (asec, amsec * 1000000),
324 (msec, mmsec * 1000000))
325 elif func == 'lutimes':
326 os.lutimes(filename, (atime, mtime))
327 else:
328 dirfd = os.open(dirname, os.O_RDONLY)
329 try:
330 os.utimensat(dirfd, os.path.basename(filename),
331 (asec, amsec * 1000000),
332 (msec, mmsec * 1000000))
333 finally:
334 os.close(dirfd)
335 st = os.stat(filename)
336 self.assertAlmostEqual(st.st_atime, atime, places=3)
337 self.assertAlmostEqual(st.st_mtime, mtime, places=3)
338
339
Thomas Wouters89f507f2006-12-13 04:49:30 +0000340 # Restrict test to Win32, since there is no guarantee other
341 # systems support centiseconds
342 if sys.platform == 'win32':
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000343 def get_file_system(path):
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000344 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000345 import ctypes
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000346 kernel32 = ctypes.windll.kernel32
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000347 buf = ctypes.create_unicode_buffer("", 100)
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000348 if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000349 return buf.value
350
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000351 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000352 def test_1565150(self):
353 t1 = 1159195039.25
354 os.utime(self.fname, (t1, t1))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000355 self.assertEqual(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000356
Amaury Forgeot d'Arca251a852011-01-03 00:19:11 +0000357 def test_large_time(self):
358 t1 = 5000000000 # some day in 2128
359 os.utime(self.fname, (t1, t1))
360 self.assertEqual(os.stat(self.fname).st_mtime, t1)
361
Guido van Rossumd8faa362007-04-27 19:54:29 +0000362 def test_1686475(self):
363 # Verify that an open file can be stat'ed
364 try:
365 os.stat(r"c:\pagefile.sys")
366 except WindowsError as e:
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000367 if e.errno == 2: # file does not exist; cannot run test
Guido van Rossumd8faa362007-04-27 19:54:29 +0000368 return
369 self.fail("Could not stat pagefile.sys")
370
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000371from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000372
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000373class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000374 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000375 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000376
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000377 def setUp(self):
378 self.__save = dict(os.environ)
Victor Stinnerb745a742010-05-18 17:17:23 +0000379 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000380 self.__saveb = dict(os.environb)
Christian Heimes90333392007-11-01 19:08:42 +0000381 for key, value in self._reference().items():
382 os.environ[key] = value
383
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000384 def tearDown(self):
385 os.environ.clear()
386 os.environ.update(self.__save)
Victor Stinnerb745a742010-05-18 17:17:23 +0000387 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000388 os.environb.clear()
389 os.environb.update(self.__saveb)
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000390
Christian Heimes90333392007-11-01 19:08:42 +0000391 def _reference(self):
392 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
393
394 def _empty_mapping(self):
395 os.environ.clear()
396 return os.environ
397
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000398 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000399 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000400 os.environ.clear()
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000401 if os.path.exists("/bin/sh"):
402 os.environ.update(HELLO="World")
Brian Curtin810921b2010-10-30 21:24:21 +0000403 with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
404 value = popen.read().strip()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000405 self.assertEqual(value, "World")
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000406
Christian Heimes1a13d592007-11-08 14:16:55 +0000407 def test_os_popen_iter(self):
408 if os.path.exists("/bin/sh"):
Brian Curtin810921b2010-10-30 21:24:21 +0000409 with os.popen(
410 "/bin/sh -c 'echo \"line1\nline2\nline3\"'") as popen:
411 it = iter(popen)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000412 self.assertEqual(next(it), "line1\n")
413 self.assertEqual(next(it), "line2\n")
414 self.assertEqual(next(it), "line3\n")
Brian Curtin810921b2010-10-30 21:24:21 +0000415 self.assertRaises(StopIteration, next, it)
Christian Heimes1a13d592007-11-08 14:16:55 +0000416
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000417 # Verify environ keys and values from the OS are of the
418 # correct str type.
419 def test_keyvalue_types(self):
420 for key, val in os.environ.items():
Ezio Melottib3aedd42010-11-20 19:04:17 +0000421 self.assertEqual(type(key), str)
422 self.assertEqual(type(val), str)
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000423
Christian Heimes90333392007-11-01 19:08:42 +0000424 def test_items(self):
425 for key, value in self._reference().items():
426 self.assertEqual(os.environ.get(key), value)
427
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000428 # Issue 7310
429 def test___repr__(self):
430 """Check that the repr() of os.environ looks like environ({...})."""
431 env = os.environ
Victor Stinner96f0de92010-07-29 00:29:00 +0000432 self.assertEqual(repr(env), 'environ({{{}}})'.format(', '.join(
433 '{!r}: {!r}'.format(key, value)
434 for key, value in env.items())))
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000435
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000436 def test_get_exec_path(self):
437 defpath_list = os.defpath.split(os.pathsep)
438 test_path = ['/monty', '/python', '', '/flying/circus']
439 test_env = {'PATH': os.pathsep.join(test_path)}
440
441 saved_environ = os.environ
442 try:
443 os.environ = dict(test_env)
444 # Test that defaulting to os.environ works.
445 self.assertSequenceEqual(test_path, os.get_exec_path())
446 self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
447 finally:
448 os.environ = saved_environ
449
450 # No PATH environment variable
451 self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
452 # Empty PATH environment variable
453 self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
454 # Supplied PATH environment variable
455 self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
456
Victor Stinnerb745a742010-05-18 17:17:23 +0000457 if os.supports_bytes_environ:
458 # env cannot contain 'PATH' and b'PATH' keys
Victor Stinner38430e22010-08-19 17:10:18 +0000459 try:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000460 # ignore BytesWarning warning
461 with warnings.catch_warnings(record=True):
462 mixed_env = {'PATH': '1', b'PATH': b'2'}
Victor Stinner38430e22010-08-19 17:10:18 +0000463 except BytesWarning:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000464 # mixed_env cannot be created with python -bb
Victor Stinner38430e22010-08-19 17:10:18 +0000465 pass
466 else:
467 self.assertRaises(ValueError, os.get_exec_path, mixed_env)
Victor Stinnerb745a742010-05-18 17:17:23 +0000468
469 # bytes key and/or value
470 self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}),
471 ['abc'])
472 self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}),
473 ['abc'])
474 self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}),
475 ['abc'])
476
477 @unittest.skipUnless(os.supports_bytes_environ,
478 "os.environb required for this test.")
Victor Stinner84ae1182010-05-06 22:05:07 +0000479 def test_environb(self):
480 # os.environ -> os.environb
481 value = 'euro\u20ac'
482 try:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000483 value_bytes = value.encode(sys.getfilesystemencoding(),
484 'surrogateescape')
Victor Stinner84ae1182010-05-06 22:05:07 +0000485 except UnicodeEncodeError:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000486 msg = "U+20AC character is not encodable to %s" % (
487 sys.getfilesystemencoding(),)
Benjamin Peterson932d3f42010-05-06 22:26:31 +0000488 self.skipTest(msg)
Victor Stinner84ae1182010-05-06 22:05:07 +0000489 os.environ['unicode'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000490 self.assertEqual(os.environ['unicode'], value)
491 self.assertEqual(os.environb[b'unicode'], value_bytes)
Victor Stinner84ae1182010-05-06 22:05:07 +0000492
493 # os.environb -> os.environ
494 value = b'\xff'
495 os.environb[b'bytes'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000496 self.assertEqual(os.environb[b'bytes'], value)
Victor Stinner84ae1182010-05-06 22:05:07 +0000497 value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000498 self.assertEqual(os.environ['bytes'], value_str)
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000499
Charles-François Natali2966f102011-11-26 11:32:46 +0100500 # On FreeBSD < 7 and OS X < 10.6, unsetenv() doesn't return a value (issue
501 # #13415).
502 @support.requires_freebsd_version(7)
503 @support.requires_mac_ver(10, 6)
Victor Stinner60b385e2011-11-22 22:01:28 +0100504 def test_unset_error(self):
505 if sys.platform == "win32":
506 # an environment variable is limited to 32,767 characters
507 key = 'x' * 50000
Victor Stinnerb3f82682011-11-22 22:30:19 +0100508 self.assertRaises(ValueError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100509 else:
510 # "=" is not allowed in a variable name
511 key = 'key='
Victor Stinnerb3f82682011-11-22 22:30:19 +0100512 self.assertRaises(OSError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100513
Tim Petersc4e09402003-04-25 07:11:48 +0000514class WalkTests(unittest.TestCase):
515 """Tests for os.walk()."""
516
Charles-François Natali7372b062012-02-05 15:15:38 +0100517 def setUp(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000518 import os
519 from os.path import join
520
521 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000522 # TESTFN/
523 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000524 # tmp1
525 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000526 # tmp2
527 # SUB11/ no kids
528 # SUB2/ a file kid and a dirsymlink kid
529 # tmp3
530 # link/ a symlink to TESTFN.2
531 # TEST2/
532 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000533 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000534 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000535 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000536 sub2_path = join(walk_path, "SUB2")
537 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000538 tmp2_path = join(sub1_path, "tmp2")
539 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000540 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000541 t2_path = join(support.TESTFN, "TEST2")
542 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000543
544 # Create stuff.
545 os.makedirs(sub11_path)
546 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000547 os.makedirs(t2_path)
548 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000549 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000550 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
551 f.close()
Brian Curtin3b4499c2010-12-28 14:31:47 +0000552 if support.can_symlink():
Antoine Pitrou5311c1d2012-01-24 08:59:28 +0100553 if os.name == 'nt':
554 def symlink_to_dir(src, dest):
555 os.symlink(src, dest, True)
556 else:
557 symlink_to_dir = os.symlink
558 symlink_to_dir(os.path.abspath(t2_path), link_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000559 sub2_tree = (sub2_path, ["link"], ["tmp3"])
560 else:
561 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000562
563 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000564 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000565 self.assertEqual(len(all), 4)
566 # We can't know which order SUB1 and SUB2 will appear in.
567 # Not flipped: TESTFN, SUB1, SUB11, SUB2
568 # flipped: TESTFN, SUB2, SUB1, SUB11
569 flipped = all[0][1][0] != "SUB1"
570 all[0][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000571 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000572 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
573 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000574 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000575
576 # Prune the search.
577 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000578 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000579 all.append((root, dirs, files))
580 # Don't descend into SUB1.
581 if 'SUB1' in dirs:
582 # Note that this also mutates the dirs we appended to all!
583 dirs.remove('SUB1')
584 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000585 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
586 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000587
588 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000589 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000590 self.assertEqual(len(all), 4)
591 # We can't know which order SUB1 and SUB2 will appear in.
592 # Not flipped: SUB11, SUB1, SUB2, TESTFN
593 # flipped: SUB2, SUB11, SUB1, TESTFN
594 flipped = all[3][1][0] != "SUB1"
595 all[3][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000596 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000597 self.assertEqual(all[flipped], (sub11_path, [], []))
598 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000599 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000600
Brian Curtin3b4499c2010-12-28 14:31:47 +0000601 if support.can_symlink():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000602 # Walk, following symlinks.
603 for root, dirs, files in os.walk(walk_path, followlinks=True):
604 if root == link_path:
605 self.assertEqual(dirs, [])
606 self.assertEqual(files, ["tmp4"])
607 break
608 else:
609 self.fail("Didn't follow symlink with followlinks=True")
610
611 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000612 # Tear everything down. This is a decent use for bottom-up on
613 # Windows, which doesn't have a recursive delete command. The
614 # (not so) subtlety is that rmdir will fail unless the dir's
615 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000616 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000617 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000618 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000619 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000620 dirname = os.path.join(root, name)
621 if not os.path.islink(dirname):
622 os.rmdir(dirname)
623 else:
624 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000625 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000626
Charles-François Natali7372b062012-02-05 15:15:38 +0100627
628@unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
629class FwalkTests(WalkTests):
630 """Tests for os.fwalk()."""
631
632 def test_compare_to_walk(self):
633 # compare with walk() results
634 for topdown, followlinks in itertools.product((True, False), repeat=2):
635 args = support.TESTFN, topdown, None, followlinks
636 expected = {}
637 for root, dirs, files in os.walk(*args):
638 expected[root] = (set(dirs), set(files))
639
640 for root, dirs, files, rootfd in os.fwalk(*args):
641 self.assertIn(root, expected)
642 self.assertEqual(expected[root], (set(dirs), set(files)))
643
644 def test_dir_fd(self):
645 # check returned file descriptors
646 for topdown, followlinks in itertools.product((True, False), repeat=2):
647 args = support.TESTFN, topdown, None, followlinks
648 for root, dirs, files, rootfd in os.fwalk(*args):
649 # check that the FD is valid
650 os.fstat(rootfd)
Charles-François Natali77940902012-02-06 19:54:48 +0100651 # check that flistdir() returns consistent information
652 self.assertEqual(set(os.flistdir(rootfd)), set(dirs) | set(files))
Charles-François Natali7372b062012-02-05 15:15:38 +0100653
654 def test_fd_leak(self):
655 # Since we're opening a lot of FDs, we must be careful to avoid leaks:
656 # we both check that calling fwalk() a large number of times doesn't
657 # yield EMFILE, and that the minimum allocated FD hasn't changed.
658 minfd = os.dup(1)
659 os.close(minfd)
660 for i in range(256):
661 for x in os.fwalk(support.TESTFN):
662 pass
663 newfd = os.dup(1)
664 self.addCleanup(os.close, newfd)
665 self.assertEqual(newfd, minfd)
666
667 def tearDown(self):
668 # cleanup
669 for root, dirs, files, rootfd in os.fwalk(support.TESTFN, topdown=False):
670 for name in files:
671 os.unlinkat(rootfd, name)
672 for name in dirs:
673 st = os.fstatat(rootfd, name, os.AT_SYMLINK_NOFOLLOW)
674 if stat.S_ISDIR(st.st_mode):
675 os.unlinkat(rootfd, name, os.AT_REMOVEDIR)
676 else:
677 os.unlinkat(rootfd, name)
678 os.rmdir(support.TESTFN)
679
680
Guido van Rossume7ba4952007-06-06 23:52:48 +0000681class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000682 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000683 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000684
685 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000686 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000687 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
688 os.makedirs(path) # Should work
689 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
690 os.makedirs(path)
691
692 # Try paths with a '.' in them
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000693 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000694 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
695 os.makedirs(path)
696 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
697 'dir5', 'dir6')
698 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000699
Terry Reedy5a22b652010-12-02 07:05:56 +0000700 def test_exist_ok_existing_directory(self):
701 path = os.path.join(support.TESTFN, 'dir1')
702 mode = 0o777
703 old_mask = os.umask(0o022)
704 os.makedirs(path, mode)
705 self.assertRaises(OSError, os.makedirs, path, mode)
706 self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
707 self.assertRaises(OSError, os.makedirs, path, 0o776, exist_ok=True)
708 os.makedirs(path, mode=mode, exist_ok=True)
709 os.umask(old_mask)
710
711 def test_exist_ok_existing_regular_file(self):
712 base = support.TESTFN
713 path = os.path.join(support.TESTFN, 'dir1')
714 f = open(path, 'w')
715 f.write('abc')
716 f.close()
717 self.assertRaises(OSError, os.makedirs, path)
718 self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
719 self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
720 os.remove(path)
721
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000722 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000723 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000724 'dir4', 'dir5', 'dir6')
725 # If the tests failed, the bottom-most directory ('../dir6')
726 # may not have been created, so we look for the outermost directory
727 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000728 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000729 path = os.path.dirname(path)
730
731 os.removedirs(path)
732
Guido van Rossume7ba4952007-06-06 23:52:48 +0000733class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000734 def test_devnull(self):
Victor Stinnera6d2c762011-06-30 18:20:11 +0200735 with open(os.devnull, 'wb') as f:
736 f.write(b'hello')
737 f.close()
738 with open(os.devnull, 'rb') as f:
739 self.assertEqual(f.read(), b'')
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000740
Guido van Rossume7ba4952007-06-06 23:52:48 +0000741class URandomTests(unittest.TestCase):
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000742 def test_urandom(self):
743 try:
744 self.assertEqual(len(os.urandom(1)), 1)
745 self.assertEqual(len(os.urandom(10)), 10)
746 self.assertEqual(len(os.urandom(100)), 100)
747 self.assertEqual(len(os.urandom(1000)), 1000)
748 except NotImplementedError:
749 pass
750
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000751@contextlib.contextmanager
752def _execvpe_mockup(defpath=None):
753 """
754 Stubs out execv and execve functions when used as context manager.
755 Records exec calls. The mock execv and execve functions always raise an
756 exception as they would normally never return.
757 """
758 # A list of tuples containing (function name, first arg, args)
759 # of calls to execv or execve that have been made.
760 calls = []
761
762 def mock_execv(name, *args):
763 calls.append(('execv', name, args))
764 raise RuntimeError("execv called")
765
766 def mock_execve(name, *args):
767 calls.append(('execve', name, args))
768 raise OSError(errno.ENOTDIR, "execve called")
769
770 try:
771 orig_execv = os.execv
772 orig_execve = os.execve
773 orig_defpath = os.defpath
774 os.execv = mock_execv
775 os.execve = mock_execve
776 if defpath is not None:
777 os.defpath = defpath
778 yield calls
779 finally:
780 os.execv = orig_execv
781 os.execve = orig_execve
782 os.defpath = orig_defpath
783
Guido van Rossume7ba4952007-06-06 23:52:48 +0000784class ExecTests(unittest.TestCase):
Mark Dickinson7cf03892010-04-16 13:45:35 +0000785 @unittest.skipIf(USING_LINUXTHREADS,
786 "avoid triggering a linuxthreads bug: see issue #4970")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000787 def test_execvpe_with_bad_program(self):
Mark Dickinson7cf03892010-04-16 13:45:35 +0000788 self.assertRaises(OSError, os.execvpe, 'no such app-',
789 ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000790
Thomas Heller6790d602007-08-30 17:15:14 +0000791 def test_execvpe_with_bad_arglist(self):
792 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
793
Gregory P. Smith4ae37772010-05-08 18:05:46 +0000794 @unittest.skipUnless(hasattr(os, '_execvpe'),
795 "No internal os._execvpe function to test.")
Victor Stinnerb745a742010-05-18 17:17:23 +0000796 def _test_internal_execvpe(self, test_type):
797 program_path = os.sep + 'absolutepath'
798 if test_type is bytes:
799 program = b'executable'
800 fullpath = os.path.join(os.fsencode(program_path), program)
801 native_fullpath = fullpath
802 arguments = [b'progname', 'arg1', 'arg2']
803 else:
804 program = 'executable'
805 arguments = ['progname', 'arg1', 'arg2']
806 fullpath = os.path.join(program_path, program)
807 if os.name != "nt":
808 native_fullpath = os.fsencode(fullpath)
809 else:
810 native_fullpath = fullpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000811 env = {'spam': 'beans'}
812
Victor Stinnerb745a742010-05-18 17:17:23 +0000813 # test os._execvpe() with an absolute path
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000814 with _execvpe_mockup() as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +0000815 self.assertRaises(RuntimeError,
816 os._execvpe, fullpath, arguments)
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000817 self.assertEqual(len(calls), 1)
818 self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))
819
Victor Stinnerb745a742010-05-18 17:17:23 +0000820 # test os._execvpe() with a relative path:
821 # os.get_exec_path() returns defpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000822 with _execvpe_mockup(defpath=program_path) as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +0000823 self.assertRaises(OSError,
824 os._execvpe, program, arguments, env=env)
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000825 self.assertEqual(len(calls), 1)
Victor Stinnerb745a742010-05-18 17:17:23 +0000826 self.assertSequenceEqual(calls[0],
827 ('execve', native_fullpath, (arguments, env)))
828
829 # test os._execvpe() with a relative path:
830 # os.get_exec_path() reads the 'PATH' variable
831 with _execvpe_mockup() as calls:
832 env_path = env.copy()
Victor Stinner38430e22010-08-19 17:10:18 +0000833 if test_type is bytes:
834 env_path[b'PATH'] = program_path
835 else:
836 env_path['PATH'] = program_path
Victor Stinnerb745a742010-05-18 17:17:23 +0000837 self.assertRaises(OSError,
838 os._execvpe, program, arguments, env=env_path)
839 self.assertEqual(len(calls), 1)
840 self.assertSequenceEqual(calls[0],
841 ('execve', native_fullpath, (arguments, env_path)))
842
843 def test_internal_execvpe_str(self):
844 self._test_internal_execvpe(str)
845 if os.name != "nt":
846 self._test_internal_execvpe(bytes)
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000847
Gregory P. Smith4ae37772010-05-08 18:05:46 +0000848
Thomas Wouters477c8d52006-05-27 19:21:47 +0000849class Win32ErrorTests(unittest.TestCase):
850 def test_rename(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000851 self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000852
853 def test_remove(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000854 self.assertRaises(WindowsError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000855
856 def test_chdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000857 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000858
859 def test_mkdir(self):
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +0000860 f = open(support.TESTFN, "w")
Benjamin Petersonf91df042009-02-13 02:50:59 +0000861 try:
862 self.assertRaises(WindowsError, os.mkdir, support.TESTFN)
863 finally:
864 f.close()
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +0000865 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000866
867 def test_utime(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000868 self.assertRaises(WindowsError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000869
Thomas Wouters477c8d52006-05-27 19:21:47 +0000870 def test_chmod(self):
Benjamin Petersonf91df042009-02-13 02:50:59 +0000871 self.assertRaises(WindowsError, os.chmod, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000872
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000873class TestInvalidFD(unittest.TestCase):
Benjamin Peterson05e782f2009-01-19 15:15:02 +0000874 singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000875 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
876 #singles.append("close")
877 #We omit close because it doesn'r raise an exception on some platforms
878 def get_single(f):
879 def helper(self):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000880 if hasattr(os, f):
881 self.check(getattr(os, f))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000882 return helper
883 for f in singles:
884 locals()["test_"+f] = get_single(f)
885
Benjamin Peterson7522c742009-01-19 21:00:09 +0000886 def check(self, f, *args):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000887 try:
888 f(support.make_bad_fd(), *args)
889 except OSError as e:
890 self.assertEqual(e.errno, errno.EBADF)
891 else:
892 self.fail("%r didn't raise a OSError with a bad file descriptor"
893 % f)
Benjamin Peterson7522c742009-01-19 21:00:09 +0000894
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000895 def test_isatty(self):
896 if hasattr(os, "isatty"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000897 self.assertEqual(os.isatty(support.make_bad_fd()), False)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000898
899 def test_closerange(self):
900 if hasattr(os, "closerange"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000901 fd = support.make_bad_fd()
R. David Murray630cc482009-07-22 15:20:27 +0000902 # Make sure none of the descriptors we are about to close are
903 # currently valid (issue 6542).
904 for i in range(10):
905 try: os.fstat(fd+i)
906 except OSError:
907 pass
908 else:
909 break
910 if i < 2:
911 raise unittest.SkipTest(
912 "Unable to acquire a range of invalid file descriptors")
913 self.assertEqual(os.closerange(fd, fd + i-1), None)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000914
915 def test_dup2(self):
916 if hasattr(os, "dup2"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000917 self.check(os.dup2, 20)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000918
919 def test_fchmod(self):
920 if hasattr(os, "fchmod"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000921 self.check(os.fchmod, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000922
923 def test_fchown(self):
924 if hasattr(os, "fchown"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000925 self.check(os.fchown, -1, -1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000926
927 def test_fpathconf(self):
928 if hasattr(os, "fpathconf"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000929 self.check(os.fpathconf, "PC_NAME_MAX")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000930
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000931 def test_ftruncate(self):
932 if hasattr(os, "ftruncate"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000933 self.check(os.ftruncate, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000934
935 def test_lseek(self):
936 if hasattr(os, "lseek"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000937 self.check(os.lseek, 0, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000938
939 def test_read(self):
940 if hasattr(os, "read"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000941 self.check(os.read, 1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000942
943 def test_tcsetpgrpt(self):
944 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000945 self.check(os.tcsetpgrp, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000946
947 def test_write(self):
948 if hasattr(os, "write"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000949 self.check(os.write, b" ")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000950
Brian Curtin1b9df392010-11-24 20:24:31 +0000951
952class LinkTests(unittest.TestCase):
953 def setUp(self):
954 self.file1 = support.TESTFN
955 self.file2 = os.path.join(support.TESTFN + "2")
956
Brian Curtinc0abc4e2010-11-30 23:46:54 +0000957 def tearDown(self):
Brian Curtin1b9df392010-11-24 20:24:31 +0000958 for file in (self.file1, self.file2):
959 if os.path.exists(file):
960 os.unlink(file)
961
Brian Curtin1b9df392010-11-24 20:24:31 +0000962 def _test_link(self, file1, file2):
963 with open(file1, "w") as f1:
964 f1.write("test")
965
Victor Stinner1ab6c2d2011-11-15 22:27:41 +0100966 with warnings.catch_warnings():
967 warnings.simplefilter("ignore", DeprecationWarning)
968 os.link(file1, file2)
Brian Curtin1b9df392010-11-24 20:24:31 +0000969 with open(file1, "r") as f1, open(file2, "r") as f2:
970 self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
971
972 def test_link(self):
973 self._test_link(self.file1, self.file2)
974
975 def test_link_bytes(self):
976 self._test_link(bytes(self.file1, sys.getfilesystemencoding()),
977 bytes(self.file2, sys.getfilesystemencoding()))
978
Brian Curtinf498b752010-11-30 15:54:04 +0000979 def test_unicode_name(self):
Brian Curtin43f0c272010-11-30 15:40:04 +0000980 try:
Brian Curtinf498b752010-11-30 15:54:04 +0000981 os.fsencode("\xf1")
Brian Curtin43f0c272010-11-30 15:40:04 +0000982 except UnicodeError:
983 raise unittest.SkipTest("Unable to encode for this platform.")
984
Brian Curtinf498b752010-11-30 15:54:04 +0000985 self.file1 += "\xf1"
Brian Curtinfc889c42010-11-28 23:59:46 +0000986 self.file2 = self.file1 + "2"
987 self._test_link(self.file1, self.file2)
988
Thomas Wouters477c8d52006-05-27 19:21:47 +0000989if sys.platform != 'win32':
990 class Win32ErrorTests(unittest.TestCase):
991 pass
992
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000993 class PosixUidGidTests(unittest.TestCase):
994 if hasattr(os, 'setuid'):
995 def test_setuid(self):
996 if os.getuid() != 0:
997 self.assertRaises(os.error, os.setuid, 0)
998 self.assertRaises(OverflowError, os.setuid, 1<<32)
999
1000 if hasattr(os, 'setgid'):
1001 def test_setgid(self):
1002 if os.getuid() != 0:
1003 self.assertRaises(os.error, os.setgid, 0)
1004 self.assertRaises(OverflowError, os.setgid, 1<<32)
1005
1006 if hasattr(os, 'seteuid'):
1007 def test_seteuid(self):
1008 if os.getuid() != 0:
1009 self.assertRaises(os.error, os.seteuid, 0)
1010 self.assertRaises(OverflowError, os.seteuid, 1<<32)
1011
1012 if hasattr(os, 'setegid'):
1013 def test_setegid(self):
1014 if os.getuid() != 0:
1015 self.assertRaises(os.error, os.setegid, 0)
1016 self.assertRaises(OverflowError, os.setegid, 1<<32)
1017
1018 if hasattr(os, 'setreuid'):
1019 def test_setreuid(self):
1020 if os.getuid() != 0:
1021 self.assertRaises(os.error, os.setreuid, 0, 0)
1022 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
1023 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001024
1025 def test_setreuid_neg1(self):
1026 # Needs to accept -1. We run this in a subprocess to avoid
1027 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001028 subprocess.check_call([
1029 sys.executable, '-c',
1030 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001031
1032 if hasattr(os, 'setregid'):
1033 def test_setregid(self):
1034 if os.getuid() != 0:
1035 self.assertRaises(os.error, os.setregid, 0, 0)
1036 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
1037 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001038
1039 def test_setregid_neg1(self):
1040 # Needs to accept -1. We run this in a subprocess to avoid
1041 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001042 subprocess.check_call([
1043 sys.executable, '-c',
1044 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Martin v. Löwis011e8422009-05-05 04:43:17 +00001045
1046 class Pep383Tests(unittest.TestCase):
Martin v. Löwis011e8422009-05-05 04:43:17 +00001047 def setUp(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001048 if support.TESTFN_UNENCODABLE:
1049 self.dir = support.TESTFN_UNENCODABLE
1050 else:
1051 self.dir = support.TESTFN
1052 self.bdir = os.fsencode(self.dir)
1053
1054 bytesfn = []
1055 def add_filename(fn):
1056 try:
1057 fn = os.fsencode(fn)
1058 except UnicodeEncodeError:
1059 return
1060 bytesfn.append(fn)
1061 add_filename(support.TESTFN_UNICODE)
1062 if support.TESTFN_UNENCODABLE:
1063 add_filename(support.TESTFN_UNENCODABLE)
1064 if not bytesfn:
1065 self.skipTest("couldn't create any non-ascii filename")
1066
1067 self.unicodefn = set()
Martin v. Löwis011e8422009-05-05 04:43:17 +00001068 os.mkdir(self.dir)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001069 try:
1070 for fn in bytesfn:
Victor Stinnerbf816222011-06-30 23:25:47 +02001071 support.create_empty_file(os.path.join(self.bdir, fn))
Victor Stinnere8d51452010-08-19 01:05:19 +00001072 fn = os.fsdecode(fn)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001073 if fn in self.unicodefn:
1074 raise ValueError("duplicate filename")
1075 self.unicodefn.add(fn)
1076 except:
1077 shutil.rmtree(self.dir)
1078 raise
Martin v. Löwis011e8422009-05-05 04:43:17 +00001079
1080 def tearDown(self):
1081 shutil.rmtree(self.dir)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001082
1083 def test_listdir(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001084 expected = self.unicodefn
1085 found = set(os.listdir(self.dir))
Ezio Melottib3aedd42010-11-20 19:04:17 +00001086 self.assertEqual(found, expected)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001087
1088 def test_open(self):
1089 for fn in self.unicodefn:
Victor Stinnera6d2c762011-06-30 18:20:11 +02001090 f = open(os.path.join(self.dir, fn), 'rb')
Martin v. Löwis011e8422009-05-05 04:43:17 +00001091 f.close()
1092
1093 def test_stat(self):
1094 for fn in self.unicodefn:
1095 os.stat(os.path.join(self.dir, fn))
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001096else:
1097 class PosixUidGidTests(unittest.TestCase):
1098 pass
Martin v. Löwis011e8422009-05-05 04:43:17 +00001099 class Pep383Tests(unittest.TestCase):
1100 pass
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001101
Brian Curtineb24d742010-04-12 17:16:38 +00001102@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
1103class Win32KillTests(unittest.TestCase):
Brian Curtinc3acbc32010-05-28 16:08:40 +00001104 def _kill(self, sig):
1105 # Start sys.executable as a subprocess and communicate from the
1106 # subprocess to the parent that the interpreter is ready. When it
1107 # becomes ready, send *sig* via os.kill to the subprocess and check
1108 # that the return code is equal to *sig*.
1109 import ctypes
1110 from ctypes import wintypes
1111 import msvcrt
1112
1113 # Since we can't access the contents of the process' stdout until the
1114 # process has exited, use PeekNamedPipe to see what's inside stdout
1115 # without waiting. This is done so we can tell that the interpreter
1116 # is started and running at a point where it could handle a signal.
1117 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
1118 PeekNamedPipe.restype = wintypes.BOOL
1119 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
1120 ctypes.POINTER(ctypes.c_char), # stdout buf
1121 wintypes.DWORD, # Buffer size
1122 ctypes.POINTER(wintypes.DWORD), # bytes read
1123 ctypes.POINTER(wintypes.DWORD), # bytes avail
1124 ctypes.POINTER(wintypes.DWORD)) # bytes left
1125 msg = "running"
1126 proc = subprocess.Popen([sys.executable, "-c",
1127 "import sys;"
1128 "sys.stdout.write('{}');"
1129 "sys.stdout.flush();"
1130 "input()".format(msg)],
1131 stdout=subprocess.PIPE,
1132 stderr=subprocess.PIPE,
1133 stdin=subprocess.PIPE)
Brian Curtin43ec5772010-11-05 15:17:11 +00001134 self.addCleanup(proc.stdout.close)
1135 self.addCleanup(proc.stderr.close)
1136 self.addCleanup(proc.stdin.close)
Brian Curtinc3acbc32010-05-28 16:08:40 +00001137
1138 count, max = 0, 100
1139 while count < max and proc.poll() is None:
1140 # Create a string buffer to store the result of stdout from the pipe
1141 buf = ctypes.create_string_buffer(len(msg))
1142 # Obtain the text currently in proc.stdout
1143 # Bytes read/avail/left are left as NULL and unused
1144 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
1145 buf, ctypes.sizeof(buf), None, None, None)
1146 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
1147 if buf.value:
1148 self.assertEqual(msg, buf.value.decode())
1149 break
1150 time.sleep(0.1)
1151 count += 1
1152 else:
1153 self.fail("Did not receive communication from the subprocess")
1154
Brian Curtineb24d742010-04-12 17:16:38 +00001155 os.kill(proc.pid, sig)
1156 self.assertEqual(proc.wait(), sig)
1157
1158 def test_kill_sigterm(self):
1159 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinc3acbc32010-05-28 16:08:40 +00001160 self._kill(signal.SIGTERM)
Brian Curtineb24d742010-04-12 17:16:38 +00001161
1162 def test_kill_int(self):
1163 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinc3acbc32010-05-28 16:08:40 +00001164 self._kill(100)
Brian Curtineb24d742010-04-12 17:16:38 +00001165
1166 def _kill_with_event(self, event, name):
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001167 tagname = "test_os_%s" % uuid.uuid1()
1168 m = mmap.mmap(-1, 1, tagname)
1169 m[0] = 0
Brian Curtineb24d742010-04-12 17:16:38 +00001170 # Run a script which has console control handling enabled.
1171 proc = subprocess.Popen([sys.executable,
1172 os.path.join(os.path.dirname(__file__),
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001173 "win_console_handler.py"), tagname],
Brian Curtineb24d742010-04-12 17:16:38 +00001174 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
1175 # Let the interpreter startup before we send signals. See #3137.
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001176 count, max = 0, 100
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001177 while count < max and proc.poll() is None:
Brian Curtinf668df52010-10-15 14:21:06 +00001178 if m[0] == 1:
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001179 break
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001180 time.sleep(0.1)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001181 count += 1
1182 else:
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001183 # Forcefully kill the process if we weren't able to signal it.
1184 os.kill(proc.pid, signal.SIGINT)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001185 self.fail("Subprocess didn't finish initialization")
Brian Curtineb24d742010-04-12 17:16:38 +00001186 os.kill(proc.pid, event)
1187 # proc.send_signal(event) could also be done here.
1188 # Allow time for the signal to be passed and the process to exit.
1189 time.sleep(0.5)
1190 if not proc.poll():
1191 # Forcefully kill the process if we weren't able to signal it.
1192 os.kill(proc.pid, signal.SIGINT)
1193 self.fail("subprocess did not stop on {}".format(name))
1194
1195 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
1196 def test_CTRL_C_EVENT(self):
1197 from ctypes import wintypes
1198 import ctypes
1199
1200 # Make a NULL value by creating a pointer with no argument.
1201 NULL = ctypes.POINTER(ctypes.c_int)()
1202 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
1203 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
1204 wintypes.BOOL)
1205 SetConsoleCtrlHandler.restype = wintypes.BOOL
1206
1207 # Calling this with NULL and FALSE causes the calling process to
1208 # handle CTRL+C, rather than ignore it. This property is inherited
1209 # by subprocesses.
1210 SetConsoleCtrlHandler(NULL, 0)
1211
1212 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
1213
1214 def test_CTRL_BREAK_EVENT(self):
1215 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
1216
1217
Brian Curtind40e6f72010-07-08 21:39:08 +00001218@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Brian Curtin3b4499c2010-12-28 14:31:47 +00001219@support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +00001220class Win32SymlinkTests(unittest.TestCase):
1221 filelink = 'filelinktest'
1222 filelink_target = os.path.abspath(__file__)
1223 dirlink = 'dirlinktest'
1224 dirlink_target = os.path.dirname(filelink_target)
1225 missing_link = 'missing link'
1226
1227 def setUp(self):
1228 assert os.path.exists(self.dirlink_target)
1229 assert os.path.exists(self.filelink_target)
1230 assert not os.path.exists(self.dirlink)
1231 assert not os.path.exists(self.filelink)
1232 assert not os.path.exists(self.missing_link)
1233
1234 def tearDown(self):
1235 if os.path.exists(self.filelink):
1236 os.remove(self.filelink)
1237 if os.path.exists(self.dirlink):
1238 os.rmdir(self.dirlink)
1239 if os.path.lexists(self.missing_link):
1240 os.remove(self.missing_link)
1241
1242 def test_directory_link(self):
Antoine Pitrou5311c1d2012-01-24 08:59:28 +01001243 os.symlink(self.dirlink_target, self.dirlink, True)
Brian Curtind40e6f72010-07-08 21:39:08 +00001244 self.assertTrue(os.path.exists(self.dirlink))
1245 self.assertTrue(os.path.isdir(self.dirlink))
1246 self.assertTrue(os.path.islink(self.dirlink))
1247 self.check_stat(self.dirlink, self.dirlink_target)
1248
1249 def test_file_link(self):
1250 os.symlink(self.filelink_target, self.filelink)
1251 self.assertTrue(os.path.exists(self.filelink))
1252 self.assertTrue(os.path.isfile(self.filelink))
1253 self.assertTrue(os.path.islink(self.filelink))
1254 self.check_stat(self.filelink, self.filelink_target)
1255
1256 def _create_missing_dir_link(self):
1257 'Create a "directory" link to a non-existent target'
1258 linkname = self.missing_link
1259 if os.path.lexists(linkname):
1260 os.remove(linkname)
1261 target = r'c:\\target does not exist.29r3c740'
1262 assert not os.path.exists(target)
1263 target_is_dir = True
1264 os.symlink(target, linkname, target_is_dir)
1265
1266 def test_remove_directory_link_to_missing_target(self):
1267 self._create_missing_dir_link()
1268 # For compatibility with Unix, os.remove will check the
1269 # directory status and call RemoveDirectory if the symlink
1270 # was created with target_is_dir==True.
1271 os.remove(self.missing_link)
1272
1273 @unittest.skip("currently fails; consider for improvement")
1274 def test_isdir_on_directory_link_to_missing_target(self):
1275 self._create_missing_dir_link()
1276 # consider having isdir return true for directory links
1277 self.assertTrue(os.path.isdir(self.missing_link))
1278
1279 @unittest.skip("currently fails; consider for improvement")
1280 def test_rmdir_on_directory_link_to_missing_target(self):
1281 self._create_missing_dir_link()
1282 # consider allowing rmdir to remove directory links
1283 os.rmdir(self.missing_link)
1284
1285 def check_stat(self, link, target):
1286 self.assertEqual(os.stat(link), os.stat(target))
1287 self.assertNotEqual(os.lstat(link), os.stat(link))
1288
Brian Curtind25aef52011-06-13 15:16:04 -05001289 bytes_link = os.fsencode(link)
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001290 with warnings.catch_warnings():
1291 warnings.simplefilter("ignore", DeprecationWarning)
1292 self.assertEqual(os.stat(bytes_link), os.stat(target))
1293 self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link))
Brian Curtind25aef52011-06-13 15:16:04 -05001294
1295 def test_12084(self):
1296 level1 = os.path.abspath(support.TESTFN)
1297 level2 = os.path.join(level1, "level2")
1298 level3 = os.path.join(level2, "level3")
1299 try:
1300 os.mkdir(level1)
1301 os.mkdir(level2)
1302 os.mkdir(level3)
1303
1304 file1 = os.path.abspath(os.path.join(level1, "file1"))
1305
1306 with open(file1, "w") as f:
1307 f.write("file1")
1308
1309 orig_dir = os.getcwd()
1310 try:
1311 os.chdir(level2)
1312 link = os.path.join(level2, "link")
1313 os.symlink(os.path.relpath(file1), "link")
1314 self.assertIn("link", os.listdir(os.getcwd()))
1315
1316 # Check os.stat calls from the same dir as the link
1317 self.assertEqual(os.stat(file1), os.stat("link"))
1318
1319 # Check os.stat calls from a dir below the link
1320 os.chdir(level1)
1321 self.assertEqual(os.stat(file1),
1322 os.stat(os.path.relpath(link)))
1323
1324 # Check os.stat calls from a dir above the link
1325 os.chdir(level3)
1326 self.assertEqual(os.stat(file1),
1327 os.stat(os.path.relpath(link)))
1328 finally:
1329 os.chdir(orig_dir)
1330 except OSError as err:
1331 self.fail(err)
1332 finally:
1333 os.remove(file1)
1334 shutil.rmtree(level1)
1335
Brian Curtind40e6f72010-07-08 21:39:08 +00001336
Victor Stinnere8d51452010-08-19 01:05:19 +00001337class FSEncodingTests(unittest.TestCase):
1338 def test_nop(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001339 self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
1340 self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
Benjamin Peterson31191a92010-05-09 03:22:58 +00001341
Victor Stinnere8d51452010-08-19 01:05:19 +00001342 def test_identity(self):
1343 # assert fsdecode(fsencode(x)) == x
1344 for fn in ('unicode\u0141', 'latin\xe9', 'ascii'):
1345 try:
1346 bytesfn = os.fsencode(fn)
1347 except UnicodeEncodeError:
1348 continue
Ezio Melottib3aedd42010-11-20 19:04:17 +00001349 self.assertEqual(os.fsdecode(bytesfn), fn)
Victor Stinnere8d51452010-08-19 01:05:19 +00001350
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00001351
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00001352class PidTests(unittest.TestCase):
1353 @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid")
1354 def test_getppid(self):
1355 p = subprocess.Popen([sys.executable, '-c',
1356 'import os; print(os.getppid())'],
1357 stdout=subprocess.PIPE)
1358 stdout, _ = p.communicate()
1359 # We are the parent of our subprocess
1360 self.assertEqual(int(stdout), os.getpid())
1361
1362
Brian Curtin0151b8e2010-09-24 13:43:43 +00001363# The introduction of this TestCase caused at least two different errors on
1364# *nix buildbots. Temporarily skip this to let the buildbots move along.
1365@unittest.skip("Skip due to platform/environment differences on *NIX buildbots")
Brian Curtine8e4b3b2010-09-23 20:04:14 +00001366@unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin")
1367class LoginTests(unittest.TestCase):
1368 def test_getlogin(self):
1369 user_name = os.getlogin()
1370 self.assertNotEqual(len(user_name), 0)
1371
1372
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001373@unittest.skipUnless(hasattr(os, 'getpriority') and hasattr(os, 'setpriority'),
1374 "needs os.getpriority and os.setpriority")
1375class ProgramPriorityTests(unittest.TestCase):
1376 """Tests for os.getpriority() and os.setpriority()."""
1377
1378 def test_set_get_priority(self):
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001379
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001380 base = os.getpriority(os.PRIO_PROCESS, os.getpid())
1381 os.setpriority(os.PRIO_PROCESS, os.getpid(), base + 1)
1382 try:
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001383 new_prio = os.getpriority(os.PRIO_PROCESS, os.getpid())
1384 if base >= 19 and new_prio <= 19:
1385 raise unittest.SkipTest(
1386 "unable to reliably test setpriority at current nice level of %s" % base)
1387 else:
1388 self.assertEqual(new_prio, base + 1)
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001389 finally:
1390 try:
1391 os.setpriority(os.PRIO_PROCESS, os.getpid(), base)
1392 except OSError as err:
Antoine Pitrou692f0382011-02-26 00:22:25 +00001393 if err.errno != errno.EACCES:
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001394 raise
1395
1396
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001397if threading is not None:
1398 class SendfileTestServer(asyncore.dispatcher, threading.Thread):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001399
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001400 class Handler(asynchat.async_chat):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001401
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001402 def __init__(self, conn):
1403 asynchat.async_chat.__init__(self, conn)
1404 self.in_buffer = []
1405 self.closed = False
1406 self.push(b"220 ready\r\n")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001407
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001408 def handle_read(self):
1409 data = self.recv(4096)
1410 self.in_buffer.append(data)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001411
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001412 def get_data(self):
1413 return b''.join(self.in_buffer)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001414
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001415 def handle_close(self):
1416 self.close()
1417 self.closed = True
1418
1419 def handle_error(self):
1420 raise
1421
1422 def __init__(self, address):
1423 threading.Thread.__init__(self)
1424 asyncore.dispatcher.__init__(self)
1425 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
1426 self.bind(address)
1427 self.listen(5)
1428 self.host, self.port = self.socket.getsockname()[:2]
1429 self.handler_instance = None
1430 self._active = False
1431 self._active_lock = threading.Lock()
1432
1433 # --- public API
1434
1435 @property
1436 def running(self):
1437 return self._active
1438
1439 def start(self):
1440 assert not self.running
1441 self.__flag = threading.Event()
1442 threading.Thread.start(self)
1443 self.__flag.wait()
1444
1445 def stop(self):
1446 assert self.running
1447 self._active = False
1448 self.join()
1449
1450 def wait(self):
1451 # wait for handler connection to be closed, then stop the server
1452 while not getattr(self.handler_instance, "closed", False):
1453 time.sleep(0.001)
1454 self.stop()
1455
1456 # --- internals
1457
1458 def run(self):
1459 self._active = True
1460 self.__flag.set()
1461 while self._active and asyncore.socket_map:
1462 self._active_lock.acquire()
1463 asyncore.loop(timeout=0.001, count=1)
1464 self._active_lock.release()
1465 asyncore.close_all()
1466
1467 def handle_accept(self):
1468 conn, addr = self.accept()
1469 self.handler_instance = self.Handler(conn)
1470
1471 def handle_connect(self):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001472 self.close()
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001473 handle_read = handle_connect
1474
1475 def writable(self):
1476 return 0
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001477
1478 def handle_error(self):
1479 raise
1480
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001481
Giampaolo Rodolà46134642011-02-25 20:01:05 +00001482@unittest.skipUnless(threading is not None, "test needs threading module")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001483@unittest.skipUnless(hasattr(os, 'sendfile'), "test needs os.sendfile()")
1484class TestSendfile(unittest.TestCase):
1485
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001486 DATA = b"12345abcde" * 16 * 1024 # 160 KB
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001487 SUPPORT_HEADERS_TRAILERS = not sys.platform.startswith("linux") and \
Giampaolo Rodolà4bc68572011-02-25 21:46:01 +00001488 not sys.platform.startswith("solaris") and \
1489 not sys.platform.startswith("sunos")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001490
1491 @classmethod
1492 def setUpClass(cls):
1493 with open(support.TESTFN, "wb") as f:
1494 f.write(cls.DATA)
1495
1496 @classmethod
1497 def tearDownClass(cls):
1498 support.unlink(support.TESTFN)
1499
1500 def setUp(self):
1501 self.server = SendfileTestServer((support.HOST, 0))
1502 self.server.start()
1503 self.client = socket.socket()
1504 self.client.connect((self.server.host, self.server.port))
1505 self.client.settimeout(1)
1506 # synchronize by waiting for "220 ready" response
1507 self.client.recv(1024)
1508 self.sockno = self.client.fileno()
1509 self.file = open(support.TESTFN, 'rb')
1510 self.fileno = self.file.fileno()
1511
1512 def tearDown(self):
1513 self.file.close()
1514 self.client.close()
1515 if self.server.running:
1516 self.server.stop()
1517
1518 def sendfile_wrapper(self, sock, file, offset, nbytes, headers=[], trailers=[]):
1519 """A higher level wrapper representing how an application is
1520 supposed to use sendfile().
1521 """
1522 while 1:
1523 try:
1524 if self.SUPPORT_HEADERS_TRAILERS:
1525 return os.sendfile(sock, file, offset, nbytes, headers,
1526 trailers)
1527 else:
1528 return os.sendfile(sock, file, offset, nbytes)
1529 except OSError as err:
1530 if err.errno == errno.ECONNRESET:
1531 # disconnected
1532 raise
1533 elif err.errno in (errno.EAGAIN, errno.EBUSY):
1534 # we have to retry send data
1535 continue
1536 else:
1537 raise
1538
1539 def test_send_whole_file(self):
1540 # normal send
1541 total_sent = 0
1542 offset = 0
1543 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001544 while total_sent < len(self.DATA):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001545 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
1546 if sent == 0:
1547 break
1548 offset += sent
1549 total_sent += sent
1550 self.assertTrue(sent <= nbytes)
1551 self.assertEqual(offset, total_sent)
1552
1553 self.assertEqual(total_sent, len(self.DATA))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001554 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001555 self.client.close()
1556 self.server.wait()
1557 data = self.server.handler_instance.get_data()
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001558 self.assertEqual(len(data), len(self.DATA))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001559 self.assertEqual(data, self.DATA)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001560
1561 def test_send_at_certain_offset(self):
1562 # start sending a file at a certain offset
1563 total_sent = 0
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001564 offset = len(self.DATA) // 2
1565 must_send = len(self.DATA) - offset
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001566 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001567 while total_sent < must_send:
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001568 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
1569 if sent == 0:
1570 break
1571 offset += sent
1572 total_sent += sent
1573 self.assertTrue(sent <= nbytes)
1574
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001575 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001576 self.client.close()
1577 self.server.wait()
1578 data = self.server.handler_instance.get_data()
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001579 expected = self.DATA[len(self.DATA) // 2:]
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001580 self.assertEqual(total_sent, len(expected))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001581 self.assertEqual(len(data), len(expected))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001582 self.assertEqual(data, expected)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001583
1584 def test_offset_overflow(self):
1585 # specify an offset > file size
1586 offset = len(self.DATA) + 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001587 try:
1588 sent = os.sendfile(self.sockno, self.fileno, offset, 4096)
1589 except OSError as e:
1590 # Solaris can raise EINVAL if offset >= file length, ignore.
1591 if e.errno != errno.EINVAL:
1592 raise
1593 else:
1594 self.assertEqual(sent, 0)
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001595 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001596 self.client.close()
1597 self.server.wait()
1598 data = self.server.handler_instance.get_data()
1599 self.assertEqual(data, b'')
1600
1601 def test_invalid_offset(self):
1602 with self.assertRaises(OSError) as cm:
1603 os.sendfile(self.sockno, self.fileno, -1, 4096)
1604 self.assertEqual(cm.exception.errno, errno.EINVAL)
1605
1606 # --- headers / trailers tests
1607
1608 if SUPPORT_HEADERS_TRAILERS:
1609
1610 def test_headers(self):
1611 total_sent = 0
1612 sent = os.sendfile(self.sockno, self.fileno, 0, 4096,
1613 headers=[b"x" * 512])
1614 total_sent += sent
1615 offset = 4096
1616 nbytes = 4096
1617 while 1:
1618 sent = self.sendfile_wrapper(self.sockno, self.fileno,
1619 offset, nbytes)
1620 if sent == 0:
1621 break
1622 total_sent += sent
1623 offset += sent
1624
1625 expected_data = b"x" * 512 + self.DATA
1626 self.assertEqual(total_sent, len(expected_data))
1627 self.client.close()
1628 self.server.wait()
1629 data = self.server.handler_instance.get_data()
1630 self.assertEqual(hash(data), hash(expected_data))
1631
1632 def test_trailers(self):
1633 TESTFN2 = support.TESTFN + "2"
Brett Cannonb6376802011-03-15 17:38:22 -04001634 with open(TESTFN2, 'wb') as f:
1635 f.write(b"abcde")
1636 with open(TESTFN2, 'rb')as f:
1637 self.addCleanup(os.remove, TESTFN2)
1638 os.sendfile(self.sockno, f.fileno(), 0, 4096,
1639 trailers=[b"12345"])
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001640 self.client.close()
1641 self.server.wait()
1642 data = self.server.handler_instance.get_data()
1643 self.assertEqual(data, b"abcde12345")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001644
1645 if hasattr(os, "SF_NODISKIO"):
1646 def test_flags(self):
1647 try:
1648 os.sendfile(self.sockno, self.fileno, 0, 4096,
1649 flags=os.SF_NODISKIO)
1650 except OSError as err:
1651 if err.errno not in (errno.EBUSY, errno.EAGAIN):
1652 raise
1653
1654
Benjamin Peterson799bd802011-08-31 22:15:17 -04001655def supports_extended_attributes():
1656 if not hasattr(os, "setxattr"):
1657 return False
1658 try:
1659 with open(support.TESTFN, "wb") as fp:
1660 try:
1661 os.fsetxattr(fp.fileno(), b"user.test", b"")
1662 except OSError as e:
1663 if e.errno != errno.ENOTSUP:
1664 raise
1665 return False
1666 finally:
1667 support.unlink(support.TESTFN)
1668 # Kernels < 2.6.39 don't respect setxattr flags.
1669 kernel_version = platform.release()
1670 m = re.match("2.6.(\d{1,2})", kernel_version)
1671 return m is None or int(m.group(1)) >= 39
1672
1673
1674@unittest.skipUnless(supports_extended_attributes(),
1675 "no non-broken extended attribute support")
1676class ExtendedAttributeTests(unittest.TestCase):
1677
1678 def tearDown(self):
1679 support.unlink(support.TESTFN)
1680
1681 def _check_xattrs_str(self, s, getxattr, setxattr, removexattr, listxattr):
1682 fn = support.TESTFN
1683 open(fn, "wb").close()
1684 with self.assertRaises(OSError) as cm:
1685 getxattr(fn, s("user.test"))
1686 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02001687 init_xattr = listxattr(fn)
1688 self.assertIsInstance(init_xattr, list)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001689 setxattr(fn, s("user.test"), b"")
Victor Stinnerf12e5062011-10-16 22:12:03 +02001690 xattr = set(init_xattr)
1691 xattr.add("user.test")
1692 self.assertEqual(set(listxattr(fn)), xattr)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001693 self.assertEqual(getxattr(fn, b"user.test"), b"")
1694 setxattr(fn, s("user.test"), b"hello", os.XATTR_REPLACE)
1695 self.assertEqual(getxattr(fn, b"user.test"), b"hello")
1696 with self.assertRaises(OSError) as cm:
1697 setxattr(fn, s("user.test"), b"bye", os.XATTR_CREATE)
1698 self.assertEqual(cm.exception.errno, errno.EEXIST)
1699 with self.assertRaises(OSError) as cm:
1700 setxattr(fn, s("user.test2"), b"bye", os.XATTR_REPLACE)
1701 self.assertEqual(cm.exception.errno, errno.ENODATA)
1702 setxattr(fn, s("user.test2"), b"foo", os.XATTR_CREATE)
Victor Stinnerf12e5062011-10-16 22:12:03 +02001703 xattr.add("user.test2")
1704 self.assertEqual(set(listxattr(fn)), xattr)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001705 removexattr(fn, s("user.test"))
1706 with self.assertRaises(OSError) as cm:
1707 getxattr(fn, s("user.test"))
1708 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02001709 xattr.remove("user.test")
1710 self.assertEqual(set(listxattr(fn)), xattr)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001711 self.assertEqual(getxattr(fn, s("user.test2")), b"foo")
1712 setxattr(fn, s("user.test"), b"a"*1024)
1713 self.assertEqual(getxattr(fn, s("user.test")), b"a"*1024)
1714 removexattr(fn, s("user.test"))
1715 many = sorted("user.test{}".format(i) for i in range(100))
1716 for thing in many:
1717 setxattr(fn, thing, b"x")
Victor Stinnerf12e5062011-10-16 22:12:03 +02001718 self.assertEqual(set(listxattr(fn)), set(init_xattr) | set(many))
Benjamin Peterson799bd802011-08-31 22:15:17 -04001719
1720 def _check_xattrs(self, *args):
1721 def make_bytes(s):
1722 return bytes(s, "ascii")
1723 self._check_xattrs_str(str, *args)
1724 support.unlink(support.TESTFN)
1725 self._check_xattrs_str(make_bytes, *args)
1726
1727 def test_simple(self):
1728 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
1729 os.listxattr)
1730
1731 def test_lpath(self):
1732 self._check_xattrs(os.lgetxattr, os.lsetxattr, os.lremovexattr,
1733 os.llistxattr)
1734
1735 def test_fds(self):
1736 def getxattr(path, *args):
1737 with open(path, "rb") as fp:
1738 return os.fgetxattr(fp.fileno(), *args)
1739 def setxattr(path, *args):
1740 with open(path, "wb") as fp:
1741 os.fsetxattr(fp.fileno(), *args)
1742 def removexattr(path, *args):
1743 with open(path, "wb") as fp:
1744 os.fremovexattr(fp.fileno(), *args)
1745 def listxattr(path, *args):
1746 with open(path, "rb") as fp:
1747 return os.flistxattr(fp.fileno(), *args)
1748 self._check_xattrs(getxattr, setxattr, removexattr, listxattr)
1749
1750
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001751@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
1752class Win32DeprecatedBytesAPI(unittest.TestCase):
1753 def test_deprecated(self):
1754 import nt
1755 filename = os.fsencode(support.TESTFN)
1756 with warnings.catch_warnings():
1757 warnings.simplefilter("error", DeprecationWarning)
1758 for func, *args in (
1759 (nt._getfullpathname, filename),
1760 (nt._isdir, filename),
1761 (os.access, filename, os.R_OK),
1762 (os.chdir, filename),
1763 (os.chmod, filename, 0o777),
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01001764 (os.getcwdb,),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001765 (os.link, filename, filename),
1766 (os.listdir, filename),
1767 (os.lstat, filename),
1768 (os.mkdir, filename),
1769 (os.open, filename, os.O_RDONLY),
1770 (os.rename, filename, filename),
1771 (os.rmdir, filename),
1772 (os.startfile, filename),
1773 (os.stat, filename),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001774 (os.unlink, filename),
1775 (os.utime, filename),
1776 ):
1777 self.assertRaises(DeprecationWarning, func, *args)
1778
Victor Stinner28216442011-11-16 00:34:44 +01001779 @support.skip_unless_symlink
1780 def test_symlink(self):
1781 filename = os.fsencode(support.TESTFN)
1782 with warnings.catch_warnings():
1783 warnings.simplefilter("error", DeprecationWarning)
1784 self.assertRaises(DeprecationWarning,
1785 os.symlink, filename, filename)
1786
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001787
Antoine Pitrouf26ad712011-07-15 23:00:56 +02001788@support.reap_threads
Fred Drake2e2be372001-09-20 21:33:42 +00001789def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001790 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001791 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001792 StatAttributeTests,
1793 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00001794 WalkTests,
Charles-François Natali7372b062012-02-05 15:15:38 +01001795 FwalkTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00001796 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +00001797 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001798 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001799 ExecTests,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001800 Win32ErrorTests,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001801 TestInvalidFD,
Martin v. Löwis011e8422009-05-05 04:43:17 +00001802 PosixUidGidTests,
Brian Curtineb24d742010-04-12 17:16:38 +00001803 Pep383Tests,
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00001804 Win32KillTests,
Brian Curtind40e6f72010-07-08 21:39:08 +00001805 Win32SymlinkTests,
Victor Stinnere8d51452010-08-19 01:05:19 +00001806 FSEncodingTests,
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00001807 PidTests,
Brian Curtine8e4b3b2010-09-23 20:04:14 +00001808 LoginTests,
Brian Curtin1b9df392010-11-24 20:24:31 +00001809 LinkTests,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001810 TestSendfile,
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001811 ProgramPriorityTests,
Benjamin Peterson799bd802011-08-31 22:15:17 -04001812 ExtendedAttributeTests,
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001813 Win32DeprecatedBytesAPI,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001814 )
Fred Drake2e2be372001-09-20 21:33:42 +00001815
1816if __name__ == "__main__":
1817 test_main()