blob: aeb89241072f7108488c00c601f2f085061fa7bb [file] [log] [blame]
Neal Norwitze241ce82003-02-17 18:17:05 +00001"Test posix functions"
2
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
R. David Murrayeb3615d2009-04-22 02:24:39 +00004
5# Skip these tests if there is no posix module.
6posix = support.import_module('posix')
Neal Norwitze241ce82003-02-17 18:17:05 +00007
Antoine Pitroub7572f02009-12-02 20:46:48 +00008import errno
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00009import sys
Neal Norwitze241ce82003-02-17 18:17:05 +000010import time
11import os
Charles-François Natali1e045b12011-05-22 20:42:32 +020012import fcntl
Charles-François Nataliab2d58e2012-04-17 19:48:35 +020013import platform
Christian Heimesd5e2b6f2008-03-19 21:50:51 +000014import pwd
Benjamin Petersondcf97b92008-07-02 17:30:14 +000015import shutil
Benjamin Peterson052a02b2010-08-17 01:27:09 +000016import stat
Ned Deilyba2eab22011-07-26 13:53:55 -070017import tempfile
Neal Norwitze241ce82003-02-17 18:17:05 +000018import unittest
19import warnings
R. David Murraya21e4ca2009-03-31 23:16:50 +000020
Ned Deilyba2eab22011-07-26 13:53:55 -070021_DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(),
22 support.TESTFN + '-dummy-symlink')
Neal Norwitze241ce82003-02-17 18:17:05 +000023
24class PosixTester(unittest.TestCase):
25
26 def setUp(self):
27 # create empty file
Benjamin Petersonee8712c2008-05-20 21:35:26 +000028 fp = open(support.TESTFN, 'w+')
Neal Norwitze241ce82003-02-17 18:17:05 +000029 fp.close()
Ned Deily3eb67d52011-06-28 00:00:28 -070030 self.teardown_files = [ support.TESTFN ]
Brett Cannonc8d502e2010-03-20 21:53:28 +000031 self._warnings_manager = support.check_warnings()
32 self._warnings_manager.__enter__()
33 warnings.filterwarnings('ignore', '.* potential security risk .*',
34 RuntimeWarning)
Neal Norwitze241ce82003-02-17 18:17:05 +000035
36 def tearDown(self):
Ned Deily3eb67d52011-06-28 00:00:28 -070037 for teardown_file in self.teardown_files:
38 support.unlink(teardown_file)
Brett Cannonc8d502e2010-03-20 21:53:28 +000039 self._warnings_manager.__exit__(None, None, None)
Neal Norwitze241ce82003-02-17 18:17:05 +000040
41 def testNoArgFunctions(self):
42 # test posix functions which take no arguments and have
43 # no side-effects which we need to cleanup (e.g., fork, wait, abort)
Guido van Rossumf0af3e32008-10-02 18:55:37 +000044 NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdb", "uname",
Guido van Rossum687b9c02007-10-25 23:18:51 +000045 "times", "getloadavg",
Neal Norwitze241ce82003-02-17 18:17:05 +000046 "getegid", "geteuid", "getgid", "getgroups",
Ross Lagerwall7807c352011-03-17 20:20:30 +020047 "getpid", "getpgrp", "getppid", "getuid", "sync",
Neal Norwitze241ce82003-02-17 18:17:05 +000048 ]
Neal Norwitz71b13e82003-02-23 22:12:24 +000049
Neal Norwitze241ce82003-02-17 18:17:05 +000050 for name in NO_ARG_FUNCTIONS:
51 posix_func = getattr(posix, name, None)
52 if posix_func is not None:
53 posix_func()
Neal Norwitz2ff51a82003-02-17 22:40:31 +000054 self.assertRaises(TypeError, posix_func, 1)
Neal Norwitze241ce82003-02-17 18:17:05 +000055
Serhiy Storchaka43767632013-11-03 21:31:38 +020056 @unittest.skipUnless(hasattr(posix, 'getresuid'),
57 'test needs posix.getresuid()')
58 def test_getresuid(self):
59 user_ids = posix.getresuid()
60 self.assertEqual(len(user_ids), 3)
61 for val in user_ids:
62 self.assertGreaterEqual(val, 0)
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000063
Serhiy Storchaka43767632013-11-03 21:31:38 +020064 @unittest.skipUnless(hasattr(posix, 'getresgid'),
65 'test needs posix.getresgid()')
66 def test_getresgid(self):
67 group_ids = posix.getresgid()
68 self.assertEqual(len(group_ids), 3)
69 for val in group_ids:
70 self.assertGreaterEqual(val, 0)
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000071
Serhiy Storchaka43767632013-11-03 21:31:38 +020072 @unittest.skipUnless(hasattr(posix, 'setresuid'),
73 'test needs posix.setresuid()')
74 def test_setresuid(self):
75 current_user_ids = posix.getresuid()
76 self.assertIsNone(posix.setresuid(*current_user_ids))
77 # -1 means don't change that value.
78 self.assertIsNone(posix.setresuid(-1, -1, -1))
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000079
Serhiy Storchaka43767632013-11-03 21:31:38 +020080 @unittest.skipUnless(hasattr(posix, 'setresuid'),
81 'test needs posix.setresuid()')
82 def test_setresuid_exception(self):
83 # Don't do this test if someone is silly enough to run us as root.
84 current_user_ids = posix.getresuid()
85 if 0 not in current_user_ids:
86 new_user_ids = (current_user_ids[0]+1, -1, -1)
87 self.assertRaises(OSError, posix.setresuid, *new_user_ids)
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000088
Serhiy Storchaka43767632013-11-03 21:31:38 +020089 @unittest.skipUnless(hasattr(posix, 'setresgid'),
90 'test needs posix.setresgid()')
91 def test_setresgid(self):
92 current_group_ids = posix.getresgid()
93 self.assertIsNone(posix.setresgid(*current_group_ids))
94 # -1 means don't change that value.
95 self.assertIsNone(posix.setresgid(-1, -1, -1))
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000096
Serhiy Storchaka43767632013-11-03 21:31:38 +020097 @unittest.skipUnless(hasattr(posix, 'setresgid'),
98 'test needs posix.setresgid()')
99 def test_setresgid_exception(self):
100 # Don't do this test if someone is silly enough to run us as root.
101 current_group_ids = posix.getresgid()
102 if 0 not in current_group_ids:
103 new_group_ids = (current_group_ids[0]+1, -1, -1)
104 self.assertRaises(OSError, posix.setresgid, *new_group_ids)
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000105
Antoine Pitroub7572f02009-12-02 20:46:48 +0000106 @unittest.skipUnless(hasattr(posix, 'initgroups'),
107 "test needs os.initgroups()")
108 def test_initgroups(self):
109 # It takes a string and an integer; check that it raises a TypeError
110 # for other argument lists.
111 self.assertRaises(TypeError, posix.initgroups)
112 self.assertRaises(TypeError, posix.initgroups, None)
113 self.assertRaises(TypeError, posix.initgroups, 3, "foo")
114 self.assertRaises(TypeError, posix.initgroups, "foo", 3, object())
115
116 # If a non-privileged user invokes it, it should fail with OSError
117 # EPERM.
118 if os.getuid() != 0:
Charles-François Natalie8a255a2012-05-02 20:01:38 +0200119 try:
120 name = pwd.getpwuid(posix.getuid()).pw_name
121 except KeyError:
122 # the current UID may not have a pwd entry
123 raise unittest.SkipTest("need a pwd entry")
Antoine Pitroub7572f02009-12-02 20:46:48 +0000124 try:
125 posix.initgroups(name, 13)
126 except OSError as e:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000127 self.assertEqual(e.errno, errno.EPERM)
Antoine Pitroub7572f02009-12-02 20:46:48 +0000128 else:
129 self.fail("Expected OSError to be raised by initgroups")
130
Serhiy Storchaka43767632013-11-03 21:31:38 +0200131 @unittest.skipUnless(hasattr(posix, 'statvfs'),
132 'test needs posix.statvfs()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000133 def test_statvfs(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200134 self.assertTrue(posix.statvfs(os.curdir))
Neal Norwitze241ce82003-02-17 18:17:05 +0000135
Serhiy Storchaka43767632013-11-03 21:31:38 +0200136 @unittest.skipUnless(hasattr(posix, 'fstatvfs'),
137 'test needs posix.fstatvfs()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000138 def test_fstatvfs(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200139 fp = open(support.TESTFN)
140 try:
141 self.assertTrue(posix.fstatvfs(fp.fileno()))
142 self.assertTrue(posix.statvfs(fp.fileno()))
143 finally:
144 fp.close()
Neal Norwitze241ce82003-02-17 18:17:05 +0000145
Serhiy Storchaka43767632013-11-03 21:31:38 +0200146 @unittest.skipUnless(hasattr(posix, 'ftruncate'),
147 'test needs posix.ftruncate()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000148 def test_ftruncate(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200149 fp = open(support.TESTFN, 'w+')
150 try:
151 # we need to have some data to truncate
152 fp.write('test')
153 fp.flush()
154 posix.ftruncate(fp.fileno(), 0)
155 finally:
156 fp.close()
Neal Norwitze241ce82003-02-17 18:17:05 +0000157
Ross Lagerwall7807c352011-03-17 20:20:30 +0200158 @unittest.skipUnless(hasattr(posix, 'truncate'), "test needs posix.truncate()")
159 def test_truncate(self):
160 with open(support.TESTFN, 'w') as fp:
161 fp.write('test')
162 fp.flush()
163 posix.truncate(support.TESTFN, 0)
164
Larry Hastings9cf065c2012-06-22 16:30:09 -0700165 @unittest.skipUnless(getattr(os, 'execve', None) in os.supports_fd, "test needs execve() to support the fd parameter")
Ross Lagerwall7807c352011-03-17 20:20:30 +0200166 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
Ross Lagerwalldedf6cf2011-03-20 18:27:05 +0200167 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
Ross Lagerwall7807c352011-03-17 20:20:30 +0200168 def test_fexecve(self):
169 fp = os.open(sys.executable, os.O_RDONLY)
170 try:
171 pid = os.fork()
172 if pid == 0:
173 os.chdir(os.path.split(sys.executable)[0])
Larry Hastings9cf065c2012-06-22 16:30:09 -0700174 posix.execve(fp, [sys.executable, '-c', 'pass'], os.environ)
Ross Lagerwall7807c352011-03-17 20:20:30 +0200175 else:
Ross Lagerwalldedf6cf2011-03-20 18:27:05 +0200176 self.assertEqual(os.waitpid(pid, 0), (pid, 0))
Ross Lagerwall7807c352011-03-17 20:20:30 +0200177 finally:
178 os.close(fp)
179
180 @unittest.skipUnless(hasattr(posix, 'waitid'), "test needs posix.waitid()")
181 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
182 def test_waitid(self):
183 pid = os.fork()
184 if pid == 0:
185 os.chdir(os.path.split(sys.executable)[0])
186 posix.execve(sys.executable, [sys.executable, '-c', 'pass'], os.environ)
187 else:
188 res = posix.waitid(posix.P_PID, pid, posix.WEXITED)
189 self.assertEqual(pid, res.si_pid)
190
191 @unittest.skipUnless(hasattr(posix, 'lockf'), "test needs posix.lockf()")
192 def test_lockf(self):
193 fd = os.open(support.TESTFN, os.O_WRONLY | os.O_CREAT)
194 try:
195 os.write(fd, b'test')
196 os.lseek(fd, 0, os.SEEK_SET)
197 posix.lockf(fd, posix.F_LOCK, 4)
198 # section is locked
199 posix.lockf(fd, posix.F_ULOCK, 4)
200 finally:
201 os.close(fd)
202
203 @unittest.skipUnless(hasattr(posix, 'pread'), "test needs posix.pread()")
204 def test_pread(self):
205 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
206 try:
207 os.write(fd, b'test')
208 os.lseek(fd, 0, os.SEEK_SET)
209 self.assertEqual(b'es', posix.pread(fd, 2, 1))
Florent Xiclunae41f0de2011-11-11 19:39:25 +0100210 # the first pread() shouldn't disturb the file offset
Ross Lagerwall7807c352011-03-17 20:20:30 +0200211 self.assertEqual(b'te', posix.read(fd, 2))
212 finally:
213 os.close(fd)
214
215 @unittest.skipUnless(hasattr(posix, 'pwrite'), "test needs posix.pwrite()")
216 def test_pwrite(self):
217 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
218 try:
219 os.write(fd, b'test')
220 os.lseek(fd, 0, os.SEEK_SET)
221 posix.pwrite(fd, b'xx', 1)
222 self.assertEqual(b'txxt', posix.read(fd, 4))
223 finally:
224 os.close(fd)
225
226 @unittest.skipUnless(hasattr(posix, 'posix_fallocate'),
227 "test needs posix.posix_fallocate()")
228 def test_posix_fallocate(self):
229 fd = os.open(support.TESTFN, os.O_WRONLY | os.O_CREAT)
230 try:
231 posix.posix_fallocate(fd, 0, 10)
232 except OSError as inst:
233 # issue10812, ZFS doesn't appear to support posix_fallocate,
234 # so skip Solaris-based since they are likely to have ZFS.
235 if inst.errno != errno.EINVAL or not sys.platform.startswith("sunos"):
236 raise
237 finally:
238 os.close(fd)
239
240 @unittest.skipUnless(hasattr(posix, 'posix_fadvise'),
241 "test needs posix.posix_fadvise()")
242 def test_posix_fadvise(self):
243 fd = os.open(support.TESTFN, os.O_RDONLY)
244 try:
245 posix.posix_fadvise(fd, 0, 0, posix.POSIX_FADV_WILLNEED)
246 finally:
247 os.close(fd)
248
Larry Hastings9cf065c2012-06-22 16:30:09 -0700249 @unittest.skipUnless(os.utime in os.supports_fd, "test needs fd support in os.utime")
250 def test_utime_with_fd(self):
Ross Lagerwall7807c352011-03-17 20:20:30 +0200251 now = time.time()
252 fd = os.open(support.TESTFN, os.O_RDONLY)
253 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700254 posix.utime(fd)
255 posix.utime(fd, None)
256 self.assertRaises(TypeError, posix.utime, fd, (None, None))
257 self.assertRaises(TypeError, posix.utime, fd, (now, None))
258 self.assertRaises(TypeError, posix.utime, fd, (None, now))
259 posix.utime(fd, (int(now), int(now)))
260 posix.utime(fd, (now, now))
261 self.assertRaises(ValueError, posix.utime, fd, (now, now), ns=(now, now))
262 self.assertRaises(ValueError, posix.utime, fd, (now, 0), ns=(None, None))
263 self.assertRaises(ValueError, posix.utime, fd, (None, None), ns=(now, 0))
264 posix.utime(fd, (int(now), int((now - int(now)) * 1e9)))
265 posix.utime(fd, ns=(int(now), int((now - int(now)) * 1e9)))
266
Ross Lagerwall7807c352011-03-17 20:20:30 +0200267 finally:
268 os.close(fd)
269
Larry Hastings9cf065c2012-06-22 16:30:09 -0700270 @unittest.skipUnless(os.utime in os.supports_follow_symlinks, "test needs follow_symlinks support in os.utime")
271 def test_utime_nofollow_symlinks(self):
Ross Lagerwall7807c352011-03-17 20:20:30 +0200272 now = time.time()
Larry Hastings9cf065c2012-06-22 16:30:09 -0700273 posix.utime(support.TESTFN, None, follow_symlinks=False)
274 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None), follow_symlinks=False)
275 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None), follow_symlinks=False)
276 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now), follow_symlinks=False)
277 posix.utime(support.TESTFN, (int(now), int(now)), follow_symlinks=False)
278 posix.utime(support.TESTFN, (now, now), follow_symlinks=False)
279 posix.utime(support.TESTFN, follow_symlinks=False)
Ross Lagerwall7807c352011-03-17 20:20:30 +0200280
281 @unittest.skipUnless(hasattr(posix, 'writev'), "test needs posix.writev()")
282 def test_writev(self):
283 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
284 try:
Victor Stinner57ddf782014-01-08 15:21:28 +0100285 n = os.writev(fd, (b'test1', b'tt2', b't3'))
286 self.assertEqual(n, 10)
287
Ross Lagerwall7807c352011-03-17 20:20:30 +0200288 os.lseek(fd, 0, os.SEEK_SET)
289 self.assertEqual(b'test1tt2t3', posix.read(fd, 10))
Victor Stinner57ddf782014-01-08 15:21:28 +0100290
291 # Issue #20113: empty list of buffers should not crash
Victor Stinnercd5ca6a2014-01-08 16:01:31 +0100292 try:
293 size = posix.writev(fd, [])
294 except OSError:
295 # writev(fd, []) raises OSError(22, "Invalid argument")
296 # on OpenIndiana
297 pass
298 else:
299 self.assertEqual(size, 0)
Ross Lagerwall7807c352011-03-17 20:20:30 +0200300 finally:
301 os.close(fd)
302
303 @unittest.skipUnless(hasattr(posix, 'readv'), "test needs posix.readv()")
304 def test_readv(self):
305 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
306 try:
307 os.write(fd, b'test1tt2t3')
308 os.lseek(fd, 0, os.SEEK_SET)
309 buf = [bytearray(i) for i in [5, 3, 2]]
310 self.assertEqual(posix.readv(fd, buf), 10)
311 self.assertEqual([b'test1', b'tt2', b't3'], [bytes(i) for i in buf])
Victor Stinner57ddf782014-01-08 15:21:28 +0100312
313 # Issue #20113: empty list of buffers should not crash
Victor Stinnercd5ca6a2014-01-08 16:01:31 +0100314 try:
315 size = posix.readv(fd, [])
316 except OSError:
317 # readv(fd, []) raises OSError(22, "Invalid argument")
318 # on OpenIndiana
319 pass
320 else:
321 self.assertEqual(size, 0)
Ross Lagerwall7807c352011-03-17 20:20:30 +0200322 finally:
323 os.close(fd)
324
Serhiy Storchaka43767632013-11-03 21:31:38 +0200325 @unittest.skipUnless(hasattr(posix, 'dup'),
326 'test needs posix.dup()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000327 def test_dup(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200328 fp = open(support.TESTFN)
329 try:
330 fd = posix.dup(fp.fileno())
331 self.assertIsInstance(fd, int)
332 os.close(fd)
333 finally:
334 fp.close()
Neal Norwitze241ce82003-02-17 18:17:05 +0000335
Serhiy Storchaka43767632013-11-03 21:31:38 +0200336 @unittest.skipUnless(hasattr(posix, 'confstr'),
337 'test needs posix.confstr()')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000338 def test_confstr(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200339 self.assertRaises(ValueError, posix.confstr, "CS_garbage")
340 self.assertEqual(len(posix.confstr("CS_PATH")) > 0, True)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000341
Serhiy Storchaka43767632013-11-03 21:31:38 +0200342 @unittest.skipUnless(hasattr(posix, 'dup2'),
343 'test needs posix.dup2()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000344 def test_dup2(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200345 fp1 = open(support.TESTFN)
346 fp2 = open(support.TESTFN)
347 try:
348 posix.dup2(fp1.fileno(), fp2.fileno())
349 finally:
350 fp1.close()
351 fp2.close()
Neal Norwitze241ce82003-02-17 18:17:05 +0000352
Charles-François Natali1e045b12011-05-22 20:42:32 +0200353 @unittest.skipUnless(hasattr(os, 'O_CLOEXEC'), "needs os.O_CLOEXEC")
Charles-François Natali239bb962011-06-03 12:55:15 +0200354 @support.requires_linux_version(2, 6, 23)
Charles-François Natali1e045b12011-05-22 20:42:32 +0200355 def test_oscloexec(self):
356 fd = os.open(support.TESTFN, os.O_RDONLY|os.O_CLOEXEC)
357 self.addCleanup(os.close, fd)
Victor Stinnere36f3752011-05-24 00:29:43 +0200358 self.assertTrue(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC)
Charles-François Natali1e045b12011-05-22 20:42:32 +0200359
Serhiy Storchaka43767632013-11-03 21:31:38 +0200360 @unittest.skipUnless(hasattr(posix, 'O_EXLOCK'),
361 'test needs posix.O_EXLOCK')
Skip Montanaro98470002005-06-17 01:14:49 +0000362 def test_osexlock(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200363 fd = os.open(support.TESTFN,
364 os.O_WRONLY|os.O_EXLOCK|os.O_CREAT)
365 self.assertRaises(OSError, os.open, support.TESTFN,
366 os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
367 os.close(fd)
368
369 if hasattr(posix, "O_SHLOCK"):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000370 fd = os.open(support.TESTFN,
Serhiy Storchaka43767632013-11-03 21:31:38 +0200371 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000372 self.assertRaises(OSError, os.open, support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000373 os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
374 os.close(fd)
375
Serhiy Storchaka43767632013-11-03 21:31:38 +0200376 @unittest.skipUnless(hasattr(posix, 'O_SHLOCK'),
377 'test needs posix.O_SHLOCK')
Skip Montanaro98470002005-06-17 01:14:49 +0000378 def test_osshlock(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200379 fd1 = os.open(support.TESTFN,
380 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
381 fd2 = os.open(support.TESTFN,
382 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
383 os.close(fd2)
384 os.close(fd1)
385
386 if hasattr(posix, "O_EXLOCK"):
387 fd = os.open(support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000388 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
Serhiy Storchaka43767632013-11-03 21:31:38 +0200389 self.assertRaises(OSError, os.open, support.TESTFN,
390 os.O_RDONLY|os.O_EXLOCK|os.O_NONBLOCK)
391 os.close(fd)
Skip Montanaro98470002005-06-17 01:14:49 +0000392
Serhiy Storchaka43767632013-11-03 21:31:38 +0200393 @unittest.skipUnless(hasattr(posix, 'fstat'),
394 'test needs posix.fstat()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000395 def test_fstat(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200396 fp = open(support.TESTFN)
397 try:
398 self.assertTrue(posix.fstat(fp.fileno()))
399 self.assertTrue(posix.stat(fp.fileno()))
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200400
Serhiy Storchaka43767632013-11-03 21:31:38 +0200401 self.assertRaisesRegex(TypeError,
402 'should be string, bytes or integer, not',
403 posix.stat, float(fp.fileno()))
404 finally:
405 fp.close()
Neal Norwitze241ce82003-02-17 18:17:05 +0000406
Serhiy Storchaka43767632013-11-03 21:31:38 +0200407 @unittest.skipUnless(hasattr(posix, 'stat'),
408 'test needs posix.stat()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000409 def test_stat(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200410 self.assertTrue(posix.stat(support.TESTFN))
411 self.assertTrue(posix.stat(os.fsencode(support.TESTFN)))
412 self.assertTrue(posix.stat(bytearray(os.fsencode(support.TESTFN))))
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200413
Serhiy Storchaka43767632013-11-03 21:31:38 +0200414 self.assertRaisesRegex(TypeError,
415 'can\'t specify None for path argument',
416 posix.stat, None)
417 self.assertRaisesRegex(TypeError,
418 'should be string, bytes or integer, not',
419 posix.stat, list(support.TESTFN))
420 self.assertRaisesRegex(TypeError,
421 'should be string, bytes or integer, not',
422 posix.stat, list(os.fsencode(support.TESTFN)))
Neal Norwitze241ce82003-02-17 18:17:05 +0000423
Benjamin Peterson052a02b2010-08-17 01:27:09 +0000424 @unittest.skipUnless(hasattr(posix, 'mkfifo'), "don't have mkfifo()")
425 def test_mkfifo(self):
426 support.unlink(support.TESTFN)
427 posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR)
428 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
429
430 @unittest.skipUnless(hasattr(posix, 'mknod') and hasattr(stat, 'S_IFIFO'),
431 "don't have mknod()/S_IFIFO")
432 def test_mknod(self):
433 # Test using mknod() to create a FIFO (the only use specified
434 # by POSIX).
435 support.unlink(support.TESTFN)
436 mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
437 try:
438 posix.mknod(support.TESTFN, mode, 0)
439 except OSError as e:
440 # Some old systems don't allow unprivileged users to use
441 # mknod(), or only support creating device nodes.
442 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
443 else:
444 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
445
Serhiy Storchaka16b2e4f2015-04-20 09:22:13 +0300446 @unittest.skipUnless(hasattr(posix, 'stat'), 'test needs posix.stat()')
447 @unittest.skipUnless(hasattr(posix, 'makedev'), 'test needs posix.makedev()')
448 def test_makedev(self):
449 st = posix.stat(support.TESTFN)
450 dev = st.st_dev
451 self.assertIsInstance(dev, int)
452 self.assertGreaterEqual(dev, 0)
453
454 major = posix.major(dev)
455 self.assertIsInstance(major, int)
456 self.assertGreaterEqual(major, 0)
457 self.assertEqual(posix.major(dev), major)
458 self.assertRaises(TypeError, posix.major, float(dev))
459 self.assertRaises(TypeError, posix.major)
460 self.assertRaises((ValueError, OverflowError), posix.major, -1)
461
462 minor = posix.minor(dev)
463 self.assertIsInstance(minor, int)
464 self.assertGreaterEqual(minor, 0)
465 self.assertEqual(posix.minor(dev), minor)
466 self.assertRaises(TypeError, posix.minor, float(dev))
467 self.assertRaises(TypeError, posix.minor)
468 self.assertRaises((ValueError, OverflowError), posix.minor, -1)
469
470 self.assertEqual(posix.makedev(major, minor), dev)
471 self.assertRaises(TypeError, posix.makedev, float(major), minor)
472 self.assertRaises(TypeError, posix.makedev, major, float(minor))
473 self.assertRaises(TypeError, posix.makedev, major)
474 self.assertRaises(TypeError, posix.makedev)
475
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200476 def _test_all_chown_common(self, chown_func, first_param, stat_func):
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000477 """Common code for chown, fchown and lchown tests."""
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200478 def check_stat(uid, gid):
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200479 if stat_func is not None:
480 stat = stat_func(first_param)
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200481 self.assertEqual(stat.st_uid, uid)
482 self.assertEqual(stat.st_gid, gid)
483 uid = os.getuid()
484 gid = os.getgid()
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200485 # test a successful chown call
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200486 chown_func(first_param, uid, gid)
487 check_stat(uid, gid)
488 chown_func(first_param, -1, gid)
489 check_stat(uid, gid)
490 chown_func(first_param, uid, -1)
491 check_stat(uid, gid)
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200492
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200493 if uid == 0:
494 # Try an amusingly large uid/gid to make sure we handle
495 # large unsigned values. (chown lets you use any
496 # uid/gid you like, even if they aren't defined.)
497 #
498 # This problem keeps coming up:
499 # http://bugs.python.org/issue1747858
500 # http://bugs.python.org/issue4591
501 # http://bugs.python.org/issue15301
502 # Hopefully the fix in 4591 fixes it for good!
503 #
504 # This part of the test only runs when run as root.
505 # Only scary people run their tests as root.
506
507 big_value = 2**31
508 chown_func(first_param, big_value, big_value)
509 check_stat(big_value, big_value)
510 chown_func(first_param, -1, -1)
511 check_stat(big_value, big_value)
512 chown_func(first_param, uid, gid)
513 check_stat(uid, gid)
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200514 elif platform.system() in ('HP-UX', 'SunOS'):
515 # HP-UX and Solaris can allow a non-root user to chown() to root
516 # (issue #5113)
517 raise unittest.SkipTest("Skipping because of non-standard chown() "
518 "behavior")
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000519 else:
520 # non-root cannot chown to root, raises OSError
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200521 self.assertRaises(OSError, chown_func, first_param, 0, 0)
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200522 check_stat(uid, gid)
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200523 self.assertRaises(OSError, chown_func, first_param, 0, -1)
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200524 check_stat(uid, gid)
Serhiy Storchakaa2964b32013-02-21 14:34:36 +0200525 if 0 not in os.getgroups():
Serhiy Storchakab3d62ce2013-02-20 19:48:22 +0200526 self.assertRaises(OSError, chown_func, first_param, -1, 0)
527 check_stat(uid, gid)
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200528 # test illegal types
529 for t in str, float:
530 self.assertRaises(TypeError, chown_func, first_param, t(uid), gid)
531 check_stat(uid, gid)
532 self.assertRaises(TypeError, chown_func, first_param, uid, t(gid))
533 check_stat(uid, gid)
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000534
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000535 @unittest.skipUnless(hasattr(posix, 'chown'), "test needs os.chown()")
536 def test_chown(self):
537 # raise an OSError if the file does not exist
538 os.unlink(support.TESTFN)
539 self.assertRaises(OSError, posix.chown, support.TESTFN, -1, -1)
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000540
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000541 # re-create the file
Victor Stinnerbf816222011-06-30 23:25:47 +0200542 support.create_empty_file(support.TESTFN)
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200543 self._test_all_chown_common(posix.chown, support.TESTFN,
544 getattr(posix, 'stat', None))
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000545
546 @unittest.skipUnless(hasattr(posix, 'fchown'), "test needs os.fchown()")
547 def test_fchown(self):
548 os.unlink(support.TESTFN)
549
550 # re-create the file
551 test_file = open(support.TESTFN, 'w')
552 try:
553 fd = test_file.fileno()
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200554 self._test_all_chown_common(posix.fchown, fd,
555 getattr(posix, 'fstat', None))
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000556 finally:
557 test_file.close()
558
559 @unittest.skipUnless(hasattr(posix, 'lchown'), "test needs os.lchown()")
560 def test_lchown(self):
561 os.unlink(support.TESTFN)
562 # create a symlink
Ned Deily3eb67d52011-06-28 00:00:28 -0700563 os.symlink(_DUMMY_SYMLINK, support.TESTFN)
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200564 self._test_all_chown_common(posix.lchown, support.TESTFN,
565 getattr(posix, 'lstat', None))
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000566
Serhiy Storchaka43767632013-11-03 21:31:38 +0200567 @unittest.skipUnless(hasattr(posix, 'chdir'), 'test needs posix.chdir()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000568 def test_chdir(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200569 posix.chdir(os.curdir)
570 self.assertRaises(OSError, posix.chdir, support.TESTFN)
Neal Norwitze241ce82003-02-17 18:17:05 +0000571
Martin v. Löwisc9e1c7d2010-07-23 12:16:41 +0000572 def test_listdir(self):
Larry Hastingsfdaea062012-06-25 04:42:23 -0700573 self.assertTrue(support.TESTFN in posix.listdir(os.curdir))
Martin v. Löwisc9e1c7d2010-07-23 12:16:41 +0000574
575 def test_listdir_default(self):
Larry Hastingsfdaea062012-06-25 04:42:23 -0700576 # When listdir is called without argument,
577 # it's the same as listdir(os.curdir).
578 self.assertTrue(support.TESTFN in posix.listdir())
Neal Norwitze241ce82003-02-17 18:17:05 +0000579
Larry Hastingsfdaea062012-06-25 04:42:23 -0700580 def test_listdir_bytes(self):
581 # When listdir is called with a bytes object,
582 # the returned strings are of type bytes.
583 self.assertTrue(os.fsencode(support.TESTFN) in posix.listdir(b'.'))
584
585 @unittest.skipUnless(posix.listdir in os.supports_fd,
586 "test needs fd support for posix.listdir()")
587 def test_listdir_fd(self):
Antoine Pitrou8250e232011-02-25 23:41:16 +0000588 f = posix.open(posix.getcwd(), posix.O_RDONLY)
Charles-François Natali7546ad32012-01-08 18:34:06 +0100589 self.addCleanup(posix.close, f)
Antoine Pitrou8250e232011-02-25 23:41:16 +0000590 self.assertEqual(
591 sorted(posix.listdir('.')),
Larry Hastings9cf065c2012-06-22 16:30:09 -0700592 sorted(posix.listdir(f))
Antoine Pitrou8250e232011-02-25 23:41:16 +0000593 )
Charles-François Natali7546ad32012-01-08 18:34:06 +0100594 # Check that the fd offset was reset (issue #13739)
Charles-François Natali7546ad32012-01-08 18:34:06 +0100595 self.assertEqual(
596 sorted(posix.listdir('.')),
Larry Hastings9cf065c2012-06-22 16:30:09 -0700597 sorted(posix.listdir(f))
Charles-François Natali7546ad32012-01-08 18:34:06 +0100598 )
Antoine Pitrou8250e232011-02-25 23:41:16 +0000599
Serhiy Storchaka43767632013-11-03 21:31:38 +0200600 @unittest.skipUnless(hasattr(posix, 'access'), 'test needs posix.access()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000601 def test_access(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200602 self.assertTrue(posix.access(support.TESTFN, os.R_OK))
Neal Norwitze241ce82003-02-17 18:17:05 +0000603
Serhiy Storchaka43767632013-11-03 21:31:38 +0200604 @unittest.skipUnless(hasattr(posix, 'umask'), 'test needs posix.umask()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000605 def test_umask(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200606 old_mask = posix.umask(0)
607 self.assertIsInstance(old_mask, int)
608 posix.umask(old_mask)
Neal Norwitze241ce82003-02-17 18:17:05 +0000609
Serhiy Storchaka43767632013-11-03 21:31:38 +0200610 @unittest.skipUnless(hasattr(posix, 'strerror'),
611 'test needs posix.strerror()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000612 def test_strerror(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200613 self.assertTrue(posix.strerror(0))
Neal Norwitze241ce82003-02-17 18:17:05 +0000614
Serhiy Storchaka43767632013-11-03 21:31:38 +0200615 @unittest.skipUnless(hasattr(posix, 'pipe'), 'test needs posix.pipe()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000616 def test_pipe(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200617 reader, writer = posix.pipe()
618 os.close(reader)
619 os.close(writer)
Neal Norwitze241ce82003-02-17 18:17:05 +0000620
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200621 @unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()")
Charles-François Natali239bb962011-06-03 12:55:15 +0200622 @support.requires_linux_version(2, 6, 27)
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200623 def test_pipe2(self):
624 self.assertRaises(TypeError, os.pipe2, 'DEADBEEF')
625 self.assertRaises(TypeError, os.pipe2, 0, 0)
626
Charles-François Natali368f34b2011-06-06 19:49:47 +0200627 # try calling with flags = 0, like os.pipe()
628 r, w = os.pipe2(0)
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200629 os.close(r)
630 os.close(w)
631
632 # test flags
633 r, w = os.pipe2(os.O_CLOEXEC|os.O_NONBLOCK)
634 self.addCleanup(os.close, r)
635 self.addCleanup(os.close, w)
Victor Stinnerbff989e2013-08-28 12:25:40 +0200636 self.assertFalse(os.get_inheritable(r))
637 self.assertFalse(os.get_inheritable(w))
638 self.assertTrue(fcntl.fcntl(r, fcntl.F_GETFL) & os.O_NONBLOCK)
639 self.assertTrue(fcntl.fcntl(w, fcntl.F_GETFL) & os.O_NONBLOCK)
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200640 # try reading from an empty pipe: this should fail, not block
641 self.assertRaises(OSError, os.read, r, 1)
642 # try a write big enough to fill-up the pipe: this should either
643 # fail or perform a partial write, not block
644 try:
645 os.write(w, b'x' * support.PIPE_MAX_SIZE)
646 except OSError:
647 pass
648
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200649 @support.cpython_only
650 @unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()")
651 @support.requires_linux_version(2, 6, 27)
652 def test_pipe2_c_limits(self):
Serhiy Storchaka78980432013-01-15 01:12:17 +0200653 # Issue 15989
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200654 import _testcapi
Serhiy Storchaka78980432013-01-15 01:12:17 +0200655 self.assertRaises(OverflowError, os.pipe2, _testcapi.INT_MAX + 1)
656 self.assertRaises(OverflowError, os.pipe2, _testcapi.UINT_MAX + 1)
657
Serhiy Storchaka43767632013-11-03 21:31:38 +0200658 @unittest.skipUnless(hasattr(posix, 'utime'), 'test needs posix.utime()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000659 def test_utime(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200660 now = time.time()
661 posix.utime(support.TESTFN, None)
662 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None))
663 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None))
664 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now))
665 posix.utime(support.TESTFN, (int(now), int(now)))
666 posix.utime(support.TESTFN, (now, now))
Neal Norwitze241ce82003-02-17 18:17:05 +0000667
Larry Hastings9cf065c2012-06-22 16:30:09 -0700668 def _test_chflags_regular_file(self, chflags_func, target_file, **kwargs):
Ned Deily3eb67d52011-06-28 00:00:28 -0700669 st = os.stat(target_file)
670 self.assertTrue(hasattr(st, 'st_flags'))
Trent Nelson75959cf2012-08-21 23:59:31 +0000671
672 # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
673 flags = st.st_flags | stat.UF_IMMUTABLE
674 try:
675 chflags_func(target_file, flags, **kwargs)
676 except OSError as err:
677 if err.errno != errno.EOPNOTSUPP:
678 raise
679 msg = 'chflag UF_IMMUTABLE not supported by underlying fs'
680 self.skipTest(msg)
681
Ned Deily3eb67d52011-06-28 00:00:28 -0700682 try:
683 new_st = os.stat(target_file)
684 self.assertEqual(st.st_flags | stat.UF_IMMUTABLE, new_st.st_flags)
685 try:
686 fd = open(target_file, 'w+')
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200687 except OSError as e:
Ned Deily3eb67d52011-06-28 00:00:28 -0700688 self.assertEqual(e.errno, errno.EPERM)
689 finally:
690 posix.chflags(target_file, st.st_flags)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000691
Ned Deily3eb67d52011-06-28 00:00:28 -0700692 @unittest.skipUnless(hasattr(posix, 'chflags'), 'test needs os.chflags()')
693 def test_chflags(self):
694 self._test_chflags_regular_file(posix.chflags, support.TESTFN)
695
696 @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
697 def test_lchflags_regular_file(self):
698 self._test_chflags_regular_file(posix.lchflags, support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700699 self._test_chflags_regular_file(posix.chflags, support.TESTFN, follow_symlinks=False)
Ned Deily3eb67d52011-06-28 00:00:28 -0700700
701 @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
702 def test_lchflags_symlink(self):
703 testfn_st = os.stat(support.TESTFN)
704
705 self.assertTrue(hasattr(testfn_st, 'st_flags'))
706
707 os.symlink(support.TESTFN, _DUMMY_SYMLINK)
708 self.teardown_files.append(_DUMMY_SYMLINK)
709 dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
710
Larry Hastings9cf065c2012-06-22 16:30:09 -0700711 def chflags_nofollow(path, flags):
712 return posix.chflags(path, flags, follow_symlinks=False)
Ned Deily3eb67d52011-06-28 00:00:28 -0700713
Larry Hastings9cf065c2012-06-22 16:30:09 -0700714 for fn in (posix.lchflags, chflags_nofollow):
Trent Nelson75959cf2012-08-21 23:59:31 +0000715 # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
716 flags = dummy_symlink_st.st_flags | stat.UF_IMMUTABLE
717 try:
718 fn(_DUMMY_SYMLINK, flags)
719 except OSError as err:
720 if err.errno != errno.EOPNOTSUPP:
721 raise
722 msg = 'chflag UF_IMMUTABLE not supported by underlying fs'
723 self.skipTest(msg)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700724 try:
725 new_testfn_st = os.stat(support.TESTFN)
726 new_dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
727
728 self.assertEqual(testfn_st.st_flags, new_testfn_st.st_flags)
729 self.assertEqual(dummy_symlink_st.st_flags | stat.UF_IMMUTABLE,
730 new_dummy_symlink_st.st_flags)
731 finally:
732 fn(_DUMMY_SYMLINK, dummy_symlink_st.st_flags)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000733
Guido van Rossum98297ee2007-11-06 21:34:58 +0000734 def test_environ(self):
Victor Stinner17b490d2010-05-06 22:19:30 +0000735 if os.name == "nt":
736 item_type = str
737 else:
738 item_type = bytes
Guido van Rossum98297ee2007-11-06 21:34:58 +0000739 for k, v in posix.environ.items():
Victor Stinner17b490d2010-05-06 22:19:30 +0000740 self.assertEqual(type(k), item_type)
741 self.assertEqual(type(v), item_type)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000742
Serhiy Storchaka43767632013-11-03 21:31:38 +0200743 @unittest.skipUnless(hasattr(posix, 'getcwd'), 'test needs posix.getcwd()')
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000744 def test_getcwd_long_pathnames(self):
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500745 dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
746 curdir = os.getcwd()
747 base_path = os.path.abspath(support.TESTFN) + '.getcwd'
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000748
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500749 try:
750 os.mkdir(base_path)
751 os.chdir(base_path)
752 except:
753 # Just returning nothing instead of the SkipTest exception, because
754 # the test results in Error in that case. Is that ok?
755 # raise unittest.SkipTest("cannot create directory for testing")
756 return
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000757
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500758 def _create_and_do_getcwd(dirname, current_path_length = 0):
759 try:
760 os.mkdir(dirname)
761 except:
762 raise unittest.SkipTest("mkdir cannot create directory sufficiently deep for getcwd test")
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000763
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500764 os.chdir(dirname)
765 try:
766 os.getcwd()
767 if current_path_length < 1027:
768 _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1)
769 finally:
770 os.chdir('..')
771 os.rmdir(dirname)
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000772
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500773 _create_and_do_getcwd(dirname)
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000774
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500775 finally:
776 os.chdir(curdir)
777 support.rmtree(base_path)
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000778
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200779 @unittest.skipUnless(hasattr(posix, 'getgrouplist'), "test needs posix.getgrouplist()")
780 @unittest.skipUnless(hasattr(pwd, 'getpwuid'), "test needs pwd.getpwuid()")
781 @unittest.skipUnless(hasattr(os, 'getuid'), "test needs os.getuid()")
782 def test_getgrouplist(self):
Ross Lagerwalla0b315f2012-12-13 15:20:26 +0000783 user = pwd.getpwuid(os.getuid())[0]
784 group = pwd.getpwuid(os.getuid())[3]
785 self.assertIn(group, posix.getgrouplist(user, group))
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200786
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200787
Antoine Pitrou318b8f32011-01-12 18:45:27 +0000788 @unittest.skipUnless(hasattr(os, 'getegid'), "test needs os.getegid()")
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000789 def test_getgroups(self):
Jesus Cea61f32cb2014-06-28 18:39:35 +0200790 with os.popen('id -G 2>/dev/null') as idg:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000791 groups = idg.read().strip()
Charles-François Natalie8a255a2012-05-02 20:01:38 +0200792 ret = idg.close()
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000793
Benjamin Petersonb29614e2012-10-09 11:16:03 -0400794 if ret is not None or not groups:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000795 raise unittest.SkipTest("need working 'id -G'")
796
Ned Deily028915e2013-02-02 15:08:52 -0800797 # Issues 16698: OS X ABIs prior to 10.6 have limits on getgroups()
798 if sys.platform == 'darwin':
799 import sysconfig
800 dt = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') or '10.0'
Ned Deily04cdfa12014-06-25 13:36:14 -0700801 if tuple(int(n) for n in dt.split('.')[0:2]) < (10, 6):
Ned Deily028915e2013-02-02 15:08:52 -0800802 raise unittest.SkipTest("getgroups(2) is broken prior to 10.6")
803
Ronald Oussoren7fb6f512010-08-01 19:18:13 +0000804 # 'id -G' and 'os.getgroups()' should return the same
805 # groups, ignoring order and duplicates.
Antoine Pitrou318b8f32011-01-12 18:45:27 +0000806 # #10822 - it is implementation defined whether posix.getgroups()
807 # includes the effective gid so we include it anyway, since id -G does
Ronald Oussorencb615e62010-07-24 14:15:19 +0000808 self.assertEqual(
Ronald Oussoren7fb6f512010-08-01 19:18:13 +0000809 set([int(x) for x in groups.split()]),
Antoine Pitrou318b8f32011-01-12 18:45:27 +0000810 set(posix.getgroups() + [posix.getegid()]))
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000811
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000812 # tests for the posix *at functions follow
813
Larry Hastings9cf065c2012-06-22 16:30:09 -0700814 @unittest.skipUnless(os.access in os.supports_dir_fd, "test needs dir_fd support for os.access()")
815 def test_access_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000816 f = posix.open(posix.getcwd(), posix.O_RDONLY)
817 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700818 self.assertTrue(posix.access(support.TESTFN, os.R_OK, dir_fd=f))
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000819 finally:
820 posix.close(f)
821
Larry Hastings9cf065c2012-06-22 16:30:09 -0700822 @unittest.skipUnless(os.chmod in os.supports_dir_fd, "test needs dir_fd support in os.chmod()")
823 def test_chmod_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000824 os.chmod(support.TESTFN, stat.S_IRUSR)
825
826 f = posix.open(posix.getcwd(), posix.O_RDONLY)
827 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700828 posix.chmod(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000829
830 s = posix.stat(support.TESTFN)
831 self.assertEqual(s[0] & stat.S_IRWXU, stat.S_IRUSR | stat.S_IWUSR)
832 finally:
833 posix.close(f)
834
Larry Hastings9cf065c2012-06-22 16:30:09 -0700835 @unittest.skipUnless(os.chown in os.supports_dir_fd, "test needs dir_fd support in os.chown()")
836 def test_chown_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000837 support.unlink(support.TESTFN)
Victor Stinnerbf816222011-06-30 23:25:47 +0200838 support.create_empty_file(support.TESTFN)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000839
840 f = posix.open(posix.getcwd(), posix.O_RDONLY)
841 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700842 posix.chown(support.TESTFN, os.getuid(), os.getgid(), dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000843 finally:
844 posix.close(f)
845
Larry Hastings9cf065c2012-06-22 16:30:09 -0700846 @unittest.skipUnless(os.stat in os.supports_dir_fd, "test needs dir_fd support in os.stat()")
847 def test_stat_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000848 support.unlink(support.TESTFN)
849 with open(support.TESTFN, 'w') as outfile:
850 outfile.write("testline\n")
851
852 f = posix.open(posix.getcwd(), posix.O_RDONLY)
853 try:
854 s1 = posix.stat(support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700855 s2 = posix.stat(support.TESTFN, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000856 self.assertEqual(s1, s2)
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200857 s2 = posix.stat(support.TESTFN, dir_fd=None)
858 self.assertEqual(s1, s2)
859 self.assertRaisesRegex(TypeError, 'should be integer, not',
860 posix.stat, support.TESTFN, dir_fd=posix.getcwd())
861 self.assertRaisesRegex(TypeError, 'should be integer, not',
862 posix.stat, support.TESTFN, dir_fd=float(f))
863 self.assertRaises(OverflowError,
864 posix.stat, support.TESTFN, dir_fd=10**20)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000865 finally:
866 posix.close(f)
867
Larry Hastings9cf065c2012-06-22 16:30:09 -0700868 @unittest.skipUnless(os.utime in os.supports_dir_fd, "test needs dir_fd support in os.utime()")
869 def test_utime_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000870 f = posix.open(posix.getcwd(), posix.O_RDONLY)
871 try:
872 now = time.time()
Larry Hastings9cf065c2012-06-22 16:30:09 -0700873 posix.utime(support.TESTFN, None, dir_fd=f)
874 posix.utime(support.TESTFN, dir_fd=f)
875 self.assertRaises(TypeError, posix.utime, support.TESTFN, now, dir_fd=f)
876 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None), dir_fd=f)
877 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None), dir_fd=f)
878 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now), dir_fd=f)
879 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, "x"), dir_fd=f)
880 posix.utime(support.TESTFN, (int(now), int(now)), dir_fd=f)
881 posix.utime(support.TESTFN, (now, now), dir_fd=f)
882 posix.utime(support.TESTFN,
883 (int(now), int((now - int(now)) * 1e9)), dir_fd=f)
884 posix.utime(support.TESTFN, dir_fd=f,
885 times=(int(now), int((now - int(now)) * 1e9)))
886
Larry Hastings90867a52012-06-22 17:01:41 -0700887 # try dir_fd and follow_symlinks together
Larry Hastings9cf065c2012-06-22 16:30:09 -0700888 if os.utime in os.supports_follow_symlinks:
Larry Hastings90867a52012-06-22 17:01:41 -0700889 try:
890 posix.utime(support.TESTFN, follow_symlinks=False, dir_fd=f)
Georg Brandl969288e2012-06-26 09:25:44 +0200891 except ValueError:
Larry Hastings90867a52012-06-22 17:01:41 -0700892 # whoops! using both together not supported on this platform.
893 pass
Larry Hastings9cf065c2012-06-22 16:30:09 -0700894
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000895 finally:
896 posix.close(f)
897
Larry Hastings9cf065c2012-06-22 16:30:09 -0700898 @unittest.skipUnless(os.link in os.supports_dir_fd, "test needs dir_fd support in os.link()")
899 def test_link_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000900 f = posix.open(posix.getcwd(), posix.O_RDONLY)
901 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700902 posix.link(support.TESTFN, support.TESTFN + 'link', src_dir_fd=f, dst_dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000903 # should have same inodes
904 self.assertEqual(posix.stat(support.TESTFN)[1],
905 posix.stat(support.TESTFN + 'link')[1])
906 finally:
907 posix.close(f)
908 support.unlink(support.TESTFN + 'link')
909
Larry Hastings9cf065c2012-06-22 16:30:09 -0700910 @unittest.skipUnless(os.mkdir in os.supports_dir_fd, "test needs dir_fd support in os.mkdir()")
911 def test_mkdir_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000912 f = posix.open(posix.getcwd(), posix.O_RDONLY)
913 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700914 posix.mkdir(support.TESTFN + 'dir', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000915 posix.stat(support.TESTFN + 'dir') # should not raise exception
916 finally:
917 posix.close(f)
918 support.rmtree(support.TESTFN + 'dir')
919
Larry Hastings9cf065c2012-06-22 16:30:09 -0700920 @unittest.skipUnless((os.mknod in os.supports_dir_fd) and hasattr(stat, 'S_IFIFO'),
921 "test requires both stat.S_IFIFO and dir_fd support for os.mknod()")
922 def test_mknod_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000923 # Test using mknodat() to create a FIFO (the only use specified
924 # by POSIX).
925 support.unlink(support.TESTFN)
926 mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
927 f = posix.open(posix.getcwd(), posix.O_RDONLY)
928 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700929 posix.mknod(support.TESTFN, mode, 0, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000930 except OSError as e:
931 # Some old systems don't allow unprivileged users to use
932 # mknod(), or only support creating device nodes.
933 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
934 else:
935 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
936 finally:
937 posix.close(f)
938
Larry Hastings9cf065c2012-06-22 16:30:09 -0700939 @unittest.skipUnless(os.open in os.supports_dir_fd, "test needs dir_fd support in os.open()")
940 def test_open_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000941 support.unlink(support.TESTFN)
942 with open(support.TESTFN, 'w') as outfile:
943 outfile.write("testline\n")
944 a = posix.open(posix.getcwd(), posix.O_RDONLY)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700945 b = posix.open(support.TESTFN, posix.O_RDONLY, dir_fd=a)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000946 try:
947 res = posix.read(b, 9).decode(encoding="utf-8")
948 self.assertEqual("testline\n", res)
949 finally:
950 posix.close(a)
951 posix.close(b)
952
Larry Hastings9cf065c2012-06-22 16:30:09 -0700953 @unittest.skipUnless(os.readlink in os.supports_dir_fd, "test needs dir_fd support in os.readlink()")
954 def test_readlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000955 os.symlink(support.TESTFN, support.TESTFN + 'link')
956 f = posix.open(posix.getcwd(), posix.O_RDONLY)
957 try:
958 self.assertEqual(posix.readlink(support.TESTFN + 'link'),
Larry Hastings9cf065c2012-06-22 16:30:09 -0700959 posix.readlink(support.TESTFN + 'link', dir_fd=f))
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000960 finally:
961 support.unlink(support.TESTFN + 'link')
962 posix.close(f)
963
Larry Hastings9cf065c2012-06-22 16:30:09 -0700964 @unittest.skipUnless(os.rename in os.supports_dir_fd, "test needs dir_fd support in os.rename()")
965 def test_rename_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000966 support.unlink(support.TESTFN)
Victor Stinnerbf816222011-06-30 23:25:47 +0200967 support.create_empty_file(support.TESTFN + 'ren')
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000968 f = posix.open(posix.getcwd(), posix.O_RDONLY)
969 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700970 posix.rename(support.TESTFN + 'ren', support.TESTFN, src_dir_fd=f, dst_dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000971 except:
972 posix.rename(support.TESTFN + 'ren', support.TESTFN)
973 raise
974 else:
Andrew Svetlov5b898402012-12-18 21:26:36 +0200975 posix.stat(support.TESTFN) # should not raise exception
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000976 finally:
977 posix.close(f)
978
Larry Hastings9cf065c2012-06-22 16:30:09 -0700979 @unittest.skipUnless(os.symlink in os.supports_dir_fd, "test needs dir_fd support in os.symlink()")
980 def test_symlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000981 f = posix.open(posix.getcwd(), posix.O_RDONLY)
982 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700983 posix.symlink(support.TESTFN, support.TESTFN + 'link', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000984 self.assertEqual(posix.readlink(support.TESTFN + 'link'), support.TESTFN)
985 finally:
986 posix.close(f)
987 support.unlink(support.TESTFN + 'link')
988
Larry Hastings9cf065c2012-06-22 16:30:09 -0700989 @unittest.skipUnless(os.unlink in os.supports_dir_fd, "test needs dir_fd support in os.unlink()")
990 def test_unlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000991 f = posix.open(posix.getcwd(), posix.O_RDONLY)
Victor Stinnerbf816222011-06-30 23:25:47 +0200992 support.create_empty_file(support.TESTFN + 'del')
Andrew Svetlov5b898402012-12-18 21:26:36 +0200993 posix.stat(support.TESTFN + 'del') # should not raise exception
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000994 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700995 posix.unlink(support.TESTFN + 'del', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000996 except:
997 support.unlink(support.TESTFN + 'del')
998 raise
999 else:
1000 self.assertRaises(OSError, posix.stat, support.TESTFN + 'link')
1001 finally:
1002 posix.close(f)
1003
Larry Hastings9cf065c2012-06-22 16:30:09 -07001004 @unittest.skipUnless(os.mkfifo in os.supports_dir_fd, "test needs dir_fd support in os.mkfifo()")
1005 def test_mkfifo_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001006 support.unlink(support.TESTFN)
1007 f = posix.open(posix.getcwd(), posix.O_RDONLY)
1008 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001009 posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001010 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
1011 finally:
1012 posix.close(f)
1013
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001014 requires_sched_h = unittest.skipUnless(hasattr(posix, 'sched_yield'),
1015 "don't have scheduling support")
Antoine Pitrou84869872012-08-04 16:16:35 +02001016 requires_sched_affinity = unittest.skipUnless(hasattr(posix, 'sched_setaffinity'),
Benjamin Peterson50ba2712011-08-02 22:15:40 -05001017 "don't have sched affinity support")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001018
1019 @requires_sched_h
1020 def test_sched_yield(self):
1021 # This has no error conditions (at least on Linux).
1022 posix.sched_yield()
1023
1024 @requires_sched_h
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02001025 @unittest.skipUnless(hasattr(posix, 'sched_get_priority_max'),
1026 "requires sched_get_priority_max()")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001027 def test_sched_priority(self):
1028 # Round-robin usually has interesting priorities.
1029 pol = posix.SCHED_RR
1030 lo = posix.sched_get_priority_min(pol)
1031 hi = posix.sched_get_priority_max(pol)
1032 self.assertIsInstance(lo, int)
1033 self.assertIsInstance(hi, int)
1034 self.assertGreaterEqual(hi, lo)
Benjamin Peterson539b6c42011-08-02 22:09:37 -05001035 # OSX evidently just returns 15 without checking the argument.
1036 if sys.platform != "darwin":
Benjamin Petersonc1581582011-08-02 22:10:55 -05001037 self.assertRaises(OSError, posix.sched_get_priority_min, -23)
1038 self.assertRaises(OSError, posix.sched_get_priority_max, -23)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001039
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05001040 @unittest.skipUnless(hasattr(posix, 'sched_setscheduler'), "can't change scheduler")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001041 def test_get_and_set_scheduler_and_param(self):
1042 possible_schedulers = [sched for name, sched in posix.__dict__.items()
1043 if name.startswith("SCHED_")]
1044 mine = posix.sched_getscheduler(0)
1045 self.assertIn(mine, possible_schedulers)
1046 try:
Jesus Ceaceb5d162011-09-10 01:16:55 +02001047 parent = posix.sched_getscheduler(os.getppid())
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001048 except OSError as e:
Jesus Ceaceb5d162011-09-10 01:16:55 +02001049 if e.errno != errno.EPERM:
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001050 raise
1051 else:
Jesus Ceaceb5d162011-09-10 01:16:55 +02001052 self.assertIn(parent, possible_schedulers)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001053 self.assertRaises(OSError, posix.sched_getscheduler, -1)
1054 self.assertRaises(OSError, posix.sched_getparam, -1)
1055 param = posix.sched_getparam(0)
1056 self.assertIsInstance(param.sched_priority, int)
Charles-François Natali7b911cb2011-08-21 12:41:43 +02001057
Charles-François Natalib402a5c2013-01-13 14:13:25 +01001058 # POSIX states that calling sched_setparam() or sched_setscheduler() on
1059 # a process with a scheduling policy other than SCHED_FIFO or SCHED_RR
1060 # is implementation-defined: NetBSD and FreeBSD can return EINVAL.
1061 if not sys.platform.startswith(('freebsd', 'netbsd')):
1062 try:
1063 posix.sched_setscheduler(0, mine, param)
1064 posix.sched_setparam(0, param)
1065 except OSError as e:
1066 if e.errno != errno.EPERM:
1067 raise
Charles-François Natali7b911cb2011-08-21 12:41:43 +02001068 self.assertRaises(OSError, posix.sched_setparam, -1, param)
1069
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001070 self.assertRaises(OSError, posix.sched_setscheduler, -1, mine, param)
1071 self.assertRaises(TypeError, posix.sched_setscheduler, 0, mine, None)
1072 self.assertRaises(TypeError, posix.sched_setparam, 0, 43)
1073 param = posix.sched_param(None)
1074 self.assertRaises(TypeError, posix.sched_setparam, 0, param)
1075 large = 214748364700
1076 param = posix.sched_param(large)
1077 self.assertRaises(OverflowError, posix.sched_setparam, 0, param)
1078 param = posix.sched_param(sched_priority=-large)
1079 self.assertRaises(OverflowError, posix.sched_setparam, 0, param)
1080
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05001081 @unittest.skipUnless(hasattr(posix, "sched_rr_get_interval"), "no function")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001082 def test_sched_rr_get_interval(self):
Benjamin Peterson43234ab2011-08-02 22:19:14 -05001083 try:
1084 interval = posix.sched_rr_get_interval(0)
1085 except OSError as e:
1086 # This likely means that sched_rr_get_interval is only valid for
1087 # processes with the SCHED_RR scheduler in effect.
1088 if e.errno != errno.EINVAL:
1089 raise
1090 self.skipTest("only works on SCHED_RR processes")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001091 self.assertIsInstance(interval, float)
1092 # Reasonable constraints, I think.
1093 self.assertGreaterEqual(interval, 0.)
1094 self.assertLess(interval, 1.)
1095
Benjamin Peterson2740af82011-08-02 17:41:34 -05001096 @requires_sched_affinity
Antoine Pitrou84869872012-08-04 16:16:35 +02001097 def test_sched_getaffinity(self):
1098 mask = posix.sched_getaffinity(0)
1099 self.assertIsInstance(mask, set)
1100 self.assertGreaterEqual(len(mask), 1)
1101 self.assertRaises(OSError, posix.sched_getaffinity, -1)
1102 for cpu in mask:
1103 self.assertIsInstance(cpu, int)
1104 self.assertGreaterEqual(cpu, 0)
1105 self.assertLess(cpu, 1 << 32)
1106
1107 @requires_sched_affinity
1108 def test_sched_setaffinity(self):
1109 mask = posix.sched_getaffinity(0)
1110 if len(mask) > 1:
1111 # Empty masks are forbidden
1112 mask.pop()
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001113 posix.sched_setaffinity(0, mask)
Antoine Pitrou84869872012-08-04 16:16:35 +02001114 self.assertEqual(posix.sched_getaffinity(0), mask)
1115 self.assertRaises(OSError, posix.sched_setaffinity, 0, [])
1116 self.assertRaises(ValueError, posix.sched_setaffinity, 0, [-10])
1117 self.assertRaises(OverflowError, posix.sched_setaffinity, 0, [1<<128])
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001118 self.assertRaises(OSError, posix.sched_setaffinity, -1, mask)
1119
Victor Stinner8b905bd2011-10-25 13:34:04 +02001120 def test_rtld_constants(self):
1121 # check presence of major RTLD_* constants
1122 posix.RTLD_LAZY
1123 posix.RTLD_NOW
1124 posix.RTLD_GLOBAL
1125 posix.RTLD_LOCAL
1126
Jesus Cea60c13dd2012-06-23 02:58:14 +02001127 @unittest.skipUnless(hasattr(os, 'SEEK_HOLE'),
1128 "test needs an OS that reports file holes")
Hynek Schlawackf841e422012-06-24 09:51:46 +02001129 def test_fs_holes(self):
Jesus Cea94363612012-06-22 18:32:07 +02001130 # Even if the filesystem doesn't report holes,
1131 # if the OS supports it the SEEK_* constants
1132 # will be defined and will have a consistent
1133 # behaviour:
1134 # os.SEEK_DATA = current position
1135 # os.SEEK_HOLE = end of file position
Hynek Schlawackf841e422012-06-24 09:51:46 +02001136 with open(support.TESTFN, 'r+b') as fp:
Jesus Cea94363612012-06-22 18:32:07 +02001137 fp.write(b"hello")
1138 fp.flush()
1139 size = fp.tell()
1140 fno = fp.fileno()
Jesus Cead46f7d22012-07-07 14:56:04 +02001141 try :
1142 for i in range(size):
1143 self.assertEqual(i, os.lseek(fno, i, os.SEEK_DATA))
1144 self.assertLessEqual(size, os.lseek(fno, i, os.SEEK_HOLE))
1145 self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_DATA)
1146 self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_HOLE)
1147 except OSError :
1148 # Some OSs claim to support SEEK_HOLE/SEEK_DATA
1149 # but it is not true.
1150 # For instance:
1151 # http://lists.freebsd.org/pipermail/freebsd-amd64/2012-January/014332.html
1152 raise unittest.SkipTest("OSError raised!")
Jesus Cea94363612012-06-22 18:32:07 +02001153
Larry Hastingsb0827312014-02-09 22:05:19 -08001154 def test_path_error2(self):
1155 """
1156 Test functions that call path_error2(), providing two filenames in their exceptions.
1157 """
Victor Stinner047b7ae2014-10-05 17:37:41 +02001158 for name in ("rename", "replace", "link"):
Larry Hastingsb0827312014-02-09 22:05:19 -08001159 function = getattr(os, name, None)
Victor Stinnerbed04a72014-10-05 17:37:59 +02001160 if function is None:
1161 continue
Larry Hastingsb0827312014-02-09 22:05:19 -08001162
Victor Stinnerbed04a72014-10-05 17:37:59 +02001163 for dst in ("noodly2", support.TESTFN):
1164 try:
1165 function('doesnotexistfilename', dst)
1166 except OSError as e:
1167 self.assertIn("'doesnotexistfilename' -> '{}'".format(dst), str(e))
1168 break
1169 else:
1170 self.fail("No valid path_error2() test for os." + name)
Larry Hastingsb0827312014-02-09 22:05:19 -08001171
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001172 def test_path_with_null_character(self):
1173 fn = support.TESTFN
1174 fn_with_NUL = fn + '\0'
1175 self.addCleanup(support.unlink, fn)
1176 support.unlink(fn)
1177 fd = None
1178 try:
1179 with self.assertRaises(TypeError):
1180 fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # raises
1181 finally:
1182 if fd is not None:
1183 os.close(fd)
1184 self.assertFalse(os.path.exists(fn))
1185 self.assertRaises(TypeError, os.mkdir, fn_with_NUL)
1186 self.assertFalse(os.path.exists(fn))
1187 open(fn, 'wb').close()
1188 self.assertRaises(TypeError, os.stat, fn_with_NUL)
1189
1190 def test_path_with_null_byte(self):
1191 fn = os.fsencode(support.TESTFN)
1192 fn_with_NUL = fn + b'\0'
1193 self.addCleanup(support.unlink, fn)
1194 support.unlink(fn)
1195 fd = None
1196 try:
1197 with self.assertRaises(ValueError):
1198 fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # raises
1199 finally:
1200 if fd is not None:
1201 os.close(fd)
1202 self.assertFalse(os.path.exists(fn))
1203 self.assertRaises(ValueError, os.mkdir, fn_with_NUL)
1204 self.assertFalse(os.path.exists(fn))
1205 open(fn, 'wb').close()
1206 self.assertRaises(ValueError, os.stat, fn_with_NUL)
1207
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001208class PosixGroupsTester(unittest.TestCase):
1209
1210 def setUp(self):
1211 if posix.getuid() != 0:
1212 raise unittest.SkipTest("not enough privileges")
1213 if not hasattr(posix, 'getgroups'):
1214 raise unittest.SkipTest("need posix.getgroups")
1215 if sys.platform == 'darwin':
1216 raise unittest.SkipTest("getgroups(2) is broken on OSX")
1217 self.saved_groups = posix.getgroups()
1218
1219 def tearDown(self):
1220 if hasattr(posix, 'setgroups'):
1221 posix.setgroups(self.saved_groups)
1222 elif hasattr(posix, 'initgroups'):
1223 name = pwd.getpwuid(posix.getuid()).pw_name
1224 posix.initgroups(name, self.saved_groups[0])
1225
1226 @unittest.skipUnless(hasattr(posix, 'initgroups'),
1227 "test needs posix.initgroups()")
1228 def test_initgroups(self):
1229 # find missing group
1230
Benjamin Peterson659a6f52014-03-01 19:14:12 -05001231 g = max(self.saved_groups or [0]) + 1
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001232 name = pwd.getpwuid(posix.getuid()).pw_name
1233 posix.initgroups(name, g)
1234 self.assertIn(g, posix.getgroups())
1235
1236 @unittest.skipUnless(hasattr(posix, 'setgroups'),
1237 "test needs posix.setgroups()")
1238 def test_setgroups(self):
Antoine Pitroue5a91012010-09-04 17:32:06 +00001239 for groups in [[0], list(range(16))]:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001240 posix.setgroups(groups)
1241 self.assertListEqual(groups, posix.getgroups())
1242
Neal Norwitze241ce82003-02-17 18:17:05 +00001243def test_main():
Antoine Pitrou68c95922011-03-20 17:33:57 +01001244 try:
1245 support.run_unittest(PosixTester, PosixGroupsTester)
1246 finally:
1247 support.reap_children()
Neal Norwitze241ce82003-02-17 18:17:05 +00001248
1249if __name__ == '__main__':
1250 test_main()