blob: 720e78b317257dcb27e82010d83c3cc75a58a027 [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
17import uuid
Gregory P. Smitha81c8562012-06-03 14:30:44 -070018import stat
Georg Brandl2daf6ae2012-02-20 19:54:16 +010019from test.script_helper import assert_python_ok
Fred Drake38c2ef02001-07-17 20:52:51 +000020
Mark Dickinson7cf03892010-04-16 13:45:35 +000021# Detect whether we're on a Linux system that uses the (now outdated
22# and unmaintained) linuxthreads threading library. There's an issue
23# when combining linuxthreads with a failed execv call: see
24# http://bugs.python.org/issue4970.
Mark Dickinson89589c92010-04-16 13:51:27 +000025if (hasattr(os, "confstr_names") and
26 "CS_GNU_LIBPTHREAD_VERSION" in os.confstr_names):
Mark Dickinson7cf03892010-04-16 13:45:35 +000027 libpthread = os.confstr("CS_GNU_LIBPTHREAD_VERSION")
28 USING_LINUXTHREADS= libpthread.startswith("linuxthreads")
29else:
30 USING_LINUXTHREADS= False
Brian Curtineb24d742010-04-12 17:16:38 +000031
Thomas Wouters0e3f5912006-08-11 14:57:12 +000032# Tests creating TESTFN
33class FileTests(unittest.TestCase):
34 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000035 if os.path.exists(support.TESTFN):
36 os.unlink(support.TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000037 tearDown = setUp
38
39 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000040 f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000041 os.close(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000042 self.assertTrue(os.access(support.TESTFN, os.W_OK))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000043
Christian Heimesfdab48e2008-01-20 09:06:41 +000044 def test_closerange(self):
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000045 first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
46 # We must allocate two consecutive file descriptors, otherwise
47 # it will mess up other file descriptors (perhaps even the three
48 # standard ones).
49 second = os.dup(first)
50 try:
51 retries = 0
52 while second != first + 1:
53 os.close(first)
54 retries += 1
55 if retries > 10:
56 # XXX test skipped
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000057 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000058 first, second = second, os.dup(second)
59 finally:
60 os.close(second)
Christian Heimesfdab48e2008-01-20 09:06:41 +000061 # close a fd that is open, and one that isn't
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000062 os.closerange(first, first + 2)
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000063 self.assertRaises(OSError, os.write, first, b"a")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000064
Benjamin Peterson1cc6df92010-06-30 17:39:45 +000065 @support.cpython_only
Hirokazu Yamamoto4c19e6e2008-09-08 23:41:21 +000066 def test_rename(self):
67 path = support.TESTFN
68 old = sys.getrefcount(path)
69 self.assertRaises(TypeError, os.rename, path, 0)
70 new = sys.getrefcount(path)
71 self.assertEqual(old, new)
72
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000073 def test_read(self):
74 with open(support.TESTFN, "w+b") as fobj:
75 fobj.write(b"spam")
76 fobj.flush()
77 fd = fobj.fileno()
78 os.lseek(fd, 0, 0)
79 s = os.read(fd, 4)
80 self.assertEqual(type(s), bytes)
81 self.assertEqual(s, b"spam")
82
83 def test_write(self):
84 # os.write() accepts bytes- and buffer-like objects but not strings
85 fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY)
86 self.assertRaises(TypeError, os.write, fd, "beans")
87 os.write(fd, b"bacon\n")
88 os.write(fd, bytearray(b"eggs\n"))
89 os.write(fd, memoryview(b"spam\n"))
90 os.close(fd)
91 with open(support.TESTFN, "rb") as fobj:
Antoine Pitroud62269f2008-09-15 23:54:52 +000092 self.assertEqual(fobj.read().splitlines(),
93 [b"bacon", b"eggs", b"spam"])
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000094
Victor Stinnere0daff12011-03-20 23:36:35 +010095 def write_windows_console(self, *args):
96 retcode = subprocess.call(args,
97 # use a new console to not flood the test output
98 creationflags=subprocess.CREATE_NEW_CONSOLE,
99 # use a shell to hide the console window (SW_HIDE)
100 shell=True)
101 self.assertEqual(retcode, 0)
102
103 @unittest.skipUnless(sys.platform == 'win32',
104 'test specific to the Windows console')
105 def test_write_windows_console(self):
106 # Issue #11395: the Windows console returns an error (12: not enough
107 # space error) on writing into stdout if stdout mode is binary and the
108 # length is greater than 66,000 bytes (or less, depending on heap
109 # usage).
110 code = "print('x' * 100000)"
111 self.write_windows_console(sys.executable, "-c", code)
112 self.write_windows_console(sys.executable, "-u", "-c", code)
113
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000114 def fdopen_helper(self, *args):
115 fd = os.open(support.TESTFN, os.O_RDONLY)
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200116 f = os.fdopen(fd, *args)
117 f.close()
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000118
119 def test_fdopen(self):
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200120 fd = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
121 os.close(fd)
122
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000123 self.fdopen_helper()
124 self.fdopen_helper('r')
125 self.fdopen_helper('r', 100)
126
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200127
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000128# Test attributes on return values from os.*stat* family.
129class StatAttributeTests(unittest.TestCase):
130 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000131 os.mkdir(support.TESTFN)
132 self.fname = os.path.join(support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000133 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +0000134 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000135 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000136
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000137 def tearDown(self):
138 os.unlink(self.fname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000139 os.rmdir(support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000140
Antoine Pitrou38425292010-09-21 18:19:07 +0000141 def check_stat_attributes(self, fname):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000142 if not hasattr(os, "stat"):
143 return
144
145 import stat
Antoine Pitrou38425292010-09-21 18:19:07 +0000146 result = os.stat(fname)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000147
148 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000149 self.assertEqual(result[stat.ST_SIZE], 3)
150 self.assertEqual(result.st_size, 3)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000151
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000152 # Make sure all the attributes are there
153 members = dir(result)
154 for name in dir(stat):
155 if name[:3] == 'ST_':
156 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000157 if name.endswith("TIME"):
158 def trunc(x): return int(x)
159 else:
160 def trunc(x): return x
Ezio Melottib3aedd42010-11-20 19:04:17 +0000161 self.assertEqual(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000162 result[getattr(stat, name)])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000163 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000164
165 try:
166 result[200]
Andrew Svetlov737fb892012-12-18 21:14:22 +0200167 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000168 except IndexError:
169 pass
170
171 # Make sure that assignment fails
172 try:
173 result.st_mode = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200174 self.fail("No exception raised")
Collin Winter42dae6a2007-03-28 21:44:53 +0000175 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000176 pass
177
178 try:
179 result.st_rdev = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200180 self.fail("No exception raised")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000181 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000182 pass
183
184 try:
185 result.parrot = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200186 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000187 except AttributeError:
188 pass
189
190 # Use the stat_result constructor with a too-short tuple.
191 try:
192 result2 = os.stat_result((10,))
Andrew Svetlov737fb892012-12-18 21:14:22 +0200193 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000194 except TypeError:
195 pass
196
Ezio Melotti42da6632011-03-15 05:18:48 +0200197 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000198 try:
199 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
200 except TypeError:
201 pass
202
Antoine Pitrou38425292010-09-21 18:19:07 +0000203 def test_stat_attributes(self):
204 self.check_stat_attributes(self.fname)
205
206 def test_stat_attributes_bytes(self):
207 try:
208 fname = self.fname.encode(sys.getfilesystemencoding())
209 except UnicodeEncodeError:
210 self.skipTest("cannot encode %a for the filesystem" % self.fname)
211 self.check_stat_attributes(fname)
Tim Peterse0c446b2001-10-18 21:57:37 +0000212
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000213 def test_statvfs_attributes(self):
214 if not hasattr(os, "statvfs"):
215 return
216
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000217 try:
218 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000219 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000220 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000221 if e.errno == errno.ENOSYS:
222 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000223
224 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000225 self.assertEqual(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000226
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000227 # Make sure all the attributes are there.
228 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
229 'ffree', 'favail', 'flag', 'namemax')
230 for value, member in enumerate(members):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000231 self.assertEqual(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000232
233 # Make sure that assignment really fails
234 try:
235 result.f_bfree = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200236 self.fail("No exception raised")
Collin Winter42dae6a2007-03-28 21:44:53 +0000237 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000238 pass
239
240 try:
241 result.parrot = 1
Andrew Svetlov737fb892012-12-18 21:14:22 +0200242 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000243 except AttributeError:
244 pass
245
246 # Use the constructor with a too-short tuple.
247 try:
248 result2 = os.statvfs_result((10,))
Andrew Svetlov737fb892012-12-18 21:14:22 +0200249 self.fail("No exception raised")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000250 except TypeError:
251 pass
252
Ezio Melotti42da6632011-03-15 05:18:48 +0200253 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000254 try:
255 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
256 except TypeError:
257 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000258
Thomas Wouters89f507f2006-12-13 04:49:30 +0000259 def test_utime_dir(self):
260 delta = 1000000
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000261 st = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000262 # round to int, because some systems may support sub-second
263 # time stamps in stat, but not in utime.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000264 os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
265 st2 = os.stat(support.TESTFN)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000266 self.assertEqual(st2.st_mtime, int(st.st_mtime-delta))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000267
268 # Restrict test to Win32, since there is no guarantee other
269 # systems support centiseconds
270 if sys.platform == 'win32':
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000271 def get_file_system(path):
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000272 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000273 import ctypes
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000274 kernel32 = ctypes.windll.kernel32
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000275 buf = ctypes.create_unicode_buffer("", 100)
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000276 if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000277 return buf.value
278
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000279 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000280 def test_1565150(self):
281 t1 = 1159195039.25
282 os.utime(self.fname, (t1, t1))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000283 self.assertEqual(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000284
Amaury Forgeot d'Arca251a852011-01-03 00:19:11 +0000285 def test_large_time(self):
286 t1 = 5000000000 # some day in 2128
287 os.utime(self.fname, (t1, t1))
288 self.assertEqual(os.stat(self.fname).st_mtime, t1)
289
Guido van Rossumd8faa362007-04-27 19:54:29 +0000290 def test_1686475(self):
291 # Verify that an open file can be stat'ed
292 try:
293 os.stat(r"c:\pagefile.sys")
294 except WindowsError as e:
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000295 if e.errno == 2: # file does not exist; cannot run test
Guido van Rossumd8faa362007-04-27 19:54:29 +0000296 return
297 self.fail("Could not stat pagefile.sys")
298
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000299from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000300
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000301class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000302 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000303 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000304
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000305 def setUp(self):
306 self.__save = dict(os.environ)
Victor Stinnerb745a742010-05-18 17:17:23 +0000307 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000308 self.__saveb = dict(os.environb)
Christian Heimes90333392007-11-01 19:08:42 +0000309 for key, value in self._reference().items():
310 os.environ[key] = value
311
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000312 def tearDown(self):
313 os.environ.clear()
314 os.environ.update(self.__save)
Victor Stinnerb745a742010-05-18 17:17:23 +0000315 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000316 os.environb.clear()
317 os.environb.update(self.__saveb)
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000318
Christian Heimes90333392007-11-01 19:08:42 +0000319 def _reference(self):
320 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
321
322 def _empty_mapping(self):
323 os.environ.clear()
324 return os.environ
325
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000326 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000327 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000328 os.environ.clear()
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000329 if os.path.exists("/bin/sh"):
330 os.environ.update(HELLO="World")
Brian Curtin810921b2010-10-30 21:24:21 +0000331 with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
332 value = popen.read().strip()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000333 self.assertEqual(value, "World")
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000334
Christian Heimes1a13d592007-11-08 14:16:55 +0000335 def test_os_popen_iter(self):
336 if os.path.exists("/bin/sh"):
Brian Curtin810921b2010-10-30 21:24:21 +0000337 with os.popen(
338 "/bin/sh -c 'echo \"line1\nline2\nline3\"'") as popen:
339 it = iter(popen)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000340 self.assertEqual(next(it), "line1\n")
341 self.assertEqual(next(it), "line2\n")
342 self.assertEqual(next(it), "line3\n")
Brian Curtin810921b2010-10-30 21:24:21 +0000343 self.assertRaises(StopIteration, next, it)
Christian Heimes1a13d592007-11-08 14:16:55 +0000344
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000345 # Verify environ keys and values from the OS are of the
346 # correct str type.
347 def test_keyvalue_types(self):
348 for key, val in os.environ.items():
Ezio Melottib3aedd42010-11-20 19:04:17 +0000349 self.assertEqual(type(key), str)
350 self.assertEqual(type(val), str)
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000351
Christian Heimes90333392007-11-01 19:08:42 +0000352 def test_items(self):
353 for key, value in self._reference().items():
354 self.assertEqual(os.environ.get(key), value)
355
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000356 # Issue 7310
357 def test___repr__(self):
358 """Check that the repr() of os.environ looks like environ({...})."""
359 env = os.environ
Victor Stinner96f0de92010-07-29 00:29:00 +0000360 self.assertEqual(repr(env), 'environ({{{}}})'.format(', '.join(
361 '{!r}: {!r}'.format(key, value)
362 for key, value in env.items())))
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000363
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000364 def test_get_exec_path(self):
365 defpath_list = os.defpath.split(os.pathsep)
366 test_path = ['/monty', '/python', '', '/flying/circus']
367 test_env = {'PATH': os.pathsep.join(test_path)}
368
369 saved_environ = os.environ
370 try:
371 os.environ = dict(test_env)
372 # Test that defaulting to os.environ works.
373 self.assertSequenceEqual(test_path, os.get_exec_path())
374 self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
375 finally:
376 os.environ = saved_environ
377
378 # No PATH environment variable
379 self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
380 # Empty PATH environment variable
381 self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
382 # Supplied PATH environment variable
383 self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
384
Victor Stinnerb745a742010-05-18 17:17:23 +0000385 if os.supports_bytes_environ:
386 # env cannot contain 'PATH' and b'PATH' keys
Victor Stinner38430e22010-08-19 17:10:18 +0000387 try:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000388 # ignore BytesWarning warning
389 with warnings.catch_warnings(record=True):
390 mixed_env = {'PATH': '1', b'PATH': b'2'}
Victor Stinner38430e22010-08-19 17:10:18 +0000391 except BytesWarning:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000392 # mixed_env cannot be created with python -bb
Victor Stinner38430e22010-08-19 17:10:18 +0000393 pass
394 else:
395 self.assertRaises(ValueError, os.get_exec_path, mixed_env)
Victor Stinnerb745a742010-05-18 17:17:23 +0000396
397 # bytes key and/or value
398 self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}),
399 ['abc'])
400 self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}),
401 ['abc'])
402 self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}),
403 ['abc'])
404
405 @unittest.skipUnless(os.supports_bytes_environ,
406 "os.environb required for this test.")
Victor Stinner84ae1182010-05-06 22:05:07 +0000407 def test_environb(self):
408 # os.environ -> os.environb
409 value = 'euro\u20ac'
410 try:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000411 value_bytes = value.encode(sys.getfilesystemencoding(),
412 'surrogateescape')
Victor Stinner84ae1182010-05-06 22:05:07 +0000413 except UnicodeEncodeError:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000414 msg = "U+20AC character is not encodable to %s" % (
415 sys.getfilesystemencoding(),)
Benjamin Peterson932d3f42010-05-06 22:26:31 +0000416 self.skipTest(msg)
Victor Stinner84ae1182010-05-06 22:05:07 +0000417 os.environ['unicode'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000418 self.assertEqual(os.environ['unicode'], value)
419 self.assertEqual(os.environb[b'unicode'], value_bytes)
Victor Stinner84ae1182010-05-06 22:05:07 +0000420
421 # os.environb -> os.environ
422 value = b'\xff'
423 os.environb[b'bytes'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000424 self.assertEqual(os.environb[b'bytes'], value)
Victor Stinner84ae1182010-05-06 22:05:07 +0000425 value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000426 self.assertEqual(os.environ['bytes'], value_str)
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000427
Charles-François Natali7be8f682011-11-27 12:49:27 +0100428 # On FreeBSD < 7 and OS X < 10.6, unsetenv() doesn't return a value (issue
429 # #13415).
430 @unittest.skipIf(sys.platform.startswith(('freebsd', 'darwin')),
431 "due to known OS bug: see issue #13415")
Victor Stinner60b385e2011-11-22 22:01:28 +0100432 def test_unset_error(self):
433 if sys.platform == "win32":
434 # an environment variable is limited to 32,767 characters
435 key = 'x' * 50000
Victor Stinnerb3f82682011-11-22 22:30:19 +0100436 self.assertRaises(ValueError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100437 else:
438 # "=" is not allowed in a variable name
439 key = 'key='
Victor Stinnerb3f82682011-11-22 22:30:19 +0100440 self.assertRaises(OSError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100441
Tim Petersc4e09402003-04-25 07:11:48 +0000442class WalkTests(unittest.TestCase):
443 """Tests for os.walk()."""
444
445 def test_traversal(self):
446 import os
447 from os.path import join
448
449 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000450 # TESTFN/
451 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000452 # tmp1
453 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000454 # tmp2
455 # SUB11/ no kids
456 # SUB2/ a file kid and a dirsymlink kid
457 # tmp3
458 # link/ a symlink to TESTFN.2
459 # TEST2/
460 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000461 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000462 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000463 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000464 sub2_path = join(walk_path, "SUB2")
465 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000466 tmp2_path = join(sub1_path, "tmp2")
467 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000468 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000469 t2_path = join(support.TESTFN, "TEST2")
470 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000471
472 # Create stuff.
473 os.makedirs(sub11_path)
474 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000475 os.makedirs(t2_path)
476 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000477 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000478 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
479 f.close()
Brian Curtin3b4499c2010-12-28 14:31:47 +0000480 if support.can_symlink():
Antoine Pitrou5311c1d2012-01-24 08:59:28 +0100481 if os.name == 'nt':
482 def symlink_to_dir(src, dest):
483 os.symlink(src, dest, True)
484 else:
485 symlink_to_dir = os.symlink
486 symlink_to_dir(os.path.abspath(t2_path), link_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000487 sub2_tree = (sub2_path, ["link"], ["tmp3"])
488 else:
489 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000490
491 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000492 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000493 self.assertEqual(len(all), 4)
494 # We can't know which order SUB1 and SUB2 will appear in.
495 # Not flipped: TESTFN, SUB1, SUB11, SUB2
496 # flipped: TESTFN, SUB2, SUB1, SUB11
497 flipped = all[0][1][0] != "SUB1"
498 all[0][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000499 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000500 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
501 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000502 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000503
504 # Prune the search.
505 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000506 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000507 all.append((root, dirs, files))
508 # Don't descend into SUB1.
509 if 'SUB1' in dirs:
510 # Note that this also mutates the dirs we appended to all!
511 dirs.remove('SUB1')
512 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000513 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
514 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000515
516 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000517 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000518 self.assertEqual(len(all), 4)
519 # We can't know which order SUB1 and SUB2 will appear in.
520 # Not flipped: SUB11, SUB1, SUB2, TESTFN
521 # flipped: SUB2, SUB11, SUB1, TESTFN
522 flipped = all[3][1][0] != "SUB1"
523 all[3][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000524 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000525 self.assertEqual(all[flipped], (sub11_path, [], []))
526 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000527 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000528
Brian Curtin3b4499c2010-12-28 14:31:47 +0000529 if support.can_symlink():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000530 # Walk, following symlinks.
531 for root, dirs, files in os.walk(walk_path, followlinks=True):
532 if root == link_path:
533 self.assertEqual(dirs, [])
534 self.assertEqual(files, ["tmp4"])
535 break
536 else:
537 self.fail("Didn't follow symlink with followlinks=True")
538
539 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000540 # Tear everything down. This is a decent use for bottom-up on
541 # Windows, which doesn't have a recursive delete command. The
542 # (not so) subtlety is that rmdir will fail unless the dir's
543 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000544 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000545 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000546 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000547 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000548 dirname = os.path.join(root, name)
549 if not os.path.islink(dirname):
550 os.rmdir(dirname)
551 else:
552 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000553 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000554
Guido van Rossume7ba4952007-06-06 23:52:48 +0000555class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000556 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000557 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000558
559 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000560 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000561 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
562 os.makedirs(path) # Should work
563 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
564 os.makedirs(path)
565
566 # Try paths with a '.' in them
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000567 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000568 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
569 os.makedirs(path)
570 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
571 'dir5', 'dir6')
572 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000573
Terry Reedy5a22b652010-12-02 07:05:56 +0000574 def test_exist_ok_existing_directory(self):
575 path = os.path.join(support.TESTFN, 'dir1')
576 mode = 0o777
577 old_mask = os.umask(0o022)
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700578 try:
579 os.makedirs(path, mode)
580 self.assertRaises(OSError, os.makedirs, path, mode)
581 self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
582 self.assertRaises(OSError, os.makedirs, path, 0o776, exist_ok=True)
583 os.makedirs(path, mode=mode, exist_ok=True)
584 finally:
585 os.umask(old_mask)
586
587 def test_exist_ok_s_isgid_directory(self):
588 path = os.path.join(support.TESTFN, 'dir1')
589 S_ISGID = stat.S_ISGID
590 mode = 0o777
591 old_mask = os.umask(0o022)
592 try:
593 existing_testfn_mode = stat.S_IMODE(
594 os.lstat(support.TESTFN).st_mode)
Ned Deilyc622f422012-08-08 20:57:24 -0700595 try:
596 os.chmod(support.TESTFN, existing_testfn_mode | S_ISGID)
597 except OSError:
598 raise unittest.SkipTest('Cannot set S_ISGID for dir.')
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700599 if (os.lstat(support.TESTFN).st_mode & S_ISGID != S_ISGID):
600 raise unittest.SkipTest('No support for S_ISGID dir mode.')
601 # The os should apply S_ISGID from the parent dir for us, but
602 # this test need not depend on that behavior. Be explicit.
603 os.makedirs(path, mode | S_ISGID)
604 # http://bugs.python.org/issue14992
605 # Should not fail when the bit is already set.
606 os.makedirs(path, mode, exist_ok=True)
607 # remove the bit.
608 os.chmod(path, stat.S_IMODE(os.lstat(path).st_mode) & ~S_ISGID)
609 with self.assertRaises(OSError):
610 # Should fail when the bit is not already set when demanded.
611 os.makedirs(path, mode | S_ISGID, exist_ok=True)
612 finally:
613 os.umask(old_mask)
Terry Reedy5a22b652010-12-02 07:05:56 +0000614
615 def test_exist_ok_existing_regular_file(self):
616 base = support.TESTFN
617 path = os.path.join(support.TESTFN, 'dir1')
618 f = open(path, 'w')
619 f.write('abc')
620 f.close()
621 self.assertRaises(OSError, os.makedirs, path)
622 self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
623 self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
624 os.remove(path)
625
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000626 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000627 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000628 'dir4', 'dir5', 'dir6')
629 # If the tests failed, the bottom-most directory ('../dir6')
630 # may not have been created, so we look for the outermost directory
631 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000632 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000633 path = os.path.dirname(path)
634
635 os.removedirs(path)
636
Andrew Svetlov405faed2012-12-25 12:18:09 +0200637
638class RemoveDirsTests(unittest.TestCase):
639 def setUp(self):
640 os.makedirs(support.TESTFN)
641
642 def tearDown(self):
643 support.rmtree(support.TESTFN)
644
645 def test_remove_all(self):
646 dira = os.path.join(support.TESTFN, 'dira')
647 os.mkdir(dira)
648 dirb = os.path.join(dira, 'dirb')
649 os.mkdir(dirb)
650 os.removedirs(dirb)
651 self.assertFalse(os.path.exists(dirb))
652 self.assertFalse(os.path.exists(dira))
653 self.assertFalse(os.path.exists(support.TESTFN))
654
655 def test_remove_partial(self):
656 dira = os.path.join(support.TESTFN, 'dira')
657 os.mkdir(dira)
658 dirb = os.path.join(dira, 'dirb')
659 os.mkdir(dirb)
660 with open(os.path.join(dira, 'file.txt'), 'w') as f:
661 f.write('text')
662 os.removedirs(dirb)
663 self.assertFalse(os.path.exists(dirb))
664 self.assertTrue(os.path.exists(dira))
665 self.assertTrue(os.path.exists(support.TESTFN))
666
667 def test_remove_nothing(self):
668 dira = os.path.join(support.TESTFN, 'dira')
669 os.mkdir(dira)
670 dirb = os.path.join(dira, 'dirb')
671 os.mkdir(dirb)
672 with open(os.path.join(dirb, 'file.txt'), 'w') as f:
673 f.write('text')
674 with self.assertRaises(OSError):
675 os.removedirs(dirb)
676 self.assertTrue(os.path.exists(dirb))
677 self.assertTrue(os.path.exists(dira))
678 self.assertTrue(os.path.exists(support.TESTFN))
679
680
Guido van Rossume7ba4952007-06-06 23:52:48 +0000681class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000682 def test_devnull(self):
Victor Stinnera6d2c762011-06-30 18:20:11 +0200683 with open(os.devnull, 'wb') as f:
684 f.write(b'hello')
685 f.close()
686 with open(os.devnull, 'rb') as f:
687 self.assertEqual(f.read(), b'')
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000688
Andrew Svetlov405faed2012-12-25 12:18:09 +0200689
Guido van Rossume7ba4952007-06-06 23:52:48 +0000690class URandomTests(unittest.TestCase):
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100691 def test_urandom_length(self):
692 self.assertEqual(len(os.urandom(0)), 0)
693 self.assertEqual(len(os.urandom(1)), 1)
694 self.assertEqual(len(os.urandom(10)), 10)
695 self.assertEqual(len(os.urandom(100)), 100)
696 self.assertEqual(len(os.urandom(1000)), 1000)
697
698 def test_urandom_value(self):
699 data1 = os.urandom(16)
700 data2 = os.urandom(16)
701 self.assertNotEqual(data1, data2)
702
703 def get_urandom_subprocess(self, count):
704 code = '\n'.join((
705 'import os, sys',
706 'data = os.urandom(%s)' % count,
707 'sys.stdout.buffer.write(data)',
708 'sys.stdout.buffer.flush()'))
709 out = assert_python_ok('-c', code)
710 stdout = out[1]
711 self.assertEqual(len(stdout), 16)
712 return stdout
713
714 def test_urandom_subprocess(self):
715 data1 = self.get_urandom_subprocess(16)
716 data2 = self.get_urandom_subprocess(16)
717 self.assertNotEqual(data1, data2)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000718
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000719@contextlib.contextmanager
720def _execvpe_mockup(defpath=None):
721 """
722 Stubs out execv and execve functions when used as context manager.
723 Records exec calls. The mock execv and execve functions always raise an
724 exception as they would normally never return.
725 """
726 # A list of tuples containing (function name, first arg, args)
727 # of calls to execv or execve that have been made.
728 calls = []
729
730 def mock_execv(name, *args):
731 calls.append(('execv', name, args))
732 raise RuntimeError("execv called")
733
734 def mock_execve(name, *args):
735 calls.append(('execve', name, args))
736 raise OSError(errno.ENOTDIR, "execve called")
737
738 try:
739 orig_execv = os.execv
740 orig_execve = os.execve
741 orig_defpath = os.defpath
742 os.execv = mock_execv
743 os.execve = mock_execve
744 if defpath is not None:
745 os.defpath = defpath
746 yield calls
747 finally:
748 os.execv = orig_execv
749 os.execve = orig_execve
750 os.defpath = orig_defpath
751
Guido van Rossume7ba4952007-06-06 23:52:48 +0000752class ExecTests(unittest.TestCase):
Mark Dickinson7cf03892010-04-16 13:45:35 +0000753 @unittest.skipIf(USING_LINUXTHREADS,
754 "avoid triggering a linuxthreads bug: see issue #4970")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000755 def test_execvpe_with_bad_program(self):
Mark Dickinson7cf03892010-04-16 13:45:35 +0000756 self.assertRaises(OSError, os.execvpe, 'no such app-',
757 ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000758
Thomas Heller6790d602007-08-30 17:15:14 +0000759 def test_execvpe_with_bad_arglist(self):
760 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
761
Gregory P. Smith4ae37772010-05-08 18:05:46 +0000762 @unittest.skipUnless(hasattr(os, '_execvpe'),
763 "No internal os._execvpe function to test.")
Victor Stinnerb745a742010-05-18 17:17:23 +0000764 def _test_internal_execvpe(self, test_type):
765 program_path = os.sep + 'absolutepath'
766 if test_type is bytes:
767 program = b'executable'
768 fullpath = os.path.join(os.fsencode(program_path), program)
769 native_fullpath = fullpath
770 arguments = [b'progname', 'arg1', 'arg2']
771 else:
772 program = 'executable'
773 arguments = ['progname', 'arg1', 'arg2']
774 fullpath = os.path.join(program_path, program)
775 if os.name != "nt":
776 native_fullpath = os.fsencode(fullpath)
777 else:
778 native_fullpath = fullpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000779 env = {'spam': 'beans'}
780
Victor Stinnerb745a742010-05-18 17:17:23 +0000781 # test os._execvpe() with an absolute path
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000782 with _execvpe_mockup() as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +0000783 self.assertRaises(RuntimeError,
784 os._execvpe, fullpath, arguments)
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000785 self.assertEqual(len(calls), 1)
786 self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))
787
Victor Stinnerb745a742010-05-18 17:17:23 +0000788 # test os._execvpe() with a relative path:
789 # os.get_exec_path() returns defpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000790 with _execvpe_mockup(defpath=program_path) as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +0000791 self.assertRaises(OSError,
792 os._execvpe, program, arguments, env=env)
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000793 self.assertEqual(len(calls), 1)
Victor Stinnerb745a742010-05-18 17:17:23 +0000794 self.assertSequenceEqual(calls[0],
795 ('execve', native_fullpath, (arguments, env)))
796
797 # test os._execvpe() with a relative path:
798 # os.get_exec_path() reads the 'PATH' variable
799 with _execvpe_mockup() as calls:
800 env_path = env.copy()
Victor Stinner38430e22010-08-19 17:10:18 +0000801 if test_type is bytes:
802 env_path[b'PATH'] = program_path
803 else:
804 env_path['PATH'] = program_path
Victor Stinnerb745a742010-05-18 17:17:23 +0000805 self.assertRaises(OSError,
806 os._execvpe, program, arguments, env=env_path)
807 self.assertEqual(len(calls), 1)
808 self.assertSequenceEqual(calls[0],
809 ('execve', native_fullpath, (arguments, env_path)))
810
811 def test_internal_execvpe_str(self):
812 self._test_internal_execvpe(str)
813 if os.name != "nt":
814 self._test_internal_execvpe(bytes)
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000815
Gregory P. Smith4ae37772010-05-08 18:05:46 +0000816
Thomas Wouters477c8d52006-05-27 19:21:47 +0000817class Win32ErrorTests(unittest.TestCase):
818 def test_rename(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000819 self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000820
821 def test_remove(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000822 self.assertRaises(WindowsError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000823
824 def test_chdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000825 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000826
827 def test_mkdir(self):
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +0000828 f = open(support.TESTFN, "w")
Benjamin Petersonf91df042009-02-13 02:50:59 +0000829 try:
830 self.assertRaises(WindowsError, os.mkdir, support.TESTFN)
831 finally:
832 f.close()
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +0000833 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000834
835 def test_utime(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000836 self.assertRaises(WindowsError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000837
Thomas Wouters477c8d52006-05-27 19:21:47 +0000838 def test_chmod(self):
Benjamin Petersonf91df042009-02-13 02:50:59 +0000839 self.assertRaises(WindowsError, os.chmod, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000840
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000841class TestInvalidFD(unittest.TestCase):
Benjamin Peterson05e782f2009-01-19 15:15:02 +0000842 singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000843 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
844 #singles.append("close")
845 #We omit close because it doesn'r raise an exception on some platforms
846 def get_single(f):
847 def helper(self):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000848 if hasattr(os, f):
849 self.check(getattr(os, f))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000850 return helper
851 for f in singles:
852 locals()["test_"+f] = get_single(f)
853
Benjamin Peterson7522c742009-01-19 21:00:09 +0000854 def check(self, f, *args):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000855 try:
856 f(support.make_bad_fd(), *args)
857 except OSError as e:
858 self.assertEqual(e.errno, errno.EBADF)
859 else:
860 self.fail("%r didn't raise a OSError with a bad file descriptor"
861 % f)
Benjamin Peterson7522c742009-01-19 21:00:09 +0000862
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000863 def test_isatty(self):
864 if hasattr(os, "isatty"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000865 self.assertEqual(os.isatty(support.make_bad_fd()), False)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000866
867 def test_closerange(self):
868 if hasattr(os, "closerange"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000869 fd = support.make_bad_fd()
R. David Murray630cc482009-07-22 15:20:27 +0000870 # Make sure none of the descriptors we are about to close are
871 # currently valid (issue 6542).
872 for i in range(10):
873 try: os.fstat(fd+i)
874 except OSError:
875 pass
876 else:
877 break
878 if i < 2:
879 raise unittest.SkipTest(
880 "Unable to acquire a range of invalid file descriptors")
881 self.assertEqual(os.closerange(fd, fd + i-1), None)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000882
883 def test_dup2(self):
884 if hasattr(os, "dup2"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000885 self.check(os.dup2, 20)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000886
887 def test_fchmod(self):
888 if hasattr(os, "fchmod"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000889 self.check(os.fchmod, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000890
891 def test_fchown(self):
892 if hasattr(os, "fchown"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000893 self.check(os.fchown, -1, -1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000894
895 def test_fpathconf(self):
896 if hasattr(os, "fpathconf"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000897 self.check(os.fpathconf, "PC_NAME_MAX")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000898
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000899 def test_ftruncate(self):
900 if hasattr(os, "ftruncate"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000901 self.check(os.ftruncate, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000902
903 def test_lseek(self):
904 if hasattr(os, "lseek"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000905 self.check(os.lseek, 0, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000906
907 def test_read(self):
908 if hasattr(os, "read"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000909 self.check(os.read, 1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000910
911 def test_tcsetpgrpt(self):
912 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000913 self.check(os.tcsetpgrp, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000914
915 def test_write(self):
916 if hasattr(os, "write"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000917 self.check(os.write, b" ")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000918
Brian Curtin1b9df392010-11-24 20:24:31 +0000919
920class LinkTests(unittest.TestCase):
921 def setUp(self):
922 self.file1 = support.TESTFN
923 self.file2 = os.path.join(support.TESTFN + "2")
924
Brian Curtinc0abc4e2010-11-30 23:46:54 +0000925 def tearDown(self):
Brian Curtin1b9df392010-11-24 20:24:31 +0000926 for file in (self.file1, self.file2):
927 if os.path.exists(file):
928 os.unlink(file)
929
Brian Curtin1b9df392010-11-24 20:24:31 +0000930 def _test_link(self, file1, file2):
931 with open(file1, "w") as f1:
932 f1.write("test")
933
934 os.link(file1, file2)
935 with open(file1, "r") as f1, open(file2, "r") as f2:
936 self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
937
938 def test_link(self):
939 self._test_link(self.file1, self.file2)
940
941 def test_link_bytes(self):
942 self._test_link(bytes(self.file1, sys.getfilesystemencoding()),
943 bytes(self.file2, sys.getfilesystemencoding()))
944
Brian Curtinf498b752010-11-30 15:54:04 +0000945 def test_unicode_name(self):
Brian Curtin43f0c272010-11-30 15:40:04 +0000946 try:
Brian Curtinf498b752010-11-30 15:54:04 +0000947 os.fsencode("\xf1")
Brian Curtin43f0c272010-11-30 15:40:04 +0000948 except UnicodeError:
949 raise unittest.SkipTest("Unable to encode for this platform.")
950
Brian Curtinf498b752010-11-30 15:54:04 +0000951 self.file1 += "\xf1"
Brian Curtinfc889c42010-11-28 23:59:46 +0000952 self.file2 = self.file1 + "2"
953 self._test_link(self.file1, self.file2)
954
Thomas Wouters477c8d52006-05-27 19:21:47 +0000955if sys.platform != 'win32':
956 class Win32ErrorTests(unittest.TestCase):
957 pass
958
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000959 class PosixUidGidTests(unittest.TestCase):
960 if hasattr(os, 'setuid'):
961 def test_setuid(self):
962 if os.getuid() != 0:
963 self.assertRaises(os.error, os.setuid, 0)
964 self.assertRaises(OverflowError, os.setuid, 1<<32)
965
966 if hasattr(os, 'setgid'):
967 def test_setgid(self):
968 if os.getuid() != 0:
969 self.assertRaises(os.error, os.setgid, 0)
970 self.assertRaises(OverflowError, os.setgid, 1<<32)
971
972 if hasattr(os, 'seteuid'):
973 def test_seteuid(self):
974 if os.getuid() != 0:
975 self.assertRaises(os.error, os.seteuid, 0)
976 self.assertRaises(OverflowError, os.seteuid, 1<<32)
977
978 if hasattr(os, 'setegid'):
979 def test_setegid(self):
980 if os.getuid() != 0:
981 self.assertRaises(os.error, os.setegid, 0)
982 self.assertRaises(OverflowError, os.setegid, 1<<32)
983
984 if hasattr(os, 'setreuid'):
985 def test_setreuid(self):
986 if os.getuid() != 0:
987 self.assertRaises(os.error, os.setreuid, 0, 0)
988 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
989 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000990
991 def test_setreuid_neg1(self):
992 # Needs to accept -1. We run this in a subprocess to avoid
993 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000994 subprocess.check_call([
995 sys.executable, '-c',
996 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000997
998 if hasattr(os, 'setregid'):
999 def test_setregid(self):
1000 if os.getuid() != 0:
1001 self.assertRaises(os.error, os.setregid, 0, 0)
1002 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
1003 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001004
1005 def test_setregid_neg1(self):
1006 # Needs to accept -1. We run this in a subprocess to avoid
1007 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +00001008 subprocess.check_call([
1009 sys.executable, '-c',
1010 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Martin v. Löwis011e8422009-05-05 04:43:17 +00001011
1012 class Pep383Tests(unittest.TestCase):
Martin v. Löwis011e8422009-05-05 04:43:17 +00001013 def setUp(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001014 if support.TESTFN_UNENCODABLE:
1015 self.dir = support.TESTFN_UNENCODABLE
Victor Stinner0af71aa2013-01-03 01:50:30 +01001016 elif support.TESTFN_NONASCII:
1017 self.dir = support.TESTFN_NONASCII
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001018 else:
1019 self.dir = support.TESTFN
1020 self.bdir = os.fsencode(self.dir)
1021
1022 bytesfn = []
1023 def add_filename(fn):
1024 try:
1025 fn = os.fsencode(fn)
1026 except UnicodeEncodeError:
1027 return
1028 bytesfn.append(fn)
1029 add_filename(support.TESTFN_UNICODE)
1030 if support.TESTFN_UNENCODABLE:
1031 add_filename(support.TESTFN_UNENCODABLE)
Victor Stinner0af71aa2013-01-03 01:50:30 +01001032 if support.TESTFN_NONASCII:
1033 add_filename(support.TESTFN_NONASCII)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001034 if not bytesfn:
1035 self.skipTest("couldn't create any non-ascii filename")
1036
1037 self.unicodefn = set()
Martin v. Löwis011e8422009-05-05 04:43:17 +00001038 os.mkdir(self.dir)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001039 try:
1040 for fn in bytesfn:
1041 f = open(os.path.join(self.bdir, fn), "w")
1042 f.close()
Victor Stinnere8d51452010-08-19 01:05:19 +00001043 fn = os.fsdecode(fn)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001044 if fn in self.unicodefn:
1045 raise ValueError("duplicate filename")
1046 self.unicodefn.add(fn)
1047 except:
1048 shutil.rmtree(self.dir)
1049 raise
Martin v. Löwis011e8422009-05-05 04:43:17 +00001050
1051 def tearDown(self):
1052 shutil.rmtree(self.dir)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001053
1054 def test_listdir(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001055 expected = self.unicodefn
1056 found = set(os.listdir(self.dir))
Ezio Melottib3aedd42010-11-20 19:04:17 +00001057 self.assertEqual(found, expected)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001058
1059 def test_open(self):
1060 for fn in self.unicodefn:
Victor Stinnera6d2c762011-06-30 18:20:11 +02001061 f = open(os.path.join(self.dir, fn), 'rb')
Martin v. Löwis011e8422009-05-05 04:43:17 +00001062 f.close()
1063
Victor Stinnere4110dc2013-01-01 23:05:55 +01001064 @unittest.skipUnless(hasattr(os, 'statvfs'),
1065 "need os.statvfs()")
1066 def test_statvfs(self):
1067 # issue #9645
1068 for fn in self.unicodefn:
1069 # should not fail with file not found error
1070 fullname = os.path.join(self.dir, fn)
1071 os.statvfs(fullname)
1072
Martin v. Löwis011e8422009-05-05 04:43:17 +00001073 def test_stat(self):
1074 for fn in self.unicodefn:
1075 os.stat(os.path.join(self.dir, fn))
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001076else:
1077 class PosixUidGidTests(unittest.TestCase):
1078 pass
Martin v. Löwis011e8422009-05-05 04:43:17 +00001079 class Pep383Tests(unittest.TestCase):
1080 pass
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001081
Brian Curtineb24d742010-04-12 17:16:38 +00001082@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
1083class Win32KillTests(unittest.TestCase):
Brian Curtinc3acbc32010-05-28 16:08:40 +00001084 def _kill(self, sig):
1085 # Start sys.executable as a subprocess and communicate from the
1086 # subprocess to the parent that the interpreter is ready. When it
1087 # becomes ready, send *sig* via os.kill to the subprocess and check
1088 # that the return code is equal to *sig*.
1089 import ctypes
1090 from ctypes import wintypes
1091 import msvcrt
1092
1093 # Since we can't access the contents of the process' stdout until the
1094 # process has exited, use PeekNamedPipe to see what's inside stdout
1095 # without waiting. This is done so we can tell that the interpreter
1096 # is started and running at a point where it could handle a signal.
1097 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
1098 PeekNamedPipe.restype = wintypes.BOOL
1099 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
1100 ctypes.POINTER(ctypes.c_char), # stdout buf
1101 wintypes.DWORD, # Buffer size
1102 ctypes.POINTER(wintypes.DWORD), # bytes read
1103 ctypes.POINTER(wintypes.DWORD), # bytes avail
1104 ctypes.POINTER(wintypes.DWORD)) # bytes left
1105 msg = "running"
1106 proc = subprocess.Popen([sys.executable, "-c",
1107 "import sys;"
1108 "sys.stdout.write('{}');"
1109 "sys.stdout.flush();"
1110 "input()".format(msg)],
1111 stdout=subprocess.PIPE,
1112 stderr=subprocess.PIPE,
1113 stdin=subprocess.PIPE)
Brian Curtin43ec5772010-11-05 15:17:11 +00001114 self.addCleanup(proc.stdout.close)
1115 self.addCleanup(proc.stderr.close)
1116 self.addCleanup(proc.stdin.close)
Brian Curtinc3acbc32010-05-28 16:08:40 +00001117
1118 count, max = 0, 100
1119 while count < max and proc.poll() is None:
1120 # Create a string buffer to store the result of stdout from the pipe
1121 buf = ctypes.create_string_buffer(len(msg))
1122 # Obtain the text currently in proc.stdout
1123 # Bytes read/avail/left are left as NULL and unused
1124 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
1125 buf, ctypes.sizeof(buf), None, None, None)
1126 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
1127 if buf.value:
1128 self.assertEqual(msg, buf.value.decode())
1129 break
1130 time.sleep(0.1)
1131 count += 1
1132 else:
1133 self.fail("Did not receive communication from the subprocess")
1134
Brian Curtineb24d742010-04-12 17:16:38 +00001135 os.kill(proc.pid, sig)
1136 self.assertEqual(proc.wait(), sig)
1137
1138 def test_kill_sigterm(self):
1139 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinc3acbc32010-05-28 16:08:40 +00001140 self._kill(signal.SIGTERM)
Brian Curtineb24d742010-04-12 17:16:38 +00001141
1142 def test_kill_int(self):
1143 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinc3acbc32010-05-28 16:08:40 +00001144 self._kill(100)
Brian Curtineb24d742010-04-12 17:16:38 +00001145
1146 def _kill_with_event(self, event, name):
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001147 tagname = "test_os_%s" % uuid.uuid1()
1148 m = mmap.mmap(-1, 1, tagname)
1149 m[0] = 0
Brian Curtineb24d742010-04-12 17:16:38 +00001150 # Run a script which has console control handling enabled.
1151 proc = subprocess.Popen([sys.executable,
1152 os.path.join(os.path.dirname(__file__),
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001153 "win_console_handler.py"), tagname],
Brian Curtineb24d742010-04-12 17:16:38 +00001154 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
1155 # Let the interpreter startup before we send signals. See #3137.
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001156 count, max = 0, 100
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001157 while count < max and proc.poll() is None:
Brian Curtinf668df52010-10-15 14:21:06 +00001158 if m[0] == 1:
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001159 break
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001160 time.sleep(0.1)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001161 count += 1
1162 else:
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001163 # Forcefully kill the process if we weren't able to signal it.
1164 os.kill(proc.pid, signal.SIGINT)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001165 self.fail("Subprocess didn't finish initialization")
Brian Curtineb24d742010-04-12 17:16:38 +00001166 os.kill(proc.pid, event)
1167 # proc.send_signal(event) could also be done here.
1168 # Allow time for the signal to be passed and the process to exit.
1169 time.sleep(0.5)
1170 if not proc.poll():
1171 # Forcefully kill the process if we weren't able to signal it.
1172 os.kill(proc.pid, signal.SIGINT)
1173 self.fail("subprocess did not stop on {}".format(name))
1174
1175 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
1176 def test_CTRL_C_EVENT(self):
1177 from ctypes import wintypes
1178 import ctypes
1179
1180 # Make a NULL value by creating a pointer with no argument.
1181 NULL = ctypes.POINTER(ctypes.c_int)()
1182 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
1183 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
1184 wintypes.BOOL)
1185 SetConsoleCtrlHandler.restype = wintypes.BOOL
1186
1187 # Calling this with NULL and FALSE causes the calling process to
1188 # handle CTRL+C, rather than ignore it. This property is inherited
1189 # by subprocesses.
1190 SetConsoleCtrlHandler(NULL, 0)
1191
1192 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
1193
1194 def test_CTRL_BREAK_EVENT(self):
1195 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
1196
1197
Brian Curtind40e6f72010-07-08 21:39:08 +00001198@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Brian Curtin3b4499c2010-12-28 14:31:47 +00001199@support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +00001200class Win32SymlinkTests(unittest.TestCase):
1201 filelink = 'filelinktest'
1202 filelink_target = os.path.abspath(__file__)
1203 dirlink = 'dirlinktest'
1204 dirlink_target = os.path.dirname(filelink_target)
1205 missing_link = 'missing link'
1206
1207 def setUp(self):
1208 assert os.path.exists(self.dirlink_target)
1209 assert os.path.exists(self.filelink_target)
1210 assert not os.path.exists(self.dirlink)
1211 assert not os.path.exists(self.filelink)
1212 assert not os.path.exists(self.missing_link)
1213
1214 def tearDown(self):
1215 if os.path.exists(self.filelink):
1216 os.remove(self.filelink)
1217 if os.path.exists(self.dirlink):
1218 os.rmdir(self.dirlink)
1219 if os.path.lexists(self.missing_link):
1220 os.remove(self.missing_link)
1221
1222 def test_directory_link(self):
Antoine Pitrou5311c1d2012-01-24 08:59:28 +01001223 os.symlink(self.dirlink_target, self.dirlink, True)
Brian Curtind40e6f72010-07-08 21:39:08 +00001224 self.assertTrue(os.path.exists(self.dirlink))
1225 self.assertTrue(os.path.isdir(self.dirlink))
1226 self.assertTrue(os.path.islink(self.dirlink))
1227 self.check_stat(self.dirlink, self.dirlink_target)
1228
1229 def test_file_link(self):
1230 os.symlink(self.filelink_target, self.filelink)
1231 self.assertTrue(os.path.exists(self.filelink))
1232 self.assertTrue(os.path.isfile(self.filelink))
1233 self.assertTrue(os.path.islink(self.filelink))
1234 self.check_stat(self.filelink, self.filelink_target)
1235
1236 def _create_missing_dir_link(self):
1237 'Create a "directory" link to a non-existent target'
1238 linkname = self.missing_link
1239 if os.path.lexists(linkname):
1240 os.remove(linkname)
1241 target = r'c:\\target does not exist.29r3c740'
1242 assert not os.path.exists(target)
1243 target_is_dir = True
1244 os.symlink(target, linkname, target_is_dir)
1245
1246 def test_remove_directory_link_to_missing_target(self):
1247 self._create_missing_dir_link()
1248 # For compatibility with Unix, os.remove will check the
1249 # directory status and call RemoveDirectory if the symlink
1250 # was created with target_is_dir==True.
1251 os.remove(self.missing_link)
1252
1253 @unittest.skip("currently fails; consider for improvement")
1254 def test_isdir_on_directory_link_to_missing_target(self):
1255 self._create_missing_dir_link()
1256 # consider having isdir return true for directory links
1257 self.assertTrue(os.path.isdir(self.missing_link))
1258
1259 @unittest.skip("currently fails; consider for improvement")
1260 def test_rmdir_on_directory_link_to_missing_target(self):
1261 self._create_missing_dir_link()
1262 # consider allowing rmdir to remove directory links
1263 os.rmdir(self.missing_link)
1264
1265 def check_stat(self, link, target):
1266 self.assertEqual(os.stat(link), os.stat(target))
1267 self.assertNotEqual(os.lstat(link), os.stat(link))
1268
Brian Curtind25aef52011-06-13 15:16:04 -05001269 bytes_link = os.fsencode(link)
1270 self.assertEqual(os.stat(bytes_link), os.stat(target))
1271 self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link))
1272
1273 def test_12084(self):
1274 level1 = os.path.abspath(support.TESTFN)
1275 level2 = os.path.join(level1, "level2")
1276 level3 = os.path.join(level2, "level3")
1277 try:
1278 os.mkdir(level1)
1279 os.mkdir(level2)
1280 os.mkdir(level3)
1281
1282 file1 = os.path.abspath(os.path.join(level1, "file1"))
1283
1284 with open(file1, "w") as f:
1285 f.write("file1")
1286
1287 orig_dir = os.getcwd()
1288 try:
1289 os.chdir(level2)
1290 link = os.path.join(level2, "link")
1291 os.symlink(os.path.relpath(file1), "link")
1292 self.assertIn("link", os.listdir(os.getcwd()))
1293
1294 # Check os.stat calls from the same dir as the link
1295 self.assertEqual(os.stat(file1), os.stat("link"))
1296
1297 # Check os.stat calls from a dir below the link
1298 os.chdir(level1)
1299 self.assertEqual(os.stat(file1),
1300 os.stat(os.path.relpath(link)))
1301
1302 # Check os.stat calls from a dir above the link
1303 os.chdir(level3)
1304 self.assertEqual(os.stat(file1),
1305 os.stat(os.path.relpath(link)))
1306 finally:
1307 os.chdir(orig_dir)
1308 except OSError as err:
1309 self.fail(err)
1310 finally:
1311 os.remove(file1)
1312 shutil.rmtree(level1)
1313
Brian Curtind40e6f72010-07-08 21:39:08 +00001314
Victor Stinnere8d51452010-08-19 01:05:19 +00001315class FSEncodingTests(unittest.TestCase):
1316 def test_nop(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001317 self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
1318 self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
Benjamin Peterson31191a92010-05-09 03:22:58 +00001319
Victor Stinnere8d51452010-08-19 01:05:19 +00001320 def test_identity(self):
1321 # assert fsdecode(fsencode(x)) == x
1322 for fn in ('unicode\u0141', 'latin\xe9', 'ascii'):
1323 try:
1324 bytesfn = os.fsencode(fn)
1325 except UnicodeEncodeError:
1326 continue
Ezio Melottib3aedd42010-11-20 19:04:17 +00001327 self.assertEqual(os.fsdecode(bytesfn), fn)
Victor Stinnere8d51452010-08-19 01:05:19 +00001328
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00001329
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00001330class PidTests(unittest.TestCase):
1331 @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid")
1332 def test_getppid(self):
1333 p = subprocess.Popen([sys.executable, '-c',
1334 'import os; print(os.getppid())'],
1335 stdout=subprocess.PIPE)
1336 stdout, _ = p.communicate()
1337 # We are the parent of our subprocess
1338 self.assertEqual(int(stdout), os.getpid())
1339
1340
Brian Curtin0151b8e2010-09-24 13:43:43 +00001341# The introduction of this TestCase caused at least two different errors on
1342# *nix buildbots. Temporarily skip this to let the buildbots move along.
1343@unittest.skip("Skip due to platform/environment differences on *NIX buildbots")
Brian Curtine8e4b3b2010-09-23 20:04:14 +00001344@unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin")
1345class LoginTests(unittest.TestCase):
1346 def test_getlogin(self):
1347 user_name = os.getlogin()
1348 self.assertNotEqual(len(user_name), 0)
1349
1350
Fred Drake2e2be372001-09-20 21:33:42 +00001351def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001352 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001353 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001354 StatAttributeTests,
1355 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00001356 WalkTests,
1357 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +00001358 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001359 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001360 ExecTests,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001361 Win32ErrorTests,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001362 TestInvalidFD,
Martin v. Löwis011e8422009-05-05 04:43:17 +00001363 PosixUidGidTests,
Brian Curtineb24d742010-04-12 17:16:38 +00001364 Pep383Tests,
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00001365 Win32KillTests,
Brian Curtind40e6f72010-07-08 21:39:08 +00001366 Win32SymlinkTests,
Victor Stinnere8d51452010-08-19 01:05:19 +00001367 FSEncodingTests,
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00001368 PidTests,
Brian Curtine8e4b3b2010-09-23 20:04:14 +00001369 LoginTests,
Brian Curtin1b9df392010-11-24 20:24:31 +00001370 LinkTests,
Andrew Svetlov405faed2012-12-25 12:18:09 +02001371 RemoveDirsTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001372 )
Fred Drake2e2be372001-09-20 21:33:42 +00001373
1374if __name__ == "__main__":
1375 test_main()