blob: 56be375b78c32b800e6b2ddc7c776c7c6b863441 [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
Fred Drake38c2ef02001-07-17 20:52:51 +000018
Mark Dickinson7cf03892010-04-16 13:45:35 +000019# Detect whether we're on a Linux system that uses the (now outdated
20# and unmaintained) linuxthreads threading library. There's an issue
21# when combining linuxthreads with a failed execv call: see
22# http://bugs.python.org/issue4970.
Mark Dickinson89589c92010-04-16 13:51:27 +000023if (hasattr(os, "confstr_names") and
24 "CS_GNU_LIBPTHREAD_VERSION" in os.confstr_names):
Mark Dickinson7cf03892010-04-16 13:45:35 +000025 libpthread = os.confstr("CS_GNU_LIBPTHREAD_VERSION")
26 USING_LINUXTHREADS= libpthread.startswith("linuxthreads")
27else:
28 USING_LINUXTHREADS= False
Brian Curtineb24d742010-04-12 17:16:38 +000029
Thomas Wouters0e3f5912006-08-11 14:57:12 +000030# Tests creating TESTFN
31class FileTests(unittest.TestCase):
32 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000033 if os.path.exists(support.TESTFN):
34 os.unlink(support.TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000035 tearDown = setUp
36
37 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000038 f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000039 os.close(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000040 self.assertTrue(os.access(support.TESTFN, os.W_OK))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000041
Christian Heimesfdab48e2008-01-20 09:06:41 +000042 def test_closerange(self):
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000043 first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
44 # We must allocate two consecutive file descriptors, otherwise
45 # it will mess up other file descriptors (perhaps even the three
46 # standard ones).
47 second = os.dup(first)
48 try:
49 retries = 0
50 while second != first + 1:
51 os.close(first)
52 retries += 1
53 if retries > 10:
54 # XXX test skipped
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000055 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000056 first, second = second, os.dup(second)
57 finally:
58 os.close(second)
Christian Heimesfdab48e2008-01-20 09:06:41 +000059 # close a fd that is open, and one that isn't
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000060 os.closerange(first, first + 2)
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000061 self.assertRaises(OSError, os.write, first, b"a")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000062
Benjamin Peterson1cc6df92010-06-30 17:39:45 +000063 @support.cpython_only
Hirokazu Yamamoto4c19e6e2008-09-08 23:41:21 +000064 def test_rename(self):
65 path = support.TESTFN
66 old = sys.getrefcount(path)
67 self.assertRaises(TypeError, os.rename, path, 0)
68 new = sys.getrefcount(path)
69 self.assertEqual(old, new)
70
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000071 def test_read(self):
72 with open(support.TESTFN, "w+b") as fobj:
73 fobj.write(b"spam")
74 fobj.flush()
75 fd = fobj.fileno()
76 os.lseek(fd, 0, 0)
77 s = os.read(fd, 4)
78 self.assertEqual(type(s), bytes)
79 self.assertEqual(s, b"spam")
80
81 def test_write(self):
82 # os.write() accepts bytes- and buffer-like objects but not strings
83 fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY)
84 self.assertRaises(TypeError, os.write, fd, "beans")
85 os.write(fd, b"bacon\n")
86 os.write(fd, bytearray(b"eggs\n"))
87 os.write(fd, memoryview(b"spam\n"))
88 os.close(fd)
89 with open(support.TESTFN, "rb") as fobj:
Antoine Pitroud62269f2008-09-15 23:54:52 +000090 self.assertEqual(fobj.read().splitlines(),
91 [b"bacon", b"eggs", b"spam"])
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000092
Victor Stinnere0daff12011-03-20 23:36:35 +010093 def write_windows_console(self, *args):
94 retcode = subprocess.call(args,
95 # use a new console to not flood the test output
96 creationflags=subprocess.CREATE_NEW_CONSOLE,
97 # use a shell to hide the console window (SW_HIDE)
98 shell=True)
99 self.assertEqual(retcode, 0)
100
101 @unittest.skipUnless(sys.platform == 'win32',
102 'test specific to the Windows console')
103 def test_write_windows_console(self):
104 # Issue #11395: the Windows console returns an error (12: not enough
105 # space error) on writing into stdout if stdout mode is binary and the
106 # length is greater than 66,000 bytes (or less, depending on heap
107 # usage).
108 code = "print('x' * 100000)"
109 self.write_windows_console(sys.executable, "-c", code)
110 self.write_windows_console(sys.executable, "-u", "-c", code)
111
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000112
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000113class TemporaryFileTests(unittest.TestCase):
114 def setUp(self):
115 self.files = []
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000116 os.mkdir(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000117
118 def tearDown(self):
119 for name in self.files:
120 os.unlink(name)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000121 os.rmdir(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000122
123 def check_tempfile(self, name):
124 # make sure it doesn't already exist:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000125 self.assertFalse(os.path.exists(name),
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000126 "file already exists for temporary file")
127 # make sure we can create the file
128 open(name, "w")
129 self.files.append(name)
130
131 def test_tempnam(self):
132 if not hasattr(os, "tempnam"):
133 return
134 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
135 r"test_os$")
136 self.check_tempfile(os.tempnam())
137
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000138 name = os.tempnam(support.TESTFN)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000139 self.check_tempfile(name)
140
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000141 name = os.tempnam(support.TESTFN, "pfx")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000142 self.assertTrue(os.path.basename(name)[:3] == "pfx")
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000143 self.check_tempfile(name)
144
145 def test_tmpfile(self):
146 if not hasattr(os, "tmpfile"):
147 return
148 # As with test_tmpnam() below, the Windows implementation of tmpfile()
149 # attempts to create a file in the root directory of the current drive.
150 # On Vista and Server 2008, this test will always fail for normal users
151 # as writing to the root directory requires elevated privileges. With
152 # XP and below, the semantics of tmpfile() are the same, but the user
153 # running the test is more likely to have administrative privileges on
154 # their account already. If that's the case, then os.tmpfile() should
155 # work. In order to make this test as useful as possible, rather than
156 # trying to detect Windows versions or whether or not the user has the
157 # right permissions, just try and create a file in the root directory
158 # and see if it raises a 'Permission denied' OSError. If it does, then
159 # test that a subsequent call to os.tmpfile() raises the same error. If
160 # it doesn't, assume we're on XP or below and the user running the test
161 # has administrative privileges, and proceed with the test as normal.
162 if sys.platform == 'win32':
163 name = '\\python_test_os_test_tmpfile.txt'
164 if os.path.exists(name):
165 os.remove(name)
166 try:
167 fp = open(name, 'w')
168 except IOError as first:
169 # open() failed, assert tmpfile() fails in the same way.
170 # Although open() raises an IOError and os.tmpfile() raises an
171 # OSError(), 'args' will be (13, 'Permission denied') in both
172 # cases.
173 try:
174 fp = os.tmpfile()
175 except OSError as second:
176 self.assertEqual(first.args, second.args)
177 else:
178 self.fail("expected os.tmpfile() to raise OSError")
179 return
180 else:
181 # open() worked, therefore, tmpfile() should work. Close our
182 # dummy file and proceed with the test as normal.
183 fp.close()
184 os.remove(name)
185
186 fp = os.tmpfile()
187 fp.write("foobar")
188 fp.seek(0,0)
189 s = fp.read()
190 fp.close()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000191 self.assertTrue(s == "foobar")
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000192
193 def test_tmpnam(self):
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000194 if not hasattr(os, "tmpnam"):
195 return
196 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
197 r"test_os$")
198 name = os.tmpnam()
199 if sys.platform in ("win32",):
200 # The Windows tmpnam() seems useless. From the MS docs:
201 #
202 # The character string that tmpnam creates consists of
203 # the path prefix, defined by the entry P_tmpdir in the
204 # file STDIO.H, followed by a sequence consisting of the
205 # digit characters '0' through '9'; the numerical value
206 # of this string is in the range 1 - 65,535. Changing the
207 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
208 # change the operation of tmpnam.
209 #
210 # The really bizarre part is that, at least under MSVC6,
211 # P_tmpdir is "\\". That is, the path returned refers to
212 # the root of the current drive. That's a terrible place to
213 # put temp files, and, depending on privileges, the user
214 # may not even be able to open a file in the root directory.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000215 self.assertFalse(os.path.exists(name),
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000216 "file already exists for temporary file")
217 else:
218 self.check_tempfile(name)
219
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000220 def fdopen_helper(self, *args):
221 fd = os.open(support.TESTFN, os.O_RDONLY)
222 fp2 = os.fdopen(fd, *args)
223 fp2.close()
224
225 def test_fdopen(self):
226 self.fdopen_helper()
227 self.fdopen_helper('r')
228 self.fdopen_helper('r', 100)
229
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000230# Test attributes on return values from os.*stat* family.
231class StatAttributeTests(unittest.TestCase):
232 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000233 os.mkdir(support.TESTFN)
234 self.fname = os.path.join(support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000235 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +0000236 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000237 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000238
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000239 def tearDown(self):
240 os.unlink(self.fname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000241 os.rmdir(support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000242
Antoine Pitrou38425292010-09-21 18:19:07 +0000243 def check_stat_attributes(self, fname):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000244 if not hasattr(os, "stat"):
245 return
246
247 import stat
Antoine Pitrou38425292010-09-21 18:19:07 +0000248 result = os.stat(fname)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000249
250 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000251 self.assertEqual(result[stat.ST_SIZE], 3)
252 self.assertEqual(result.st_size, 3)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000253
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000254 # Make sure all the attributes are there
255 members = dir(result)
256 for name in dir(stat):
257 if name[:3] == 'ST_':
258 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000259 if name.endswith("TIME"):
260 def trunc(x): return int(x)
261 else:
262 def trunc(x): return x
Ezio Melottib3aedd42010-11-20 19:04:17 +0000263 self.assertEqual(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000264 result[getattr(stat, name)])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000265 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000266
267 try:
268 result[200]
269 self.fail("No exception thrown")
270 except IndexError:
271 pass
272
273 # Make sure that assignment fails
274 try:
275 result.st_mode = 1
276 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000277 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000278 pass
279
280 try:
281 result.st_rdev = 1
282 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000283 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000284 pass
285
286 try:
287 result.parrot = 1
288 self.fail("No exception thrown")
289 except AttributeError:
290 pass
291
292 # Use the stat_result constructor with a too-short tuple.
293 try:
294 result2 = os.stat_result((10,))
295 self.fail("No exception thrown")
296 except TypeError:
297 pass
298
Ezio Melotti42da6632011-03-15 05:18:48 +0200299 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000300 try:
301 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
302 except TypeError:
303 pass
304
Antoine Pitrou38425292010-09-21 18:19:07 +0000305 def test_stat_attributes(self):
306 self.check_stat_attributes(self.fname)
307
308 def test_stat_attributes_bytes(self):
309 try:
310 fname = self.fname.encode(sys.getfilesystemencoding())
311 except UnicodeEncodeError:
312 self.skipTest("cannot encode %a for the filesystem" % self.fname)
313 self.check_stat_attributes(fname)
Tim Peterse0c446b2001-10-18 21:57:37 +0000314
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000315 def test_statvfs_attributes(self):
316 if not hasattr(os, "statvfs"):
317 return
318
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000319 try:
320 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000321 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000322 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000323 if e.errno == errno.ENOSYS:
324 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000325
326 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000327 self.assertEqual(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000328
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000329 # Make sure all the attributes are there.
330 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
331 'ffree', 'favail', 'flag', 'namemax')
332 for value, member in enumerate(members):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000333 self.assertEqual(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000334
335 # Make sure that assignment really fails
336 try:
337 result.f_bfree = 1
338 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000339 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000340 pass
341
342 try:
343 result.parrot = 1
344 self.fail("No exception thrown")
345 except AttributeError:
346 pass
347
348 # Use the constructor with a too-short tuple.
349 try:
350 result2 = os.statvfs_result((10,))
351 self.fail("No exception thrown")
352 except TypeError:
353 pass
354
Ezio Melotti42da6632011-03-15 05:18:48 +0200355 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000356 try:
357 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
358 except TypeError:
359 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000360
Thomas Wouters89f507f2006-12-13 04:49:30 +0000361 def test_utime_dir(self):
362 delta = 1000000
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000363 st = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000364 # round to int, because some systems may support sub-second
365 # time stamps in stat, but not in utime.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000366 os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
367 st2 = os.stat(support.TESTFN)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000368 self.assertEqual(st2.st_mtime, int(st.st_mtime-delta))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000369
370 # Restrict test to Win32, since there is no guarantee other
371 # systems support centiseconds
372 if sys.platform == 'win32':
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000373 def get_file_system(path):
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000374 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000375 import ctypes
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000376 kernel32 = ctypes.windll.kernel32
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000377 buf = ctypes.create_unicode_buffer("", 100)
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000378 if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000379 return buf.value
380
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000381 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000382 def test_1565150(self):
383 t1 = 1159195039.25
384 os.utime(self.fname, (t1, t1))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000385 self.assertEqual(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000386
Amaury Forgeot d'Arca251a852011-01-03 00:19:11 +0000387 def test_large_time(self):
388 t1 = 5000000000 # some day in 2128
389 os.utime(self.fname, (t1, t1))
390 self.assertEqual(os.stat(self.fname).st_mtime, t1)
391
Guido van Rossumd8faa362007-04-27 19:54:29 +0000392 def test_1686475(self):
393 # Verify that an open file can be stat'ed
394 try:
395 os.stat(r"c:\pagefile.sys")
396 except WindowsError as e:
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000397 if e.errno == 2: # file does not exist; cannot run test
Guido van Rossumd8faa362007-04-27 19:54:29 +0000398 return
399 self.fail("Could not stat pagefile.sys")
400
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000401from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000402
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000403class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000404 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000405 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000406
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000407 def setUp(self):
408 self.__save = dict(os.environ)
Victor Stinnerb745a742010-05-18 17:17:23 +0000409 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000410 self.__saveb = dict(os.environb)
Christian Heimes90333392007-11-01 19:08:42 +0000411 for key, value in self._reference().items():
412 os.environ[key] = value
413
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000414 def tearDown(self):
415 os.environ.clear()
416 os.environ.update(self.__save)
Victor Stinnerb745a742010-05-18 17:17:23 +0000417 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000418 os.environb.clear()
419 os.environb.update(self.__saveb)
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000420
Christian Heimes90333392007-11-01 19:08:42 +0000421 def _reference(self):
422 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
423
424 def _empty_mapping(self):
425 os.environ.clear()
426 return os.environ
427
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000428 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000429 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000430 os.environ.clear()
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000431 if os.path.exists("/bin/sh"):
432 os.environ.update(HELLO="World")
Brian Curtin810921b2010-10-30 21:24:21 +0000433 with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
434 value = popen.read().strip()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000435 self.assertEqual(value, "World")
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000436
Christian Heimes1a13d592007-11-08 14:16:55 +0000437 def test_os_popen_iter(self):
438 if os.path.exists("/bin/sh"):
Brian Curtin810921b2010-10-30 21:24:21 +0000439 with os.popen(
440 "/bin/sh -c 'echo \"line1\nline2\nline3\"'") as popen:
441 it = iter(popen)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000442 self.assertEqual(next(it), "line1\n")
443 self.assertEqual(next(it), "line2\n")
444 self.assertEqual(next(it), "line3\n")
Brian Curtin810921b2010-10-30 21:24:21 +0000445 self.assertRaises(StopIteration, next, it)
Christian Heimes1a13d592007-11-08 14:16:55 +0000446
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000447 # Verify environ keys and values from the OS are of the
448 # correct str type.
449 def test_keyvalue_types(self):
450 for key, val in os.environ.items():
Ezio Melottib3aedd42010-11-20 19:04:17 +0000451 self.assertEqual(type(key), str)
452 self.assertEqual(type(val), str)
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000453
Christian Heimes90333392007-11-01 19:08:42 +0000454 def test_items(self):
455 for key, value in self._reference().items():
456 self.assertEqual(os.environ.get(key), value)
457
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000458 # Issue 7310
459 def test___repr__(self):
460 """Check that the repr() of os.environ looks like environ({...})."""
461 env = os.environ
Victor Stinner96f0de92010-07-29 00:29:00 +0000462 self.assertEqual(repr(env), 'environ({{{}}})'.format(', '.join(
463 '{!r}: {!r}'.format(key, value)
464 for key, value in env.items())))
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000465
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000466 def test_get_exec_path(self):
467 defpath_list = os.defpath.split(os.pathsep)
468 test_path = ['/monty', '/python', '', '/flying/circus']
469 test_env = {'PATH': os.pathsep.join(test_path)}
470
471 saved_environ = os.environ
472 try:
473 os.environ = dict(test_env)
474 # Test that defaulting to os.environ works.
475 self.assertSequenceEqual(test_path, os.get_exec_path())
476 self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
477 finally:
478 os.environ = saved_environ
479
480 # No PATH environment variable
481 self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
482 # Empty PATH environment variable
483 self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
484 # Supplied PATH environment variable
485 self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
486
Victor Stinnerb745a742010-05-18 17:17:23 +0000487 if os.supports_bytes_environ:
488 # env cannot contain 'PATH' and b'PATH' keys
Victor Stinner38430e22010-08-19 17:10:18 +0000489 try:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000490 # ignore BytesWarning warning
491 with warnings.catch_warnings(record=True):
492 mixed_env = {'PATH': '1', b'PATH': b'2'}
Victor Stinner38430e22010-08-19 17:10:18 +0000493 except BytesWarning:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000494 # mixed_env cannot be created with python -bb
Victor Stinner38430e22010-08-19 17:10:18 +0000495 pass
496 else:
497 self.assertRaises(ValueError, os.get_exec_path, mixed_env)
Victor Stinnerb745a742010-05-18 17:17:23 +0000498
499 # bytes key and/or value
500 self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}),
501 ['abc'])
502 self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}),
503 ['abc'])
504 self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}),
505 ['abc'])
506
507 @unittest.skipUnless(os.supports_bytes_environ,
508 "os.environb required for this test.")
Victor Stinner84ae1182010-05-06 22:05:07 +0000509 def test_environb(self):
510 # os.environ -> os.environb
511 value = 'euro\u20ac'
512 try:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000513 value_bytes = value.encode(sys.getfilesystemencoding(),
514 'surrogateescape')
Victor Stinner84ae1182010-05-06 22:05:07 +0000515 except UnicodeEncodeError:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000516 msg = "U+20AC character is not encodable to %s" % (
517 sys.getfilesystemencoding(),)
Benjamin Peterson932d3f42010-05-06 22:26:31 +0000518 self.skipTest(msg)
Victor Stinner84ae1182010-05-06 22:05:07 +0000519 os.environ['unicode'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000520 self.assertEqual(os.environ['unicode'], value)
521 self.assertEqual(os.environb[b'unicode'], value_bytes)
Victor Stinner84ae1182010-05-06 22:05:07 +0000522
523 # os.environb -> os.environ
524 value = b'\xff'
525 os.environb[b'bytes'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000526 self.assertEqual(os.environb[b'bytes'], value)
Victor Stinner84ae1182010-05-06 22:05:07 +0000527 value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000528 self.assertEqual(os.environ['bytes'], value_str)
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000529
Tim Petersc4e09402003-04-25 07:11:48 +0000530class WalkTests(unittest.TestCase):
531 """Tests for os.walk()."""
532
533 def test_traversal(self):
534 import os
535 from os.path import join
536
537 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000538 # TESTFN/
539 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000540 # tmp1
541 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000542 # tmp2
543 # SUB11/ no kids
544 # SUB2/ a file kid and a dirsymlink kid
545 # tmp3
546 # link/ a symlink to TESTFN.2
547 # TEST2/
548 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000549 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000550 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000551 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000552 sub2_path = join(walk_path, "SUB2")
553 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000554 tmp2_path = join(sub1_path, "tmp2")
555 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000556 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000557 t2_path = join(support.TESTFN, "TEST2")
558 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000559
560 # Create stuff.
561 os.makedirs(sub11_path)
562 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000563 os.makedirs(t2_path)
564 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000565 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000566 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
567 f.close()
Brian Curtin3b4499c2010-12-28 14:31:47 +0000568 if support.can_symlink():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000569 os.symlink(os.path.abspath(t2_path), link_path)
570 sub2_tree = (sub2_path, ["link"], ["tmp3"])
571 else:
572 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000573
574 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000575 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000576 self.assertEqual(len(all), 4)
577 # We can't know which order SUB1 and SUB2 will appear in.
578 # Not flipped: TESTFN, SUB1, SUB11, SUB2
579 # flipped: TESTFN, SUB2, SUB1, SUB11
580 flipped = all[0][1][0] != "SUB1"
581 all[0][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000582 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000583 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
584 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000585 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000586
587 # Prune the search.
588 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000589 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000590 all.append((root, dirs, files))
591 # Don't descend into SUB1.
592 if 'SUB1' in dirs:
593 # Note that this also mutates the dirs we appended to all!
594 dirs.remove('SUB1')
595 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000596 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
597 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000598
599 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000600 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000601 self.assertEqual(len(all), 4)
602 # We can't know which order SUB1 and SUB2 will appear in.
603 # Not flipped: SUB11, SUB1, SUB2, TESTFN
604 # flipped: SUB2, SUB11, SUB1, TESTFN
605 flipped = all[3][1][0] != "SUB1"
606 all[3][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000607 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000608 self.assertEqual(all[flipped], (sub11_path, [], []))
609 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000610 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000611
Brian Curtin3b4499c2010-12-28 14:31:47 +0000612 if support.can_symlink():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000613 # Walk, following symlinks.
614 for root, dirs, files in os.walk(walk_path, followlinks=True):
615 if root == link_path:
616 self.assertEqual(dirs, [])
617 self.assertEqual(files, ["tmp4"])
618 break
619 else:
620 self.fail("Didn't follow symlink with followlinks=True")
621
622 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000623 # Tear everything down. This is a decent use for bottom-up on
624 # Windows, which doesn't have a recursive delete command. The
625 # (not so) subtlety is that rmdir will fail unless the dir's
626 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000627 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000628 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000629 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000630 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000631 dirname = os.path.join(root, name)
632 if not os.path.islink(dirname):
633 os.rmdir(dirname)
634 else:
635 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000636 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000637
Guido van Rossume7ba4952007-06-06 23:52:48 +0000638class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000639 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000640 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000641
642 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000643 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000644 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
645 os.makedirs(path) # Should work
646 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
647 os.makedirs(path)
648
649 # Try paths with a '.' in them
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000650 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000651 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
652 os.makedirs(path)
653 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
654 'dir5', 'dir6')
655 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000656
Terry Reedy5a22b652010-12-02 07:05:56 +0000657 def test_exist_ok_existing_directory(self):
658 path = os.path.join(support.TESTFN, 'dir1')
659 mode = 0o777
660 old_mask = os.umask(0o022)
661 os.makedirs(path, mode)
662 self.assertRaises(OSError, os.makedirs, path, mode)
663 self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
664 self.assertRaises(OSError, os.makedirs, path, 0o776, exist_ok=True)
665 os.makedirs(path, mode=mode, exist_ok=True)
666 os.umask(old_mask)
667
668 def test_exist_ok_existing_regular_file(self):
669 base = support.TESTFN
670 path = os.path.join(support.TESTFN, 'dir1')
671 f = open(path, 'w')
672 f.write('abc')
673 f.close()
674 self.assertRaises(OSError, os.makedirs, path)
675 self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
676 self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
677 os.remove(path)
678
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000679 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000680 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000681 'dir4', 'dir5', 'dir6')
682 # If the tests failed, the bottom-most directory ('../dir6')
683 # may not have been created, so we look for the outermost directory
684 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000685 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000686 path = os.path.dirname(path)
687
688 os.removedirs(path)
689
Guido van Rossume7ba4952007-06-06 23:52:48 +0000690class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000691 def test_devnull(self):
Alex Martelli01c77c62006-08-24 02:58:11 +0000692 f = open(os.devnull, 'w')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000693 f.write('hello')
694 f.close()
Alex Martelli01c77c62006-08-24 02:58:11 +0000695 f = open(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000696 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000697 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000698
Guido van Rossume7ba4952007-06-06 23:52:48 +0000699class URandomTests(unittest.TestCase):
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000700 def test_urandom(self):
701 try:
702 self.assertEqual(len(os.urandom(1)), 1)
703 self.assertEqual(len(os.urandom(10)), 10)
704 self.assertEqual(len(os.urandom(100)), 100)
705 self.assertEqual(len(os.urandom(1000)), 1000)
706 except NotImplementedError:
707 pass
708
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000709@contextlib.contextmanager
710def _execvpe_mockup(defpath=None):
711 """
712 Stubs out execv and execve functions when used as context manager.
713 Records exec calls. The mock execv and execve functions always raise an
714 exception as they would normally never return.
715 """
716 # A list of tuples containing (function name, first arg, args)
717 # of calls to execv or execve that have been made.
718 calls = []
719
720 def mock_execv(name, *args):
721 calls.append(('execv', name, args))
722 raise RuntimeError("execv called")
723
724 def mock_execve(name, *args):
725 calls.append(('execve', name, args))
726 raise OSError(errno.ENOTDIR, "execve called")
727
728 try:
729 orig_execv = os.execv
730 orig_execve = os.execve
731 orig_defpath = os.defpath
732 os.execv = mock_execv
733 os.execve = mock_execve
734 if defpath is not None:
735 os.defpath = defpath
736 yield calls
737 finally:
738 os.execv = orig_execv
739 os.execve = orig_execve
740 os.defpath = orig_defpath
741
Guido van Rossume7ba4952007-06-06 23:52:48 +0000742class ExecTests(unittest.TestCase):
Mark Dickinson7cf03892010-04-16 13:45:35 +0000743 @unittest.skipIf(USING_LINUXTHREADS,
744 "avoid triggering a linuxthreads bug: see issue #4970")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000745 def test_execvpe_with_bad_program(self):
Mark Dickinson7cf03892010-04-16 13:45:35 +0000746 self.assertRaises(OSError, os.execvpe, 'no such app-',
747 ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000748
Thomas Heller6790d602007-08-30 17:15:14 +0000749 def test_execvpe_with_bad_arglist(self):
750 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
751
Gregory P. Smith4ae37772010-05-08 18:05:46 +0000752 @unittest.skipUnless(hasattr(os, '_execvpe'),
753 "No internal os._execvpe function to test.")
Victor Stinnerb745a742010-05-18 17:17:23 +0000754 def _test_internal_execvpe(self, test_type):
755 program_path = os.sep + 'absolutepath'
756 if test_type is bytes:
757 program = b'executable'
758 fullpath = os.path.join(os.fsencode(program_path), program)
759 native_fullpath = fullpath
760 arguments = [b'progname', 'arg1', 'arg2']
761 else:
762 program = 'executable'
763 arguments = ['progname', 'arg1', 'arg2']
764 fullpath = os.path.join(program_path, program)
765 if os.name != "nt":
766 native_fullpath = os.fsencode(fullpath)
767 else:
768 native_fullpath = fullpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000769 env = {'spam': 'beans'}
770
Victor Stinnerb745a742010-05-18 17:17:23 +0000771 # test os._execvpe() with an absolute path
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000772 with _execvpe_mockup() as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +0000773 self.assertRaises(RuntimeError,
774 os._execvpe, fullpath, arguments)
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000775 self.assertEqual(len(calls), 1)
776 self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))
777
Victor Stinnerb745a742010-05-18 17:17:23 +0000778 # test os._execvpe() with a relative path:
779 # os.get_exec_path() returns defpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000780 with _execvpe_mockup(defpath=program_path) as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +0000781 self.assertRaises(OSError,
782 os._execvpe, program, arguments, env=env)
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000783 self.assertEqual(len(calls), 1)
Victor Stinnerb745a742010-05-18 17:17:23 +0000784 self.assertSequenceEqual(calls[0],
785 ('execve', native_fullpath, (arguments, env)))
786
787 # test os._execvpe() with a relative path:
788 # os.get_exec_path() reads the 'PATH' variable
789 with _execvpe_mockup() as calls:
790 env_path = env.copy()
Victor Stinner38430e22010-08-19 17:10:18 +0000791 if test_type is bytes:
792 env_path[b'PATH'] = program_path
793 else:
794 env_path['PATH'] = program_path
Victor Stinnerb745a742010-05-18 17:17:23 +0000795 self.assertRaises(OSError,
796 os._execvpe, program, arguments, env=env_path)
797 self.assertEqual(len(calls), 1)
798 self.assertSequenceEqual(calls[0],
799 ('execve', native_fullpath, (arguments, env_path)))
800
801 def test_internal_execvpe_str(self):
802 self._test_internal_execvpe(str)
803 if os.name != "nt":
804 self._test_internal_execvpe(bytes)
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000805
Gregory P. Smith4ae37772010-05-08 18:05:46 +0000806
Thomas Wouters477c8d52006-05-27 19:21:47 +0000807class Win32ErrorTests(unittest.TestCase):
808 def test_rename(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000809 self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000810
811 def test_remove(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000812 self.assertRaises(WindowsError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000813
814 def test_chdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000815 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000816
817 def test_mkdir(self):
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +0000818 f = open(support.TESTFN, "w")
Benjamin Petersonf91df042009-02-13 02:50:59 +0000819 try:
820 self.assertRaises(WindowsError, os.mkdir, support.TESTFN)
821 finally:
822 f.close()
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +0000823 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000824
825 def test_utime(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000826 self.assertRaises(WindowsError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000827
Thomas Wouters477c8d52006-05-27 19:21:47 +0000828 def test_chmod(self):
Benjamin Petersonf91df042009-02-13 02:50:59 +0000829 self.assertRaises(WindowsError, os.chmod, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000830
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000831class TestInvalidFD(unittest.TestCase):
Benjamin Peterson05e782f2009-01-19 15:15:02 +0000832 singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000833 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
834 #singles.append("close")
835 #We omit close because it doesn'r raise an exception on some platforms
836 def get_single(f):
837 def helper(self):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000838 if hasattr(os, f):
839 self.check(getattr(os, f))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000840 return helper
841 for f in singles:
842 locals()["test_"+f] = get_single(f)
843
Benjamin Peterson7522c742009-01-19 21:00:09 +0000844 def check(self, f, *args):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000845 try:
846 f(support.make_bad_fd(), *args)
847 except OSError as e:
848 self.assertEqual(e.errno, errno.EBADF)
849 else:
850 self.fail("%r didn't raise a OSError with a bad file descriptor"
851 % f)
Benjamin Peterson7522c742009-01-19 21:00:09 +0000852
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000853 def test_isatty(self):
854 if hasattr(os, "isatty"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000855 self.assertEqual(os.isatty(support.make_bad_fd()), False)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000856
857 def test_closerange(self):
858 if hasattr(os, "closerange"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000859 fd = support.make_bad_fd()
R. David Murray630cc482009-07-22 15:20:27 +0000860 # Make sure none of the descriptors we are about to close are
861 # currently valid (issue 6542).
862 for i in range(10):
863 try: os.fstat(fd+i)
864 except OSError:
865 pass
866 else:
867 break
868 if i < 2:
869 raise unittest.SkipTest(
870 "Unable to acquire a range of invalid file descriptors")
871 self.assertEqual(os.closerange(fd, fd + i-1), None)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000872
873 def test_dup2(self):
874 if hasattr(os, "dup2"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000875 self.check(os.dup2, 20)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000876
877 def test_fchmod(self):
878 if hasattr(os, "fchmod"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000879 self.check(os.fchmod, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000880
881 def test_fchown(self):
882 if hasattr(os, "fchown"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000883 self.check(os.fchown, -1, -1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000884
885 def test_fpathconf(self):
886 if hasattr(os, "fpathconf"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000887 self.check(os.fpathconf, "PC_NAME_MAX")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000888
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000889 def test_ftruncate(self):
890 if hasattr(os, "ftruncate"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000891 self.check(os.ftruncate, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000892
893 def test_lseek(self):
894 if hasattr(os, "lseek"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000895 self.check(os.lseek, 0, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000896
897 def test_read(self):
898 if hasattr(os, "read"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000899 self.check(os.read, 1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000900
901 def test_tcsetpgrpt(self):
902 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000903 self.check(os.tcsetpgrp, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000904
905 def test_write(self):
906 if hasattr(os, "write"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000907 self.check(os.write, b" ")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000908
Brian Curtin1b9df392010-11-24 20:24:31 +0000909
910class LinkTests(unittest.TestCase):
911 def setUp(self):
912 self.file1 = support.TESTFN
913 self.file2 = os.path.join(support.TESTFN + "2")
914
Brian Curtinc0abc4e2010-11-30 23:46:54 +0000915 def tearDown(self):
Brian Curtin1b9df392010-11-24 20:24:31 +0000916 for file in (self.file1, self.file2):
917 if os.path.exists(file):
918 os.unlink(file)
919
Brian Curtin1b9df392010-11-24 20:24:31 +0000920 def _test_link(self, file1, file2):
921 with open(file1, "w") as f1:
922 f1.write("test")
923
924 os.link(file1, file2)
925 with open(file1, "r") as f1, open(file2, "r") as f2:
926 self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
927
928 def test_link(self):
929 self._test_link(self.file1, self.file2)
930
931 def test_link_bytes(self):
932 self._test_link(bytes(self.file1, sys.getfilesystemencoding()),
933 bytes(self.file2, sys.getfilesystemencoding()))
934
Brian Curtinf498b752010-11-30 15:54:04 +0000935 def test_unicode_name(self):
Brian Curtin43f0c272010-11-30 15:40:04 +0000936 try:
Brian Curtinf498b752010-11-30 15:54:04 +0000937 os.fsencode("\xf1")
Brian Curtin43f0c272010-11-30 15:40:04 +0000938 except UnicodeError:
939 raise unittest.SkipTest("Unable to encode for this platform.")
940
Brian Curtinf498b752010-11-30 15:54:04 +0000941 self.file1 += "\xf1"
Brian Curtinfc889c42010-11-28 23:59:46 +0000942 self.file2 = self.file1 + "2"
943 self._test_link(self.file1, self.file2)
944
Thomas Wouters477c8d52006-05-27 19:21:47 +0000945if sys.platform != 'win32':
946 class Win32ErrorTests(unittest.TestCase):
947 pass
948
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000949 class PosixUidGidTests(unittest.TestCase):
950 if hasattr(os, 'setuid'):
951 def test_setuid(self):
952 if os.getuid() != 0:
953 self.assertRaises(os.error, os.setuid, 0)
954 self.assertRaises(OverflowError, os.setuid, 1<<32)
955
956 if hasattr(os, 'setgid'):
957 def test_setgid(self):
958 if os.getuid() != 0:
959 self.assertRaises(os.error, os.setgid, 0)
960 self.assertRaises(OverflowError, os.setgid, 1<<32)
961
962 if hasattr(os, 'seteuid'):
963 def test_seteuid(self):
964 if os.getuid() != 0:
965 self.assertRaises(os.error, os.seteuid, 0)
966 self.assertRaises(OverflowError, os.seteuid, 1<<32)
967
968 if hasattr(os, 'setegid'):
969 def test_setegid(self):
970 if os.getuid() != 0:
971 self.assertRaises(os.error, os.setegid, 0)
972 self.assertRaises(OverflowError, os.setegid, 1<<32)
973
974 if hasattr(os, 'setreuid'):
975 def test_setreuid(self):
976 if os.getuid() != 0:
977 self.assertRaises(os.error, os.setreuid, 0, 0)
978 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
979 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000980
981 def test_setreuid_neg1(self):
982 # Needs to accept -1. We run this in a subprocess to avoid
983 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000984 subprocess.check_call([
985 sys.executable, '-c',
986 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000987
988 if hasattr(os, 'setregid'):
989 def test_setregid(self):
990 if os.getuid() != 0:
991 self.assertRaises(os.error, os.setregid, 0, 0)
992 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
993 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000994
995 def test_setregid_neg1(self):
996 # Needs to accept -1. We run this in a subprocess to avoid
997 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000998 subprocess.check_call([
999 sys.executable, '-c',
1000 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Martin v. Löwis011e8422009-05-05 04:43:17 +00001001
1002 class Pep383Tests(unittest.TestCase):
Martin v. Löwis011e8422009-05-05 04:43:17 +00001003 def setUp(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001004 if support.TESTFN_UNENCODABLE:
1005 self.dir = support.TESTFN_UNENCODABLE
1006 else:
1007 self.dir = support.TESTFN
1008 self.bdir = os.fsencode(self.dir)
1009
1010 bytesfn = []
1011 def add_filename(fn):
1012 try:
1013 fn = os.fsencode(fn)
1014 except UnicodeEncodeError:
1015 return
1016 bytesfn.append(fn)
1017 add_filename(support.TESTFN_UNICODE)
1018 if support.TESTFN_UNENCODABLE:
1019 add_filename(support.TESTFN_UNENCODABLE)
1020 if not bytesfn:
1021 self.skipTest("couldn't create any non-ascii filename")
1022
1023 self.unicodefn = set()
Martin v. Löwis011e8422009-05-05 04:43:17 +00001024 os.mkdir(self.dir)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001025 try:
1026 for fn in bytesfn:
1027 f = open(os.path.join(self.bdir, fn), "w")
1028 f.close()
Victor Stinnere8d51452010-08-19 01:05:19 +00001029 fn = os.fsdecode(fn)
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001030 if fn in self.unicodefn:
1031 raise ValueError("duplicate filename")
1032 self.unicodefn.add(fn)
1033 except:
1034 shutil.rmtree(self.dir)
1035 raise
Martin v. Löwis011e8422009-05-05 04:43:17 +00001036
1037 def tearDown(self):
1038 shutil.rmtree(self.dir)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001039
1040 def test_listdir(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +00001041 expected = self.unicodefn
1042 found = set(os.listdir(self.dir))
Ezio Melottib3aedd42010-11-20 19:04:17 +00001043 self.assertEqual(found, expected)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001044
1045 def test_open(self):
1046 for fn in self.unicodefn:
1047 f = open(os.path.join(self.dir, fn))
1048 f.close()
1049
1050 def test_stat(self):
1051 for fn in self.unicodefn:
1052 os.stat(os.path.join(self.dir, fn))
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001053else:
1054 class PosixUidGidTests(unittest.TestCase):
1055 pass
Martin v. Löwis011e8422009-05-05 04:43:17 +00001056 class Pep383Tests(unittest.TestCase):
1057 pass
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001058
Brian Curtineb24d742010-04-12 17:16:38 +00001059@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
1060class Win32KillTests(unittest.TestCase):
Brian Curtinc3acbc32010-05-28 16:08:40 +00001061 def _kill(self, sig):
1062 # Start sys.executable as a subprocess and communicate from the
1063 # subprocess to the parent that the interpreter is ready. When it
1064 # becomes ready, send *sig* via os.kill to the subprocess and check
1065 # that the return code is equal to *sig*.
1066 import ctypes
1067 from ctypes import wintypes
1068 import msvcrt
1069
1070 # Since we can't access the contents of the process' stdout until the
1071 # process has exited, use PeekNamedPipe to see what's inside stdout
1072 # without waiting. This is done so we can tell that the interpreter
1073 # is started and running at a point where it could handle a signal.
1074 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
1075 PeekNamedPipe.restype = wintypes.BOOL
1076 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
1077 ctypes.POINTER(ctypes.c_char), # stdout buf
1078 wintypes.DWORD, # Buffer size
1079 ctypes.POINTER(wintypes.DWORD), # bytes read
1080 ctypes.POINTER(wintypes.DWORD), # bytes avail
1081 ctypes.POINTER(wintypes.DWORD)) # bytes left
1082 msg = "running"
1083 proc = subprocess.Popen([sys.executable, "-c",
1084 "import sys;"
1085 "sys.stdout.write('{}');"
1086 "sys.stdout.flush();"
1087 "input()".format(msg)],
1088 stdout=subprocess.PIPE,
1089 stderr=subprocess.PIPE,
1090 stdin=subprocess.PIPE)
Brian Curtin43ec5772010-11-05 15:17:11 +00001091 self.addCleanup(proc.stdout.close)
1092 self.addCleanup(proc.stderr.close)
1093 self.addCleanup(proc.stdin.close)
Brian Curtinc3acbc32010-05-28 16:08:40 +00001094
1095 count, max = 0, 100
1096 while count < max and proc.poll() is None:
1097 # Create a string buffer to store the result of stdout from the pipe
1098 buf = ctypes.create_string_buffer(len(msg))
1099 # Obtain the text currently in proc.stdout
1100 # Bytes read/avail/left are left as NULL and unused
1101 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
1102 buf, ctypes.sizeof(buf), None, None, None)
1103 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
1104 if buf.value:
1105 self.assertEqual(msg, buf.value.decode())
1106 break
1107 time.sleep(0.1)
1108 count += 1
1109 else:
1110 self.fail("Did not receive communication from the subprocess")
1111
Brian Curtineb24d742010-04-12 17:16:38 +00001112 os.kill(proc.pid, sig)
1113 self.assertEqual(proc.wait(), sig)
1114
1115 def test_kill_sigterm(self):
1116 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinc3acbc32010-05-28 16:08:40 +00001117 self._kill(signal.SIGTERM)
Brian Curtineb24d742010-04-12 17:16:38 +00001118
1119 def test_kill_int(self):
1120 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinc3acbc32010-05-28 16:08:40 +00001121 self._kill(100)
Brian Curtineb24d742010-04-12 17:16:38 +00001122
1123 def _kill_with_event(self, event, name):
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001124 tagname = "test_os_%s" % uuid.uuid1()
1125 m = mmap.mmap(-1, 1, tagname)
1126 m[0] = 0
Brian Curtineb24d742010-04-12 17:16:38 +00001127 # Run a script which has console control handling enabled.
1128 proc = subprocess.Popen([sys.executable,
1129 os.path.join(os.path.dirname(__file__),
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001130 "win_console_handler.py"), tagname],
Brian Curtineb24d742010-04-12 17:16:38 +00001131 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
1132 # Let the interpreter startup before we send signals. See #3137.
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001133 count, max = 0, 100
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001134 while count < max and proc.poll() is None:
Brian Curtinf668df52010-10-15 14:21:06 +00001135 if m[0] == 1:
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001136 break
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001137 time.sleep(0.1)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001138 count += 1
1139 else:
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001140 # Forcefully kill the process if we weren't able to signal it.
1141 os.kill(proc.pid, signal.SIGINT)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001142 self.fail("Subprocess didn't finish initialization")
Brian Curtineb24d742010-04-12 17:16:38 +00001143 os.kill(proc.pid, event)
1144 # proc.send_signal(event) could also be done here.
1145 # Allow time for the signal to be passed and the process to exit.
1146 time.sleep(0.5)
1147 if not proc.poll():
1148 # Forcefully kill the process if we weren't able to signal it.
1149 os.kill(proc.pid, signal.SIGINT)
1150 self.fail("subprocess did not stop on {}".format(name))
1151
1152 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
1153 def test_CTRL_C_EVENT(self):
1154 from ctypes import wintypes
1155 import ctypes
1156
1157 # Make a NULL value by creating a pointer with no argument.
1158 NULL = ctypes.POINTER(ctypes.c_int)()
1159 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
1160 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
1161 wintypes.BOOL)
1162 SetConsoleCtrlHandler.restype = wintypes.BOOL
1163
1164 # Calling this with NULL and FALSE causes the calling process to
1165 # handle CTRL+C, rather than ignore it. This property is inherited
1166 # by subprocesses.
1167 SetConsoleCtrlHandler(NULL, 0)
1168
1169 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
1170
1171 def test_CTRL_BREAK_EVENT(self):
1172 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
1173
1174
Brian Curtind40e6f72010-07-08 21:39:08 +00001175@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Brian Curtin3b4499c2010-12-28 14:31:47 +00001176@support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +00001177class Win32SymlinkTests(unittest.TestCase):
1178 filelink = 'filelinktest'
1179 filelink_target = os.path.abspath(__file__)
1180 dirlink = 'dirlinktest'
1181 dirlink_target = os.path.dirname(filelink_target)
1182 missing_link = 'missing link'
1183
1184 def setUp(self):
1185 assert os.path.exists(self.dirlink_target)
1186 assert os.path.exists(self.filelink_target)
1187 assert not os.path.exists(self.dirlink)
1188 assert not os.path.exists(self.filelink)
1189 assert not os.path.exists(self.missing_link)
1190
1191 def tearDown(self):
1192 if os.path.exists(self.filelink):
1193 os.remove(self.filelink)
1194 if os.path.exists(self.dirlink):
1195 os.rmdir(self.dirlink)
1196 if os.path.lexists(self.missing_link):
1197 os.remove(self.missing_link)
1198
1199 def test_directory_link(self):
1200 os.symlink(self.dirlink_target, self.dirlink)
1201 self.assertTrue(os.path.exists(self.dirlink))
1202 self.assertTrue(os.path.isdir(self.dirlink))
1203 self.assertTrue(os.path.islink(self.dirlink))
1204 self.check_stat(self.dirlink, self.dirlink_target)
1205
1206 def test_file_link(self):
1207 os.symlink(self.filelink_target, self.filelink)
1208 self.assertTrue(os.path.exists(self.filelink))
1209 self.assertTrue(os.path.isfile(self.filelink))
1210 self.assertTrue(os.path.islink(self.filelink))
1211 self.check_stat(self.filelink, self.filelink_target)
1212
1213 def _create_missing_dir_link(self):
1214 'Create a "directory" link to a non-existent target'
1215 linkname = self.missing_link
1216 if os.path.lexists(linkname):
1217 os.remove(linkname)
1218 target = r'c:\\target does not exist.29r3c740'
1219 assert not os.path.exists(target)
1220 target_is_dir = True
1221 os.symlink(target, linkname, target_is_dir)
1222
1223 def test_remove_directory_link_to_missing_target(self):
1224 self._create_missing_dir_link()
1225 # For compatibility with Unix, os.remove will check the
1226 # directory status and call RemoveDirectory if the symlink
1227 # was created with target_is_dir==True.
1228 os.remove(self.missing_link)
1229
1230 @unittest.skip("currently fails; consider for improvement")
1231 def test_isdir_on_directory_link_to_missing_target(self):
1232 self._create_missing_dir_link()
1233 # consider having isdir return true for directory links
1234 self.assertTrue(os.path.isdir(self.missing_link))
1235
1236 @unittest.skip("currently fails; consider for improvement")
1237 def test_rmdir_on_directory_link_to_missing_target(self):
1238 self._create_missing_dir_link()
1239 # consider allowing rmdir to remove directory links
1240 os.rmdir(self.missing_link)
1241
1242 def check_stat(self, link, target):
1243 self.assertEqual(os.stat(link), os.stat(target))
1244 self.assertNotEqual(os.lstat(link), os.stat(link))
1245
1246
Victor Stinnere8d51452010-08-19 01:05:19 +00001247class FSEncodingTests(unittest.TestCase):
1248 def test_nop(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001249 self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
1250 self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
Benjamin Peterson31191a92010-05-09 03:22:58 +00001251
Victor Stinnere8d51452010-08-19 01:05:19 +00001252 def test_identity(self):
1253 # assert fsdecode(fsencode(x)) == x
1254 for fn in ('unicode\u0141', 'latin\xe9', 'ascii'):
1255 try:
1256 bytesfn = os.fsencode(fn)
1257 except UnicodeEncodeError:
1258 continue
Ezio Melottib3aedd42010-11-20 19:04:17 +00001259 self.assertEqual(os.fsdecode(bytesfn), fn)
Victor Stinnere8d51452010-08-19 01:05:19 +00001260
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00001261
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00001262class PidTests(unittest.TestCase):
1263 @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid")
1264 def test_getppid(self):
1265 p = subprocess.Popen([sys.executable, '-c',
1266 'import os; print(os.getppid())'],
1267 stdout=subprocess.PIPE)
1268 stdout, _ = p.communicate()
1269 # We are the parent of our subprocess
1270 self.assertEqual(int(stdout), os.getpid())
1271
1272
Brian Curtin0151b8e2010-09-24 13:43:43 +00001273# The introduction of this TestCase caused at least two different errors on
1274# *nix buildbots. Temporarily skip this to let the buildbots move along.
1275@unittest.skip("Skip due to platform/environment differences on *NIX buildbots")
Brian Curtine8e4b3b2010-09-23 20:04:14 +00001276@unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin")
1277class LoginTests(unittest.TestCase):
1278 def test_getlogin(self):
1279 user_name = os.getlogin()
1280 self.assertNotEqual(len(user_name), 0)
1281
1282
Fred Drake2e2be372001-09-20 21:33:42 +00001283def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001284 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001285 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001286 StatAttributeTests,
1287 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00001288 WalkTests,
1289 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +00001290 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001291 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001292 ExecTests,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001293 Win32ErrorTests,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001294 TestInvalidFD,
Martin v. Löwis011e8422009-05-05 04:43:17 +00001295 PosixUidGidTests,
Brian Curtineb24d742010-04-12 17:16:38 +00001296 Pep383Tests,
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00001297 Win32KillTests,
Brian Curtind40e6f72010-07-08 21:39:08 +00001298 Win32SymlinkTests,
Victor Stinnere8d51452010-08-19 01:05:19 +00001299 FSEncodingTests,
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00001300 PidTests,
Brian Curtine8e4b3b2010-09-23 20:04:14 +00001301 LoginTests,
Brian Curtin1b9df392010-11-24 20:24:31 +00001302 LinkTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001303 )
Fred Drake2e2be372001-09-20 21:33:42 +00001304
1305if __name__ == "__main__":
1306 test_main()