blob: 2a59c381749c80dc469179f547bb691ca97e29fe [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 Nataliab2d58e2012-04-17 19:48:35 +020012import platform
Christian Heimesd5e2b6f2008-03-19 21:50:51 +000013import pwd
Benjamin Petersondcf97b92008-07-02 17:30:14 +000014import shutil
Benjamin Peterson052a02b2010-08-17 01:27:09 +000015import stat
Ned Deilyba2eab22011-07-26 13:53:55 -070016import tempfile
Neal Norwitze241ce82003-02-17 18:17:05 +000017import unittest
18import warnings
R. David Murraya21e4ca2009-03-31 23:16:50 +000019
Ned Deilyba2eab22011-07-26 13:53:55 -070020_DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(),
21 support.TESTFN + '-dummy-symlink')
Neal Norwitze241ce82003-02-17 18:17:05 +000022
23class PosixTester(unittest.TestCase):
24
25 def setUp(self):
26 # create empty file
Benjamin Petersonee8712c2008-05-20 21:35:26 +000027 fp = open(support.TESTFN, 'w+')
Neal Norwitze241ce82003-02-17 18:17:05 +000028 fp.close()
Ned Deily3eb67d52011-06-28 00:00:28 -070029 self.teardown_files = [ support.TESTFN ]
Brett Cannonc8d502e2010-03-20 21:53:28 +000030 self._warnings_manager = support.check_warnings()
31 self._warnings_manager.__enter__()
32 warnings.filterwarnings('ignore', '.* potential security risk .*',
33 RuntimeWarning)
Neal Norwitze241ce82003-02-17 18:17:05 +000034
35 def tearDown(self):
Ned Deily3eb67d52011-06-28 00:00:28 -070036 for teardown_file in self.teardown_files:
37 support.unlink(teardown_file)
Brett Cannonc8d502e2010-03-20 21:53:28 +000038 self._warnings_manager.__exit__(None, None, None)
Neal Norwitze241ce82003-02-17 18:17:05 +000039
40 def testNoArgFunctions(self):
41 # test posix functions which take no arguments and have
42 # no side-effects which we need to cleanup (e.g., fork, wait, abort)
Guido van Rossumf0af3e32008-10-02 18:55:37 +000043 NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdb", "uname",
Guido van Rossum687b9c02007-10-25 23:18:51 +000044 "times", "getloadavg",
Neal Norwitze241ce82003-02-17 18:17:05 +000045 "getegid", "geteuid", "getgid", "getgroups",
Ross Lagerwall7807c352011-03-17 20:20:30 +020046 "getpid", "getpgrp", "getppid", "getuid", "sync",
Neal Norwitze241ce82003-02-17 18:17:05 +000047 ]
Neal Norwitz71b13e82003-02-23 22:12:24 +000048
Neal Norwitze241ce82003-02-17 18:17:05 +000049 for name in NO_ARG_FUNCTIONS:
50 posix_func = getattr(posix, name, None)
51 if posix_func is not None:
52 posix_func()
Neal Norwitz2ff51a82003-02-17 22:40:31 +000053 self.assertRaises(TypeError, posix_func, 1)
Neal Norwitze241ce82003-02-17 18:17:05 +000054
Serhiy Storchaka43767632013-11-03 21:31:38 +020055 @unittest.skipUnless(hasattr(posix, 'getresuid'),
56 'test needs posix.getresuid()')
57 def test_getresuid(self):
58 user_ids = posix.getresuid()
59 self.assertEqual(len(user_ids), 3)
60 for val in user_ids:
61 self.assertGreaterEqual(val, 0)
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000062
Serhiy Storchaka43767632013-11-03 21:31:38 +020063 @unittest.skipUnless(hasattr(posix, 'getresgid'),
64 'test needs posix.getresgid()')
65 def test_getresgid(self):
66 group_ids = posix.getresgid()
67 self.assertEqual(len(group_ids), 3)
68 for val in group_ids:
69 self.assertGreaterEqual(val, 0)
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000070
Serhiy Storchaka43767632013-11-03 21:31:38 +020071 @unittest.skipUnless(hasattr(posix, 'setresuid'),
72 'test needs posix.setresuid()')
73 def test_setresuid(self):
74 current_user_ids = posix.getresuid()
75 self.assertIsNone(posix.setresuid(*current_user_ids))
76 # -1 means don't change that value.
77 self.assertIsNone(posix.setresuid(-1, -1, -1))
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000078
Serhiy Storchaka43767632013-11-03 21:31:38 +020079 @unittest.skipUnless(hasattr(posix, 'setresuid'),
80 'test needs posix.setresuid()')
81 def test_setresuid_exception(self):
82 # Don't do this test if someone is silly enough to run us as root.
83 current_user_ids = posix.getresuid()
84 if 0 not in current_user_ids:
85 new_user_ids = (current_user_ids[0]+1, -1, -1)
86 self.assertRaises(OSError, posix.setresuid, *new_user_ids)
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000087
Serhiy Storchaka43767632013-11-03 21:31:38 +020088 @unittest.skipUnless(hasattr(posix, 'setresgid'),
89 'test needs posix.setresgid()')
90 def test_setresgid(self):
91 current_group_ids = posix.getresgid()
92 self.assertIsNone(posix.setresgid(*current_group_ids))
93 # -1 means don't change that value.
94 self.assertIsNone(posix.setresgid(-1, -1, -1))
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000095
Serhiy Storchaka43767632013-11-03 21:31:38 +020096 @unittest.skipUnless(hasattr(posix, 'setresgid'),
97 'test needs posix.setresgid()')
98 def test_setresgid_exception(self):
99 # Don't do this test if someone is silly enough to run us as root.
100 current_group_ids = posix.getresgid()
101 if 0 not in current_group_ids:
102 new_group_ids = (current_group_ids[0]+1, -1, -1)
103 self.assertRaises(OSError, posix.setresgid, *new_group_ids)
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000104
Antoine Pitroub7572f02009-12-02 20:46:48 +0000105 @unittest.skipUnless(hasattr(posix, 'initgroups'),
106 "test needs os.initgroups()")
107 def test_initgroups(self):
108 # It takes a string and an integer; check that it raises a TypeError
109 # for other argument lists.
110 self.assertRaises(TypeError, posix.initgroups)
111 self.assertRaises(TypeError, posix.initgroups, None)
112 self.assertRaises(TypeError, posix.initgroups, 3, "foo")
113 self.assertRaises(TypeError, posix.initgroups, "foo", 3, object())
114
115 # If a non-privileged user invokes it, it should fail with OSError
116 # EPERM.
117 if os.getuid() != 0:
Charles-François Natalie8a255a2012-05-02 20:01:38 +0200118 try:
119 name = pwd.getpwuid(posix.getuid()).pw_name
120 except KeyError:
121 # the current UID may not have a pwd entry
122 raise unittest.SkipTest("need a pwd entry")
Antoine Pitroub7572f02009-12-02 20:46:48 +0000123 try:
124 posix.initgroups(name, 13)
125 except OSError as e:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000126 self.assertEqual(e.errno, errno.EPERM)
Antoine Pitroub7572f02009-12-02 20:46:48 +0000127 else:
128 self.fail("Expected OSError to be raised by initgroups")
129
Serhiy Storchaka43767632013-11-03 21:31:38 +0200130 @unittest.skipUnless(hasattr(posix, 'statvfs'),
131 'test needs posix.statvfs()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000132 def test_statvfs(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200133 self.assertTrue(posix.statvfs(os.curdir))
Neal Norwitze241ce82003-02-17 18:17:05 +0000134
Serhiy Storchaka43767632013-11-03 21:31:38 +0200135 @unittest.skipUnless(hasattr(posix, 'fstatvfs'),
136 'test needs posix.fstatvfs()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000137 def test_fstatvfs(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200138 fp = open(support.TESTFN)
139 try:
140 self.assertTrue(posix.fstatvfs(fp.fileno()))
141 self.assertTrue(posix.statvfs(fp.fileno()))
142 finally:
143 fp.close()
Neal Norwitze241ce82003-02-17 18:17:05 +0000144
Serhiy Storchaka43767632013-11-03 21:31:38 +0200145 @unittest.skipUnless(hasattr(posix, 'ftruncate'),
146 'test needs posix.ftruncate()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000147 def test_ftruncate(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200148 fp = open(support.TESTFN, 'w+')
149 try:
150 # we need to have some data to truncate
151 fp.write('test')
152 fp.flush()
153 posix.ftruncate(fp.fileno(), 0)
154 finally:
155 fp.close()
Neal Norwitze241ce82003-02-17 18:17:05 +0000156
Ross Lagerwall7807c352011-03-17 20:20:30 +0200157 @unittest.skipUnless(hasattr(posix, 'truncate'), "test needs posix.truncate()")
158 def test_truncate(self):
159 with open(support.TESTFN, 'w') as fp:
160 fp.write('test')
161 fp.flush()
162 posix.truncate(support.TESTFN, 0)
163
Larry Hastings9cf065c2012-06-22 16:30:09 -0700164 @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 +0200165 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
Ross Lagerwalldedf6cf2011-03-20 18:27:05 +0200166 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
Ross Lagerwall7807c352011-03-17 20:20:30 +0200167 def test_fexecve(self):
168 fp = os.open(sys.executable, os.O_RDONLY)
169 try:
170 pid = os.fork()
171 if pid == 0:
172 os.chdir(os.path.split(sys.executable)[0])
Larry Hastings9cf065c2012-06-22 16:30:09 -0700173 posix.execve(fp, [sys.executable, '-c', 'pass'], os.environ)
Ross Lagerwall7807c352011-03-17 20:20:30 +0200174 else:
Ross Lagerwalldedf6cf2011-03-20 18:27:05 +0200175 self.assertEqual(os.waitpid(pid, 0), (pid, 0))
Ross Lagerwall7807c352011-03-17 20:20:30 +0200176 finally:
177 os.close(fp)
178
179 @unittest.skipUnless(hasattr(posix, 'waitid'), "test needs posix.waitid()")
180 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
181 def test_waitid(self):
182 pid = os.fork()
183 if pid == 0:
184 os.chdir(os.path.split(sys.executable)[0])
185 posix.execve(sys.executable, [sys.executable, '-c', 'pass'], os.environ)
186 else:
187 res = posix.waitid(posix.P_PID, pid, posix.WEXITED)
188 self.assertEqual(pid, res.si_pid)
189
190 @unittest.skipUnless(hasattr(posix, 'lockf'), "test needs posix.lockf()")
191 def test_lockf(self):
192 fd = os.open(support.TESTFN, os.O_WRONLY | os.O_CREAT)
193 try:
194 os.write(fd, b'test')
195 os.lseek(fd, 0, os.SEEK_SET)
196 posix.lockf(fd, posix.F_LOCK, 4)
197 # section is locked
198 posix.lockf(fd, posix.F_ULOCK, 4)
199 finally:
200 os.close(fd)
201
202 @unittest.skipUnless(hasattr(posix, 'pread'), "test needs posix.pread()")
203 def test_pread(self):
204 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
205 try:
206 os.write(fd, b'test')
207 os.lseek(fd, 0, os.SEEK_SET)
208 self.assertEqual(b'es', posix.pread(fd, 2, 1))
Florent Xiclunae41f0de2011-11-11 19:39:25 +0100209 # the first pread() shouldn't disturb the file offset
Ross Lagerwall7807c352011-03-17 20:20:30 +0200210 self.assertEqual(b'te', posix.read(fd, 2))
211 finally:
212 os.close(fd)
213
214 @unittest.skipUnless(hasattr(posix, 'pwrite'), "test needs posix.pwrite()")
215 def test_pwrite(self):
216 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
217 try:
218 os.write(fd, b'test')
219 os.lseek(fd, 0, os.SEEK_SET)
220 posix.pwrite(fd, b'xx', 1)
221 self.assertEqual(b'txxt', posix.read(fd, 4))
222 finally:
223 os.close(fd)
224
225 @unittest.skipUnless(hasattr(posix, 'posix_fallocate'),
226 "test needs posix.posix_fallocate()")
227 def test_posix_fallocate(self):
228 fd = os.open(support.TESTFN, os.O_WRONLY | os.O_CREAT)
229 try:
230 posix.posix_fallocate(fd, 0, 10)
231 except OSError as inst:
232 # issue10812, ZFS doesn't appear to support posix_fallocate,
233 # so skip Solaris-based since they are likely to have ZFS.
234 if inst.errno != errno.EINVAL or not sys.platform.startswith("sunos"):
235 raise
236 finally:
237 os.close(fd)
238
239 @unittest.skipUnless(hasattr(posix, 'posix_fadvise'),
240 "test needs posix.posix_fadvise()")
241 def test_posix_fadvise(self):
242 fd = os.open(support.TESTFN, os.O_RDONLY)
243 try:
244 posix.posix_fadvise(fd, 0, 0, posix.POSIX_FADV_WILLNEED)
245 finally:
246 os.close(fd)
247
Larry Hastings9cf065c2012-06-22 16:30:09 -0700248 @unittest.skipUnless(os.utime in os.supports_fd, "test needs fd support in os.utime")
249 def test_utime_with_fd(self):
Ross Lagerwall7807c352011-03-17 20:20:30 +0200250 now = time.time()
251 fd = os.open(support.TESTFN, os.O_RDONLY)
252 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700253 posix.utime(fd)
254 posix.utime(fd, None)
255 self.assertRaises(TypeError, posix.utime, fd, (None, None))
256 self.assertRaises(TypeError, posix.utime, fd, (now, None))
257 self.assertRaises(TypeError, posix.utime, fd, (None, now))
258 posix.utime(fd, (int(now), int(now)))
259 posix.utime(fd, (now, now))
260 self.assertRaises(ValueError, posix.utime, fd, (now, now), ns=(now, now))
261 self.assertRaises(ValueError, posix.utime, fd, (now, 0), ns=(None, None))
262 self.assertRaises(ValueError, posix.utime, fd, (None, None), ns=(now, 0))
263 posix.utime(fd, (int(now), int((now - int(now)) * 1e9)))
264 posix.utime(fd, ns=(int(now), int((now - int(now)) * 1e9)))
265
Ross Lagerwall7807c352011-03-17 20:20:30 +0200266 finally:
267 os.close(fd)
268
Larry Hastings9cf065c2012-06-22 16:30:09 -0700269 @unittest.skipUnless(os.utime in os.supports_follow_symlinks, "test needs follow_symlinks support in os.utime")
270 def test_utime_nofollow_symlinks(self):
Ross Lagerwall7807c352011-03-17 20:20:30 +0200271 now = time.time()
Larry Hastings9cf065c2012-06-22 16:30:09 -0700272 posix.utime(support.TESTFN, None, follow_symlinks=False)
273 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None), follow_symlinks=False)
274 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None), follow_symlinks=False)
275 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now), follow_symlinks=False)
276 posix.utime(support.TESTFN, (int(now), int(now)), follow_symlinks=False)
277 posix.utime(support.TESTFN, (now, now), follow_symlinks=False)
278 posix.utime(support.TESTFN, follow_symlinks=False)
Ross Lagerwall7807c352011-03-17 20:20:30 +0200279
280 @unittest.skipUnless(hasattr(posix, 'writev'), "test needs posix.writev()")
281 def test_writev(self):
282 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
283 try:
Victor Stinner57ddf782014-01-08 15:21:28 +0100284 n = os.writev(fd, (b'test1', b'tt2', b't3'))
285 self.assertEqual(n, 10)
286
Ross Lagerwall7807c352011-03-17 20:20:30 +0200287 os.lseek(fd, 0, os.SEEK_SET)
288 self.assertEqual(b'test1tt2t3', posix.read(fd, 10))
Victor Stinner57ddf782014-01-08 15:21:28 +0100289
290 # Issue #20113: empty list of buffers should not crash
Victor Stinnercd5ca6a2014-01-08 16:01:31 +0100291 try:
292 size = posix.writev(fd, [])
293 except OSError:
294 # writev(fd, []) raises OSError(22, "Invalid argument")
295 # on OpenIndiana
296 pass
297 else:
298 self.assertEqual(size, 0)
Ross Lagerwall7807c352011-03-17 20:20:30 +0200299 finally:
300 os.close(fd)
301
302 @unittest.skipUnless(hasattr(posix, 'readv'), "test needs posix.readv()")
303 def test_readv(self):
304 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
305 try:
306 os.write(fd, b'test1tt2t3')
307 os.lseek(fd, 0, os.SEEK_SET)
308 buf = [bytearray(i) for i in [5, 3, 2]]
309 self.assertEqual(posix.readv(fd, buf), 10)
310 self.assertEqual([b'test1', b'tt2', b't3'], [bytes(i) for i in buf])
Victor Stinner57ddf782014-01-08 15:21:28 +0100311
312 # Issue #20113: empty list of buffers should not crash
Victor Stinnercd5ca6a2014-01-08 16:01:31 +0100313 try:
314 size = posix.readv(fd, [])
315 except OSError:
316 # readv(fd, []) raises OSError(22, "Invalid argument")
317 # on OpenIndiana
318 pass
319 else:
320 self.assertEqual(size, 0)
Ross Lagerwall7807c352011-03-17 20:20:30 +0200321 finally:
322 os.close(fd)
323
Serhiy Storchaka43767632013-11-03 21:31:38 +0200324 @unittest.skipUnless(hasattr(posix, 'dup'),
325 'test needs posix.dup()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000326 def test_dup(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200327 fp = open(support.TESTFN)
328 try:
329 fd = posix.dup(fp.fileno())
330 self.assertIsInstance(fd, int)
331 os.close(fd)
332 finally:
333 fp.close()
Neal Norwitze241ce82003-02-17 18:17:05 +0000334
Serhiy Storchaka43767632013-11-03 21:31:38 +0200335 @unittest.skipUnless(hasattr(posix, 'confstr'),
336 'test needs posix.confstr()')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000337 def test_confstr(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200338 self.assertRaises(ValueError, posix.confstr, "CS_garbage")
339 self.assertEqual(len(posix.confstr("CS_PATH")) > 0, True)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000340
Serhiy Storchaka43767632013-11-03 21:31:38 +0200341 @unittest.skipUnless(hasattr(posix, 'dup2'),
342 'test needs posix.dup2()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000343 def test_dup2(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200344 fp1 = open(support.TESTFN)
345 fp2 = open(support.TESTFN)
346 try:
347 posix.dup2(fp1.fileno(), fp2.fileno())
348 finally:
349 fp1.close()
350 fp2.close()
Neal Norwitze241ce82003-02-17 18:17:05 +0000351
Charles-François Natali1e045b12011-05-22 20:42:32 +0200352 @unittest.skipUnless(hasattr(os, 'O_CLOEXEC'), "needs os.O_CLOEXEC")
Charles-François Natali239bb962011-06-03 12:55:15 +0200353 @support.requires_linux_version(2, 6, 23)
Charles-François Natali1e045b12011-05-22 20:42:32 +0200354 def test_oscloexec(self):
355 fd = os.open(support.TESTFN, os.O_RDONLY|os.O_CLOEXEC)
356 self.addCleanup(os.close, fd)
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200357 self.assertFalse(os.get_inheritable(fd))
Charles-François Natali1e045b12011-05-22 20:42:32 +0200358
Serhiy Storchaka43767632013-11-03 21:31:38 +0200359 @unittest.skipUnless(hasattr(posix, 'O_EXLOCK'),
360 'test needs posix.O_EXLOCK')
Skip Montanaro98470002005-06-17 01:14:49 +0000361 def test_osexlock(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200362 fd = os.open(support.TESTFN,
363 os.O_WRONLY|os.O_EXLOCK|os.O_CREAT)
364 self.assertRaises(OSError, os.open, support.TESTFN,
365 os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
366 os.close(fd)
367
368 if hasattr(posix, "O_SHLOCK"):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000369 fd = os.open(support.TESTFN,
Serhiy Storchaka43767632013-11-03 21:31:38 +0200370 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000371 self.assertRaises(OSError, os.open, support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000372 os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
373 os.close(fd)
374
Serhiy Storchaka43767632013-11-03 21:31:38 +0200375 @unittest.skipUnless(hasattr(posix, 'O_SHLOCK'),
376 'test needs posix.O_SHLOCK')
Skip Montanaro98470002005-06-17 01:14:49 +0000377 def test_osshlock(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200378 fd1 = os.open(support.TESTFN,
379 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
380 fd2 = os.open(support.TESTFN,
381 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
382 os.close(fd2)
383 os.close(fd1)
384
385 if hasattr(posix, "O_EXLOCK"):
386 fd = os.open(support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000387 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
Serhiy Storchaka43767632013-11-03 21:31:38 +0200388 self.assertRaises(OSError, os.open, support.TESTFN,
389 os.O_RDONLY|os.O_EXLOCK|os.O_NONBLOCK)
390 os.close(fd)
Skip Montanaro98470002005-06-17 01:14:49 +0000391
Serhiy Storchaka43767632013-11-03 21:31:38 +0200392 @unittest.skipUnless(hasattr(posix, 'fstat'),
393 'test needs posix.fstat()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000394 def test_fstat(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200395 fp = open(support.TESTFN)
396 try:
397 self.assertTrue(posix.fstat(fp.fileno()))
398 self.assertTrue(posix.stat(fp.fileno()))
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200399
Serhiy Storchaka43767632013-11-03 21:31:38 +0200400 self.assertRaisesRegex(TypeError,
401 'should be string, bytes or integer, not',
402 posix.stat, float(fp.fileno()))
403 finally:
404 fp.close()
Neal Norwitze241ce82003-02-17 18:17:05 +0000405
Serhiy Storchaka43767632013-11-03 21:31:38 +0200406 @unittest.skipUnless(hasattr(posix, 'stat'),
407 'test needs posix.stat()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000408 def test_stat(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200409 self.assertTrue(posix.stat(support.TESTFN))
410 self.assertTrue(posix.stat(os.fsencode(support.TESTFN)))
411 self.assertTrue(posix.stat(bytearray(os.fsencode(support.TESTFN))))
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200412
Serhiy Storchaka43767632013-11-03 21:31:38 +0200413 self.assertRaisesRegex(TypeError,
414 'can\'t specify None for path argument',
415 posix.stat, None)
416 self.assertRaisesRegex(TypeError,
417 'should be string, bytes or integer, not',
418 posix.stat, list(support.TESTFN))
419 self.assertRaisesRegex(TypeError,
420 'should be string, bytes or integer, not',
421 posix.stat, list(os.fsencode(support.TESTFN)))
Neal Norwitze241ce82003-02-17 18:17:05 +0000422
Benjamin Peterson052a02b2010-08-17 01:27:09 +0000423 @unittest.skipUnless(hasattr(posix, 'mkfifo'), "don't have mkfifo()")
424 def test_mkfifo(self):
425 support.unlink(support.TESTFN)
426 posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR)
427 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
428
429 @unittest.skipUnless(hasattr(posix, 'mknod') and hasattr(stat, 'S_IFIFO'),
430 "don't have mknod()/S_IFIFO")
431 def test_mknod(self):
432 # Test using mknod() to create a FIFO (the only use specified
433 # by POSIX).
434 support.unlink(support.TESTFN)
435 mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
436 try:
437 posix.mknod(support.TESTFN, mode, 0)
438 except OSError as e:
439 # Some old systems don't allow unprivileged users to use
440 # mknod(), or only support creating device nodes.
441 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
442 else:
443 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
444
Martin Panterbf19d162015-09-09 01:01:13 +0000445 # Keyword arguments are also supported
446 support.unlink(support.TESTFN)
447 try:
448 posix.mknod(path=support.TESTFN, mode=mode, device=0,
449 dir_fd=None)
450 except OSError as e:
451 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
452
Serhiy Storchaka16b2e4f2015-04-20 09:22:13 +0300453 @unittest.skipUnless(hasattr(posix, 'stat'), 'test needs posix.stat()')
454 @unittest.skipUnless(hasattr(posix, 'makedev'), 'test needs posix.makedev()')
455 def test_makedev(self):
456 st = posix.stat(support.TESTFN)
457 dev = st.st_dev
458 self.assertIsInstance(dev, int)
459 self.assertGreaterEqual(dev, 0)
460
461 major = posix.major(dev)
462 self.assertIsInstance(major, int)
463 self.assertGreaterEqual(major, 0)
464 self.assertEqual(posix.major(dev), major)
465 self.assertRaises(TypeError, posix.major, float(dev))
466 self.assertRaises(TypeError, posix.major)
467 self.assertRaises((ValueError, OverflowError), posix.major, -1)
468
469 minor = posix.minor(dev)
470 self.assertIsInstance(minor, int)
471 self.assertGreaterEqual(minor, 0)
472 self.assertEqual(posix.minor(dev), minor)
473 self.assertRaises(TypeError, posix.minor, float(dev))
474 self.assertRaises(TypeError, posix.minor)
475 self.assertRaises((ValueError, OverflowError), posix.minor, -1)
476
477 self.assertEqual(posix.makedev(major, minor), dev)
478 self.assertRaises(TypeError, posix.makedev, float(major), minor)
479 self.assertRaises(TypeError, posix.makedev, major, float(minor))
480 self.assertRaises(TypeError, posix.makedev, major)
481 self.assertRaises(TypeError, posix.makedev)
482
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200483 def _test_all_chown_common(self, chown_func, first_param, stat_func):
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000484 """Common code for chown, fchown and lchown tests."""
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200485 def check_stat(uid, gid):
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200486 if stat_func is not None:
487 stat = stat_func(first_param)
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200488 self.assertEqual(stat.st_uid, uid)
489 self.assertEqual(stat.st_gid, gid)
490 uid = os.getuid()
491 gid = os.getgid()
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200492 # test a successful chown call
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200493 chown_func(first_param, uid, gid)
494 check_stat(uid, gid)
495 chown_func(first_param, -1, gid)
496 check_stat(uid, gid)
497 chown_func(first_param, uid, -1)
498 check_stat(uid, gid)
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200499
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200500 if uid == 0:
501 # Try an amusingly large uid/gid to make sure we handle
502 # large unsigned values. (chown lets you use any
503 # uid/gid you like, even if they aren't defined.)
504 #
505 # This problem keeps coming up:
506 # http://bugs.python.org/issue1747858
507 # http://bugs.python.org/issue4591
508 # http://bugs.python.org/issue15301
509 # Hopefully the fix in 4591 fixes it for good!
510 #
511 # This part of the test only runs when run as root.
512 # Only scary people run their tests as root.
513
514 big_value = 2**31
515 chown_func(first_param, big_value, big_value)
516 check_stat(big_value, big_value)
517 chown_func(first_param, -1, -1)
518 check_stat(big_value, big_value)
519 chown_func(first_param, uid, gid)
520 check_stat(uid, gid)
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200521 elif platform.system() in ('HP-UX', 'SunOS'):
522 # HP-UX and Solaris can allow a non-root user to chown() to root
523 # (issue #5113)
524 raise unittest.SkipTest("Skipping because of non-standard chown() "
525 "behavior")
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000526 else:
527 # non-root cannot chown to root, raises OSError
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200528 self.assertRaises(OSError, chown_func, first_param, 0, 0)
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200529 check_stat(uid, gid)
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200530 self.assertRaises(OSError, chown_func, first_param, 0, -1)
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200531 check_stat(uid, gid)
Serhiy Storchakaa2964b32013-02-21 14:34:36 +0200532 if 0 not in os.getgroups():
Serhiy Storchakab3d62ce2013-02-20 19:48:22 +0200533 self.assertRaises(OSError, chown_func, first_param, -1, 0)
534 check_stat(uid, gid)
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200535 # test illegal types
536 for t in str, float:
537 self.assertRaises(TypeError, chown_func, first_param, t(uid), gid)
538 check_stat(uid, gid)
539 self.assertRaises(TypeError, chown_func, first_param, uid, t(gid))
540 check_stat(uid, gid)
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000541
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000542 @unittest.skipUnless(hasattr(posix, 'chown'), "test needs os.chown()")
543 def test_chown(self):
544 # raise an OSError if the file does not exist
545 os.unlink(support.TESTFN)
546 self.assertRaises(OSError, posix.chown, support.TESTFN, -1, -1)
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000547
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000548 # re-create the file
Victor Stinnerbf816222011-06-30 23:25:47 +0200549 support.create_empty_file(support.TESTFN)
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200550 self._test_all_chown_common(posix.chown, support.TESTFN,
551 getattr(posix, 'stat', None))
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000552
553 @unittest.skipUnless(hasattr(posix, 'fchown'), "test needs os.fchown()")
554 def test_fchown(self):
555 os.unlink(support.TESTFN)
556
557 # re-create the file
558 test_file = open(support.TESTFN, 'w')
559 try:
560 fd = test_file.fileno()
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200561 self._test_all_chown_common(posix.fchown, fd,
562 getattr(posix, 'fstat', None))
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000563 finally:
564 test_file.close()
565
566 @unittest.skipUnless(hasattr(posix, 'lchown'), "test needs os.lchown()")
567 def test_lchown(self):
568 os.unlink(support.TESTFN)
569 # create a symlink
Ned Deily3eb67d52011-06-28 00:00:28 -0700570 os.symlink(_DUMMY_SYMLINK, support.TESTFN)
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200571 self._test_all_chown_common(posix.lchown, support.TESTFN,
572 getattr(posix, 'lstat', None))
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000573
Serhiy Storchaka43767632013-11-03 21:31:38 +0200574 @unittest.skipUnless(hasattr(posix, 'chdir'), 'test needs posix.chdir()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000575 def test_chdir(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200576 posix.chdir(os.curdir)
577 self.assertRaises(OSError, posix.chdir, support.TESTFN)
Neal Norwitze241ce82003-02-17 18:17:05 +0000578
Martin v. Löwisc9e1c7d2010-07-23 12:16:41 +0000579 def test_listdir(self):
Larry Hastingsfdaea062012-06-25 04:42:23 -0700580 self.assertTrue(support.TESTFN in posix.listdir(os.curdir))
Martin v. Löwisc9e1c7d2010-07-23 12:16:41 +0000581
582 def test_listdir_default(self):
Larry Hastingsfdaea062012-06-25 04:42:23 -0700583 # When listdir is called without argument,
584 # it's the same as listdir(os.curdir).
585 self.assertTrue(support.TESTFN in posix.listdir())
Neal Norwitze241ce82003-02-17 18:17:05 +0000586
Larry Hastingsfdaea062012-06-25 04:42:23 -0700587 def test_listdir_bytes(self):
588 # When listdir is called with a bytes object,
589 # the returned strings are of type bytes.
590 self.assertTrue(os.fsencode(support.TESTFN) in posix.listdir(b'.'))
591
592 @unittest.skipUnless(posix.listdir in os.supports_fd,
593 "test needs fd support for posix.listdir()")
594 def test_listdir_fd(self):
Antoine Pitrou8250e232011-02-25 23:41:16 +0000595 f = posix.open(posix.getcwd(), posix.O_RDONLY)
Charles-François Natali7546ad32012-01-08 18:34:06 +0100596 self.addCleanup(posix.close, f)
Antoine Pitrou8250e232011-02-25 23:41:16 +0000597 self.assertEqual(
598 sorted(posix.listdir('.')),
Larry Hastings9cf065c2012-06-22 16:30:09 -0700599 sorted(posix.listdir(f))
Antoine Pitrou8250e232011-02-25 23:41:16 +0000600 )
Charles-François Natali7546ad32012-01-08 18:34:06 +0100601 # Check that the fd offset was reset (issue #13739)
Charles-François Natali7546ad32012-01-08 18:34:06 +0100602 self.assertEqual(
603 sorted(posix.listdir('.')),
Larry Hastings9cf065c2012-06-22 16:30:09 -0700604 sorted(posix.listdir(f))
Charles-François Natali7546ad32012-01-08 18:34:06 +0100605 )
Antoine Pitrou8250e232011-02-25 23:41:16 +0000606
Serhiy Storchaka43767632013-11-03 21:31:38 +0200607 @unittest.skipUnless(hasattr(posix, 'access'), 'test needs posix.access()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000608 def test_access(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200609 self.assertTrue(posix.access(support.TESTFN, os.R_OK))
Neal Norwitze241ce82003-02-17 18:17:05 +0000610
Serhiy Storchaka43767632013-11-03 21:31:38 +0200611 @unittest.skipUnless(hasattr(posix, 'umask'), 'test needs posix.umask()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000612 def test_umask(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200613 old_mask = posix.umask(0)
614 self.assertIsInstance(old_mask, int)
615 posix.umask(old_mask)
Neal Norwitze241ce82003-02-17 18:17:05 +0000616
Serhiy Storchaka43767632013-11-03 21:31:38 +0200617 @unittest.skipUnless(hasattr(posix, 'strerror'),
618 'test needs posix.strerror()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000619 def test_strerror(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200620 self.assertTrue(posix.strerror(0))
Neal Norwitze241ce82003-02-17 18:17:05 +0000621
Serhiy Storchaka43767632013-11-03 21:31:38 +0200622 @unittest.skipUnless(hasattr(posix, 'pipe'), 'test needs posix.pipe()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000623 def test_pipe(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200624 reader, writer = posix.pipe()
625 os.close(reader)
626 os.close(writer)
Neal Norwitze241ce82003-02-17 18:17:05 +0000627
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200628 @unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()")
Charles-François Natali239bb962011-06-03 12:55:15 +0200629 @support.requires_linux_version(2, 6, 27)
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200630 def test_pipe2(self):
631 self.assertRaises(TypeError, os.pipe2, 'DEADBEEF')
632 self.assertRaises(TypeError, os.pipe2, 0, 0)
633
Charles-François Natali368f34b2011-06-06 19:49:47 +0200634 # try calling with flags = 0, like os.pipe()
635 r, w = os.pipe2(0)
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200636 os.close(r)
637 os.close(w)
638
639 # test flags
640 r, w = os.pipe2(os.O_CLOEXEC|os.O_NONBLOCK)
641 self.addCleanup(os.close, r)
642 self.addCleanup(os.close, w)
Victor Stinnerbff989e2013-08-28 12:25:40 +0200643 self.assertFalse(os.get_inheritable(r))
644 self.assertFalse(os.get_inheritable(w))
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200645 self.assertFalse(os.get_blocking(r))
646 self.assertFalse(os.get_blocking(w))
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200647 # try reading from an empty pipe: this should fail, not block
648 self.assertRaises(OSError, os.read, r, 1)
649 # try a write big enough to fill-up the pipe: this should either
650 # fail or perform a partial write, not block
651 try:
652 os.write(w, b'x' * support.PIPE_MAX_SIZE)
653 except OSError:
654 pass
655
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200656 @support.cpython_only
657 @unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()")
658 @support.requires_linux_version(2, 6, 27)
659 def test_pipe2_c_limits(self):
Serhiy Storchaka78980432013-01-15 01:12:17 +0200660 # Issue 15989
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200661 import _testcapi
Serhiy Storchaka78980432013-01-15 01:12:17 +0200662 self.assertRaises(OverflowError, os.pipe2, _testcapi.INT_MAX + 1)
663 self.assertRaises(OverflowError, os.pipe2, _testcapi.UINT_MAX + 1)
664
Serhiy Storchaka43767632013-11-03 21:31:38 +0200665 @unittest.skipUnless(hasattr(posix, 'utime'), 'test needs posix.utime()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000666 def test_utime(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200667 now = time.time()
668 posix.utime(support.TESTFN, None)
669 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None))
670 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None))
671 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now))
672 posix.utime(support.TESTFN, (int(now), int(now)))
673 posix.utime(support.TESTFN, (now, now))
Neal Norwitze241ce82003-02-17 18:17:05 +0000674
Larry Hastings9cf065c2012-06-22 16:30:09 -0700675 def _test_chflags_regular_file(self, chflags_func, target_file, **kwargs):
Ned Deily3eb67d52011-06-28 00:00:28 -0700676 st = os.stat(target_file)
677 self.assertTrue(hasattr(st, 'st_flags'))
Trent Nelson75959cf2012-08-21 23:59:31 +0000678
679 # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
680 flags = st.st_flags | stat.UF_IMMUTABLE
681 try:
682 chflags_func(target_file, flags, **kwargs)
683 except OSError as err:
684 if err.errno != errno.EOPNOTSUPP:
685 raise
686 msg = 'chflag UF_IMMUTABLE not supported by underlying fs'
687 self.skipTest(msg)
688
Ned Deily3eb67d52011-06-28 00:00:28 -0700689 try:
690 new_st = os.stat(target_file)
691 self.assertEqual(st.st_flags | stat.UF_IMMUTABLE, new_st.st_flags)
692 try:
693 fd = open(target_file, 'w+')
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200694 except OSError as e:
Ned Deily3eb67d52011-06-28 00:00:28 -0700695 self.assertEqual(e.errno, errno.EPERM)
696 finally:
697 posix.chflags(target_file, st.st_flags)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000698
Ned Deily3eb67d52011-06-28 00:00:28 -0700699 @unittest.skipUnless(hasattr(posix, 'chflags'), 'test needs os.chflags()')
700 def test_chflags(self):
701 self._test_chflags_regular_file(posix.chflags, support.TESTFN)
702
703 @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
704 def test_lchflags_regular_file(self):
705 self._test_chflags_regular_file(posix.lchflags, support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700706 self._test_chflags_regular_file(posix.chflags, support.TESTFN, follow_symlinks=False)
Ned Deily3eb67d52011-06-28 00:00:28 -0700707
708 @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
709 def test_lchflags_symlink(self):
710 testfn_st = os.stat(support.TESTFN)
711
712 self.assertTrue(hasattr(testfn_st, 'st_flags'))
713
714 os.symlink(support.TESTFN, _DUMMY_SYMLINK)
715 self.teardown_files.append(_DUMMY_SYMLINK)
716 dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
717
Larry Hastings9cf065c2012-06-22 16:30:09 -0700718 def chflags_nofollow(path, flags):
719 return posix.chflags(path, flags, follow_symlinks=False)
Ned Deily3eb67d52011-06-28 00:00:28 -0700720
Larry Hastings9cf065c2012-06-22 16:30:09 -0700721 for fn in (posix.lchflags, chflags_nofollow):
Trent Nelson75959cf2012-08-21 23:59:31 +0000722 # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
723 flags = dummy_symlink_st.st_flags | stat.UF_IMMUTABLE
724 try:
725 fn(_DUMMY_SYMLINK, flags)
726 except OSError as err:
727 if err.errno != errno.EOPNOTSUPP:
728 raise
729 msg = 'chflag UF_IMMUTABLE not supported by underlying fs'
730 self.skipTest(msg)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700731 try:
732 new_testfn_st = os.stat(support.TESTFN)
733 new_dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
734
735 self.assertEqual(testfn_st.st_flags, new_testfn_st.st_flags)
736 self.assertEqual(dummy_symlink_st.st_flags | stat.UF_IMMUTABLE,
737 new_dummy_symlink_st.st_flags)
738 finally:
739 fn(_DUMMY_SYMLINK, dummy_symlink_st.st_flags)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000740
Guido van Rossum98297ee2007-11-06 21:34:58 +0000741 def test_environ(self):
Victor Stinner17b490d2010-05-06 22:19:30 +0000742 if os.name == "nt":
743 item_type = str
744 else:
745 item_type = bytes
Guido van Rossum98297ee2007-11-06 21:34:58 +0000746 for k, v in posix.environ.items():
Victor Stinner17b490d2010-05-06 22:19:30 +0000747 self.assertEqual(type(k), item_type)
748 self.assertEqual(type(v), item_type)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000749
Serhiy Storchaka43767632013-11-03 21:31:38 +0200750 @unittest.skipUnless(hasattr(posix, 'getcwd'), 'test needs posix.getcwd()')
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000751 def test_getcwd_long_pathnames(self):
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500752 dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
753 curdir = os.getcwd()
754 base_path = os.path.abspath(support.TESTFN) + '.getcwd'
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000755
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500756 try:
757 os.mkdir(base_path)
758 os.chdir(base_path)
759 except:
760 # Just returning nothing instead of the SkipTest exception, because
761 # the test results in Error in that case. Is that ok?
762 # raise unittest.SkipTest("cannot create directory for testing")
763 return
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000764
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500765 def _create_and_do_getcwd(dirname, current_path_length = 0):
766 try:
767 os.mkdir(dirname)
768 except:
769 raise unittest.SkipTest("mkdir cannot create directory sufficiently deep for getcwd test")
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000770
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500771 os.chdir(dirname)
772 try:
773 os.getcwd()
774 if current_path_length < 1027:
775 _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1)
776 finally:
777 os.chdir('..')
778 os.rmdir(dirname)
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000779
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500780 _create_and_do_getcwd(dirname)
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000781
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500782 finally:
783 os.chdir(curdir)
784 support.rmtree(base_path)
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000785
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200786 @unittest.skipUnless(hasattr(posix, 'getgrouplist'), "test needs posix.getgrouplist()")
787 @unittest.skipUnless(hasattr(pwd, 'getpwuid'), "test needs pwd.getpwuid()")
788 @unittest.skipUnless(hasattr(os, 'getuid'), "test needs os.getuid()")
789 def test_getgrouplist(self):
Ross Lagerwalla0b315f2012-12-13 15:20:26 +0000790 user = pwd.getpwuid(os.getuid())[0]
791 group = pwd.getpwuid(os.getuid())[3]
792 self.assertIn(group, posix.getgrouplist(user, group))
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200793
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200794
Antoine Pitrou318b8f32011-01-12 18:45:27 +0000795 @unittest.skipUnless(hasattr(os, 'getegid'), "test needs os.getegid()")
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000796 def test_getgroups(self):
Jesus Cea61f32cb2014-06-28 18:39:35 +0200797 with os.popen('id -G 2>/dev/null') as idg:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000798 groups = idg.read().strip()
Charles-François Natalie8a255a2012-05-02 20:01:38 +0200799 ret = idg.close()
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000800
Benjamin Petersonb29614e2012-10-09 11:16:03 -0400801 if ret is not None or not groups:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000802 raise unittest.SkipTest("need working 'id -G'")
803
Ned Deily028915e2013-02-02 15:08:52 -0800804 # Issues 16698: OS X ABIs prior to 10.6 have limits on getgroups()
805 if sys.platform == 'darwin':
806 import sysconfig
807 dt = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') or '10.0'
Ned Deily04cdfa12014-06-25 13:36:14 -0700808 if tuple(int(n) for n in dt.split('.')[0:2]) < (10, 6):
Ned Deily028915e2013-02-02 15:08:52 -0800809 raise unittest.SkipTest("getgroups(2) is broken prior to 10.6")
810
Ronald Oussoren7fb6f512010-08-01 19:18:13 +0000811 # 'id -G' and 'os.getgroups()' should return the same
812 # groups, ignoring order and duplicates.
Antoine Pitrou318b8f32011-01-12 18:45:27 +0000813 # #10822 - it is implementation defined whether posix.getgroups()
814 # includes the effective gid so we include it anyway, since id -G does
Ronald Oussorencb615e62010-07-24 14:15:19 +0000815 self.assertEqual(
Ronald Oussoren7fb6f512010-08-01 19:18:13 +0000816 set([int(x) for x in groups.split()]),
Antoine Pitrou318b8f32011-01-12 18:45:27 +0000817 set(posix.getgroups() + [posix.getegid()]))
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000818
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000819 # tests for the posix *at functions follow
820
Larry Hastings9cf065c2012-06-22 16:30:09 -0700821 @unittest.skipUnless(os.access in os.supports_dir_fd, "test needs dir_fd support for os.access()")
822 def test_access_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000823 f = posix.open(posix.getcwd(), posix.O_RDONLY)
824 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700825 self.assertTrue(posix.access(support.TESTFN, os.R_OK, dir_fd=f))
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000826 finally:
827 posix.close(f)
828
Larry Hastings9cf065c2012-06-22 16:30:09 -0700829 @unittest.skipUnless(os.chmod in os.supports_dir_fd, "test needs dir_fd support in os.chmod()")
830 def test_chmod_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000831 os.chmod(support.TESTFN, stat.S_IRUSR)
832
833 f = posix.open(posix.getcwd(), posix.O_RDONLY)
834 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700835 posix.chmod(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000836
837 s = posix.stat(support.TESTFN)
838 self.assertEqual(s[0] & stat.S_IRWXU, stat.S_IRUSR | stat.S_IWUSR)
839 finally:
840 posix.close(f)
841
Larry Hastings9cf065c2012-06-22 16:30:09 -0700842 @unittest.skipUnless(os.chown in os.supports_dir_fd, "test needs dir_fd support in os.chown()")
843 def test_chown_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000844 support.unlink(support.TESTFN)
Victor Stinnerbf816222011-06-30 23:25:47 +0200845 support.create_empty_file(support.TESTFN)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000846
847 f = posix.open(posix.getcwd(), posix.O_RDONLY)
848 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700849 posix.chown(support.TESTFN, os.getuid(), os.getgid(), dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000850 finally:
851 posix.close(f)
852
Larry Hastings9cf065c2012-06-22 16:30:09 -0700853 @unittest.skipUnless(os.stat in os.supports_dir_fd, "test needs dir_fd support in os.stat()")
854 def test_stat_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000855 support.unlink(support.TESTFN)
856 with open(support.TESTFN, 'w') as outfile:
857 outfile.write("testline\n")
858
859 f = posix.open(posix.getcwd(), posix.O_RDONLY)
860 try:
861 s1 = posix.stat(support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700862 s2 = posix.stat(support.TESTFN, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000863 self.assertEqual(s1, s2)
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200864 s2 = posix.stat(support.TESTFN, dir_fd=None)
865 self.assertEqual(s1, s2)
866 self.assertRaisesRegex(TypeError, 'should be integer, not',
867 posix.stat, support.TESTFN, dir_fd=posix.getcwd())
868 self.assertRaisesRegex(TypeError, 'should be integer, not',
869 posix.stat, support.TESTFN, dir_fd=float(f))
870 self.assertRaises(OverflowError,
871 posix.stat, support.TESTFN, dir_fd=10**20)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000872 finally:
873 posix.close(f)
874
Larry Hastings9cf065c2012-06-22 16:30:09 -0700875 @unittest.skipUnless(os.utime in os.supports_dir_fd, "test needs dir_fd support in os.utime()")
876 def test_utime_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000877 f = posix.open(posix.getcwd(), posix.O_RDONLY)
878 try:
879 now = time.time()
Larry Hastings9cf065c2012-06-22 16:30:09 -0700880 posix.utime(support.TESTFN, None, dir_fd=f)
881 posix.utime(support.TESTFN, dir_fd=f)
882 self.assertRaises(TypeError, posix.utime, support.TESTFN, now, dir_fd=f)
883 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None), dir_fd=f)
884 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None), dir_fd=f)
885 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now), dir_fd=f)
886 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, "x"), dir_fd=f)
887 posix.utime(support.TESTFN, (int(now), int(now)), dir_fd=f)
888 posix.utime(support.TESTFN, (now, now), dir_fd=f)
889 posix.utime(support.TESTFN,
890 (int(now), int((now - int(now)) * 1e9)), dir_fd=f)
891 posix.utime(support.TESTFN, dir_fd=f,
892 times=(int(now), int((now - int(now)) * 1e9)))
893
Larry Hastings90867a52012-06-22 17:01:41 -0700894 # try dir_fd and follow_symlinks together
Larry Hastings9cf065c2012-06-22 16:30:09 -0700895 if os.utime in os.supports_follow_symlinks:
Larry Hastings90867a52012-06-22 17:01:41 -0700896 try:
897 posix.utime(support.TESTFN, follow_symlinks=False, dir_fd=f)
Georg Brandl969288e2012-06-26 09:25:44 +0200898 except ValueError:
Larry Hastings90867a52012-06-22 17:01:41 -0700899 # whoops! using both together not supported on this platform.
900 pass
Larry Hastings9cf065c2012-06-22 16:30:09 -0700901
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000902 finally:
903 posix.close(f)
904
Larry Hastings9cf065c2012-06-22 16:30:09 -0700905 @unittest.skipUnless(os.link in os.supports_dir_fd, "test needs dir_fd support in os.link()")
906 def test_link_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000907 f = posix.open(posix.getcwd(), posix.O_RDONLY)
908 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700909 posix.link(support.TESTFN, support.TESTFN + 'link', src_dir_fd=f, dst_dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000910 # should have same inodes
911 self.assertEqual(posix.stat(support.TESTFN)[1],
912 posix.stat(support.TESTFN + 'link')[1])
913 finally:
914 posix.close(f)
915 support.unlink(support.TESTFN + 'link')
916
Larry Hastings9cf065c2012-06-22 16:30:09 -0700917 @unittest.skipUnless(os.mkdir in os.supports_dir_fd, "test needs dir_fd support in os.mkdir()")
918 def test_mkdir_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000919 f = posix.open(posix.getcwd(), posix.O_RDONLY)
920 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700921 posix.mkdir(support.TESTFN + 'dir', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000922 posix.stat(support.TESTFN + 'dir') # should not raise exception
923 finally:
924 posix.close(f)
925 support.rmtree(support.TESTFN + 'dir')
926
Larry Hastings9cf065c2012-06-22 16:30:09 -0700927 @unittest.skipUnless((os.mknod in os.supports_dir_fd) and hasattr(stat, 'S_IFIFO'),
928 "test requires both stat.S_IFIFO and dir_fd support for os.mknod()")
929 def test_mknod_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000930 # Test using mknodat() to create a FIFO (the only use specified
931 # by POSIX).
932 support.unlink(support.TESTFN)
933 mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
934 f = posix.open(posix.getcwd(), posix.O_RDONLY)
935 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700936 posix.mknod(support.TESTFN, mode, 0, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000937 except OSError as e:
938 # Some old systems don't allow unprivileged users to use
939 # mknod(), or only support creating device nodes.
940 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
941 else:
942 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
943 finally:
944 posix.close(f)
945
Larry Hastings9cf065c2012-06-22 16:30:09 -0700946 @unittest.skipUnless(os.open in os.supports_dir_fd, "test needs dir_fd support in os.open()")
947 def test_open_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000948 support.unlink(support.TESTFN)
949 with open(support.TESTFN, 'w') as outfile:
950 outfile.write("testline\n")
951 a = posix.open(posix.getcwd(), posix.O_RDONLY)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700952 b = posix.open(support.TESTFN, posix.O_RDONLY, dir_fd=a)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000953 try:
954 res = posix.read(b, 9).decode(encoding="utf-8")
955 self.assertEqual("testline\n", res)
956 finally:
957 posix.close(a)
958 posix.close(b)
959
Larry Hastings9cf065c2012-06-22 16:30:09 -0700960 @unittest.skipUnless(os.readlink in os.supports_dir_fd, "test needs dir_fd support in os.readlink()")
961 def test_readlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000962 os.symlink(support.TESTFN, support.TESTFN + 'link')
963 f = posix.open(posix.getcwd(), posix.O_RDONLY)
964 try:
965 self.assertEqual(posix.readlink(support.TESTFN + 'link'),
Larry Hastings9cf065c2012-06-22 16:30:09 -0700966 posix.readlink(support.TESTFN + 'link', dir_fd=f))
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000967 finally:
968 support.unlink(support.TESTFN + 'link')
969 posix.close(f)
970
Larry Hastings9cf065c2012-06-22 16:30:09 -0700971 @unittest.skipUnless(os.rename in os.supports_dir_fd, "test needs dir_fd support in os.rename()")
972 def test_rename_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000973 support.unlink(support.TESTFN)
Victor Stinnerbf816222011-06-30 23:25:47 +0200974 support.create_empty_file(support.TESTFN + 'ren')
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000975 f = posix.open(posix.getcwd(), posix.O_RDONLY)
976 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700977 posix.rename(support.TESTFN + 'ren', support.TESTFN, src_dir_fd=f, dst_dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000978 except:
979 posix.rename(support.TESTFN + 'ren', support.TESTFN)
980 raise
981 else:
Andrew Svetlov5b898402012-12-18 21:26:36 +0200982 posix.stat(support.TESTFN) # should not raise exception
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000983 finally:
984 posix.close(f)
985
Larry Hastings9cf065c2012-06-22 16:30:09 -0700986 @unittest.skipUnless(os.symlink in os.supports_dir_fd, "test needs dir_fd support in os.symlink()")
987 def test_symlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000988 f = posix.open(posix.getcwd(), posix.O_RDONLY)
989 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700990 posix.symlink(support.TESTFN, support.TESTFN + 'link', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000991 self.assertEqual(posix.readlink(support.TESTFN + 'link'), support.TESTFN)
992 finally:
993 posix.close(f)
994 support.unlink(support.TESTFN + 'link')
995
Larry Hastings9cf065c2012-06-22 16:30:09 -0700996 @unittest.skipUnless(os.unlink in os.supports_dir_fd, "test needs dir_fd support in os.unlink()")
997 def test_unlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000998 f = posix.open(posix.getcwd(), posix.O_RDONLY)
Victor Stinnerbf816222011-06-30 23:25:47 +0200999 support.create_empty_file(support.TESTFN + 'del')
Andrew Svetlov5b898402012-12-18 21:26:36 +02001000 posix.stat(support.TESTFN + 'del') # should not raise exception
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001001 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001002 posix.unlink(support.TESTFN + 'del', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001003 except:
1004 support.unlink(support.TESTFN + 'del')
1005 raise
1006 else:
1007 self.assertRaises(OSError, posix.stat, support.TESTFN + 'link')
1008 finally:
1009 posix.close(f)
1010
Larry Hastings9cf065c2012-06-22 16:30:09 -07001011 @unittest.skipUnless(os.mkfifo in os.supports_dir_fd, "test needs dir_fd support in os.mkfifo()")
1012 def test_mkfifo_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001013 support.unlink(support.TESTFN)
1014 f = posix.open(posix.getcwd(), posix.O_RDONLY)
1015 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001016 posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001017 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
1018 finally:
1019 posix.close(f)
1020
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001021 requires_sched_h = unittest.skipUnless(hasattr(posix, 'sched_yield'),
1022 "don't have scheduling support")
Antoine Pitrou84869872012-08-04 16:16:35 +02001023 requires_sched_affinity = unittest.skipUnless(hasattr(posix, 'sched_setaffinity'),
Benjamin Peterson50ba2712011-08-02 22:15:40 -05001024 "don't have sched affinity support")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001025
1026 @requires_sched_h
1027 def test_sched_yield(self):
1028 # This has no error conditions (at least on Linux).
1029 posix.sched_yield()
1030
1031 @requires_sched_h
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02001032 @unittest.skipUnless(hasattr(posix, 'sched_get_priority_max'),
1033 "requires sched_get_priority_max()")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001034 def test_sched_priority(self):
1035 # Round-robin usually has interesting priorities.
1036 pol = posix.SCHED_RR
1037 lo = posix.sched_get_priority_min(pol)
1038 hi = posix.sched_get_priority_max(pol)
1039 self.assertIsInstance(lo, int)
1040 self.assertIsInstance(hi, int)
1041 self.assertGreaterEqual(hi, lo)
Benjamin Peterson539b6c42011-08-02 22:09:37 -05001042 # OSX evidently just returns 15 without checking the argument.
1043 if sys.platform != "darwin":
Benjamin Petersonc1581582011-08-02 22:10:55 -05001044 self.assertRaises(OSError, posix.sched_get_priority_min, -23)
1045 self.assertRaises(OSError, posix.sched_get_priority_max, -23)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001046
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05001047 @unittest.skipUnless(hasattr(posix, 'sched_setscheduler'), "can't change scheduler")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001048 def test_get_and_set_scheduler_and_param(self):
1049 possible_schedulers = [sched for name, sched in posix.__dict__.items()
1050 if name.startswith("SCHED_")]
1051 mine = posix.sched_getscheduler(0)
1052 self.assertIn(mine, possible_schedulers)
1053 try:
Jesus Ceaceb5d162011-09-10 01:16:55 +02001054 parent = posix.sched_getscheduler(os.getppid())
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001055 except OSError as e:
Jesus Ceaceb5d162011-09-10 01:16:55 +02001056 if e.errno != errno.EPERM:
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001057 raise
1058 else:
Jesus Ceaceb5d162011-09-10 01:16:55 +02001059 self.assertIn(parent, possible_schedulers)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001060 self.assertRaises(OSError, posix.sched_getscheduler, -1)
1061 self.assertRaises(OSError, posix.sched_getparam, -1)
1062 param = posix.sched_getparam(0)
1063 self.assertIsInstance(param.sched_priority, int)
Charles-François Natali7b911cb2011-08-21 12:41:43 +02001064
Charles-François Natalib402a5c2013-01-13 14:13:25 +01001065 # POSIX states that calling sched_setparam() or sched_setscheduler() on
1066 # a process with a scheduling policy other than SCHED_FIFO or SCHED_RR
1067 # is implementation-defined: NetBSD and FreeBSD can return EINVAL.
1068 if not sys.platform.startswith(('freebsd', 'netbsd')):
1069 try:
1070 posix.sched_setscheduler(0, mine, param)
1071 posix.sched_setparam(0, param)
1072 except OSError as e:
1073 if e.errno != errno.EPERM:
1074 raise
Charles-François Natali7b911cb2011-08-21 12:41:43 +02001075 self.assertRaises(OSError, posix.sched_setparam, -1, param)
1076
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001077 self.assertRaises(OSError, posix.sched_setscheduler, -1, mine, param)
1078 self.assertRaises(TypeError, posix.sched_setscheduler, 0, mine, None)
1079 self.assertRaises(TypeError, posix.sched_setparam, 0, 43)
1080 param = posix.sched_param(None)
1081 self.assertRaises(TypeError, posix.sched_setparam, 0, param)
1082 large = 214748364700
1083 param = posix.sched_param(large)
1084 self.assertRaises(OverflowError, posix.sched_setparam, 0, param)
1085 param = posix.sched_param(sched_priority=-large)
1086 self.assertRaises(OverflowError, posix.sched_setparam, 0, param)
1087
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05001088 @unittest.skipUnless(hasattr(posix, "sched_rr_get_interval"), "no function")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001089 def test_sched_rr_get_interval(self):
Benjamin Peterson43234ab2011-08-02 22:19:14 -05001090 try:
1091 interval = posix.sched_rr_get_interval(0)
1092 except OSError as e:
1093 # This likely means that sched_rr_get_interval is only valid for
1094 # processes with the SCHED_RR scheduler in effect.
1095 if e.errno != errno.EINVAL:
1096 raise
1097 self.skipTest("only works on SCHED_RR processes")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001098 self.assertIsInstance(interval, float)
1099 # Reasonable constraints, I think.
1100 self.assertGreaterEqual(interval, 0.)
1101 self.assertLess(interval, 1.)
1102
Benjamin Peterson2740af82011-08-02 17:41:34 -05001103 @requires_sched_affinity
Antoine Pitrou84869872012-08-04 16:16:35 +02001104 def test_sched_getaffinity(self):
1105 mask = posix.sched_getaffinity(0)
1106 self.assertIsInstance(mask, set)
1107 self.assertGreaterEqual(len(mask), 1)
1108 self.assertRaises(OSError, posix.sched_getaffinity, -1)
1109 for cpu in mask:
1110 self.assertIsInstance(cpu, int)
1111 self.assertGreaterEqual(cpu, 0)
1112 self.assertLess(cpu, 1 << 32)
1113
1114 @requires_sched_affinity
1115 def test_sched_setaffinity(self):
1116 mask = posix.sched_getaffinity(0)
1117 if len(mask) > 1:
1118 # Empty masks are forbidden
1119 mask.pop()
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001120 posix.sched_setaffinity(0, mask)
Antoine Pitrou84869872012-08-04 16:16:35 +02001121 self.assertEqual(posix.sched_getaffinity(0), mask)
1122 self.assertRaises(OSError, posix.sched_setaffinity, 0, [])
1123 self.assertRaises(ValueError, posix.sched_setaffinity, 0, [-10])
1124 self.assertRaises(OverflowError, posix.sched_setaffinity, 0, [1<<128])
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001125 self.assertRaises(OSError, posix.sched_setaffinity, -1, mask)
1126
Victor Stinner8b905bd2011-10-25 13:34:04 +02001127 def test_rtld_constants(self):
1128 # check presence of major RTLD_* constants
1129 posix.RTLD_LAZY
1130 posix.RTLD_NOW
1131 posix.RTLD_GLOBAL
1132 posix.RTLD_LOCAL
1133
Jesus Cea60c13dd2012-06-23 02:58:14 +02001134 @unittest.skipUnless(hasattr(os, 'SEEK_HOLE'),
1135 "test needs an OS that reports file holes")
Hynek Schlawackf841e422012-06-24 09:51:46 +02001136 def test_fs_holes(self):
Jesus Cea94363612012-06-22 18:32:07 +02001137 # Even if the filesystem doesn't report holes,
1138 # if the OS supports it the SEEK_* constants
1139 # will be defined and will have a consistent
1140 # behaviour:
1141 # os.SEEK_DATA = current position
1142 # os.SEEK_HOLE = end of file position
Hynek Schlawackf841e422012-06-24 09:51:46 +02001143 with open(support.TESTFN, 'r+b') as fp:
Jesus Cea94363612012-06-22 18:32:07 +02001144 fp.write(b"hello")
1145 fp.flush()
1146 size = fp.tell()
1147 fno = fp.fileno()
Jesus Cead46f7d22012-07-07 14:56:04 +02001148 try :
1149 for i in range(size):
1150 self.assertEqual(i, os.lseek(fno, i, os.SEEK_DATA))
1151 self.assertLessEqual(size, os.lseek(fno, i, os.SEEK_HOLE))
1152 self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_DATA)
1153 self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_HOLE)
1154 except OSError :
1155 # Some OSs claim to support SEEK_HOLE/SEEK_DATA
1156 # but it is not true.
1157 # For instance:
1158 # http://lists.freebsd.org/pipermail/freebsd-amd64/2012-January/014332.html
1159 raise unittest.SkipTest("OSError raised!")
Jesus Cea94363612012-06-22 18:32:07 +02001160
Larry Hastingsb0827312014-02-09 22:05:19 -08001161 def test_path_error2(self):
1162 """
1163 Test functions that call path_error2(), providing two filenames in their exceptions.
1164 """
Victor Stinner047b7ae2014-10-05 17:37:41 +02001165 for name in ("rename", "replace", "link"):
Larry Hastingsb0827312014-02-09 22:05:19 -08001166 function = getattr(os, name, None)
Victor Stinnerbed04a72014-10-05 17:37:59 +02001167 if function is None:
1168 continue
Larry Hastingsb0827312014-02-09 22:05:19 -08001169
Victor Stinnerbed04a72014-10-05 17:37:59 +02001170 for dst in ("noodly2", support.TESTFN):
1171 try:
1172 function('doesnotexistfilename', dst)
1173 except OSError as e:
1174 self.assertIn("'doesnotexistfilename' -> '{}'".format(dst), str(e))
1175 break
1176 else:
1177 self.fail("No valid path_error2() test for os." + name)
Larry Hastingsb0827312014-02-09 22:05:19 -08001178
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001179 def test_path_with_null_character(self):
1180 fn = support.TESTFN
1181 fn_with_NUL = fn + '\0'
1182 self.addCleanup(support.unlink, fn)
1183 support.unlink(fn)
1184 fd = None
1185 try:
Serhiy Storchaka7e9d1d12015-04-20 10:12:28 +03001186 with self.assertRaises(ValueError):
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001187 fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # raises
1188 finally:
1189 if fd is not None:
1190 os.close(fd)
1191 self.assertFalse(os.path.exists(fn))
Serhiy Storchaka7e9d1d12015-04-20 10:12:28 +03001192 self.assertRaises(ValueError, os.mkdir, fn_with_NUL)
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001193 self.assertFalse(os.path.exists(fn))
1194 open(fn, 'wb').close()
Serhiy Storchaka7e9d1d12015-04-20 10:12:28 +03001195 self.assertRaises(ValueError, os.stat, fn_with_NUL)
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001196
1197 def test_path_with_null_byte(self):
1198 fn = os.fsencode(support.TESTFN)
1199 fn_with_NUL = fn + b'\0'
1200 self.addCleanup(support.unlink, fn)
1201 support.unlink(fn)
1202 fd = None
1203 try:
1204 with self.assertRaises(ValueError):
1205 fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # raises
1206 finally:
1207 if fd is not None:
1208 os.close(fd)
1209 self.assertFalse(os.path.exists(fn))
1210 self.assertRaises(ValueError, os.mkdir, fn_with_NUL)
1211 self.assertFalse(os.path.exists(fn))
1212 open(fn, 'wb').close()
1213 self.assertRaises(ValueError, os.stat, fn_with_NUL)
1214
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001215class PosixGroupsTester(unittest.TestCase):
1216
1217 def setUp(self):
1218 if posix.getuid() != 0:
1219 raise unittest.SkipTest("not enough privileges")
1220 if not hasattr(posix, 'getgroups'):
1221 raise unittest.SkipTest("need posix.getgroups")
1222 if sys.platform == 'darwin':
1223 raise unittest.SkipTest("getgroups(2) is broken on OSX")
1224 self.saved_groups = posix.getgroups()
1225
1226 def tearDown(self):
1227 if hasattr(posix, 'setgroups'):
1228 posix.setgroups(self.saved_groups)
1229 elif hasattr(posix, 'initgroups'):
1230 name = pwd.getpwuid(posix.getuid()).pw_name
1231 posix.initgroups(name, self.saved_groups[0])
1232
1233 @unittest.skipUnless(hasattr(posix, 'initgroups'),
1234 "test needs posix.initgroups()")
1235 def test_initgroups(self):
1236 # find missing group
1237
Benjamin Peterson659a6f52014-03-01 19:14:12 -05001238 g = max(self.saved_groups or [0]) + 1
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001239 name = pwd.getpwuid(posix.getuid()).pw_name
1240 posix.initgroups(name, g)
1241 self.assertIn(g, posix.getgroups())
1242
1243 @unittest.skipUnless(hasattr(posix, 'setgroups'),
1244 "test needs posix.setgroups()")
1245 def test_setgroups(self):
Antoine Pitroue5a91012010-09-04 17:32:06 +00001246 for groups in [[0], list(range(16))]:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001247 posix.setgroups(groups)
1248 self.assertListEqual(groups, posix.getgroups())
1249
Neal Norwitze241ce82003-02-17 18:17:05 +00001250def test_main():
Antoine Pitrou68c95922011-03-20 17:33:57 +01001251 try:
1252 support.run_unittest(PosixTester, PosixGroupsTester)
1253 finally:
1254 support.reap_children()
Neal Norwitze241ce82003-02-17 18:17:05 +00001255
1256if __name__ == '__main__':
1257 test_main()