blob: 7f955d1e90fc2be9c38acfd106eb4c08bddd6378 [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
Thomas Wouters89f507f2006-12-13 04:49:30 +0000303 # Restrict test to Win32, since there is no guarantee other
304 # systems support centiseconds
305 if sys.platform == 'win32':
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000306 def get_file_system(path):
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000307 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000308 import ctypes
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000309 kernel32 = ctypes.windll.kernel32
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000310 buf = ctypes.create_unicode_buffer("", 100)
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000311 if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000312 return buf.value
313
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000314 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000315 def test_1565150(self):
316 t1 = 1159195039.25
317 os.utime(self.fname, (t1, t1))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000318 self.assertEqual(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000319
Amaury Forgeot d'Arca251a852011-01-03 00:19:11 +0000320 def test_large_time(self):
321 t1 = 5000000000 # some day in 2128
322 os.utime(self.fname, (t1, t1))
323 self.assertEqual(os.stat(self.fname).st_mtime, t1)
324
Guido van Rossumd8faa362007-04-27 19:54:29 +0000325 def test_1686475(self):
326 # Verify that an open file can be stat'ed
327 try:
328 os.stat(r"c:\pagefile.sys")
329 except WindowsError as e:
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000330 if e.errno == 2: # file does not exist; cannot run test
Guido van Rossumd8faa362007-04-27 19:54:29 +0000331 return
332 self.fail("Could not stat pagefile.sys")
333
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000334from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000335
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000336class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000337 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000338 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000339
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000340 def setUp(self):
341 self.__save = dict(os.environ)
Victor Stinnerb745a742010-05-18 17:17:23 +0000342 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000343 self.__saveb = dict(os.environb)
Christian Heimes90333392007-11-01 19:08:42 +0000344 for key, value in self._reference().items():
345 os.environ[key] = value
346
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000347 def tearDown(self):
348 os.environ.clear()
349 os.environ.update(self.__save)
Victor Stinnerb745a742010-05-18 17:17:23 +0000350 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000351 os.environb.clear()
352 os.environb.update(self.__saveb)
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000353
Christian Heimes90333392007-11-01 19:08:42 +0000354 def _reference(self):
355 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
356
357 def _empty_mapping(self):
358 os.environ.clear()
359 return os.environ
360
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000361 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000362 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000363 os.environ.clear()
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000364 if os.path.exists("/bin/sh"):
365 os.environ.update(HELLO="World")
Brian Curtin810921b2010-10-30 21:24:21 +0000366 with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
367 value = popen.read().strip()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000368 self.assertEqual(value, "World")
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000369
Christian Heimes1a13d592007-11-08 14:16:55 +0000370 def test_os_popen_iter(self):
371 if os.path.exists("/bin/sh"):
Brian Curtin810921b2010-10-30 21:24:21 +0000372 with os.popen(
373 "/bin/sh -c 'echo \"line1\nline2\nline3\"'") as popen:
374 it = iter(popen)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000375 self.assertEqual(next(it), "line1\n")
376 self.assertEqual(next(it), "line2\n")
377 self.assertEqual(next(it), "line3\n")
Brian Curtin810921b2010-10-30 21:24:21 +0000378 self.assertRaises(StopIteration, next, it)
Christian Heimes1a13d592007-11-08 14:16:55 +0000379
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000380 # Verify environ keys and values from the OS are of the
381 # correct str type.
382 def test_keyvalue_types(self):
383 for key, val in os.environ.items():
Ezio Melottib3aedd42010-11-20 19:04:17 +0000384 self.assertEqual(type(key), str)
385 self.assertEqual(type(val), str)
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000386
Christian Heimes90333392007-11-01 19:08:42 +0000387 def test_items(self):
388 for key, value in self._reference().items():
389 self.assertEqual(os.environ.get(key), value)
390
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000391 # Issue 7310
392 def test___repr__(self):
393 """Check that the repr() of os.environ looks like environ({...})."""
394 env = os.environ
Victor Stinner96f0de92010-07-29 00:29:00 +0000395 self.assertEqual(repr(env), 'environ({{{}}})'.format(', '.join(
396 '{!r}: {!r}'.format(key, value)
397 for key, value in env.items())))
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000398
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000399 def test_get_exec_path(self):
400 defpath_list = os.defpath.split(os.pathsep)
401 test_path = ['/monty', '/python', '', '/flying/circus']
402 test_env = {'PATH': os.pathsep.join(test_path)}
403
404 saved_environ = os.environ
405 try:
406 os.environ = dict(test_env)
407 # Test that defaulting to os.environ works.
408 self.assertSequenceEqual(test_path, os.get_exec_path())
409 self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
410 finally:
411 os.environ = saved_environ
412
413 # No PATH environment variable
414 self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
415 # Empty PATH environment variable
416 self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
417 # Supplied PATH environment variable
418 self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
419
Victor Stinnerb745a742010-05-18 17:17:23 +0000420 if os.supports_bytes_environ:
421 # env cannot contain 'PATH' and b'PATH' keys
Victor Stinner38430e22010-08-19 17:10:18 +0000422 try:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000423 # ignore BytesWarning warning
424 with warnings.catch_warnings(record=True):
425 mixed_env = {'PATH': '1', b'PATH': b'2'}
Victor Stinner38430e22010-08-19 17:10:18 +0000426 except BytesWarning:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000427 # mixed_env cannot be created with python -bb
Victor Stinner38430e22010-08-19 17:10:18 +0000428 pass
429 else:
430 self.assertRaises(ValueError, os.get_exec_path, mixed_env)
Victor Stinnerb745a742010-05-18 17:17:23 +0000431
432 # bytes key and/or value
433 self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}),
434 ['abc'])
435 self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}),
436 ['abc'])
437 self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}),
438 ['abc'])
439
440 @unittest.skipUnless(os.supports_bytes_environ,
441 "os.environb required for this test.")
Victor Stinner84ae1182010-05-06 22:05:07 +0000442 def test_environb(self):
443 # os.environ -> os.environb
444 value = 'euro\u20ac'
445 try:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000446 value_bytes = value.encode(sys.getfilesystemencoding(),
447 'surrogateescape')
Victor Stinner84ae1182010-05-06 22:05:07 +0000448 except UnicodeEncodeError:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000449 msg = "U+20AC character is not encodable to %s" % (
450 sys.getfilesystemencoding(),)
Benjamin Peterson932d3f42010-05-06 22:26:31 +0000451 self.skipTest(msg)
Victor Stinner84ae1182010-05-06 22:05:07 +0000452 os.environ['unicode'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000453 self.assertEqual(os.environ['unicode'], value)
454 self.assertEqual(os.environb[b'unicode'], value_bytes)
Victor Stinner84ae1182010-05-06 22:05:07 +0000455
456 # os.environb -> os.environ
457 value = b'\xff'
458 os.environb[b'bytes'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000459 self.assertEqual(os.environb[b'bytes'], value)
Victor Stinner84ae1182010-05-06 22:05:07 +0000460 value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000461 self.assertEqual(os.environ['bytes'], value_str)
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000462
Charles-François Natali2966f102011-11-26 11:32:46 +0100463 # On FreeBSD < 7 and OS X < 10.6, unsetenv() doesn't return a value (issue
464 # #13415).
465 @support.requires_freebsd_version(7)
466 @support.requires_mac_ver(10, 6)
Victor Stinner60b385e2011-11-22 22:01:28 +0100467 def test_unset_error(self):
468 if sys.platform == "win32":
469 # an environment variable is limited to 32,767 characters
470 key = 'x' * 50000
Victor Stinnerb3f82682011-11-22 22:30:19 +0100471 self.assertRaises(ValueError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100472 else:
473 # "=" is not allowed in a variable name
474 key = 'key='
Victor Stinnerb3f82682011-11-22 22:30:19 +0100475 self.assertRaises(OSError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100476
Tim Petersc4e09402003-04-25 07:11:48 +0000477class WalkTests(unittest.TestCase):
478 """Tests for os.walk()."""
479
Charles-François Natali7372b062012-02-05 15:15:38 +0100480 def setUp(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000481 import os
482 from os.path import join
483
484 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000485 # TESTFN/
486 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000487 # tmp1
488 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000489 # tmp2
490 # SUB11/ no kids
491 # SUB2/ a file kid and a dirsymlink kid
492 # tmp3
493 # link/ a symlink to TESTFN.2
494 # TEST2/
495 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000496 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000497 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000498 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000499 sub2_path = join(walk_path, "SUB2")
500 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000501 tmp2_path = join(sub1_path, "tmp2")
502 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000503 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000504 t2_path = join(support.TESTFN, "TEST2")
505 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000506
507 # Create stuff.
508 os.makedirs(sub11_path)
509 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000510 os.makedirs(t2_path)
511 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000512 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000513 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
514 f.close()
Brian Curtin3b4499c2010-12-28 14:31:47 +0000515 if support.can_symlink():
Antoine Pitrou5311c1d2012-01-24 08:59:28 +0100516 if os.name == 'nt':
517 def symlink_to_dir(src, dest):
518 os.symlink(src, dest, True)
519 else:
520 symlink_to_dir = os.symlink
521 symlink_to_dir(os.path.abspath(t2_path), link_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000522 sub2_tree = (sub2_path, ["link"], ["tmp3"])
523 else:
524 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000525
526 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000527 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000528 self.assertEqual(len(all), 4)
529 # We can't know which order SUB1 and SUB2 will appear in.
530 # Not flipped: TESTFN, SUB1, SUB11, SUB2
531 # flipped: TESTFN, SUB2, SUB1, SUB11
532 flipped = all[0][1][0] != "SUB1"
533 all[0][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000534 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000535 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
536 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000537 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000538
539 # Prune the search.
540 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000541 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000542 all.append((root, dirs, files))
543 # Don't descend into SUB1.
544 if 'SUB1' in dirs:
545 # Note that this also mutates the dirs we appended to all!
546 dirs.remove('SUB1')
547 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000548 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
549 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000550
551 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000552 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000553 self.assertEqual(len(all), 4)
554 # We can't know which order SUB1 and SUB2 will appear in.
555 # Not flipped: SUB11, SUB1, SUB2, TESTFN
556 # flipped: SUB2, SUB11, SUB1, TESTFN
557 flipped = all[3][1][0] != "SUB1"
558 all[3][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000559 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000560 self.assertEqual(all[flipped], (sub11_path, [], []))
561 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000562 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000563
Brian Curtin3b4499c2010-12-28 14:31:47 +0000564 if support.can_symlink():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000565 # Walk, following symlinks.
566 for root, dirs, files in os.walk(walk_path, followlinks=True):
567 if root == link_path:
568 self.assertEqual(dirs, [])
569 self.assertEqual(files, ["tmp4"])
570 break
571 else:
572 self.fail("Didn't follow symlink with followlinks=True")
573
574 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000575 # Tear everything down. This is a decent use for bottom-up on
576 # Windows, which doesn't have a recursive delete command. The
577 # (not so) subtlety is that rmdir will fail unless the dir's
578 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000579 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000580 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000581 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000582 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000583 dirname = os.path.join(root, name)
584 if not os.path.islink(dirname):
585 os.rmdir(dirname)
586 else:
587 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000588 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000589
Charles-François Natali7372b062012-02-05 15:15:38 +0100590
591@unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
592class FwalkTests(WalkTests):
593 """Tests for os.fwalk()."""
594
595 def test_compare_to_walk(self):
596 # compare with walk() results
597 for topdown, followlinks in itertools.product((True, False), repeat=2):
598 args = support.TESTFN, topdown, None, followlinks
599 expected = {}
600 for root, dirs, files in os.walk(*args):
601 expected[root] = (set(dirs), set(files))
602
603 for root, dirs, files, rootfd in os.fwalk(*args):
604 self.assertIn(root, expected)
605 self.assertEqual(expected[root], (set(dirs), set(files)))
606
607 def test_dir_fd(self):
608 # check returned file descriptors
609 for topdown, followlinks in itertools.product((True, False), repeat=2):
610 args = support.TESTFN, topdown, None, followlinks
611 for root, dirs, files, rootfd in os.fwalk(*args):
612 # check that the FD is valid
613 os.fstat(rootfd)
614 # check that fdlistdir() returns consistent information
615 self.assertEqual(set(os.fdlistdir(rootfd)), set(dirs) | set(files))
616
617 def test_fd_leak(self):
618 # Since we're opening a lot of FDs, we must be careful to avoid leaks:
619 # we both check that calling fwalk() a large number of times doesn't
620 # yield EMFILE, and that the minimum allocated FD hasn't changed.
621 minfd = os.dup(1)
622 os.close(minfd)
623 for i in range(256):
624 for x in os.fwalk(support.TESTFN):
625 pass
626 newfd = os.dup(1)
627 self.addCleanup(os.close, newfd)
628 self.assertEqual(newfd, minfd)
629
630 def tearDown(self):
631 # cleanup
632 for root, dirs, files, rootfd in os.fwalk(support.TESTFN, topdown=False):
633 for name in files:
634 os.unlinkat(rootfd, name)
635 for name in dirs:
636 st = os.fstatat(rootfd, name, os.AT_SYMLINK_NOFOLLOW)
637 if stat.S_ISDIR(st.st_mode):
638 os.unlinkat(rootfd, name, os.AT_REMOVEDIR)
639 else:
640 os.unlinkat(rootfd, name)
641 os.rmdir(support.TESTFN)
642
643
Guido van Rossume7ba4952007-06-06 23:52:48 +0000644class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000645 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000646 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000647
648 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000649 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000650 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
651 os.makedirs(path) # Should work
652 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
653 os.makedirs(path)
654
655 # Try paths with a '.' in them
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000656 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000657 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
658 os.makedirs(path)
659 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
660 'dir5', 'dir6')
661 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000662
Terry Reedy5a22b652010-12-02 07:05:56 +0000663 def test_exist_ok_existing_directory(self):
664 path = os.path.join(support.TESTFN, 'dir1')
665 mode = 0o777
666 old_mask = os.umask(0o022)
667 os.makedirs(path, mode)
668 self.assertRaises(OSError, os.makedirs, path, mode)
669 self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
670 self.assertRaises(OSError, os.makedirs, path, 0o776, exist_ok=True)
671 os.makedirs(path, mode=mode, exist_ok=True)
672 os.umask(old_mask)
673
674 def test_exist_ok_existing_regular_file(self):
675 base = support.TESTFN
676 path = os.path.join(support.TESTFN, 'dir1')
677 f = open(path, 'w')
678 f.write('abc')
679 f.close()
680 self.assertRaises(OSError, os.makedirs, path)
681 self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
682 self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
683 os.remove(path)
684
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000685 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000686 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000687 'dir4', 'dir5', 'dir6')
688 # If the tests failed, the bottom-most directory ('../dir6')
689 # may not have been created, so we look for the outermost directory
690 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000691 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000692 path = os.path.dirname(path)
693
694 os.removedirs(path)
695
Guido van Rossume7ba4952007-06-06 23:52:48 +0000696class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000697 def test_devnull(self):
Victor Stinnera6d2c762011-06-30 18:20:11 +0200698 with open(os.devnull, 'wb') as f:
699 f.write(b'hello')
700 f.close()
701 with open(os.devnull, 'rb') as f:
702 self.assertEqual(f.read(), b'')
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000703
Guido van Rossume7ba4952007-06-06 23:52:48 +0000704class URandomTests(unittest.TestCase):
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000705 def test_urandom(self):
706 try:
707 self.assertEqual(len(os.urandom(1)), 1)
708 self.assertEqual(len(os.urandom(10)), 10)
709 self.assertEqual(len(os.urandom(100)), 100)
710 self.assertEqual(len(os.urandom(1000)), 1000)
711 except NotImplementedError:
712 pass
713
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000714@contextlib.contextmanager
715def _execvpe_mockup(defpath=None):
716 """
717 Stubs out execv and execve functions when used as context manager.
718 Records exec calls. The mock execv and execve functions always raise an
719 exception as they would normally never return.
720 """
721 # A list of tuples containing (function name, first arg, args)
722 # of calls to execv or execve that have been made.
723 calls = []
724
725 def mock_execv(name, *args):
726 calls.append(('execv', name, args))
727 raise RuntimeError("execv called")
728
729 def mock_execve(name, *args):
730 calls.append(('execve', name, args))
731 raise OSError(errno.ENOTDIR, "execve called")
732
733 try:
734 orig_execv = os.execv
735 orig_execve = os.execve
736 orig_defpath = os.defpath
737 os.execv = mock_execv
738 os.execve = mock_execve
739 if defpath is not None:
740 os.defpath = defpath
741 yield calls
742 finally:
743 os.execv = orig_execv
744 os.execve = orig_execve
745 os.defpath = orig_defpath
746
Guido van Rossume7ba4952007-06-06 23:52:48 +0000747class ExecTests(unittest.TestCase):
Mark Dickinson7cf03892010-04-16 13:45:35 +0000748 @unittest.skipIf(USING_LINUXTHREADS,
749 "avoid triggering a linuxthreads bug: see issue #4970")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000750 def test_execvpe_with_bad_program(self):
Mark Dickinson7cf03892010-04-16 13:45:35 +0000751 self.assertRaises(OSError, os.execvpe, 'no such app-',
752 ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000753
Thomas Heller6790d602007-08-30 17:15:14 +0000754 def test_execvpe_with_bad_arglist(self):
755 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
756
Gregory P. Smith4ae37772010-05-08 18:05:46 +0000757 @unittest.skipUnless(hasattr(os, '_execvpe'),
758 "No internal os._execvpe function to test.")
Victor Stinnerb745a742010-05-18 17:17:23 +0000759 def _test_internal_execvpe(self, test_type):
760 program_path = os.sep + 'absolutepath'
761 if test_type is bytes:
762 program = b'executable'
763 fullpath = os.path.join(os.fsencode(program_path), program)
764 native_fullpath = fullpath
765 arguments = [b'progname', 'arg1', 'arg2']
766 else:
767 program = 'executable'
768 arguments = ['progname', 'arg1', 'arg2']
769 fullpath = os.path.join(program_path, program)
770 if os.name != "nt":
771 native_fullpath = os.fsencode(fullpath)
772 else:
773 native_fullpath = fullpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000774 env = {'spam': 'beans'}
775
Victor Stinnerb745a742010-05-18 17:17:23 +0000776 # test os._execvpe() with an absolute path
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000777 with _execvpe_mockup() as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +0000778 self.assertRaises(RuntimeError,
779 os._execvpe, fullpath, arguments)
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000780 self.assertEqual(len(calls), 1)
781 self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))
782
Victor Stinnerb745a742010-05-18 17:17:23 +0000783 # test os._execvpe() with a relative path:
784 # os.get_exec_path() returns defpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000785 with _execvpe_mockup(defpath=program_path) as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +0000786 self.assertRaises(OSError,
787 os._execvpe, program, arguments, env=env)
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000788 self.assertEqual(len(calls), 1)
Victor Stinnerb745a742010-05-18 17:17:23 +0000789 self.assertSequenceEqual(calls[0],
790 ('execve', native_fullpath, (arguments, env)))
791
792 # test os._execvpe() with a relative path:
793 # os.get_exec_path() reads the 'PATH' variable
794 with _execvpe_mockup() as calls:
795 env_path = env.copy()
Victor Stinner38430e22010-08-19 17:10:18 +0000796 if test_type is bytes:
797 env_path[b'PATH'] = program_path
798 else:
799 env_path['PATH'] = program_path
Victor Stinnerb745a742010-05-18 17:17:23 +0000800 self.assertRaises(OSError,
801 os._execvpe, program, arguments, env=env_path)
802 self.assertEqual(len(calls), 1)
803 self.assertSequenceEqual(calls[0],
804 ('execve', native_fullpath, (arguments, env_path)))
805
806 def test_internal_execvpe_str(self):
807 self._test_internal_execvpe(str)
808 if os.name != "nt":
809 self._test_internal_execvpe(bytes)
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000810
Gregory P. Smith4ae37772010-05-08 18:05:46 +0000811
Thomas Wouters477c8d52006-05-27 19:21:47 +0000812class Win32ErrorTests(unittest.TestCase):
813 def test_rename(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000814 self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000815
816 def test_remove(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000817 self.assertRaises(WindowsError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000818
819 def test_chdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000820 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000821
822 def test_mkdir(self):
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +0000823 f = open(support.TESTFN, "w")
Benjamin Petersonf91df042009-02-13 02:50:59 +0000824 try:
825 self.assertRaises(WindowsError, os.mkdir, support.TESTFN)
826 finally:
827 f.close()
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +0000828 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000829
830 def test_utime(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000831 self.assertRaises(WindowsError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000832
Thomas Wouters477c8d52006-05-27 19:21:47 +0000833 def test_chmod(self):
Benjamin Petersonf91df042009-02-13 02:50:59 +0000834 self.assertRaises(WindowsError, os.chmod, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000835
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000836class TestInvalidFD(unittest.TestCase):
Benjamin Peterson05e782f2009-01-19 15:15:02 +0000837 singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000838 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
839 #singles.append("close")
840 #We omit close because it doesn'r raise an exception on some platforms
841 def get_single(f):
842 def helper(self):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000843 if hasattr(os, f):
844 self.check(getattr(os, f))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000845 return helper
846 for f in singles:
847 locals()["test_"+f] = get_single(f)
848
Benjamin Peterson7522c742009-01-19 21:00:09 +0000849 def check(self, f, *args):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000850 try:
851 f(support.make_bad_fd(), *args)
852 except OSError as e:
853 self.assertEqual(e.errno, errno.EBADF)
854 else:
855 self.fail("%r didn't raise a OSError with a bad file descriptor"
856 % f)
Benjamin Peterson7522c742009-01-19 21:00:09 +0000857
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000858 def test_isatty(self):
859 if hasattr(os, "isatty"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000860 self.assertEqual(os.isatty(support.make_bad_fd()), False)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000861
862 def test_closerange(self):
863 if hasattr(os, "closerange"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000864 fd = support.make_bad_fd()
R. David Murray630cc482009-07-22 15:20:27 +0000865 # Make sure none of the descriptors we are about to close are
866 # currently valid (issue 6542).
867 for i in range(10):
868 try: os.fstat(fd+i)
869 except OSError:
870 pass
871 else:
872 break
873 if i < 2:
874 raise unittest.SkipTest(
875 "Unable to acquire a range of invalid file descriptors")
876 self.assertEqual(os.closerange(fd, fd + i-1), None)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000877
878 def test_dup2(self):
879 if hasattr(os, "dup2"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000880 self.check(os.dup2, 20)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000881
882 def test_fchmod(self):
883 if hasattr(os, "fchmod"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000884 self.check(os.fchmod, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000885
886 def test_fchown(self):
887 if hasattr(os, "fchown"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000888 self.check(os.fchown, -1, -1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000889
890 def test_fpathconf(self):
891 if hasattr(os, "fpathconf"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000892 self.check(os.fpathconf, "PC_NAME_MAX")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000893
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000894 def test_ftruncate(self):
895 if hasattr(os, "ftruncate"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000896 self.check(os.ftruncate, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000897
898 def test_lseek(self):
899 if hasattr(os, "lseek"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000900 self.check(os.lseek, 0, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000901
902 def test_read(self):
903 if hasattr(os, "read"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000904 self.check(os.read, 1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000905
906 def test_tcsetpgrpt(self):
907 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000908 self.check(os.tcsetpgrp, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000909
910 def test_write(self):
911 if hasattr(os, "write"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000912 self.check(os.write, b" ")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000913
Brian Curtin1b9df392010-11-24 20:24:31 +0000914
915class LinkTests(unittest.TestCase):
916 def setUp(self):
917 self.file1 = support.TESTFN
918 self.file2 = os.path.join(support.TESTFN + "2")
919
Brian Curtinc0abc4e2010-11-30 23:46:54 +0000920 def tearDown(self):
Brian Curtin1b9df392010-11-24 20:24:31 +0000921 for file in (self.file1, self.file2):
922 if os.path.exists(file):
923 os.unlink(file)
924
Brian Curtin1b9df392010-11-24 20:24:31 +0000925 def _test_link(self, file1, file2):
926 with open(file1, "w") as f1:
927 f1.write("test")
928
Victor Stinner1ab6c2d2011-11-15 22:27:41 +0100929 with warnings.catch_warnings():
930 warnings.simplefilter("ignore", DeprecationWarning)
931 os.link(file1, file2)
Brian Curtin1b9df392010-11-24 20:24:31 +0000932 with open(file1, "r") as f1, open(file2, "r") as f2:
933 self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
934
935 def test_link(self):
936 self._test_link(self.file1, self.file2)
937
938 def test_link_bytes(self):
939 self._test_link(bytes(self.file1, sys.getfilesystemencoding()),
940 bytes(self.file2, sys.getfilesystemencoding()))
941
Brian Curtinf498b752010-11-30 15:54:04 +0000942 def test_unicode_name(self):
Brian Curtin43f0c272010-11-30 15:40:04 +0000943 try:
Brian Curtinf498b752010-11-30 15:54:04 +0000944 os.fsencode("\xf1")
Brian Curtin43f0c272010-11-30 15:40:04 +0000945 except UnicodeError:
946 raise unittest.SkipTest("Unable to encode for this platform.")
947
Brian Curtinf498b752010-11-30 15:54:04 +0000948 self.file1 += "\xf1"
Brian Curtinfc889c42010-11-28 23:59:46 +0000949 self.file2 = self.file1 + "2"
950 self._test_link(self.file1, self.file2)
951
Thomas Wouters477c8d52006-05-27 19:21:47 +0000952if sys.platform != 'win32':
953 class Win32ErrorTests(unittest.TestCase):
954 pass
955
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000956 class PosixUidGidTests(unittest.TestCase):
957 if hasattr(os, 'setuid'):
958 def test_setuid(self):
959 if os.getuid() != 0:
960 self.assertRaises(os.error, os.setuid, 0)
961 self.assertRaises(OverflowError, os.setuid, 1<<32)
962
963 if hasattr(os, 'setgid'):
964 def test_setgid(self):
965 if os.getuid() != 0:
966 self.assertRaises(os.error, os.setgid, 0)
967 self.assertRaises(OverflowError, os.setgid, 1<<32)
968
969 if hasattr(os, 'seteuid'):
970 def test_seteuid(self):
971 if os.getuid() != 0:
972 self.assertRaises(os.error, os.seteuid, 0)
973 self.assertRaises(OverflowError, os.seteuid, 1<<32)
974
975 if hasattr(os, 'setegid'):
976 def test_setegid(self):
977 if os.getuid() != 0:
978 self.assertRaises(os.error, os.setegid, 0)
979 self.assertRaises(OverflowError, os.setegid, 1<<32)
980
981 if hasattr(os, 'setreuid'):
982 def test_setreuid(self):
983 if os.getuid() != 0:
984 self.assertRaises(os.error, os.setreuid, 0, 0)
985 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
986 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000987
988 def test_setreuid_neg1(self):
989 # Needs to accept -1. We run this in a subprocess to avoid
990 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000991 subprocess.check_call([
992 sys.executable, '-c',
993 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000994
995 if hasattr(os, 'setregid'):
996 def test_setregid(self):
997 if os.getuid() != 0:
998 self.assertRaises(os.error, os.setregid, 0, 0)
999 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
1000 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001001
1002 def test_setregid_neg1(self):
1003 # Needs to accept -1. We run this in a subprocess to avoid
1004 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001005 subprocess.check_call([
1006 sys.executable, '-c',
1007 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Martin v. Löwis011e8422009-05-05 04:43:17 +00001008
1009 class Pep383Tests(unittest.TestCase):
Martin v. Löwis011e8422009-05-05 04:43:17 +00001010 def setUp(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001011 if support.TESTFN_UNENCODABLE:
1012 self.dir = support.TESTFN_UNENCODABLE
1013 else:
1014 self.dir = support.TESTFN
1015 self.bdir = os.fsencode(self.dir)
1016
1017 bytesfn = []
1018 def add_filename(fn):
1019 try:
1020 fn = os.fsencode(fn)
1021 except UnicodeEncodeError:
1022 return
1023 bytesfn.append(fn)
1024 add_filename(support.TESTFN_UNICODE)
1025 if support.TESTFN_UNENCODABLE:
1026 add_filename(support.TESTFN_UNENCODABLE)
1027 if not bytesfn:
1028 self.skipTest("couldn't create any non-ascii filename")
1029
1030 self.unicodefn = set()
Martin v. Löwis011e8422009-05-05 04:43:17 +00001031 os.mkdir(self.dir)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001032 try:
1033 for fn in bytesfn:
Victor Stinnerbf816222011-06-30 23:25:47 +02001034 support.create_empty_file(os.path.join(self.bdir, fn))
Victor Stinnere8d51452010-08-19 01:05:19 +00001035 fn = os.fsdecode(fn)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001036 if fn in self.unicodefn:
1037 raise ValueError("duplicate filename")
1038 self.unicodefn.add(fn)
1039 except:
1040 shutil.rmtree(self.dir)
1041 raise
Martin v. Löwis011e8422009-05-05 04:43:17 +00001042
1043 def tearDown(self):
1044 shutil.rmtree(self.dir)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001045
1046 def test_listdir(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001047 expected = self.unicodefn
1048 found = set(os.listdir(self.dir))
Ezio Melottib3aedd42010-11-20 19:04:17 +00001049 self.assertEqual(found, expected)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001050
1051 def test_open(self):
1052 for fn in self.unicodefn:
Victor Stinnera6d2c762011-06-30 18:20:11 +02001053 f = open(os.path.join(self.dir, fn), 'rb')
Martin v. Löwis011e8422009-05-05 04:43:17 +00001054 f.close()
1055
1056 def test_stat(self):
1057 for fn in self.unicodefn:
1058 os.stat(os.path.join(self.dir, fn))
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001059else:
1060 class PosixUidGidTests(unittest.TestCase):
1061 pass
Martin v. Löwis011e8422009-05-05 04:43:17 +00001062 class Pep383Tests(unittest.TestCase):
1063 pass
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001064
Brian Curtineb24d742010-04-12 17:16:38 +00001065@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
1066class Win32KillTests(unittest.TestCase):
Brian Curtinc3acbc32010-05-28 16:08:40 +00001067 def _kill(self, sig):
1068 # Start sys.executable as a subprocess and communicate from the
1069 # subprocess to the parent that the interpreter is ready. When it
1070 # becomes ready, send *sig* via os.kill to the subprocess and check
1071 # that the return code is equal to *sig*.
1072 import ctypes
1073 from ctypes import wintypes
1074 import msvcrt
1075
1076 # Since we can't access the contents of the process' stdout until the
1077 # process has exited, use PeekNamedPipe to see what's inside stdout
1078 # without waiting. This is done so we can tell that the interpreter
1079 # is started and running at a point where it could handle a signal.
1080 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
1081 PeekNamedPipe.restype = wintypes.BOOL
1082 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
1083 ctypes.POINTER(ctypes.c_char), # stdout buf
1084 wintypes.DWORD, # Buffer size
1085 ctypes.POINTER(wintypes.DWORD), # bytes read
1086 ctypes.POINTER(wintypes.DWORD), # bytes avail
1087 ctypes.POINTER(wintypes.DWORD)) # bytes left
1088 msg = "running"
1089 proc = subprocess.Popen([sys.executable, "-c",
1090 "import sys;"
1091 "sys.stdout.write('{}');"
1092 "sys.stdout.flush();"
1093 "input()".format(msg)],
1094 stdout=subprocess.PIPE,
1095 stderr=subprocess.PIPE,
1096 stdin=subprocess.PIPE)
Brian Curtin43ec5772010-11-05 15:17:11 +00001097 self.addCleanup(proc.stdout.close)
1098 self.addCleanup(proc.stderr.close)
1099 self.addCleanup(proc.stdin.close)
Brian Curtinc3acbc32010-05-28 16:08:40 +00001100
1101 count, max = 0, 100
1102 while count < max and proc.poll() is None:
1103 # Create a string buffer to store the result of stdout from the pipe
1104 buf = ctypes.create_string_buffer(len(msg))
1105 # Obtain the text currently in proc.stdout
1106 # Bytes read/avail/left are left as NULL and unused
1107 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
1108 buf, ctypes.sizeof(buf), None, None, None)
1109 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
1110 if buf.value:
1111 self.assertEqual(msg, buf.value.decode())
1112 break
1113 time.sleep(0.1)
1114 count += 1
1115 else:
1116 self.fail("Did not receive communication from the subprocess")
1117
Brian Curtineb24d742010-04-12 17:16:38 +00001118 os.kill(proc.pid, sig)
1119 self.assertEqual(proc.wait(), sig)
1120
1121 def test_kill_sigterm(self):
1122 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinc3acbc32010-05-28 16:08:40 +00001123 self._kill(signal.SIGTERM)
Brian Curtineb24d742010-04-12 17:16:38 +00001124
1125 def test_kill_int(self):
1126 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinc3acbc32010-05-28 16:08:40 +00001127 self._kill(100)
Brian Curtineb24d742010-04-12 17:16:38 +00001128
1129 def _kill_with_event(self, event, name):
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001130 tagname = "test_os_%s" % uuid.uuid1()
1131 m = mmap.mmap(-1, 1, tagname)
1132 m[0] = 0
Brian Curtineb24d742010-04-12 17:16:38 +00001133 # Run a script which has console control handling enabled.
1134 proc = subprocess.Popen([sys.executable,
1135 os.path.join(os.path.dirname(__file__),
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001136 "win_console_handler.py"), tagname],
Brian Curtineb24d742010-04-12 17:16:38 +00001137 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
1138 # Let the interpreter startup before we send signals. See #3137.
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001139 count, max = 0, 100
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001140 while count < max and proc.poll() is None:
Brian Curtinf668df52010-10-15 14:21:06 +00001141 if m[0] == 1:
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001142 break
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001143 time.sleep(0.1)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001144 count += 1
1145 else:
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001146 # Forcefully kill the process if we weren't able to signal it.
1147 os.kill(proc.pid, signal.SIGINT)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001148 self.fail("Subprocess didn't finish initialization")
Brian Curtineb24d742010-04-12 17:16:38 +00001149 os.kill(proc.pid, event)
1150 # proc.send_signal(event) could also be done here.
1151 # Allow time for the signal to be passed and the process to exit.
1152 time.sleep(0.5)
1153 if not proc.poll():
1154 # Forcefully kill the process if we weren't able to signal it.
1155 os.kill(proc.pid, signal.SIGINT)
1156 self.fail("subprocess did not stop on {}".format(name))
1157
1158 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
1159 def test_CTRL_C_EVENT(self):
1160 from ctypes import wintypes
1161 import ctypes
1162
1163 # Make a NULL value by creating a pointer with no argument.
1164 NULL = ctypes.POINTER(ctypes.c_int)()
1165 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
1166 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
1167 wintypes.BOOL)
1168 SetConsoleCtrlHandler.restype = wintypes.BOOL
1169
1170 # Calling this with NULL and FALSE causes the calling process to
1171 # handle CTRL+C, rather than ignore it. This property is inherited
1172 # by subprocesses.
1173 SetConsoleCtrlHandler(NULL, 0)
1174
1175 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
1176
1177 def test_CTRL_BREAK_EVENT(self):
1178 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
1179
1180
Brian Curtind40e6f72010-07-08 21:39:08 +00001181@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Brian Curtin3b4499c2010-12-28 14:31:47 +00001182@support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +00001183class Win32SymlinkTests(unittest.TestCase):
1184 filelink = 'filelinktest'
1185 filelink_target = os.path.abspath(__file__)
1186 dirlink = 'dirlinktest'
1187 dirlink_target = os.path.dirname(filelink_target)
1188 missing_link = 'missing link'
1189
1190 def setUp(self):
1191 assert os.path.exists(self.dirlink_target)
1192 assert os.path.exists(self.filelink_target)
1193 assert not os.path.exists(self.dirlink)
1194 assert not os.path.exists(self.filelink)
1195 assert not os.path.exists(self.missing_link)
1196
1197 def tearDown(self):
1198 if os.path.exists(self.filelink):
1199 os.remove(self.filelink)
1200 if os.path.exists(self.dirlink):
1201 os.rmdir(self.dirlink)
1202 if os.path.lexists(self.missing_link):
1203 os.remove(self.missing_link)
1204
1205 def test_directory_link(self):
Antoine Pitrou5311c1d2012-01-24 08:59:28 +01001206 os.symlink(self.dirlink_target, self.dirlink, True)
Brian Curtind40e6f72010-07-08 21:39:08 +00001207 self.assertTrue(os.path.exists(self.dirlink))
1208 self.assertTrue(os.path.isdir(self.dirlink))
1209 self.assertTrue(os.path.islink(self.dirlink))
1210 self.check_stat(self.dirlink, self.dirlink_target)
1211
1212 def test_file_link(self):
1213 os.symlink(self.filelink_target, self.filelink)
1214 self.assertTrue(os.path.exists(self.filelink))
1215 self.assertTrue(os.path.isfile(self.filelink))
1216 self.assertTrue(os.path.islink(self.filelink))
1217 self.check_stat(self.filelink, self.filelink_target)
1218
1219 def _create_missing_dir_link(self):
1220 'Create a "directory" link to a non-existent target'
1221 linkname = self.missing_link
1222 if os.path.lexists(linkname):
1223 os.remove(linkname)
1224 target = r'c:\\target does not exist.29r3c740'
1225 assert not os.path.exists(target)
1226 target_is_dir = True
1227 os.symlink(target, linkname, target_is_dir)
1228
1229 def test_remove_directory_link_to_missing_target(self):
1230 self._create_missing_dir_link()
1231 # For compatibility with Unix, os.remove will check the
1232 # directory status and call RemoveDirectory if the symlink
1233 # was created with target_is_dir==True.
1234 os.remove(self.missing_link)
1235
1236 @unittest.skip("currently fails; consider for improvement")
1237 def test_isdir_on_directory_link_to_missing_target(self):
1238 self._create_missing_dir_link()
1239 # consider having isdir return true for directory links
1240 self.assertTrue(os.path.isdir(self.missing_link))
1241
1242 @unittest.skip("currently fails; consider for improvement")
1243 def test_rmdir_on_directory_link_to_missing_target(self):
1244 self._create_missing_dir_link()
1245 # consider allowing rmdir to remove directory links
1246 os.rmdir(self.missing_link)
1247
1248 def check_stat(self, link, target):
1249 self.assertEqual(os.stat(link), os.stat(target))
1250 self.assertNotEqual(os.lstat(link), os.stat(link))
1251
Brian Curtind25aef52011-06-13 15:16:04 -05001252 bytes_link = os.fsencode(link)
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001253 with warnings.catch_warnings():
1254 warnings.simplefilter("ignore", DeprecationWarning)
1255 self.assertEqual(os.stat(bytes_link), os.stat(target))
1256 self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link))
Brian Curtind25aef52011-06-13 15:16:04 -05001257
1258 def test_12084(self):
1259 level1 = os.path.abspath(support.TESTFN)
1260 level2 = os.path.join(level1, "level2")
1261 level3 = os.path.join(level2, "level3")
1262 try:
1263 os.mkdir(level1)
1264 os.mkdir(level2)
1265 os.mkdir(level3)
1266
1267 file1 = os.path.abspath(os.path.join(level1, "file1"))
1268
1269 with open(file1, "w") as f:
1270 f.write("file1")
1271
1272 orig_dir = os.getcwd()
1273 try:
1274 os.chdir(level2)
1275 link = os.path.join(level2, "link")
1276 os.symlink(os.path.relpath(file1), "link")
1277 self.assertIn("link", os.listdir(os.getcwd()))
1278
1279 # Check os.stat calls from the same dir as the link
1280 self.assertEqual(os.stat(file1), os.stat("link"))
1281
1282 # Check os.stat calls from a dir below the link
1283 os.chdir(level1)
1284 self.assertEqual(os.stat(file1),
1285 os.stat(os.path.relpath(link)))
1286
1287 # Check os.stat calls from a dir above the link
1288 os.chdir(level3)
1289 self.assertEqual(os.stat(file1),
1290 os.stat(os.path.relpath(link)))
1291 finally:
1292 os.chdir(orig_dir)
1293 except OSError as err:
1294 self.fail(err)
1295 finally:
1296 os.remove(file1)
1297 shutil.rmtree(level1)
1298
Brian Curtind40e6f72010-07-08 21:39:08 +00001299
Victor Stinnere8d51452010-08-19 01:05:19 +00001300class FSEncodingTests(unittest.TestCase):
1301 def test_nop(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001302 self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
1303 self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
Benjamin Peterson31191a92010-05-09 03:22:58 +00001304
Victor Stinnere8d51452010-08-19 01:05:19 +00001305 def test_identity(self):
1306 # assert fsdecode(fsencode(x)) == x
1307 for fn in ('unicode\u0141', 'latin\xe9', 'ascii'):
1308 try:
1309 bytesfn = os.fsencode(fn)
1310 except UnicodeEncodeError:
1311 continue
Ezio Melottib3aedd42010-11-20 19:04:17 +00001312 self.assertEqual(os.fsdecode(bytesfn), fn)
Victor Stinnere8d51452010-08-19 01:05:19 +00001313
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00001314
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00001315class PidTests(unittest.TestCase):
1316 @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid")
1317 def test_getppid(self):
1318 p = subprocess.Popen([sys.executable, '-c',
1319 'import os; print(os.getppid())'],
1320 stdout=subprocess.PIPE)
1321 stdout, _ = p.communicate()
1322 # We are the parent of our subprocess
1323 self.assertEqual(int(stdout), os.getpid())
1324
1325
Brian Curtin0151b8e2010-09-24 13:43:43 +00001326# The introduction of this TestCase caused at least two different errors on
1327# *nix buildbots. Temporarily skip this to let the buildbots move along.
1328@unittest.skip("Skip due to platform/environment differences on *NIX buildbots")
Brian Curtine8e4b3b2010-09-23 20:04:14 +00001329@unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin")
1330class LoginTests(unittest.TestCase):
1331 def test_getlogin(self):
1332 user_name = os.getlogin()
1333 self.assertNotEqual(len(user_name), 0)
1334
1335
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001336@unittest.skipUnless(hasattr(os, 'getpriority') and hasattr(os, 'setpriority'),
1337 "needs os.getpriority and os.setpriority")
1338class ProgramPriorityTests(unittest.TestCase):
1339 """Tests for os.getpriority() and os.setpriority()."""
1340
1341 def test_set_get_priority(self):
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001342
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001343 base = os.getpriority(os.PRIO_PROCESS, os.getpid())
1344 os.setpriority(os.PRIO_PROCESS, os.getpid(), base + 1)
1345 try:
Giampaolo Rodolàcfbcec32011-02-28 19:27:16 +00001346 new_prio = os.getpriority(os.PRIO_PROCESS, os.getpid())
1347 if base >= 19 and new_prio <= 19:
1348 raise unittest.SkipTest(
1349 "unable to reliably test setpriority at current nice level of %s" % base)
1350 else:
1351 self.assertEqual(new_prio, base + 1)
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001352 finally:
1353 try:
1354 os.setpriority(os.PRIO_PROCESS, os.getpid(), base)
1355 except OSError as err:
Antoine Pitrou692f0382011-02-26 00:22:25 +00001356 if err.errno != errno.EACCES:
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001357 raise
1358
1359
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001360if threading is not None:
1361 class SendfileTestServer(asyncore.dispatcher, threading.Thread):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001362
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001363 class Handler(asynchat.async_chat):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001364
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001365 def __init__(self, conn):
1366 asynchat.async_chat.__init__(self, conn)
1367 self.in_buffer = []
1368 self.closed = False
1369 self.push(b"220 ready\r\n")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001370
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001371 def handle_read(self):
1372 data = self.recv(4096)
1373 self.in_buffer.append(data)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001374
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001375 def get_data(self):
1376 return b''.join(self.in_buffer)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001377
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001378 def handle_close(self):
1379 self.close()
1380 self.closed = True
1381
1382 def handle_error(self):
1383 raise
1384
1385 def __init__(self, address):
1386 threading.Thread.__init__(self)
1387 asyncore.dispatcher.__init__(self)
1388 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
1389 self.bind(address)
1390 self.listen(5)
1391 self.host, self.port = self.socket.getsockname()[:2]
1392 self.handler_instance = None
1393 self._active = False
1394 self._active_lock = threading.Lock()
1395
1396 # --- public API
1397
1398 @property
1399 def running(self):
1400 return self._active
1401
1402 def start(self):
1403 assert not self.running
1404 self.__flag = threading.Event()
1405 threading.Thread.start(self)
1406 self.__flag.wait()
1407
1408 def stop(self):
1409 assert self.running
1410 self._active = False
1411 self.join()
1412
1413 def wait(self):
1414 # wait for handler connection to be closed, then stop the server
1415 while not getattr(self.handler_instance, "closed", False):
1416 time.sleep(0.001)
1417 self.stop()
1418
1419 # --- internals
1420
1421 def run(self):
1422 self._active = True
1423 self.__flag.set()
1424 while self._active and asyncore.socket_map:
1425 self._active_lock.acquire()
1426 asyncore.loop(timeout=0.001, count=1)
1427 self._active_lock.release()
1428 asyncore.close_all()
1429
1430 def handle_accept(self):
1431 conn, addr = self.accept()
1432 self.handler_instance = self.Handler(conn)
1433
1434 def handle_connect(self):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001435 self.close()
Giampaolo Rodola'566f8a62011-05-18 21:28:39 +02001436 handle_read = handle_connect
1437
1438 def writable(self):
1439 return 0
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001440
1441 def handle_error(self):
1442 raise
1443
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001444
Giampaolo Rodolà46134642011-02-25 20:01:05 +00001445@unittest.skipUnless(threading is not None, "test needs threading module")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001446@unittest.skipUnless(hasattr(os, 'sendfile'), "test needs os.sendfile()")
1447class TestSendfile(unittest.TestCase):
1448
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001449 DATA = b"12345abcde" * 16 * 1024 # 160 KB
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001450 SUPPORT_HEADERS_TRAILERS = not sys.platform.startswith("linux") and \
Giampaolo Rodolà4bc68572011-02-25 21:46:01 +00001451 not sys.platform.startswith("solaris") and \
1452 not sys.platform.startswith("sunos")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001453
1454 @classmethod
1455 def setUpClass(cls):
1456 with open(support.TESTFN, "wb") as f:
1457 f.write(cls.DATA)
1458
1459 @classmethod
1460 def tearDownClass(cls):
1461 support.unlink(support.TESTFN)
1462
1463 def setUp(self):
1464 self.server = SendfileTestServer((support.HOST, 0))
1465 self.server.start()
1466 self.client = socket.socket()
1467 self.client.connect((self.server.host, self.server.port))
1468 self.client.settimeout(1)
1469 # synchronize by waiting for "220 ready" response
1470 self.client.recv(1024)
1471 self.sockno = self.client.fileno()
1472 self.file = open(support.TESTFN, 'rb')
1473 self.fileno = self.file.fileno()
1474
1475 def tearDown(self):
1476 self.file.close()
1477 self.client.close()
1478 if self.server.running:
1479 self.server.stop()
1480
1481 def sendfile_wrapper(self, sock, file, offset, nbytes, headers=[], trailers=[]):
1482 """A higher level wrapper representing how an application is
1483 supposed to use sendfile().
1484 """
1485 while 1:
1486 try:
1487 if self.SUPPORT_HEADERS_TRAILERS:
1488 return os.sendfile(sock, file, offset, nbytes, headers,
1489 trailers)
1490 else:
1491 return os.sendfile(sock, file, offset, nbytes)
1492 except OSError as err:
1493 if err.errno == errno.ECONNRESET:
1494 # disconnected
1495 raise
1496 elif err.errno in (errno.EAGAIN, errno.EBUSY):
1497 # we have to retry send data
1498 continue
1499 else:
1500 raise
1501
1502 def test_send_whole_file(self):
1503 # normal send
1504 total_sent = 0
1505 offset = 0
1506 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001507 while total_sent < len(self.DATA):
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001508 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
1509 if sent == 0:
1510 break
1511 offset += sent
1512 total_sent += sent
1513 self.assertTrue(sent <= nbytes)
1514 self.assertEqual(offset, total_sent)
1515
1516 self.assertEqual(total_sent, len(self.DATA))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001517 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001518 self.client.close()
1519 self.server.wait()
1520 data = self.server.handler_instance.get_data()
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001521 self.assertEqual(len(data), len(self.DATA))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001522 self.assertEqual(data, self.DATA)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001523
1524 def test_send_at_certain_offset(self):
1525 # start sending a file at a certain offset
1526 total_sent = 0
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001527 offset = len(self.DATA) // 2
1528 must_send = len(self.DATA) - offset
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001529 nbytes = 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001530 while total_sent < must_send:
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001531 sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
1532 if sent == 0:
1533 break
1534 offset += sent
1535 total_sent += sent
1536 self.assertTrue(sent <= nbytes)
1537
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001538 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001539 self.client.close()
1540 self.server.wait()
1541 data = self.server.handler_instance.get_data()
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001542 expected = self.DATA[len(self.DATA) // 2:]
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001543 self.assertEqual(total_sent, len(expected))
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001544 self.assertEqual(len(data), len(expected))
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001545 self.assertEqual(data, expected)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001546
1547 def test_offset_overflow(self):
1548 # specify an offset > file size
1549 offset = len(self.DATA) + 4096
Antoine Pitrou18dd0df2011-02-26 14:29:24 +00001550 try:
1551 sent = os.sendfile(self.sockno, self.fileno, offset, 4096)
1552 except OSError as e:
1553 # Solaris can raise EINVAL if offset >= file length, ignore.
1554 if e.errno != errno.EINVAL:
1555 raise
1556 else:
1557 self.assertEqual(sent, 0)
Antoine Pitrou2de51ff2011-02-26 17:52:50 +00001558 self.client.shutdown(socket.SHUT_RDWR)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001559 self.client.close()
1560 self.server.wait()
1561 data = self.server.handler_instance.get_data()
1562 self.assertEqual(data, b'')
1563
1564 def test_invalid_offset(self):
1565 with self.assertRaises(OSError) as cm:
1566 os.sendfile(self.sockno, self.fileno, -1, 4096)
1567 self.assertEqual(cm.exception.errno, errno.EINVAL)
1568
1569 # --- headers / trailers tests
1570
1571 if SUPPORT_HEADERS_TRAILERS:
1572
1573 def test_headers(self):
1574 total_sent = 0
1575 sent = os.sendfile(self.sockno, self.fileno, 0, 4096,
1576 headers=[b"x" * 512])
1577 total_sent += sent
1578 offset = 4096
1579 nbytes = 4096
1580 while 1:
1581 sent = self.sendfile_wrapper(self.sockno, self.fileno,
1582 offset, nbytes)
1583 if sent == 0:
1584 break
1585 total_sent += sent
1586 offset += sent
1587
1588 expected_data = b"x" * 512 + self.DATA
1589 self.assertEqual(total_sent, len(expected_data))
1590 self.client.close()
1591 self.server.wait()
1592 data = self.server.handler_instance.get_data()
1593 self.assertEqual(hash(data), hash(expected_data))
1594
1595 def test_trailers(self):
1596 TESTFN2 = support.TESTFN + "2"
Brett Cannonb6376802011-03-15 17:38:22 -04001597 with open(TESTFN2, 'wb') as f:
1598 f.write(b"abcde")
1599 with open(TESTFN2, 'rb')as f:
1600 self.addCleanup(os.remove, TESTFN2)
1601 os.sendfile(self.sockno, f.fileno(), 0, 4096,
1602 trailers=[b"12345"])
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001603 self.client.close()
1604 self.server.wait()
1605 data = self.server.handler_instance.get_data()
1606 self.assertEqual(data, b"abcde12345")
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001607
1608 if hasattr(os, "SF_NODISKIO"):
1609 def test_flags(self):
1610 try:
1611 os.sendfile(self.sockno, self.fileno, 0, 4096,
1612 flags=os.SF_NODISKIO)
1613 except OSError as err:
1614 if err.errno not in (errno.EBUSY, errno.EAGAIN):
1615 raise
1616
1617
Benjamin Peterson799bd802011-08-31 22:15:17 -04001618def supports_extended_attributes():
1619 if not hasattr(os, "setxattr"):
1620 return False
1621 try:
1622 with open(support.TESTFN, "wb") as fp:
1623 try:
1624 os.fsetxattr(fp.fileno(), b"user.test", b"")
1625 except OSError as e:
1626 if e.errno != errno.ENOTSUP:
1627 raise
1628 return False
1629 finally:
1630 support.unlink(support.TESTFN)
1631 # Kernels < 2.6.39 don't respect setxattr flags.
1632 kernel_version = platform.release()
1633 m = re.match("2.6.(\d{1,2})", kernel_version)
1634 return m is None or int(m.group(1)) >= 39
1635
1636
1637@unittest.skipUnless(supports_extended_attributes(),
1638 "no non-broken extended attribute support")
1639class ExtendedAttributeTests(unittest.TestCase):
1640
1641 def tearDown(self):
1642 support.unlink(support.TESTFN)
1643
1644 def _check_xattrs_str(self, s, getxattr, setxattr, removexattr, listxattr):
1645 fn = support.TESTFN
1646 open(fn, "wb").close()
1647 with self.assertRaises(OSError) as cm:
1648 getxattr(fn, s("user.test"))
1649 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02001650 init_xattr = listxattr(fn)
1651 self.assertIsInstance(init_xattr, list)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001652 setxattr(fn, s("user.test"), b"")
Victor Stinnerf12e5062011-10-16 22:12:03 +02001653 xattr = set(init_xattr)
1654 xattr.add("user.test")
1655 self.assertEqual(set(listxattr(fn)), xattr)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001656 self.assertEqual(getxattr(fn, b"user.test"), b"")
1657 setxattr(fn, s("user.test"), b"hello", os.XATTR_REPLACE)
1658 self.assertEqual(getxattr(fn, b"user.test"), b"hello")
1659 with self.assertRaises(OSError) as cm:
1660 setxattr(fn, s("user.test"), b"bye", os.XATTR_CREATE)
1661 self.assertEqual(cm.exception.errno, errno.EEXIST)
1662 with self.assertRaises(OSError) as cm:
1663 setxattr(fn, s("user.test2"), b"bye", os.XATTR_REPLACE)
1664 self.assertEqual(cm.exception.errno, errno.ENODATA)
1665 setxattr(fn, s("user.test2"), b"foo", os.XATTR_CREATE)
Victor Stinnerf12e5062011-10-16 22:12:03 +02001666 xattr.add("user.test2")
1667 self.assertEqual(set(listxattr(fn)), xattr)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001668 removexattr(fn, s("user.test"))
1669 with self.assertRaises(OSError) as cm:
1670 getxattr(fn, s("user.test"))
1671 self.assertEqual(cm.exception.errno, errno.ENODATA)
Victor Stinnerf12e5062011-10-16 22:12:03 +02001672 xattr.remove("user.test")
1673 self.assertEqual(set(listxattr(fn)), xattr)
Benjamin Peterson799bd802011-08-31 22:15:17 -04001674 self.assertEqual(getxattr(fn, s("user.test2")), b"foo")
1675 setxattr(fn, s("user.test"), b"a"*1024)
1676 self.assertEqual(getxattr(fn, s("user.test")), b"a"*1024)
1677 removexattr(fn, s("user.test"))
1678 many = sorted("user.test{}".format(i) for i in range(100))
1679 for thing in many:
1680 setxattr(fn, thing, b"x")
Victor Stinnerf12e5062011-10-16 22:12:03 +02001681 self.assertEqual(set(listxattr(fn)), set(init_xattr) | set(many))
Benjamin Peterson799bd802011-08-31 22:15:17 -04001682
1683 def _check_xattrs(self, *args):
1684 def make_bytes(s):
1685 return bytes(s, "ascii")
1686 self._check_xattrs_str(str, *args)
1687 support.unlink(support.TESTFN)
1688 self._check_xattrs_str(make_bytes, *args)
1689
1690 def test_simple(self):
1691 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
1692 os.listxattr)
1693
1694 def test_lpath(self):
1695 self._check_xattrs(os.lgetxattr, os.lsetxattr, os.lremovexattr,
1696 os.llistxattr)
1697
1698 def test_fds(self):
1699 def getxattr(path, *args):
1700 with open(path, "rb") as fp:
1701 return os.fgetxattr(fp.fileno(), *args)
1702 def setxattr(path, *args):
1703 with open(path, "wb") as fp:
1704 os.fsetxattr(fp.fileno(), *args)
1705 def removexattr(path, *args):
1706 with open(path, "wb") as fp:
1707 os.fremovexattr(fp.fileno(), *args)
1708 def listxattr(path, *args):
1709 with open(path, "rb") as fp:
1710 return os.flistxattr(fp.fileno(), *args)
1711 self._check_xattrs(getxattr, setxattr, removexattr, listxattr)
1712
1713
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001714@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
1715class Win32DeprecatedBytesAPI(unittest.TestCase):
1716 def test_deprecated(self):
1717 import nt
1718 filename = os.fsencode(support.TESTFN)
1719 with warnings.catch_warnings():
1720 warnings.simplefilter("error", DeprecationWarning)
1721 for func, *args in (
1722 (nt._getfullpathname, filename),
1723 (nt._isdir, filename),
1724 (os.access, filename, os.R_OK),
1725 (os.chdir, filename),
1726 (os.chmod, filename, 0o777),
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01001727 (os.getcwdb,),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001728 (os.link, filename, filename),
1729 (os.listdir, filename),
1730 (os.lstat, filename),
1731 (os.mkdir, filename),
1732 (os.open, filename, os.O_RDONLY),
1733 (os.rename, filename, filename),
1734 (os.rmdir, filename),
1735 (os.startfile, filename),
1736 (os.stat, filename),
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001737 (os.unlink, filename),
1738 (os.utime, filename),
1739 ):
1740 self.assertRaises(DeprecationWarning, func, *args)
1741
Victor Stinner28216442011-11-16 00:34:44 +01001742 @support.skip_unless_symlink
1743 def test_symlink(self):
1744 filename = os.fsencode(support.TESTFN)
1745 with warnings.catch_warnings():
1746 warnings.simplefilter("error", DeprecationWarning)
1747 self.assertRaises(DeprecationWarning,
1748 os.symlink, filename, filename)
1749
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001750
Antoine Pitrouf26ad712011-07-15 23:00:56 +02001751@support.reap_threads
Fred Drake2e2be372001-09-20 21:33:42 +00001752def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001753 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001754 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001755 StatAttributeTests,
1756 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00001757 WalkTests,
Charles-François Natali7372b062012-02-05 15:15:38 +01001758 FwalkTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00001759 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +00001760 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001761 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001762 ExecTests,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001763 Win32ErrorTests,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001764 TestInvalidFD,
Martin v. Löwis011e8422009-05-05 04:43:17 +00001765 PosixUidGidTests,
Brian Curtineb24d742010-04-12 17:16:38 +00001766 Pep383Tests,
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00001767 Win32KillTests,
Brian Curtind40e6f72010-07-08 21:39:08 +00001768 Win32SymlinkTests,
Victor Stinnere8d51452010-08-19 01:05:19 +00001769 FSEncodingTests,
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00001770 PidTests,
Brian Curtine8e4b3b2010-09-23 20:04:14 +00001771 LoginTests,
Brian Curtin1b9df392010-11-24 20:24:31 +00001772 LinkTests,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001773 TestSendfile,
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001774 ProgramPriorityTests,
Benjamin Peterson799bd802011-08-31 22:15:17 -04001775 ExtendedAttributeTests,
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001776 Win32DeprecatedBytesAPI,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001777 )
Fred Drake2e2be372001-09-20 21:33:42 +00001778
1779if __name__ == "__main__":
1780 test_main()