blob: 8bc8ba9fa625e0e3e9be7e3a08da3e9c36e6f200 [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
Georg Brandl2daf6ae2012-02-20 19:54:16 +010018from test.script_helper import assert_python_ok
Fred Drake38c2ef02001-07-17 20:52:51 +000019
Mark Dickinson7cf03892010-04-16 13:45:35 +000020# Detect whether we're on a Linux system that uses the (now outdated
21# and unmaintained) linuxthreads threading library. There's an issue
22# when combining linuxthreads with a failed execv call: see
23# http://bugs.python.org/issue4970.
Mark Dickinson89589c92010-04-16 13:51:27 +000024if (hasattr(os, "confstr_names") and
25 "CS_GNU_LIBPTHREAD_VERSION" in os.confstr_names):
Mark Dickinson7cf03892010-04-16 13:45:35 +000026 libpthread = os.confstr("CS_GNU_LIBPTHREAD_VERSION")
27 USING_LINUXTHREADS= libpthread.startswith("linuxthreads")
28else:
29 USING_LINUXTHREADS= False
Brian Curtineb24d742010-04-12 17:16:38 +000030
Thomas Wouters0e3f5912006-08-11 14:57:12 +000031# Tests creating TESTFN
32class FileTests(unittest.TestCase):
33 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000034 if os.path.exists(support.TESTFN):
35 os.unlink(support.TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000036 tearDown = setUp
37
38 def test_access(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000039 f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000040 os.close(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000041 self.assertTrue(os.access(support.TESTFN, os.W_OK))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000042
Christian Heimesfdab48e2008-01-20 09:06:41 +000043 def test_closerange(self):
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000044 first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
45 # We must allocate two consecutive file descriptors, otherwise
46 # it will mess up other file descriptors (perhaps even the three
47 # standard ones).
48 second = os.dup(first)
49 try:
50 retries = 0
51 while second != first + 1:
52 os.close(first)
53 retries += 1
54 if retries > 10:
55 # XXX test skipped
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000056 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000057 first, second = second, os.dup(second)
58 finally:
59 os.close(second)
Christian Heimesfdab48e2008-01-20 09:06:41 +000060 # close a fd that is open, and one that isn't
Antoine Pitroub9ee06c2008-08-16 22:03:17 +000061 os.closerange(first, first + 2)
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000062 self.assertRaises(OSError, os.write, first, b"a")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000063
Benjamin Peterson1cc6df92010-06-30 17:39:45 +000064 @support.cpython_only
Hirokazu Yamamoto4c19e6e2008-09-08 23:41:21 +000065 def test_rename(self):
66 path = support.TESTFN
67 old = sys.getrefcount(path)
68 self.assertRaises(TypeError, os.rename, path, 0)
69 new = sys.getrefcount(path)
70 self.assertEqual(old, new)
71
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000072 def test_read(self):
73 with open(support.TESTFN, "w+b") as fobj:
74 fobj.write(b"spam")
75 fobj.flush()
76 fd = fobj.fileno()
77 os.lseek(fd, 0, 0)
78 s = os.read(fd, 4)
79 self.assertEqual(type(s), bytes)
80 self.assertEqual(s, b"spam")
81
82 def test_write(self):
83 # os.write() accepts bytes- and buffer-like objects but not strings
84 fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY)
85 self.assertRaises(TypeError, os.write, fd, "beans")
86 os.write(fd, b"bacon\n")
87 os.write(fd, bytearray(b"eggs\n"))
88 os.write(fd, memoryview(b"spam\n"))
89 os.close(fd)
90 with open(support.TESTFN, "rb") as fobj:
Antoine Pitroud62269f2008-09-15 23:54:52 +000091 self.assertEqual(fobj.read().splitlines(),
92 [b"bacon", b"eggs", b"spam"])
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000093
Victor Stinnere0daff12011-03-20 23:36:35 +010094 def write_windows_console(self, *args):
95 retcode = subprocess.call(args,
96 # use a new console to not flood the test output
97 creationflags=subprocess.CREATE_NEW_CONSOLE,
98 # use a shell to hide the console window (SW_HIDE)
99 shell=True)
100 self.assertEqual(retcode, 0)
101
102 @unittest.skipUnless(sys.platform == 'win32',
103 'test specific to the Windows console')
104 def test_write_windows_console(self):
105 # Issue #11395: the Windows console returns an error (12: not enough
106 # space error) on writing into stdout if stdout mode is binary and the
107 # length is greater than 66,000 bytes (or less, depending on heap
108 # usage).
109 code = "print('x' * 100000)"
110 self.write_windows_console(sys.executable, "-c", code)
111 self.write_windows_console(sys.executable, "-u", "-c", code)
112
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000113 def fdopen_helper(self, *args):
114 fd = os.open(support.TESTFN, os.O_RDONLY)
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200115 f = os.fdopen(fd, *args)
116 f.close()
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000117
118 def test_fdopen(self):
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200119 fd = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
120 os.close(fd)
121
Amaury Forgeot d'Arce2e36ba2008-08-01 00:14:22 +0000122 self.fdopen_helper()
123 self.fdopen_helper('r')
124 self.fdopen_helper('r', 100)
125
Victor Stinnerbef7fdf2011-07-01 13:45:30 +0200126
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000127# Test attributes on return values from os.*stat* family.
128class StatAttributeTests(unittest.TestCase):
129 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000130 os.mkdir(support.TESTFN)
131 self.fname = os.path.join(support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000132 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +0000133 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000134 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000135
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000136 def tearDown(self):
137 os.unlink(self.fname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000138 os.rmdir(support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000139
Antoine Pitrou38425292010-09-21 18:19:07 +0000140 def check_stat_attributes(self, fname):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000141 if not hasattr(os, "stat"):
142 return
143
144 import stat
Antoine Pitrou38425292010-09-21 18:19:07 +0000145 result = os.stat(fname)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000146
147 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000148 self.assertEqual(result[stat.ST_SIZE], 3)
149 self.assertEqual(result.st_size, 3)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000150
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000151 # Make sure all the attributes are there
152 members = dir(result)
153 for name in dir(stat):
154 if name[:3] == 'ST_':
155 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000156 if name.endswith("TIME"):
157 def trunc(x): return int(x)
158 else:
159 def trunc(x): return x
Ezio Melottib3aedd42010-11-20 19:04:17 +0000160 self.assertEqual(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000161 result[getattr(stat, name)])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000162 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000163
164 try:
165 result[200]
166 self.fail("No exception thrown")
167 except IndexError:
168 pass
169
170 # Make sure that assignment fails
171 try:
172 result.st_mode = 1
173 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000174 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000175 pass
176
177 try:
178 result.st_rdev = 1
179 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000180 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000181 pass
182
183 try:
184 result.parrot = 1
185 self.fail("No exception thrown")
186 except AttributeError:
187 pass
188
189 # Use the stat_result constructor with a too-short tuple.
190 try:
191 result2 = os.stat_result((10,))
192 self.fail("No exception thrown")
193 except TypeError:
194 pass
195
Ezio Melotti42da6632011-03-15 05:18:48 +0200196 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000197 try:
198 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
199 except TypeError:
200 pass
201
Antoine Pitrou38425292010-09-21 18:19:07 +0000202 def test_stat_attributes(self):
203 self.check_stat_attributes(self.fname)
204
205 def test_stat_attributes_bytes(self):
206 try:
207 fname = self.fname.encode(sys.getfilesystemencoding())
208 except UnicodeEncodeError:
209 self.skipTest("cannot encode %a for the filesystem" % self.fname)
210 self.check_stat_attributes(fname)
Tim Peterse0c446b2001-10-18 21:57:37 +0000211
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000212 def test_statvfs_attributes(self):
213 if not hasattr(os, "statvfs"):
214 return
215
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000216 try:
217 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000218 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000219 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000220 if e.errno == errno.ENOSYS:
221 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000222
223 # Make sure direct access works
Ezio Melottib3aedd42010-11-20 19:04:17 +0000224 self.assertEqual(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000225
Brett Cannoncfaf10c2008-05-16 00:45:35 +0000226 # Make sure all the attributes are there.
227 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
228 'ffree', 'favail', 'flag', 'namemax')
229 for value, member in enumerate(members):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000230 self.assertEqual(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000231
232 # Make sure that assignment really fails
233 try:
234 result.f_bfree = 1
235 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000236 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000237 pass
238
239 try:
240 result.parrot = 1
241 self.fail("No exception thrown")
242 except AttributeError:
243 pass
244
245 # Use the constructor with a too-short tuple.
246 try:
247 result2 = os.statvfs_result((10,))
248 self.fail("No exception thrown")
249 except TypeError:
250 pass
251
Ezio Melotti42da6632011-03-15 05:18:48 +0200252 # Use the constructor with a too-long tuple.
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000253 try:
254 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
255 except TypeError:
256 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000257
Thomas Wouters89f507f2006-12-13 04:49:30 +0000258 def test_utime_dir(self):
259 delta = 1000000
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000260 st = os.stat(support.TESTFN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000261 # round to int, because some systems may support sub-second
262 # time stamps in stat, but not in utime.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000263 os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
264 st2 = os.stat(support.TESTFN)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000265 self.assertEqual(st2.st_mtime, int(st.st_mtime-delta))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000266
267 # Restrict test to Win32, since there is no guarantee other
268 # systems support centiseconds
269 if sys.platform == 'win32':
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000270 def get_file_system(path):
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000271 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000272 import ctypes
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000273 kernel32 = ctypes.windll.kernel32
Hirokazu Yamamoto5ef6d182008-08-20 04:17:24 +0000274 buf = ctypes.create_unicode_buffer("", 100)
Hirokazu Yamamotoca765d52008-08-20 16:18:19 +0000275 if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000276 return buf.value
277
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000278 if get_file_system(support.TESTFN) == "NTFS":
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000279 def test_1565150(self):
280 t1 = 1159195039.25
281 os.utime(self.fname, (t1, t1))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000282 self.assertEqual(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000283
Amaury Forgeot d'Arca251a852011-01-03 00:19:11 +0000284 def test_large_time(self):
285 t1 = 5000000000 # some day in 2128
286 os.utime(self.fname, (t1, t1))
287 self.assertEqual(os.stat(self.fname).st_mtime, t1)
288
Guido van Rossumd8faa362007-04-27 19:54:29 +0000289 def test_1686475(self):
290 # Verify that an open file can be stat'ed
291 try:
292 os.stat(r"c:\pagefile.sys")
293 except WindowsError as e:
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000294 if e.errno == 2: # file does not exist; cannot run test
Guido van Rossumd8faa362007-04-27 19:54:29 +0000295 return
296 self.fail("Could not stat pagefile.sys")
297
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000298from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000299
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000300class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000301 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000302 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000303
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000304 def setUp(self):
305 self.__save = dict(os.environ)
Victor Stinnerb745a742010-05-18 17:17:23 +0000306 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000307 self.__saveb = dict(os.environb)
Christian Heimes90333392007-11-01 19:08:42 +0000308 for key, value in self._reference().items():
309 os.environ[key] = value
310
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000311 def tearDown(self):
312 os.environ.clear()
313 os.environ.update(self.__save)
Victor Stinnerb745a742010-05-18 17:17:23 +0000314 if os.supports_bytes_environ:
Victor Stinner208d28c2010-05-07 00:54:14 +0000315 os.environb.clear()
316 os.environb.update(self.__saveb)
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000317
Christian Heimes90333392007-11-01 19:08:42 +0000318 def _reference(self):
319 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
320
321 def _empty_mapping(self):
322 os.environ.clear()
323 return os.environ
324
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000325 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000326 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000327 os.environ.clear()
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000328 if os.path.exists("/bin/sh"):
329 os.environ.update(HELLO="World")
Brian Curtin810921b2010-10-30 21:24:21 +0000330 with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
331 value = popen.read().strip()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000332 self.assertEqual(value, "World")
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000333
Christian Heimes1a13d592007-11-08 14:16:55 +0000334 def test_os_popen_iter(self):
335 if os.path.exists("/bin/sh"):
Brian Curtin810921b2010-10-30 21:24:21 +0000336 with os.popen(
337 "/bin/sh -c 'echo \"line1\nline2\nline3\"'") as popen:
338 it = iter(popen)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000339 self.assertEqual(next(it), "line1\n")
340 self.assertEqual(next(it), "line2\n")
341 self.assertEqual(next(it), "line3\n")
Brian Curtin810921b2010-10-30 21:24:21 +0000342 self.assertRaises(StopIteration, next, it)
Christian Heimes1a13d592007-11-08 14:16:55 +0000343
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000344 # Verify environ keys and values from the OS are of the
345 # correct str type.
346 def test_keyvalue_types(self):
347 for key, val in os.environ.items():
Ezio Melottib3aedd42010-11-20 19:04:17 +0000348 self.assertEqual(type(key), str)
349 self.assertEqual(type(val), str)
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000350
Christian Heimes90333392007-11-01 19:08:42 +0000351 def test_items(self):
352 for key, value in self._reference().items():
353 self.assertEqual(os.environ.get(key), value)
354
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000355 # Issue 7310
356 def test___repr__(self):
357 """Check that the repr() of os.environ looks like environ({...})."""
358 env = os.environ
Victor Stinner96f0de92010-07-29 00:29:00 +0000359 self.assertEqual(repr(env), 'environ({{{}}})'.format(', '.join(
360 '{!r}: {!r}'.format(key, value)
361 for key, value in env.items())))
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000362
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000363 def test_get_exec_path(self):
364 defpath_list = os.defpath.split(os.pathsep)
365 test_path = ['/monty', '/python', '', '/flying/circus']
366 test_env = {'PATH': os.pathsep.join(test_path)}
367
368 saved_environ = os.environ
369 try:
370 os.environ = dict(test_env)
371 # Test that defaulting to os.environ works.
372 self.assertSequenceEqual(test_path, os.get_exec_path())
373 self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
374 finally:
375 os.environ = saved_environ
376
377 # No PATH environment variable
378 self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
379 # Empty PATH environment variable
380 self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
381 # Supplied PATH environment variable
382 self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
383
Victor Stinnerb745a742010-05-18 17:17:23 +0000384 if os.supports_bytes_environ:
385 # env cannot contain 'PATH' and b'PATH' keys
Victor Stinner38430e22010-08-19 17:10:18 +0000386 try:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000387 # ignore BytesWarning warning
388 with warnings.catch_warnings(record=True):
389 mixed_env = {'PATH': '1', b'PATH': b'2'}
Victor Stinner38430e22010-08-19 17:10:18 +0000390 except BytesWarning:
Victor Stinner6f35eda2010-10-29 00:38:58 +0000391 # mixed_env cannot be created with python -bb
Victor Stinner38430e22010-08-19 17:10:18 +0000392 pass
393 else:
394 self.assertRaises(ValueError, os.get_exec_path, mixed_env)
Victor Stinnerb745a742010-05-18 17:17:23 +0000395
396 # bytes key and/or value
397 self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}),
398 ['abc'])
399 self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}),
400 ['abc'])
401 self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}),
402 ['abc'])
403
404 @unittest.skipUnless(os.supports_bytes_environ,
405 "os.environb required for this test.")
Victor Stinner84ae1182010-05-06 22:05:07 +0000406 def test_environb(self):
407 # os.environ -> os.environb
408 value = 'euro\u20ac'
409 try:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000410 value_bytes = value.encode(sys.getfilesystemencoding(),
411 'surrogateescape')
Victor Stinner84ae1182010-05-06 22:05:07 +0000412 except UnicodeEncodeError:
Benjamin Peterson180799d2010-05-06 22:25:42 +0000413 msg = "U+20AC character is not encodable to %s" % (
414 sys.getfilesystemencoding(),)
Benjamin Peterson932d3f42010-05-06 22:26:31 +0000415 self.skipTest(msg)
Victor Stinner84ae1182010-05-06 22:05:07 +0000416 os.environ['unicode'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000417 self.assertEqual(os.environ['unicode'], value)
418 self.assertEqual(os.environb[b'unicode'], value_bytes)
Victor Stinner84ae1182010-05-06 22:05:07 +0000419
420 # os.environb -> os.environ
421 value = b'\xff'
422 os.environb[b'bytes'] = value
Ezio Melottib3aedd42010-11-20 19:04:17 +0000423 self.assertEqual(os.environb[b'bytes'], value)
Victor Stinner84ae1182010-05-06 22:05:07 +0000424 value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000425 self.assertEqual(os.environ['bytes'], value_str)
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000426
Charles-François Natali7be8f682011-11-27 12:49:27 +0100427 # On FreeBSD < 7 and OS X < 10.6, unsetenv() doesn't return a value (issue
428 # #13415).
429 @unittest.skipIf(sys.platform.startswith(('freebsd', 'darwin')),
430 "due to known OS bug: see issue #13415")
Victor Stinner60b385e2011-11-22 22:01:28 +0100431 def test_unset_error(self):
432 if sys.platform == "win32":
433 # an environment variable is limited to 32,767 characters
434 key = 'x' * 50000
Victor Stinnerb3f82682011-11-22 22:30:19 +0100435 self.assertRaises(ValueError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100436 else:
437 # "=" is not allowed in a variable name
438 key = 'key='
Victor Stinnerb3f82682011-11-22 22:30:19 +0100439 self.assertRaises(OSError, os.environ.__delitem__, key)
Victor Stinner60b385e2011-11-22 22:01:28 +0100440
Tim Petersc4e09402003-04-25 07:11:48 +0000441class WalkTests(unittest.TestCase):
442 """Tests for os.walk()."""
443
444 def test_traversal(self):
445 import os
446 from os.path import join
447
448 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000449 # TESTFN/
450 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000451 # tmp1
452 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000453 # tmp2
454 # SUB11/ no kids
455 # SUB2/ a file kid and a dirsymlink kid
456 # tmp3
457 # link/ a symlink to TESTFN.2
458 # TEST2/
459 # tmp4 a lone file
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000460 walk_path = join(support.TESTFN, "TEST1")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000461 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000462 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000463 sub2_path = join(walk_path, "SUB2")
464 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000465 tmp2_path = join(sub1_path, "tmp2")
466 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000467 link_path = join(sub2_path, "link")
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000468 t2_path = join(support.TESTFN, "TEST2")
469 tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000470
471 # Create stuff.
472 os.makedirs(sub11_path)
473 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000474 os.makedirs(t2_path)
475 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000476 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000477 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
478 f.close()
Brian Curtin3b4499c2010-12-28 14:31:47 +0000479 if support.can_symlink():
Antoine Pitrou5311c1d2012-01-24 08:59:28 +0100480 if os.name == 'nt':
481 def symlink_to_dir(src, dest):
482 os.symlink(src, dest, True)
483 else:
484 symlink_to_dir = os.symlink
485 symlink_to_dir(os.path.abspath(t2_path), link_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000486 sub2_tree = (sub2_path, ["link"], ["tmp3"])
487 else:
488 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000489
490 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000491 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000492 self.assertEqual(len(all), 4)
493 # We can't know which order SUB1 and SUB2 will appear in.
494 # Not flipped: TESTFN, SUB1, SUB11, SUB2
495 # flipped: TESTFN, SUB2, SUB1, SUB11
496 flipped = all[0][1][0] != "SUB1"
497 all[0][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000498 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000499 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
500 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000501 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000502
503 # Prune the search.
504 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000505 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000506 all.append((root, dirs, files))
507 # Don't descend into SUB1.
508 if 'SUB1' in dirs:
509 # Note that this also mutates the dirs we appended to all!
510 dirs.remove('SUB1')
511 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000512 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
513 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000514
515 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000516 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000517 self.assertEqual(len(all), 4)
518 # We can't know which order SUB1 and SUB2 will appear in.
519 # Not flipped: SUB11, SUB1, SUB2, TESTFN
520 # flipped: SUB2, SUB11, SUB1, TESTFN
521 flipped = all[3][1][0] != "SUB1"
522 all[3][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000523 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000524 self.assertEqual(all[flipped], (sub11_path, [], []))
525 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000526 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000527
Brian Curtin3b4499c2010-12-28 14:31:47 +0000528 if support.can_symlink():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000529 # Walk, following symlinks.
530 for root, dirs, files in os.walk(walk_path, followlinks=True):
531 if root == link_path:
532 self.assertEqual(dirs, [])
533 self.assertEqual(files, ["tmp4"])
534 break
535 else:
536 self.fail("Didn't follow symlink with followlinks=True")
537
538 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000539 # Tear everything down. This is a decent use for bottom-up on
540 # Windows, which doesn't have a recursive delete command. The
541 # (not so) subtlety is that rmdir will fail unless the dir's
542 # kids are removed first, so bottom up is essential.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000543 for root, dirs, files in os.walk(support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000544 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000545 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000546 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000547 dirname = os.path.join(root, name)
548 if not os.path.islink(dirname):
549 os.rmdir(dirname)
550 else:
551 os.remove(dirname)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000552 os.rmdir(support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000553
Guido van Rossume7ba4952007-06-06 23:52:48 +0000554class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000555 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000556 os.mkdir(support.TESTFN)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000557
558 def test_makedir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000559 base = support.TESTFN
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000560 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
561 os.makedirs(path) # Should work
562 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
563 os.makedirs(path)
564
565 # Try paths with a '.' in them
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000566 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000567 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
568 os.makedirs(path)
569 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
570 'dir5', 'dir6')
571 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000572
Terry Reedy5a22b652010-12-02 07:05:56 +0000573 def test_exist_ok_existing_directory(self):
574 path = os.path.join(support.TESTFN, 'dir1')
575 mode = 0o777
576 old_mask = os.umask(0o022)
577 os.makedirs(path, mode)
578 self.assertRaises(OSError, os.makedirs, path, mode)
579 self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
580 self.assertRaises(OSError, os.makedirs, path, 0o776, exist_ok=True)
581 os.makedirs(path, mode=mode, exist_ok=True)
582 os.umask(old_mask)
583
584 def test_exist_ok_existing_regular_file(self):
585 base = support.TESTFN
586 path = os.path.join(support.TESTFN, 'dir1')
587 f = open(path, 'w')
588 f.write('abc')
589 f.close()
590 self.assertRaises(OSError, os.makedirs, path)
591 self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
592 self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
593 os.remove(path)
594
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000595 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000596 path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000597 'dir4', 'dir5', 'dir6')
598 # If the tests failed, the bottom-most directory ('../dir6')
599 # may not have been created, so we look for the outermost directory
600 # that exists.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000601 while not os.path.exists(path) and path != support.TESTFN:
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000602 path = os.path.dirname(path)
603
604 os.removedirs(path)
605
Guido van Rossume7ba4952007-06-06 23:52:48 +0000606class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000607 def test_devnull(self):
Victor Stinnera6d2c762011-06-30 18:20:11 +0200608 with open(os.devnull, 'wb') as f:
609 f.write(b'hello')
610 f.close()
611 with open(os.devnull, 'rb') as f:
612 self.assertEqual(f.read(), b'')
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000613
Guido van Rossume7ba4952007-06-06 23:52:48 +0000614class URandomTests(unittest.TestCase):
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100615 def test_urandom_length(self):
616 self.assertEqual(len(os.urandom(0)), 0)
617 self.assertEqual(len(os.urandom(1)), 1)
618 self.assertEqual(len(os.urandom(10)), 10)
619 self.assertEqual(len(os.urandom(100)), 100)
620 self.assertEqual(len(os.urandom(1000)), 1000)
621
622 def test_urandom_value(self):
623 data1 = os.urandom(16)
624 data2 = os.urandom(16)
625 self.assertNotEqual(data1, data2)
626
627 def get_urandom_subprocess(self, count):
628 code = '\n'.join((
629 'import os, sys',
630 'data = os.urandom(%s)' % count,
631 'sys.stdout.buffer.write(data)',
632 'sys.stdout.buffer.flush()'))
633 out = assert_python_ok('-c', code)
634 stdout = out[1]
635 self.assertEqual(len(stdout), 16)
636 return stdout
637
638 def test_urandom_subprocess(self):
639 data1 = self.get_urandom_subprocess(16)
640 data2 = self.get_urandom_subprocess(16)
641 self.assertNotEqual(data1, data2)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000642
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000643@contextlib.contextmanager
644def _execvpe_mockup(defpath=None):
645 """
646 Stubs out execv and execve functions when used as context manager.
647 Records exec calls. The mock execv and execve functions always raise an
648 exception as they would normally never return.
649 """
650 # A list of tuples containing (function name, first arg, args)
651 # of calls to execv or execve that have been made.
652 calls = []
653
654 def mock_execv(name, *args):
655 calls.append(('execv', name, args))
656 raise RuntimeError("execv called")
657
658 def mock_execve(name, *args):
659 calls.append(('execve', name, args))
660 raise OSError(errno.ENOTDIR, "execve called")
661
662 try:
663 orig_execv = os.execv
664 orig_execve = os.execve
665 orig_defpath = os.defpath
666 os.execv = mock_execv
667 os.execve = mock_execve
668 if defpath is not None:
669 os.defpath = defpath
670 yield calls
671 finally:
672 os.execv = orig_execv
673 os.execve = orig_execve
674 os.defpath = orig_defpath
675
Guido van Rossume7ba4952007-06-06 23:52:48 +0000676class ExecTests(unittest.TestCase):
Mark Dickinson7cf03892010-04-16 13:45:35 +0000677 @unittest.skipIf(USING_LINUXTHREADS,
678 "avoid triggering a linuxthreads bug: see issue #4970")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000679 def test_execvpe_with_bad_program(self):
Mark Dickinson7cf03892010-04-16 13:45:35 +0000680 self.assertRaises(OSError, os.execvpe, 'no such app-',
681 ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000682
Thomas Heller6790d602007-08-30 17:15:14 +0000683 def test_execvpe_with_bad_arglist(self):
684 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
685
Gregory P. Smith4ae37772010-05-08 18:05:46 +0000686 @unittest.skipUnless(hasattr(os, '_execvpe'),
687 "No internal os._execvpe function to test.")
Victor Stinnerb745a742010-05-18 17:17:23 +0000688 def _test_internal_execvpe(self, test_type):
689 program_path = os.sep + 'absolutepath'
690 if test_type is bytes:
691 program = b'executable'
692 fullpath = os.path.join(os.fsencode(program_path), program)
693 native_fullpath = fullpath
694 arguments = [b'progname', 'arg1', 'arg2']
695 else:
696 program = 'executable'
697 arguments = ['progname', 'arg1', 'arg2']
698 fullpath = os.path.join(program_path, program)
699 if os.name != "nt":
700 native_fullpath = os.fsencode(fullpath)
701 else:
702 native_fullpath = fullpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000703 env = {'spam': 'beans'}
704
Victor Stinnerb745a742010-05-18 17:17:23 +0000705 # test os._execvpe() with an absolute path
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000706 with _execvpe_mockup() as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +0000707 self.assertRaises(RuntimeError,
708 os._execvpe, fullpath, arguments)
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000709 self.assertEqual(len(calls), 1)
710 self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))
711
Victor Stinnerb745a742010-05-18 17:17:23 +0000712 # test os._execvpe() with a relative path:
713 # os.get_exec_path() returns defpath
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000714 with _execvpe_mockup(defpath=program_path) as calls:
Victor Stinnerb745a742010-05-18 17:17:23 +0000715 self.assertRaises(OSError,
716 os._execvpe, program, arguments, env=env)
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000717 self.assertEqual(len(calls), 1)
Victor Stinnerb745a742010-05-18 17:17:23 +0000718 self.assertSequenceEqual(calls[0],
719 ('execve', native_fullpath, (arguments, env)))
720
721 # test os._execvpe() with a relative path:
722 # os.get_exec_path() reads the 'PATH' variable
723 with _execvpe_mockup() as calls:
724 env_path = env.copy()
Victor Stinner38430e22010-08-19 17:10:18 +0000725 if test_type is bytes:
726 env_path[b'PATH'] = program_path
727 else:
728 env_path['PATH'] = program_path
Victor Stinnerb745a742010-05-18 17:17:23 +0000729 self.assertRaises(OSError,
730 os._execvpe, program, arguments, env=env_path)
731 self.assertEqual(len(calls), 1)
732 self.assertSequenceEqual(calls[0],
733 ('execve', native_fullpath, (arguments, env_path)))
734
735 def test_internal_execvpe_str(self):
736 self._test_internal_execvpe(str)
737 if os.name != "nt":
738 self._test_internal_execvpe(bytes)
Victor Stinnerc2d095f2010-05-17 00:14:53 +0000739
Gregory P. Smith4ae37772010-05-08 18:05:46 +0000740
Thomas Wouters477c8d52006-05-27 19:21:47 +0000741class Win32ErrorTests(unittest.TestCase):
742 def test_rename(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000743 self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000744
745 def test_remove(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000746 self.assertRaises(WindowsError, os.remove, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000747
748 def test_chdir(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000749 self.assertRaises(WindowsError, os.chdir, support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000750
751 def test_mkdir(self):
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +0000752 f = open(support.TESTFN, "w")
Benjamin Petersonf91df042009-02-13 02:50:59 +0000753 try:
754 self.assertRaises(WindowsError, os.mkdir, support.TESTFN)
755 finally:
756 f.close()
Amaury Forgeot d'Arc2fc224f2009-02-19 23:23:47 +0000757 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000758
759 def test_utime(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000760 self.assertRaises(WindowsError, os.utime, support.TESTFN, None)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000761
Thomas Wouters477c8d52006-05-27 19:21:47 +0000762 def test_chmod(self):
Benjamin Petersonf91df042009-02-13 02:50:59 +0000763 self.assertRaises(WindowsError, os.chmod, support.TESTFN, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000764
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000765class TestInvalidFD(unittest.TestCase):
Benjamin Peterson05e782f2009-01-19 15:15:02 +0000766 singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000767 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
768 #singles.append("close")
769 #We omit close because it doesn'r raise an exception on some platforms
770 def get_single(f):
771 def helper(self):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000772 if hasattr(os, f):
773 self.check(getattr(os, f))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000774 return helper
775 for f in singles:
776 locals()["test_"+f] = get_single(f)
777
Benjamin Peterson7522c742009-01-19 21:00:09 +0000778 def check(self, f, *args):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000779 try:
780 f(support.make_bad_fd(), *args)
781 except OSError as e:
782 self.assertEqual(e.errno, errno.EBADF)
783 else:
784 self.fail("%r didn't raise a OSError with a bad file descriptor"
785 % f)
Benjamin Peterson7522c742009-01-19 21:00:09 +0000786
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000787 def test_isatty(self):
788 if hasattr(os, "isatty"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000789 self.assertEqual(os.isatty(support.make_bad_fd()), False)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000790
791 def test_closerange(self):
792 if hasattr(os, "closerange"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000793 fd = support.make_bad_fd()
R. David Murray630cc482009-07-22 15:20:27 +0000794 # Make sure none of the descriptors we are about to close are
795 # currently valid (issue 6542).
796 for i in range(10):
797 try: os.fstat(fd+i)
798 except OSError:
799 pass
800 else:
801 break
802 if i < 2:
803 raise unittest.SkipTest(
804 "Unable to acquire a range of invalid file descriptors")
805 self.assertEqual(os.closerange(fd, fd + i-1), None)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000806
807 def test_dup2(self):
808 if hasattr(os, "dup2"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000809 self.check(os.dup2, 20)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000810
811 def test_fchmod(self):
812 if hasattr(os, "fchmod"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000813 self.check(os.fchmod, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000814
815 def test_fchown(self):
816 if hasattr(os, "fchown"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000817 self.check(os.fchown, -1, -1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000818
819 def test_fpathconf(self):
820 if hasattr(os, "fpathconf"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000821 self.check(os.fpathconf, "PC_NAME_MAX")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000822
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000823 def test_ftruncate(self):
824 if hasattr(os, "ftruncate"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000825 self.check(os.ftruncate, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000826
827 def test_lseek(self):
828 if hasattr(os, "lseek"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000829 self.check(os.lseek, 0, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000830
831 def test_read(self):
832 if hasattr(os, "read"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000833 self.check(os.read, 1)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000834
835 def test_tcsetpgrpt(self):
836 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000837 self.check(os.tcsetpgrp, 0)
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000838
839 def test_write(self):
840 if hasattr(os, "write"):
Benjamin Peterson7522c742009-01-19 21:00:09 +0000841 self.check(os.write, b" ")
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000842
Brian Curtin1b9df392010-11-24 20:24:31 +0000843
844class LinkTests(unittest.TestCase):
845 def setUp(self):
846 self.file1 = support.TESTFN
847 self.file2 = os.path.join(support.TESTFN + "2")
848
Brian Curtinc0abc4e2010-11-30 23:46:54 +0000849 def tearDown(self):
Brian Curtin1b9df392010-11-24 20:24:31 +0000850 for file in (self.file1, self.file2):
851 if os.path.exists(file):
852 os.unlink(file)
853
Brian Curtin1b9df392010-11-24 20:24:31 +0000854 def _test_link(self, file1, file2):
855 with open(file1, "w") as f1:
856 f1.write("test")
857
858 os.link(file1, file2)
859 with open(file1, "r") as f1, open(file2, "r") as f2:
860 self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
861
862 def test_link(self):
863 self._test_link(self.file1, self.file2)
864
865 def test_link_bytes(self):
866 self._test_link(bytes(self.file1, sys.getfilesystemencoding()),
867 bytes(self.file2, sys.getfilesystemencoding()))
868
Brian Curtinf498b752010-11-30 15:54:04 +0000869 def test_unicode_name(self):
Brian Curtin43f0c272010-11-30 15:40:04 +0000870 try:
Brian Curtinf498b752010-11-30 15:54:04 +0000871 os.fsencode("\xf1")
Brian Curtin43f0c272010-11-30 15:40:04 +0000872 except UnicodeError:
873 raise unittest.SkipTest("Unable to encode for this platform.")
874
Brian Curtinf498b752010-11-30 15:54:04 +0000875 self.file1 += "\xf1"
Brian Curtinfc889c42010-11-28 23:59:46 +0000876 self.file2 = self.file1 + "2"
877 self._test_link(self.file1, self.file2)
878
Thomas Wouters477c8d52006-05-27 19:21:47 +0000879if sys.platform != 'win32':
880 class Win32ErrorTests(unittest.TestCase):
881 pass
882
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000883 class PosixUidGidTests(unittest.TestCase):
884 if hasattr(os, 'setuid'):
885 def test_setuid(self):
886 if os.getuid() != 0:
887 self.assertRaises(os.error, os.setuid, 0)
888 self.assertRaises(OverflowError, os.setuid, 1<<32)
889
890 if hasattr(os, 'setgid'):
891 def test_setgid(self):
892 if os.getuid() != 0:
893 self.assertRaises(os.error, os.setgid, 0)
894 self.assertRaises(OverflowError, os.setgid, 1<<32)
895
896 if hasattr(os, 'seteuid'):
897 def test_seteuid(self):
898 if os.getuid() != 0:
899 self.assertRaises(os.error, os.seteuid, 0)
900 self.assertRaises(OverflowError, os.seteuid, 1<<32)
901
902 if hasattr(os, 'setegid'):
903 def test_setegid(self):
904 if os.getuid() != 0:
905 self.assertRaises(os.error, os.setegid, 0)
906 self.assertRaises(OverflowError, os.setegid, 1<<32)
907
908 if hasattr(os, 'setreuid'):
909 def test_setreuid(self):
910 if os.getuid() != 0:
911 self.assertRaises(os.error, os.setreuid, 0, 0)
912 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
913 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000914
915 def test_setreuid_neg1(self):
916 # Needs to accept -1. We run this in a subprocess to avoid
917 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000918 subprocess.check_call([
919 sys.executable, '-c',
920 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000921
922 if hasattr(os, 'setregid'):
923 def test_setregid(self):
924 if os.getuid() != 0:
925 self.assertRaises(os.error, os.setregid, 0, 0)
926 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
927 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000928
929 def test_setregid_neg1(self):
930 # Needs to accept -1. We run this in a subprocess to avoid
931 # altering the test runner's process state (issue8045).
Benjamin Petersonebe87ba2010-03-06 20:34:24 +0000932 subprocess.check_call([
933 sys.executable, '-c',
934 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Martin v. Löwis011e8422009-05-05 04:43:17 +0000935
936 class Pep383Tests(unittest.TestCase):
Martin v. Löwis011e8422009-05-05 04:43:17 +0000937 def setUp(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +0000938 if support.TESTFN_UNENCODABLE:
939 self.dir = support.TESTFN_UNENCODABLE
940 else:
941 self.dir = support.TESTFN
942 self.bdir = os.fsencode(self.dir)
943
944 bytesfn = []
945 def add_filename(fn):
946 try:
947 fn = os.fsencode(fn)
948 except UnicodeEncodeError:
949 return
950 bytesfn.append(fn)
951 add_filename(support.TESTFN_UNICODE)
952 if support.TESTFN_UNENCODABLE:
953 add_filename(support.TESTFN_UNENCODABLE)
954 if not bytesfn:
955 self.skipTest("couldn't create any non-ascii filename")
956
957 self.unicodefn = set()
Martin v. Löwis011e8422009-05-05 04:43:17 +0000958 os.mkdir(self.dir)
Victor Stinnerd91df1a2010-08-18 10:56:19 +0000959 try:
960 for fn in bytesfn:
961 f = open(os.path.join(self.bdir, fn), "w")
962 f.close()
Victor Stinnere8d51452010-08-19 01:05:19 +0000963 fn = os.fsdecode(fn)
Victor Stinnerd91df1a2010-08-18 10:56:19 +0000964 if fn in self.unicodefn:
965 raise ValueError("duplicate filename")
966 self.unicodefn.add(fn)
967 except:
968 shutil.rmtree(self.dir)
969 raise
Martin v. Löwis011e8422009-05-05 04:43:17 +0000970
971 def tearDown(self):
972 shutil.rmtree(self.dir)
Martin v. Löwis011e8422009-05-05 04:43:17 +0000973
974 def test_listdir(self):
Victor Stinnerd91df1a2010-08-18 10:56:19 +0000975 expected = self.unicodefn
976 found = set(os.listdir(self.dir))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000977 self.assertEqual(found, expected)
Martin v. Löwis011e8422009-05-05 04:43:17 +0000978
979 def test_open(self):
980 for fn in self.unicodefn:
Victor Stinnera6d2c762011-06-30 18:20:11 +0200981 f = open(os.path.join(self.dir, fn), 'rb')
Martin v. Löwis011e8422009-05-05 04:43:17 +0000982 f.close()
983
984 def test_stat(self):
985 for fn in self.unicodefn:
986 os.stat(os.path.join(self.dir, fn))
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000987else:
988 class PosixUidGidTests(unittest.TestCase):
989 pass
Martin v. Löwis011e8422009-05-05 04:43:17 +0000990 class Pep383Tests(unittest.TestCase):
991 pass
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000992
Brian Curtineb24d742010-04-12 17:16:38 +0000993@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
994class Win32KillTests(unittest.TestCase):
Brian Curtinc3acbc32010-05-28 16:08:40 +0000995 def _kill(self, sig):
996 # Start sys.executable as a subprocess and communicate from the
997 # subprocess to the parent that the interpreter is ready. When it
998 # becomes ready, send *sig* via os.kill to the subprocess and check
999 # that the return code is equal to *sig*.
1000 import ctypes
1001 from ctypes import wintypes
1002 import msvcrt
1003
1004 # Since we can't access the contents of the process' stdout until the
1005 # process has exited, use PeekNamedPipe to see what's inside stdout
1006 # without waiting. This is done so we can tell that the interpreter
1007 # is started and running at a point where it could handle a signal.
1008 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
1009 PeekNamedPipe.restype = wintypes.BOOL
1010 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
1011 ctypes.POINTER(ctypes.c_char), # stdout buf
1012 wintypes.DWORD, # Buffer size
1013 ctypes.POINTER(wintypes.DWORD), # bytes read
1014 ctypes.POINTER(wintypes.DWORD), # bytes avail
1015 ctypes.POINTER(wintypes.DWORD)) # bytes left
1016 msg = "running"
1017 proc = subprocess.Popen([sys.executable, "-c",
1018 "import sys;"
1019 "sys.stdout.write('{}');"
1020 "sys.stdout.flush();"
1021 "input()".format(msg)],
1022 stdout=subprocess.PIPE,
1023 stderr=subprocess.PIPE,
1024 stdin=subprocess.PIPE)
Brian Curtin43ec5772010-11-05 15:17:11 +00001025 self.addCleanup(proc.stdout.close)
1026 self.addCleanup(proc.stderr.close)
1027 self.addCleanup(proc.stdin.close)
Brian Curtinc3acbc32010-05-28 16:08:40 +00001028
1029 count, max = 0, 100
1030 while count < max and proc.poll() is None:
1031 # Create a string buffer to store the result of stdout from the pipe
1032 buf = ctypes.create_string_buffer(len(msg))
1033 # Obtain the text currently in proc.stdout
1034 # Bytes read/avail/left are left as NULL and unused
1035 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
1036 buf, ctypes.sizeof(buf), None, None, None)
1037 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
1038 if buf.value:
1039 self.assertEqual(msg, buf.value.decode())
1040 break
1041 time.sleep(0.1)
1042 count += 1
1043 else:
1044 self.fail("Did not receive communication from the subprocess")
1045
Brian Curtineb24d742010-04-12 17:16:38 +00001046 os.kill(proc.pid, sig)
1047 self.assertEqual(proc.wait(), sig)
1048
1049 def test_kill_sigterm(self):
1050 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinc3acbc32010-05-28 16:08:40 +00001051 self._kill(signal.SIGTERM)
Brian Curtineb24d742010-04-12 17:16:38 +00001052
1053 def test_kill_int(self):
1054 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinc3acbc32010-05-28 16:08:40 +00001055 self._kill(100)
Brian Curtineb24d742010-04-12 17:16:38 +00001056
1057 def _kill_with_event(self, event, name):
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001058 tagname = "test_os_%s" % uuid.uuid1()
1059 m = mmap.mmap(-1, 1, tagname)
1060 m[0] = 0
Brian Curtineb24d742010-04-12 17:16:38 +00001061 # Run a script which has console control handling enabled.
1062 proc = subprocess.Popen([sys.executable,
1063 os.path.join(os.path.dirname(__file__),
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001064 "win_console_handler.py"), tagname],
Brian Curtineb24d742010-04-12 17:16:38 +00001065 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
1066 # Let the interpreter startup before we send signals. See #3137.
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001067 count, max = 0, 100
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001068 while count < max and proc.poll() is None:
Brian Curtinf668df52010-10-15 14:21:06 +00001069 if m[0] == 1:
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001070 break
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001071 time.sleep(0.1)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001072 count += 1
1073 else:
Hirokazu Yamamoto8e9fe9f2010-12-05 02:41:46 +00001074 # Forcefully kill the process if we weren't able to signal it.
1075 os.kill(proc.pid, signal.SIGINT)
Hirokazu Yamamoto54c950f2010-10-08 08:38:15 +00001076 self.fail("Subprocess didn't finish initialization")
Brian Curtineb24d742010-04-12 17:16:38 +00001077 os.kill(proc.pid, event)
1078 # proc.send_signal(event) could also be done here.
1079 # Allow time for the signal to be passed and the process to exit.
1080 time.sleep(0.5)
1081 if not proc.poll():
1082 # Forcefully kill the process if we weren't able to signal it.
1083 os.kill(proc.pid, signal.SIGINT)
1084 self.fail("subprocess did not stop on {}".format(name))
1085
1086 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
1087 def test_CTRL_C_EVENT(self):
1088 from ctypes import wintypes
1089 import ctypes
1090
1091 # Make a NULL value by creating a pointer with no argument.
1092 NULL = ctypes.POINTER(ctypes.c_int)()
1093 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
1094 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
1095 wintypes.BOOL)
1096 SetConsoleCtrlHandler.restype = wintypes.BOOL
1097
1098 # Calling this with NULL and FALSE causes the calling process to
1099 # handle CTRL+C, rather than ignore it. This property is inherited
1100 # by subprocesses.
1101 SetConsoleCtrlHandler(NULL, 0)
1102
1103 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
1104
1105 def test_CTRL_BREAK_EVENT(self):
1106 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
1107
1108
Brian Curtind40e6f72010-07-08 21:39:08 +00001109@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
Brian Curtin3b4499c2010-12-28 14:31:47 +00001110@support.skip_unless_symlink
Brian Curtind40e6f72010-07-08 21:39:08 +00001111class Win32SymlinkTests(unittest.TestCase):
1112 filelink = 'filelinktest'
1113 filelink_target = os.path.abspath(__file__)
1114 dirlink = 'dirlinktest'
1115 dirlink_target = os.path.dirname(filelink_target)
1116 missing_link = 'missing link'
1117
1118 def setUp(self):
1119 assert os.path.exists(self.dirlink_target)
1120 assert os.path.exists(self.filelink_target)
1121 assert not os.path.exists(self.dirlink)
1122 assert not os.path.exists(self.filelink)
1123 assert not os.path.exists(self.missing_link)
1124
1125 def tearDown(self):
1126 if os.path.exists(self.filelink):
1127 os.remove(self.filelink)
1128 if os.path.exists(self.dirlink):
1129 os.rmdir(self.dirlink)
1130 if os.path.lexists(self.missing_link):
1131 os.remove(self.missing_link)
1132
1133 def test_directory_link(self):
Antoine Pitrou5311c1d2012-01-24 08:59:28 +01001134 os.symlink(self.dirlink_target, self.dirlink, True)
Brian Curtind40e6f72010-07-08 21:39:08 +00001135 self.assertTrue(os.path.exists(self.dirlink))
1136 self.assertTrue(os.path.isdir(self.dirlink))
1137 self.assertTrue(os.path.islink(self.dirlink))
1138 self.check_stat(self.dirlink, self.dirlink_target)
1139
1140 def test_file_link(self):
1141 os.symlink(self.filelink_target, self.filelink)
1142 self.assertTrue(os.path.exists(self.filelink))
1143 self.assertTrue(os.path.isfile(self.filelink))
1144 self.assertTrue(os.path.islink(self.filelink))
1145 self.check_stat(self.filelink, self.filelink_target)
1146
1147 def _create_missing_dir_link(self):
1148 'Create a "directory" link to a non-existent target'
1149 linkname = self.missing_link
1150 if os.path.lexists(linkname):
1151 os.remove(linkname)
1152 target = r'c:\\target does not exist.29r3c740'
1153 assert not os.path.exists(target)
1154 target_is_dir = True
1155 os.symlink(target, linkname, target_is_dir)
1156
1157 def test_remove_directory_link_to_missing_target(self):
1158 self._create_missing_dir_link()
1159 # For compatibility with Unix, os.remove will check the
1160 # directory status and call RemoveDirectory if the symlink
1161 # was created with target_is_dir==True.
1162 os.remove(self.missing_link)
1163
1164 @unittest.skip("currently fails; consider for improvement")
1165 def test_isdir_on_directory_link_to_missing_target(self):
1166 self._create_missing_dir_link()
1167 # consider having isdir return true for directory links
1168 self.assertTrue(os.path.isdir(self.missing_link))
1169
1170 @unittest.skip("currently fails; consider for improvement")
1171 def test_rmdir_on_directory_link_to_missing_target(self):
1172 self._create_missing_dir_link()
1173 # consider allowing rmdir to remove directory links
1174 os.rmdir(self.missing_link)
1175
1176 def check_stat(self, link, target):
1177 self.assertEqual(os.stat(link), os.stat(target))
1178 self.assertNotEqual(os.lstat(link), os.stat(link))
1179
Brian Curtind25aef52011-06-13 15:16:04 -05001180 bytes_link = os.fsencode(link)
1181 self.assertEqual(os.stat(bytes_link), os.stat(target))
1182 self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link))
1183
1184 def test_12084(self):
1185 level1 = os.path.abspath(support.TESTFN)
1186 level2 = os.path.join(level1, "level2")
1187 level3 = os.path.join(level2, "level3")
1188 try:
1189 os.mkdir(level1)
1190 os.mkdir(level2)
1191 os.mkdir(level3)
1192
1193 file1 = os.path.abspath(os.path.join(level1, "file1"))
1194
1195 with open(file1, "w") as f:
1196 f.write("file1")
1197
1198 orig_dir = os.getcwd()
1199 try:
1200 os.chdir(level2)
1201 link = os.path.join(level2, "link")
1202 os.symlink(os.path.relpath(file1), "link")
1203 self.assertIn("link", os.listdir(os.getcwd()))
1204
1205 # Check os.stat calls from the same dir as the link
1206 self.assertEqual(os.stat(file1), os.stat("link"))
1207
1208 # Check os.stat calls from a dir below the link
1209 os.chdir(level1)
1210 self.assertEqual(os.stat(file1),
1211 os.stat(os.path.relpath(link)))
1212
1213 # Check os.stat calls from a dir above the link
1214 os.chdir(level3)
1215 self.assertEqual(os.stat(file1),
1216 os.stat(os.path.relpath(link)))
1217 finally:
1218 os.chdir(orig_dir)
1219 except OSError as err:
1220 self.fail(err)
1221 finally:
1222 os.remove(file1)
1223 shutil.rmtree(level1)
1224
Brian Curtind40e6f72010-07-08 21:39:08 +00001225
Victor Stinnere8d51452010-08-19 01:05:19 +00001226class FSEncodingTests(unittest.TestCase):
1227 def test_nop(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001228 self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
1229 self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
Benjamin Peterson31191a92010-05-09 03:22:58 +00001230
Victor Stinnere8d51452010-08-19 01:05:19 +00001231 def test_identity(self):
1232 # assert fsdecode(fsencode(x)) == x
1233 for fn in ('unicode\u0141', 'latin\xe9', 'ascii'):
1234 try:
1235 bytesfn = os.fsencode(fn)
1236 except UnicodeEncodeError:
1237 continue
Ezio Melottib3aedd42010-11-20 19:04:17 +00001238 self.assertEqual(os.fsdecode(bytesfn), fn)
Victor Stinnere8d51452010-08-19 01:05:19 +00001239
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00001240
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00001241class PidTests(unittest.TestCase):
1242 @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid")
1243 def test_getppid(self):
1244 p = subprocess.Popen([sys.executable, '-c',
1245 'import os; print(os.getppid())'],
1246 stdout=subprocess.PIPE)
1247 stdout, _ = p.communicate()
1248 # We are the parent of our subprocess
1249 self.assertEqual(int(stdout), os.getpid())
1250
1251
Brian Curtin0151b8e2010-09-24 13:43:43 +00001252# The introduction of this TestCase caused at least two different errors on
1253# *nix buildbots. Temporarily skip this to let the buildbots move along.
1254@unittest.skip("Skip due to platform/environment differences on *NIX buildbots")
Brian Curtine8e4b3b2010-09-23 20:04:14 +00001255@unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin")
1256class LoginTests(unittest.TestCase):
1257 def test_getlogin(self):
1258 user_name = os.getlogin()
1259 self.assertNotEqual(len(user_name), 0)
1260
1261
Fred Drake2e2be372001-09-20 21:33:42 +00001262def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001263 support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001264 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001265 StatAttributeTests,
1266 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +00001267 WalkTests,
1268 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +00001269 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001270 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001271 ExecTests,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001272 Win32ErrorTests,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001273 TestInvalidFD,
Martin v. Löwis011e8422009-05-05 04:43:17 +00001274 PosixUidGidTests,
Brian Curtineb24d742010-04-12 17:16:38 +00001275 Pep383Tests,
Victor Stinnerbf9bcab2010-05-09 03:15:33 +00001276 Win32KillTests,
Brian Curtind40e6f72010-07-08 21:39:08 +00001277 Win32SymlinkTests,
Victor Stinnere8d51452010-08-19 01:05:19 +00001278 FSEncodingTests,
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00001279 PidTests,
Brian Curtine8e4b3b2010-09-23 20:04:14 +00001280 LoginTests,
Brian Curtin1b9df392010-11-24 20:24:31 +00001281 LinkTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001282 )
Fred Drake2e2be372001-09-20 21:33:42 +00001283
1284if __name__ == "__main__":
1285 test_main()