blob: 6a1c82917a9a35632afbdee37daa8c6b37ecafa7 [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 Peterson052a02b2010-08-17 01:27:09 +000014import stat
Ned Deilyba2eab22011-07-26 13:53:55 -070015import tempfile
Neal Norwitze241ce82003-02-17 18:17:05 +000016import unittest
17import warnings
R. David Murraya21e4ca2009-03-31 23:16:50 +000018
Ned Deilyba2eab22011-07-26 13:53:55 -070019_DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(),
20 support.TESTFN + '-dummy-symlink')
Neal Norwitze241ce82003-02-17 18:17:05 +000021
22class PosixTester(unittest.TestCase):
23
24 def setUp(self):
25 # create empty file
Benjamin Petersonee8712c2008-05-20 21:35:26 +000026 fp = open(support.TESTFN, 'w+')
Neal Norwitze241ce82003-02-17 18:17:05 +000027 fp.close()
Ned Deily3eb67d52011-06-28 00:00:28 -070028 self.teardown_files = [ support.TESTFN ]
Brett Cannonc8d502e2010-03-20 21:53:28 +000029 self._warnings_manager = support.check_warnings()
30 self._warnings_manager.__enter__()
31 warnings.filterwarnings('ignore', '.* potential security risk .*',
32 RuntimeWarning)
Neal Norwitze241ce82003-02-17 18:17:05 +000033
34 def tearDown(self):
Ned Deily3eb67d52011-06-28 00:00:28 -070035 for teardown_file in self.teardown_files:
36 support.unlink(teardown_file)
Brett Cannonc8d502e2010-03-20 21:53:28 +000037 self._warnings_manager.__exit__(None, None, None)
Neal Norwitze241ce82003-02-17 18:17:05 +000038
39 def testNoArgFunctions(self):
40 # test posix functions which take no arguments and have
41 # no side-effects which we need to cleanup (e.g., fork, wait, abort)
Guido van Rossumf0af3e32008-10-02 18:55:37 +000042 NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdb", "uname",
Guido van Rossum687b9c02007-10-25 23:18:51 +000043 "times", "getloadavg",
Neal Norwitze241ce82003-02-17 18:17:05 +000044 "getegid", "geteuid", "getgid", "getgroups",
Ross Lagerwall7807c352011-03-17 20:20:30 +020045 "getpid", "getpgrp", "getppid", "getuid", "sync",
Neal Norwitze241ce82003-02-17 18:17:05 +000046 ]
Neal Norwitz71b13e82003-02-23 22:12:24 +000047
Neal Norwitze241ce82003-02-17 18:17:05 +000048 for name in NO_ARG_FUNCTIONS:
49 posix_func = getattr(posix, name, None)
50 if posix_func is not None:
51 posix_func()
Neal Norwitz2ff51a82003-02-17 22:40:31 +000052 self.assertRaises(TypeError, posix_func, 1)
Neal Norwitze241ce82003-02-17 18:17:05 +000053
Serhiy Storchaka43767632013-11-03 21:31:38 +020054 @unittest.skipUnless(hasattr(posix, 'getresuid'),
55 'test needs posix.getresuid()')
56 def test_getresuid(self):
57 user_ids = posix.getresuid()
58 self.assertEqual(len(user_ids), 3)
59 for val in user_ids:
60 self.assertGreaterEqual(val, 0)
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000061
Serhiy Storchaka43767632013-11-03 21:31:38 +020062 @unittest.skipUnless(hasattr(posix, 'getresgid'),
63 'test needs posix.getresgid()')
64 def test_getresgid(self):
65 group_ids = posix.getresgid()
66 self.assertEqual(len(group_ids), 3)
67 for val in group_ids:
68 self.assertGreaterEqual(val, 0)
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000069
Serhiy Storchaka43767632013-11-03 21:31:38 +020070 @unittest.skipUnless(hasattr(posix, 'setresuid'),
71 'test needs posix.setresuid()')
72 def test_setresuid(self):
73 current_user_ids = posix.getresuid()
74 self.assertIsNone(posix.setresuid(*current_user_ids))
75 # -1 means don't change that value.
76 self.assertIsNone(posix.setresuid(-1, -1, -1))
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000077
Serhiy Storchaka43767632013-11-03 21:31:38 +020078 @unittest.skipUnless(hasattr(posix, 'setresuid'),
79 'test needs posix.setresuid()')
80 def test_setresuid_exception(self):
81 # Don't do this test if someone is silly enough to run us as root.
82 current_user_ids = posix.getresuid()
83 if 0 not in current_user_ids:
84 new_user_ids = (current_user_ids[0]+1, -1, -1)
85 self.assertRaises(OSError, posix.setresuid, *new_user_ids)
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000086
Serhiy Storchaka43767632013-11-03 21:31:38 +020087 @unittest.skipUnless(hasattr(posix, 'setresgid'),
88 'test needs posix.setresgid()')
89 def test_setresgid(self):
90 current_group_ids = posix.getresgid()
91 self.assertIsNone(posix.setresgid(*current_group_ids))
92 # -1 means don't change that value.
93 self.assertIsNone(posix.setresgid(-1, -1, -1))
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000094
Serhiy Storchaka43767632013-11-03 21:31:38 +020095 @unittest.skipUnless(hasattr(posix, 'setresgid'),
96 'test needs posix.setresgid()')
97 def test_setresgid_exception(self):
98 # Don't do this test if someone is silly enough to run us as root.
99 current_group_ids = posix.getresgid()
100 if 0 not in current_group_ids:
101 new_group_ids = (current_group_ids[0]+1, -1, -1)
102 self.assertRaises(OSError, posix.setresgid, *new_group_ids)
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000103
Antoine Pitroub7572f02009-12-02 20:46:48 +0000104 @unittest.skipUnless(hasattr(posix, 'initgroups'),
105 "test needs os.initgroups()")
106 def test_initgroups(self):
107 # It takes a string and an integer; check that it raises a TypeError
108 # for other argument lists.
109 self.assertRaises(TypeError, posix.initgroups)
110 self.assertRaises(TypeError, posix.initgroups, None)
111 self.assertRaises(TypeError, posix.initgroups, 3, "foo")
112 self.assertRaises(TypeError, posix.initgroups, "foo", 3, object())
113
114 # If a non-privileged user invokes it, it should fail with OSError
115 # EPERM.
116 if os.getuid() != 0:
Charles-François Natalie8a255a2012-05-02 20:01:38 +0200117 try:
118 name = pwd.getpwuid(posix.getuid()).pw_name
119 except KeyError:
120 # the current UID may not have a pwd entry
121 raise unittest.SkipTest("need a pwd entry")
Antoine Pitroub7572f02009-12-02 20:46:48 +0000122 try:
123 posix.initgroups(name, 13)
124 except OSError as e:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000125 self.assertEqual(e.errno, errno.EPERM)
Antoine Pitroub7572f02009-12-02 20:46:48 +0000126 else:
127 self.fail("Expected OSError to be raised by initgroups")
128
Serhiy Storchaka43767632013-11-03 21:31:38 +0200129 @unittest.skipUnless(hasattr(posix, 'statvfs'),
130 'test needs posix.statvfs()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000131 def test_statvfs(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200132 self.assertTrue(posix.statvfs(os.curdir))
Neal Norwitze241ce82003-02-17 18:17:05 +0000133
Serhiy Storchaka43767632013-11-03 21:31:38 +0200134 @unittest.skipUnless(hasattr(posix, 'fstatvfs'),
135 'test needs posix.fstatvfs()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000136 def test_fstatvfs(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200137 fp = open(support.TESTFN)
138 try:
139 self.assertTrue(posix.fstatvfs(fp.fileno()))
140 self.assertTrue(posix.statvfs(fp.fileno()))
141 finally:
142 fp.close()
Neal Norwitze241ce82003-02-17 18:17:05 +0000143
Serhiy Storchaka43767632013-11-03 21:31:38 +0200144 @unittest.skipUnless(hasattr(posix, 'ftruncate'),
145 'test needs posix.ftruncate()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000146 def test_ftruncate(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200147 fp = open(support.TESTFN, 'w+')
148 try:
149 # we need to have some data to truncate
150 fp.write('test')
151 fp.flush()
152 posix.ftruncate(fp.fileno(), 0)
153 finally:
154 fp.close()
Neal Norwitze241ce82003-02-17 18:17:05 +0000155
Ross Lagerwall7807c352011-03-17 20:20:30 +0200156 @unittest.skipUnless(hasattr(posix, 'truncate'), "test needs posix.truncate()")
157 def test_truncate(self):
158 with open(support.TESTFN, 'w') as fp:
159 fp.write('test')
160 fp.flush()
161 posix.truncate(support.TESTFN, 0)
162
Larry Hastings9cf065c2012-06-22 16:30:09 -0700163 @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 +0200164 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
Ross Lagerwalldedf6cf2011-03-20 18:27:05 +0200165 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
Ross Lagerwall7807c352011-03-17 20:20:30 +0200166 def test_fexecve(self):
167 fp = os.open(sys.executable, os.O_RDONLY)
168 try:
169 pid = os.fork()
170 if pid == 0:
171 os.chdir(os.path.split(sys.executable)[0])
Larry Hastings9cf065c2012-06-22 16:30:09 -0700172 posix.execve(fp, [sys.executable, '-c', 'pass'], os.environ)
Ross Lagerwall7807c352011-03-17 20:20:30 +0200173 else:
Ross Lagerwalldedf6cf2011-03-20 18:27:05 +0200174 self.assertEqual(os.waitpid(pid, 0), (pid, 0))
Ross Lagerwall7807c352011-03-17 20:20:30 +0200175 finally:
176 os.close(fp)
177
178 @unittest.skipUnless(hasattr(posix, 'waitid'), "test needs posix.waitid()")
179 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
180 def test_waitid(self):
181 pid = os.fork()
182 if pid == 0:
183 os.chdir(os.path.split(sys.executable)[0])
184 posix.execve(sys.executable, [sys.executable, '-c', 'pass'], os.environ)
185 else:
186 res = posix.waitid(posix.P_PID, pid, posix.WEXITED)
187 self.assertEqual(pid, res.si_pid)
188
189 @unittest.skipUnless(hasattr(posix, 'lockf'), "test needs posix.lockf()")
190 def test_lockf(self):
191 fd = os.open(support.TESTFN, os.O_WRONLY | os.O_CREAT)
192 try:
193 os.write(fd, b'test')
194 os.lseek(fd, 0, os.SEEK_SET)
195 posix.lockf(fd, posix.F_LOCK, 4)
196 # section is locked
197 posix.lockf(fd, posix.F_ULOCK, 4)
198 finally:
199 os.close(fd)
200
201 @unittest.skipUnless(hasattr(posix, 'pread'), "test needs posix.pread()")
202 def test_pread(self):
203 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
204 try:
205 os.write(fd, b'test')
206 os.lseek(fd, 0, os.SEEK_SET)
207 self.assertEqual(b'es', posix.pread(fd, 2, 1))
Florent Xiclunae41f0de2011-11-11 19:39:25 +0100208 # the first pread() shouldn't disturb the file offset
Ross Lagerwall7807c352011-03-17 20:20:30 +0200209 self.assertEqual(b'te', posix.read(fd, 2))
210 finally:
211 os.close(fd)
212
213 @unittest.skipUnless(hasattr(posix, 'pwrite'), "test needs posix.pwrite()")
214 def test_pwrite(self):
215 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
216 try:
217 os.write(fd, b'test')
218 os.lseek(fd, 0, os.SEEK_SET)
219 posix.pwrite(fd, b'xx', 1)
220 self.assertEqual(b'txxt', posix.read(fd, 4))
221 finally:
222 os.close(fd)
223
224 @unittest.skipUnless(hasattr(posix, 'posix_fallocate'),
225 "test needs posix.posix_fallocate()")
226 def test_posix_fallocate(self):
227 fd = os.open(support.TESTFN, os.O_WRONLY | os.O_CREAT)
228 try:
229 posix.posix_fallocate(fd, 0, 10)
230 except OSError as inst:
231 # issue10812, ZFS doesn't appear to support posix_fallocate,
232 # so skip Solaris-based since they are likely to have ZFS.
233 if inst.errno != errno.EINVAL or not sys.platform.startswith("sunos"):
234 raise
235 finally:
236 os.close(fd)
237
238 @unittest.skipUnless(hasattr(posix, 'posix_fadvise'),
239 "test needs posix.posix_fadvise()")
240 def test_posix_fadvise(self):
241 fd = os.open(support.TESTFN, os.O_RDONLY)
242 try:
243 posix.posix_fadvise(fd, 0, 0, posix.POSIX_FADV_WILLNEED)
244 finally:
245 os.close(fd)
246
Larry Hastings9cf065c2012-06-22 16:30:09 -0700247 @unittest.skipUnless(os.utime in os.supports_fd, "test needs fd support in os.utime")
248 def test_utime_with_fd(self):
Ross Lagerwall7807c352011-03-17 20:20:30 +0200249 now = time.time()
250 fd = os.open(support.TESTFN, os.O_RDONLY)
251 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700252 posix.utime(fd)
253 posix.utime(fd, None)
254 self.assertRaises(TypeError, posix.utime, fd, (None, None))
255 self.assertRaises(TypeError, posix.utime, fd, (now, None))
256 self.assertRaises(TypeError, posix.utime, fd, (None, now))
257 posix.utime(fd, (int(now), int(now)))
258 posix.utime(fd, (now, now))
259 self.assertRaises(ValueError, posix.utime, fd, (now, now), ns=(now, now))
260 self.assertRaises(ValueError, posix.utime, fd, (now, 0), ns=(None, None))
261 self.assertRaises(ValueError, posix.utime, fd, (None, None), ns=(now, 0))
262 posix.utime(fd, (int(now), int((now - int(now)) * 1e9)))
263 posix.utime(fd, ns=(int(now), int((now - int(now)) * 1e9)))
264
Ross Lagerwall7807c352011-03-17 20:20:30 +0200265 finally:
266 os.close(fd)
267
Larry Hastings9cf065c2012-06-22 16:30:09 -0700268 @unittest.skipUnless(os.utime in os.supports_follow_symlinks, "test needs follow_symlinks support in os.utime")
269 def test_utime_nofollow_symlinks(self):
Ross Lagerwall7807c352011-03-17 20:20:30 +0200270 now = time.time()
Larry Hastings9cf065c2012-06-22 16:30:09 -0700271 posix.utime(support.TESTFN, None, follow_symlinks=False)
272 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None), follow_symlinks=False)
273 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None), follow_symlinks=False)
274 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now), follow_symlinks=False)
275 posix.utime(support.TESTFN, (int(now), int(now)), follow_symlinks=False)
276 posix.utime(support.TESTFN, (now, now), follow_symlinks=False)
277 posix.utime(support.TESTFN, follow_symlinks=False)
Ross Lagerwall7807c352011-03-17 20:20:30 +0200278
279 @unittest.skipUnless(hasattr(posix, 'writev'), "test needs posix.writev()")
280 def test_writev(self):
281 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
282 try:
Victor Stinner57ddf782014-01-08 15:21:28 +0100283 n = os.writev(fd, (b'test1', b'tt2', b't3'))
284 self.assertEqual(n, 10)
285
Ross Lagerwall7807c352011-03-17 20:20:30 +0200286 os.lseek(fd, 0, os.SEEK_SET)
287 self.assertEqual(b'test1tt2t3', posix.read(fd, 10))
Victor Stinner57ddf782014-01-08 15:21:28 +0100288
289 # Issue #20113: empty list of buffers should not crash
Victor Stinnercd5ca6a2014-01-08 16:01:31 +0100290 try:
291 size = posix.writev(fd, [])
292 except OSError:
293 # writev(fd, []) raises OSError(22, "Invalid argument")
294 # on OpenIndiana
295 pass
296 else:
297 self.assertEqual(size, 0)
Ross Lagerwall7807c352011-03-17 20:20:30 +0200298 finally:
299 os.close(fd)
300
301 @unittest.skipUnless(hasattr(posix, 'readv'), "test needs posix.readv()")
302 def test_readv(self):
303 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
304 try:
305 os.write(fd, b'test1tt2t3')
306 os.lseek(fd, 0, os.SEEK_SET)
307 buf = [bytearray(i) for i in [5, 3, 2]]
308 self.assertEqual(posix.readv(fd, buf), 10)
309 self.assertEqual([b'test1', b'tt2', b't3'], [bytes(i) for i in buf])
Victor Stinner57ddf782014-01-08 15:21:28 +0100310
311 # Issue #20113: empty list of buffers should not crash
Victor Stinnercd5ca6a2014-01-08 16:01:31 +0100312 try:
313 size = posix.readv(fd, [])
314 except OSError:
315 # readv(fd, []) raises OSError(22, "Invalid argument")
316 # on OpenIndiana
317 pass
318 else:
319 self.assertEqual(size, 0)
Ross Lagerwall7807c352011-03-17 20:20:30 +0200320 finally:
321 os.close(fd)
322
Serhiy Storchaka43767632013-11-03 21:31:38 +0200323 @unittest.skipUnless(hasattr(posix, 'dup'),
324 'test needs posix.dup()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000325 def test_dup(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200326 fp = open(support.TESTFN)
327 try:
328 fd = posix.dup(fp.fileno())
329 self.assertIsInstance(fd, int)
330 os.close(fd)
331 finally:
332 fp.close()
Neal Norwitze241ce82003-02-17 18:17:05 +0000333
Serhiy Storchaka43767632013-11-03 21:31:38 +0200334 @unittest.skipUnless(hasattr(posix, 'confstr'),
335 'test needs posix.confstr()')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000336 def test_confstr(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200337 self.assertRaises(ValueError, posix.confstr, "CS_garbage")
338 self.assertEqual(len(posix.confstr("CS_PATH")) > 0, True)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000339
Serhiy Storchaka43767632013-11-03 21:31:38 +0200340 @unittest.skipUnless(hasattr(posix, 'dup2'),
341 'test needs posix.dup2()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000342 def test_dup2(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200343 fp1 = open(support.TESTFN)
344 fp2 = open(support.TESTFN)
345 try:
346 posix.dup2(fp1.fileno(), fp2.fileno())
347 finally:
348 fp1.close()
349 fp2.close()
Neal Norwitze241ce82003-02-17 18:17:05 +0000350
Charles-François Natali1e045b12011-05-22 20:42:32 +0200351 @unittest.skipUnless(hasattr(os, 'O_CLOEXEC'), "needs os.O_CLOEXEC")
Charles-François Natali239bb962011-06-03 12:55:15 +0200352 @support.requires_linux_version(2, 6, 23)
Charles-François Natali1e045b12011-05-22 20:42:32 +0200353 def test_oscloexec(self):
354 fd = os.open(support.TESTFN, os.O_RDONLY|os.O_CLOEXEC)
355 self.addCleanup(os.close, fd)
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200356 self.assertFalse(os.get_inheritable(fd))
Charles-François Natali1e045b12011-05-22 20:42:32 +0200357
Serhiy Storchaka43767632013-11-03 21:31:38 +0200358 @unittest.skipUnless(hasattr(posix, 'O_EXLOCK'),
359 'test needs posix.O_EXLOCK')
Skip Montanaro98470002005-06-17 01:14:49 +0000360 def test_osexlock(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200361 fd = os.open(support.TESTFN,
362 os.O_WRONLY|os.O_EXLOCK|os.O_CREAT)
363 self.assertRaises(OSError, os.open, support.TESTFN,
364 os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
365 os.close(fd)
366
367 if hasattr(posix, "O_SHLOCK"):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000368 fd = os.open(support.TESTFN,
Serhiy Storchaka43767632013-11-03 21:31:38 +0200369 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000370 self.assertRaises(OSError, os.open, support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000371 os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
372 os.close(fd)
373
Serhiy Storchaka43767632013-11-03 21:31:38 +0200374 @unittest.skipUnless(hasattr(posix, 'O_SHLOCK'),
375 'test needs posix.O_SHLOCK')
Skip Montanaro98470002005-06-17 01:14:49 +0000376 def test_osshlock(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200377 fd1 = os.open(support.TESTFN,
378 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
379 fd2 = os.open(support.TESTFN,
380 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
381 os.close(fd2)
382 os.close(fd1)
383
384 if hasattr(posix, "O_EXLOCK"):
385 fd = os.open(support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000386 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
Serhiy Storchaka43767632013-11-03 21:31:38 +0200387 self.assertRaises(OSError, os.open, support.TESTFN,
388 os.O_RDONLY|os.O_EXLOCK|os.O_NONBLOCK)
389 os.close(fd)
Skip Montanaro98470002005-06-17 01:14:49 +0000390
Serhiy Storchaka43767632013-11-03 21:31:38 +0200391 @unittest.skipUnless(hasattr(posix, 'fstat'),
392 'test needs posix.fstat()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000393 def test_fstat(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200394 fp = open(support.TESTFN)
395 try:
396 self.assertTrue(posix.fstat(fp.fileno()))
397 self.assertTrue(posix.stat(fp.fileno()))
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200398
Serhiy Storchaka43767632013-11-03 21:31:38 +0200399 self.assertRaisesRegex(TypeError,
400 'should be string, bytes or integer, not',
401 posix.stat, float(fp.fileno()))
402 finally:
403 fp.close()
Neal Norwitze241ce82003-02-17 18:17:05 +0000404
Serhiy Storchaka43767632013-11-03 21:31:38 +0200405 @unittest.skipUnless(hasattr(posix, 'stat'),
406 'test needs posix.stat()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000407 def test_stat(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200408 self.assertTrue(posix.stat(support.TESTFN))
409 self.assertTrue(posix.stat(os.fsencode(support.TESTFN)))
410 self.assertTrue(posix.stat(bytearray(os.fsencode(support.TESTFN))))
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200411
Serhiy Storchaka43767632013-11-03 21:31:38 +0200412 self.assertRaisesRegex(TypeError,
Serhiy Storchaka7155b882016-04-08 08:48:20 +0300413 'should be string, bytes or integer, not',
Serhiy Storchaka43767632013-11-03 21:31:38 +0200414 posix.stat, None)
415 self.assertRaisesRegex(TypeError,
416 'should be string, bytes or integer, not',
417 posix.stat, list(support.TESTFN))
418 self.assertRaisesRegex(TypeError,
419 'should be string, bytes or integer, not',
420 posix.stat, list(os.fsencode(support.TESTFN)))
Neal Norwitze241ce82003-02-17 18:17:05 +0000421
Benjamin Peterson052a02b2010-08-17 01:27:09 +0000422 @unittest.skipUnless(hasattr(posix, 'mkfifo'), "don't have mkfifo()")
423 def test_mkfifo(self):
424 support.unlink(support.TESTFN)
425 posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR)
426 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
427
428 @unittest.skipUnless(hasattr(posix, 'mknod') and hasattr(stat, 'S_IFIFO'),
429 "don't have mknod()/S_IFIFO")
430 def test_mknod(self):
431 # Test using mknod() to create a FIFO (the only use specified
432 # by POSIX).
433 support.unlink(support.TESTFN)
434 mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
435 try:
436 posix.mknod(support.TESTFN, mode, 0)
437 except OSError as e:
438 # Some old systems don't allow unprivileged users to use
439 # mknod(), or only support creating device nodes.
440 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
441 else:
442 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
443
Martin Panterbf19d162015-09-09 01:01:13 +0000444 # Keyword arguments are also supported
445 support.unlink(support.TESTFN)
446 try:
447 posix.mknod(path=support.TESTFN, mode=mode, device=0,
448 dir_fd=None)
449 except OSError as e:
450 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
451
Serhiy Storchaka16b2e4f2015-04-20 09:22:13 +0300452 @unittest.skipUnless(hasattr(posix, 'stat'), 'test needs posix.stat()')
453 @unittest.skipUnless(hasattr(posix, 'makedev'), 'test needs posix.makedev()')
454 def test_makedev(self):
455 st = posix.stat(support.TESTFN)
456 dev = st.st_dev
457 self.assertIsInstance(dev, int)
458 self.assertGreaterEqual(dev, 0)
459
460 major = posix.major(dev)
461 self.assertIsInstance(major, int)
462 self.assertGreaterEqual(major, 0)
463 self.assertEqual(posix.major(dev), major)
464 self.assertRaises(TypeError, posix.major, float(dev))
465 self.assertRaises(TypeError, posix.major)
466 self.assertRaises((ValueError, OverflowError), posix.major, -1)
467
468 minor = posix.minor(dev)
469 self.assertIsInstance(minor, int)
470 self.assertGreaterEqual(minor, 0)
471 self.assertEqual(posix.minor(dev), minor)
472 self.assertRaises(TypeError, posix.minor, float(dev))
473 self.assertRaises(TypeError, posix.minor)
474 self.assertRaises((ValueError, OverflowError), posix.minor, -1)
475
476 self.assertEqual(posix.makedev(major, minor), dev)
477 self.assertRaises(TypeError, posix.makedev, float(major), minor)
478 self.assertRaises(TypeError, posix.makedev, major, float(minor))
479 self.assertRaises(TypeError, posix.makedev, major)
480 self.assertRaises(TypeError, posix.makedev)
481
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200482 def _test_all_chown_common(self, chown_func, first_param, stat_func):
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000483 """Common code for chown, fchown and lchown tests."""
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200484 def check_stat(uid, gid):
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200485 if stat_func is not None:
486 stat = stat_func(first_param)
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200487 self.assertEqual(stat.st_uid, uid)
488 self.assertEqual(stat.st_gid, gid)
489 uid = os.getuid()
490 gid = os.getgid()
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200491 # test a successful chown call
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200492 chown_func(first_param, uid, gid)
493 check_stat(uid, gid)
494 chown_func(first_param, -1, gid)
495 check_stat(uid, gid)
496 chown_func(first_param, uid, -1)
497 check_stat(uid, gid)
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200498
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200499 if uid == 0:
500 # Try an amusingly large uid/gid to make sure we handle
501 # large unsigned values. (chown lets you use any
502 # uid/gid you like, even if they aren't defined.)
503 #
504 # This problem keeps coming up:
505 # http://bugs.python.org/issue1747858
506 # http://bugs.python.org/issue4591
507 # http://bugs.python.org/issue15301
508 # Hopefully the fix in 4591 fixes it for good!
509 #
510 # This part of the test only runs when run as root.
511 # Only scary people run their tests as root.
512
513 big_value = 2**31
514 chown_func(first_param, big_value, big_value)
515 check_stat(big_value, big_value)
516 chown_func(first_param, -1, -1)
517 check_stat(big_value, big_value)
518 chown_func(first_param, uid, gid)
519 check_stat(uid, gid)
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200520 elif platform.system() in ('HP-UX', 'SunOS'):
521 # HP-UX and Solaris can allow a non-root user to chown() to root
522 # (issue #5113)
523 raise unittest.SkipTest("Skipping because of non-standard chown() "
524 "behavior")
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000525 else:
526 # non-root cannot chown to root, raises OSError
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200527 self.assertRaises(OSError, chown_func, first_param, 0, 0)
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200528 check_stat(uid, gid)
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200529 self.assertRaises(OSError, chown_func, first_param, 0, -1)
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200530 check_stat(uid, gid)
Serhiy Storchakaa2964b32013-02-21 14:34:36 +0200531 if 0 not in os.getgroups():
Serhiy Storchakab3d62ce2013-02-20 19:48:22 +0200532 self.assertRaises(OSError, chown_func, first_param, -1, 0)
533 check_stat(uid, gid)
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200534 # test illegal types
535 for t in str, float:
536 self.assertRaises(TypeError, chown_func, first_param, t(uid), gid)
537 check_stat(uid, gid)
538 self.assertRaises(TypeError, chown_func, first_param, uid, t(gid))
539 check_stat(uid, gid)
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000540
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000541 @unittest.skipUnless(hasattr(posix, 'chown'), "test needs os.chown()")
542 def test_chown(self):
543 # raise an OSError if the file does not exist
544 os.unlink(support.TESTFN)
545 self.assertRaises(OSError, posix.chown, support.TESTFN, -1, -1)
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000546
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000547 # re-create the file
Victor Stinnerbf816222011-06-30 23:25:47 +0200548 support.create_empty_file(support.TESTFN)
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200549 self._test_all_chown_common(posix.chown, support.TESTFN,
550 getattr(posix, 'stat', None))
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000551
552 @unittest.skipUnless(hasattr(posix, 'fchown'), "test needs os.fchown()")
553 def test_fchown(self):
554 os.unlink(support.TESTFN)
555
556 # re-create the file
557 test_file = open(support.TESTFN, 'w')
558 try:
559 fd = test_file.fileno()
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200560 self._test_all_chown_common(posix.fchown, fd,
561 getattr(posix, 'fstat', None))
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000562 finally:
563 test_file.close()
564
565 @unittest.skipUnless(hasattr(posix, 'lchown'), "test needs os.lchown()")
566 def test_lchown(self):
567 os.unlink(support.TESTFN)
568 # create a symlink
Ned Deily3eb67d52011-06-28 00:00:28 -0700569 os.symlink(_DUMMY_SYMLINK, support.TESTFN)
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200570 self._test_all_chown_common(posix.lchown, support.TESTFN,
571 getattr(posix, 'lstat', None))
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000572
Serhiy Storchaka43767632013-11-03 21:31:38 +0200573 @unittest.skipUnless(hasattr(posix, 'chdir'), 'test needs posix.chdir()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000574 def test_chdir(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200575 posix.chdir(os.curdir)
576 self.assertRaises(OSError, posix.chdir, support.TESTFN)
Neal Norwitze241ce82003-02-17 18:17:05 +0000577
Martin v. Löwisc9e1c7d2010-07-23 12:16:41 +0000578 def test_listdir(self):
Larry Hastingsfdaea062012-06-25 04:42:23 -0700579 self.assertTrue(support.TESTFN in posix.listdir(os.curdir))
Martin v. Löwisc9e1c7d2010-07-23 12:16:41 +0000580
581 def test_listdir_default(self):
Larry Hastingsfdaea062012-06-25 04:42:23 -0700582 # When listdir is called without argument,
583 # it's the same as listdir(os.curdir).
584 self.assertTrue(support.TESTFN in posix.listdir())
Neal Norwitze241ce82003-02-17 18:17:05 +0000585
Larry Hastingsfdaea062012-06-25 04:42:23 -0700586 def test_listdir_bytes(self):
587 # When listdir is called with a bytes object,
588 # the returned strings are of type bytes.
589 self.assertTrue(os.fsencode(support.TESTFN) in posix.listdir(b'.'))
590
591 @unittest.skipUnless(posix.listdir in os.supports_fd,
592 "test needs fd support for posix.listdir()")
593 def test_listdir_fd(self):
Antoine Pitrou8250e232011-02-25 23:41:16 +0000594 f = posix.open(posix.getcwd(), posix.O_RDONLY)
Charles-François Natali7546ad32012-01-08 18:34:06 +0100595 self.addCleanup(posix.close, f)
Antoine Pitrou8250e232011-02-25 23:41:16 +0000596 self.assertEqual(
597 sorted(posix.listdir('.')),
Larry Hastings9cf065c2012-06-22 16:30:09 -0700598 sorted(posix.listdir(f))
Antoine Pitrou8250e232011-02-25 23:41:16 +0000599 )
Charles-François Natali7546ad32012-01-08 18:34:06 +0100600 # Check that the fd offset was reset (issue #13739)
Charles-François Natali7546ad32012-01-08 18:34:06 +0100601 self.assertEqual(
602 sorted(posix.listdir('.')),
Larry Hastings9cf065c2012-06-22 16:30:09 -0700603 sorted(posix.listdir(f))
Charles-François Natali7546ad32012-01-08 18:34:06 +0100604 )
Antoine Pitrou8250e232011-02-25 23:41:16 +0000605
Serhiy Storchaka43767632013-11-03 21:31:38 +0200606 @unittest.skipUnless(hasattr(posix, 'access'), 'test needs posix.access()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000607 def test_access(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200608 self.assertTrue(posix.access(support.TESTFN, os.R_OK))
Neal Norwitze241ce82003-02-17 18:17:05 +0000609
Serhiy Storchaka43767632013-11-03 21:31:38 +0200610 @unittest.skipUnless(hasattr(posix, 'umask'), 'test needs posix.umask()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000611 def test_umask(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200612 old_mask = posix.umask(0)
613 self.assertIsInstance(old_mask, int)
614 posix.umask(old_mask)
Neal Norwitze241ce82003-02-17 18:17:05 +0000615
Serhiy Storchaka43767632013-11-03 21:31:38 +0200616 @unittest.skipUnless(hasattr(posix, 'strerror'),
617 'test needs posix.strerror()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000618 def test_strerror(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200619 self.assertTrue(posix.strerror(0))
Neal Norwitze241ce82003-02-17 18:17:05 +0000620
Serhiy Storchaka43767632013-11-03 21:31:38 +0200621 @unittest.skipUnless(hasattr(posix, 'pipe'), 'test needs posix.pipe()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000622 def test_pipe(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200623 reader, writer = posix.pipe()
624 os.close(reader)
625 os.close(writer)
Neal Norwitze241ce82003-02-17 18:17:05 +0000626
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200627 @unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()")
Charles-François Natali239bb962011-06-03 12:55:15 +0200628 @support.requires_linux_version(2, 6, 27)
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200629 def test_pipe2(self):
630 self.assertRaises(TypeError, os.pipe2, 'DEADBEEF')
631 self.assertRaises(TypeError, os.pipe2, 0, 0)
632
Charles-François Natali368f34b2011-06-06 19:49:47 +0200633 # try calling with flags = 0, like os.pipe()
634 r, w = os.pipe2(0)
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200635 os.close(r)
636 os.close(w)
637
638 # test flags
639 r, w = os.pipe2(os.O_CLOEXEC|os.O_NONBLOCK)
640 self.addCleanup(os.close, r)
641 self.addCleanup(os.close, w)
Victor Stinnerbff989e2013-08-28 12:25:40 +0200642 self.assertFalse(os.get_inheritable(r))
643 self.assertFalse(os.get_inheritable(w))
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200644 self.assertFalse(os.get_blocking(r))
645 self.assertFalse(os.get_blocking(w))
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200646 # try reading from an empty pipe: this should fail, not block
647 self.assertRaises(OSError, os.read, r, 1)
648 # try a write big enough to fill-up the pipe: this should either
649 # fail or perform a partial write, not block
650 try:
651 os.write(w, b'x' * support.PIPE_MAX_SIZE)
652 except OSError:
653 pass
654
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200655 @support.cpython_only
656 @unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()")
657 @support.requires_linux_version(2, 6, 27)
658 def test_pipe2_c_limits(self):
Serhiy Storchaka78980432013-01-15 01:12:17 +0200659 # Issue 15989
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200660 import _testcapi
Serhiy Storchaka78980432013-01-15 01:12:17 +0200661 self.assertRaises(OverflowError, os.pipe2, _testcapi.INT_MAX + 1)
662 self.assertRaises(OverflowError, os.pipe2, _testcapi.UINT_MAX + 1)
663
Serhiy Storchaka43767632013-11-03 21:31:38 +0200664 @unittest.skipUnless(hasattr(posix, 'utime'), 'test needs posix.utime()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000665 def test_utime(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200666 now = time.time()
667 posix.utime(support.TESTFN, None)
668 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None))
669 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None))
670 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now))
671 posix.utime(support.TESTFN, (int(now), int(now)))
672 posix.utime(support.TESTFN, (now, now))
Neal Norwitze241ce82003-02-17 18:17:05 +0000673
Larry Hastings9cf065c2012-06-22 16:30:09 -0700674 def _test_chflags_regular_file(self, chflags_func, target_file, **kwargs):
Ned Deily3eb67d52011-06-28 00:00:28 -0700675 st = os.stat(target_file)
676 self.assertTrue(hasattr(st, 'st_flags'))
Trent Nelson75959cf2012-08-21 23:59:31 +0000677
678 # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
679 flags = st.st_flags | stat.UF_IMMUTABLE
680 try:
681 chflags_func(target_file, flags, **kwargs)
682 except OSError as err:
683 if err.errno != errno.EOPNOTSUPP:
684 raise
685 msg = 'chflag UF_IMMUTABLE not supported by underlying fs'
686 self.skipTest(msg)
687
Ned Deily3eb67d52011-06-28 00:00:28 -0700688 try:
689 new_st = os.stat(target_file)
690 self.assertEqual(st.st_flags | stat.UF_IMMUTABLE, new_st.st_flags)
691 try:
692 fd = open(target_file, 'w+')
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200693 except OSError as e:
Ned Deily3eb67d52011-06-28 00:00:28 -0700694 self.assertEqual(e.errno, errno.EPERM)
695 finally:
696 posix.chflags(target_file, st.st_flags)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000697
Ned Deily3eb67d52011-06-28 00:00:28 -0700698 @unittest.skipUnless(hasattr(posix, 'chflags'), 'test needs os.chflags()')
699 def test_chflags(self):
700 self._test_chflags_regular_file(posix.chflags, support.TESTFN)
701
702 @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
703 def test_lchflags_regular_file(self):
704 self._test_chflags_regular_file(posix.lchflags, support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700705 self._test_chflags_regular_file(posix.chflags, support.TESTFN, follow_symlinks=False)
Ned Deily3eb67d52011-06-28 00:00:28 -0700706
707 @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
708 def test_lchflags_symlink(self):
709 testfn_st = os.stat(support.TESTFN)
710
711 self.assertTrue(hasattr(testfn_st, 'st_flags'))
712
713 os.symlink(support.TESTFN, _DUMMY_SYMLINK)
714 self.teardown_files.append(_DUMMY_SYMLINK)
715 dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
716
Larry Hastings9cf065c2012-06-22 16:30:09 -0700717 def chflags_nofollow(path, flags):
718 return posix.chflags(path, flags, follow_symlinks=False)
Ned Deily3eb67d52011-06-28 00:00:28 -0700719
Larry Hastings9cf065c2012-06-22 16:30:09 -0700720 for fn in (posix.lchflags, chflags_nofollow):
Trent Nelson75959cf2012-08-21 23:59:31 +0000721 # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
722 flags = dummy_symlink_st.st_flags | stat.UF_IMMUTABLE
723 try:
724 fn(_DUMMY_SYMLINK, flags)
725 except OSError as err:
726 if err.errno != errno.EOPNOTSUPP:
727 raise
728 msg = 'chflag UF_IMMUTABLE not supported by underlying fs'
729 self.skipTest(msg)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700730 try:
731 new_testfn_st = os.stat(support.TESTFN)
732 new_dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
733
734 self.assertEqual(testfn_st.st_flags, new_testfn_st.st_flags)
735 self.assertEqual(dummy_symlink_st.st_flags | stat.UF_IMMUTABLE,
736 new_dummy_symlink_st.st_flags)
737 finally:
738 fn(_DUMMY_SYMLINK, dummy_symlink_st.st_flags)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000739
Guido van Rossum98297ee2007-11-06 21:34:58 +0000740 def test_environ(self):
Victor Stinner17b490d2010-05-06 22:19:30 +0000741 if os.name == "nt":
742 item_type = str
743 else:
744 item_type = bytes
Guido van Rossum98297ee2007-11-06 21:34:58 +0000745 for k, v in posix.environ.items():
Victor Stinner17b490d2010-05-06 22:19:30 +0000746 self.assertEqual(type(k), item_type)
747 self.assertEqual(type(v), item_type)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000748
Serhiy Storchaka43767632013-11-03 21:31:38 +0200749 @unittest.skipUnless(hasattr(posix, 'getcwd'), 'test needs posix.getcwd()')
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000750 def test_getcwd_long_pathnames(self):
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500751 dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
752 curdir = os.getcwd()
753 base_path = os.path.abspath(support.TESTFN) + '.getcwd'
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000754
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500755 try:
756 os.mkdir(base_path)
757 os.chdir(base_path)
758 except:
759 # Just returning nothing instead of the SkipTest exception, because
760 # the test results in Error in that case. Is that ok?
761 # raise unittest.SkipTest("cannot create directory for testing")
762 return
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000763
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500764 def _create_and_do_getcwd(dirname, current_path_length = 0):
765 try:
766 os.mkdir(dirname)
767 except:
768 raise unittest.SkipTest("mkdir cannot create directory sufficiently deep for getcwd test")
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000769
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500770 os.chdir(dirname)
771 try:
772 os.getcwd()
773 if current_path_length < 1027:
774 _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1)
775 finally:
776 os.chdir('..')
777 os.rmdir(dirname)
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000778
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500779 _create_and_do_getcwd(dirname)
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000780
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500781 finally:
782 os.chdir(curdir)
783 support.rmtree(base_path)
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000784
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200785 @unittest.skipUnless(hasattr(posix, 'getgrouplist'), "test needs posix.getgrouplist()")
786 @unittest.skipUnless(hasattr(pwd, 'getpwuid'), "test needs pwd.getpwuid()")
787 @unittest.skipUnless(hasattr(os, 'getuid'), "test needs os.getuid()")
788 def test_getgrouplist(self):
Ross Lagerwalla0b315f2012-12-13 15:20:26 +0000789 user = pwd.getpwuid(os.getuid())[0]
790 group = pwd.getpwuid(os.getuid())[3]
791 self.assertIn(group, posix.getgrouplist(user, group))
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200792
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200793
Antoine Pitrou318b8f32011-01-12 18:45:27 +0000794 @unittest.skipUnless(hasattr(os, 'getegid'), "test needs os.getegid()")
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000795 def test_getgroups(self):
Jesus Cea61f32cb2014-06-28 18:39:35 +0200796 with os.popen('id -G 2>/dev/null') as idg:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000797 groups = idg.read().strip()
Charles-François Natalie8a255a2012-05-02 20:01:38 +0200798 ret = idg.close()
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000799
Benjamin Petersonb29614e2012-10-09 11:16:03 -0400800 if ret is not None or not groups:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000801 raise unittest.SkipTest("need working 'id -G'")
802
Ned Deily028915e2013-02-02 15:08:52 -0800803 # Issues 16698: OS X ABIs prior to 10.6 have limits on getgroups()
804 if sys.platform == 'darwin':
805 import sysconfig
806 dt = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') or '10.0'
Ned Deily04cdfa12014-06-25 13:36:14 -0700807 if tuple(int(n) for n in dt.split('.')[0:2]) < (10, 6):
Ned Deily028915e2013-02-02 15:08:52 -0800808 raise unittest.SkipTest("getgroups(2) is broken prior to 10.6")
809
Ronald Oussoren7fb6f512010-08-01 19:18:13 +0000810 # 'id -G' and 'os.getgroups()' should return the same
811 # groups, ignoring order and duplicates.
Antoine Pitrou318b8f32011-01-12 18:45:27 +0000812 # #10822 - it is implementation defined whether posix.getgroups()
813 # includes the effective gid so we include it anyway, since id -G does
Ronald Oussorencb615e62010-07-24 14:15:19 +0000814 self.assertEqual(
Ronald Oussoren7fb6f512010-08-01 19:18:13 +0000815 set([int(x) for x in groups.split()]),
Antoine Pitrou318b8f32011-01-12 18:45:27 +0000816 set(posix.getgroups() + [posix.getegid()]))
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000817
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000818 # tests for the posix *at functions follow
819
Larry Hastings9cf065c2012-06-22 16:30:09 -0700820 @unittest.skipUnless(os.access in os.supports_dir_fd, "test needs dir_fd support for os.access()")
821 def test_access_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000822 f = posix.open(posix.getcwd(), posix.O_RDONLY)
823 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700824 self.assertTrue(posix.access(support.TESTFN, os.R_OK, dir_fd=f))
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000825 finally:
826 posix.close(f)
827
Larry Hastings9cf065c2012-06-22 16:30:09 -0700828 @unittest.skipUnless(os.chmod in os.supports_dir_fd, "test needs dir_fd support in os.chmod()")
829 def test_chmod_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000830 os.chmod(support.TESTFN, stat.S_IRUSR)
831
832 f = posix.open(posix.getcwd(), posix.O_RDONLY)
833 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700834 posix.chmod(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000835
836 s = posix.stat(support.TESTFN)
837 self.assertEqual(s[0] & stat.S_IRWXU, stat.S_IRUSR | stat.S_IWUSR)
838 finally:
839 posix.close(f)
840
Larry Hastings9cf065c2012-06-22 16:30:09 -0700841 @unittest.skipUnless(os.chown in os.supports_dir_fd, "test needs dir_fd support in os.chown()")
842 def test_chown_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000843 support.unlink(support.TESTFN)
Victor Stinnerbf816222011-06-30 23:25:47 +0200844 support.create_empty_file(support.TESTFN)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000845
846 f = posix.open(posix.getcwd(), posix.O_RDONLY)
847 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700848 posix.chown(support.TESTFN, os.getuid(), os.getgid(), dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000849 finally:
850 posix.close(f)
851
Larry Hastings9cf065c2012-06-22 16:30:09 -0700852 @unittest.skipUnless(os.stat in os.supports_dir_fd, "test needs dir_fd support in os.stat()")
853 def test_stat_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000854 support.unlink(support.TESTFN)
855 with open(support.TESTFN, 'w') as outfile:
856 outfile.write("testline\n")
857
858 f = posix.open(posix.getcwd(), posix.O_RDONLY)
859 try:
860 s1 = posix.stat(support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700861 s2 = posix.stat(support.TESTFN, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000862 self.assertEqual(s1, s2)
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200863 s2 = posix.stat(support.TESTFN, dir_fd=None)
864 self.assertEqual(s1, s2)
Serhiy Storchaka7155b882016-04-08 08:48:20 +0300865 self.assertRaisesRegex(TypeError, 'should be integer or None, not',
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200866 posix.stat, support.TESTFN, dir_fd=posix.getcwd())
Serhiy Storchaka7155b882016-04-08 08:48:20 +0300867 self.assertRaisesRegex(TypeError, 'should be integer or None, not',
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200868 posix.stat, support.TESTFN, dir_fd=float(f))
869 self.assertRaises(OverflowError,
870 posix.stat, support.TESTFN, dir_fd=10**20)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000871 finally:
872 posix.close(f)
873
Larry Hastings9cf065c2012-06-22 16:30:09 -0700874 @unittest.skipUnless(os.utime in os.supports_dir_fd, "test needs dir_fd support in os.utime()")
875 def test_utime_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000876 f = posix.open(posix.getcwd(), posix.O_RDONLY)
877 try:
878 now = time.time()
Larry Hastings9cf065c2012-06-22 16:30:09 -0700879 posix.utime(support.TESTFN, None, dir_fd=f)
880 posix.utime(support.TESTFN, dir_fd=f)
881 self.assertRaises(TypeError, posix.utime, support.TESTFN, now, dir_fd=f)
882 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None), dir_fd=f)
883 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None), dir_fd=f)
884 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now), dir_fd=f)
885 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, "x"), dir_fd=f)
886 posix.utime(support.TESTFN, (int(now), int(now)), dir_fd=f)
887 posix.utime(support.TESTFN, (now, now), dir_fd=f)
888 posix.utime(support.TESTFN,
889 (int(now), int((now - int(now)) * 1e9)), dir_fd=f)
890 posix.utime(support.TESTFN, dir_fd=f,
891 times=(int(now), int((now - int(now)) * 1e9)))
892
Larry Hastings90867a52012-06-22 17:01:41 -0700893 # try dir_fd and follow_symlinks together
Larry Hastings9cf065c2012-06-22 16:30:09 -0700894 if os.utime in os.supports_follow_symlinks:
Larry Hastings90867a52012-06-22 17:01:41 -0700895 try:
896 posix.utime(support.TESTFN, follow_symlinks=False, dir_fd=f)
Georg Brandl969288e2012-06-26 09:25:44 +0200897 except ValueError:
Larry Hastings90867a52012-06-22 17:01:41 -0700898 # whoops! using both together not supported on this platform.
899 pass
Larry Hastings9cf065c2012-06-22 16:30:09 -0700900
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000901 finally:
902 posix.close(f)
903
Larry Hastings9cf065c2012-06-22 16:30:09 -0700904 @unittest.skipUnless(os.link in os.supports_dir_fd, "test needs dir_fd support in os.link()")
905 def test_link_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000906 f = posix.open(posix.getcwd(), posix.O_RDONLY)
907 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700908 posix.link(support.TESTFN, support.TESTFN + 'link', src_dir_fd=f, dst_dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000909 # should have same inodes
910 self.assertEqual(posix.stat(support.TESTFN)[1],
911 posix.stat(support.TESTFN + 'link')[1])
912 finally:
913 posix.close(f)
914 support.unlink(support.TESTFN + 'link')
915
Larry Hastings9cf065c2012-06-22 16:30:09 -0700916 @unittest.skipUnless(os.mkdir in os.supports_dir_fd, "test needs dir_fd support in os.mkdir()")
917 def test_mkdir_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000918 f = posix.open(posix.getcwd(), posix.O_RDONLY)
919 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700920 posix.mkdir(support.TESTFN + 'dir', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000921 posix.stat(support.TESTFN + 'dir') # should not raise exception
922 finally:
923 posix.close(f)
924 support.rmtree(support.TESTFN + 'dir')
925
Larry Hastings9cf065c2012-06-22 16:30:09 -0700926 @unittest.skipUnless((os.mknod in os.supports_dir_fd) and hasattr(stat, 'S_IFIFO'),
927 "test requires both stat.S_IFIFO and dir_fd support for os.mknod()")
928 def test_mknod_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000929 # Test using mknodat() to create a FIFO (the only use specified
930 # by POSIX).
931 support.unlink(support.TESTFN)
932 mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
933 f = posix.open(posix.getcwd(), posix.O_RDONLY)
934 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700935 posix.mknod(support.TESTFN, mode, 0, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000936 except OSError as e:
937 # Some old systems don't allow unprivileged users to use
938 # mknod(), or only support creating device nodes.
939 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
940 else:
941 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
942 finally:
943 posix.close(f)
944
Larry Hastings9cf065c2012-06-22 16:30:09 -0700945 @unittest.skipUnless(os.open in os.supports_dir_fd, "test needs dir_fd support in os.open()")
946 def test_open_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000947 support.unlink(support.TESTFN)
948 with open(support.TESTFN, 'w') as outfile:
949 outfile.write("testline\n")
950 a = posix.open(posix.getcwd(), posix.O_RDONLY)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700951 b = posix.open(support.TESTFN, posix.O_RDONLY, dir_fd=a)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000952 try:
953 res = posix.read(b, 9).decode(encoding="utf-8")
954 self.assertEqual("testline\n", res)
955 finally:
956 posix.close(a)
957 posix.close(b)
958
Larry Hastings9cf065c2012-06-22 16:30:09 -0700959 @unittest.skipUnless(os.readlink in os.supports_dir_fd, "test needs dir_fd support in os.readlink()")
960 def test_readlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000961 os.symlink(support.TESTFN, support.TESTFN + 'link')
962 f = posix.open(posix.getcwd(), posix.O_RDONLY)
963 try:
964 self.assertEqual(posix.readlink(support.TESTFN + 'link'),
Larry Hastings9cf065c2012-06-22 16:30:09 -0700965 posix.readlink(support.TESTFN + 'link', dir_fd=f))
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000966 finally:
967 support.unlink(support.TESTFN + 'link')
968 posix.close(f)
969
Larry Hastings9cf065c2012-06-22 16:30:09 -0700970 @unittest.skipUnless(os.rename in os.supports_dir_fd, "test needs dir_fd support in os.rename()")
971 def test_rename_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000972 support.unlink(support.TESTFN)
Victor Stinnerbf816222011-06-30 23:25:47 +0200973 support.create_empty_file(support.TESTFN + 'ren')
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000974 f = posix.open(posix.getcwd(), posix.O_RDONLY)
975 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700976 posix.rename(support.TESTFN + 'ren', support.TESTFN, src_dir_fd=f, dst_dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000977 except:
978 posix.rename(support.TESTFN + 'ren', support.TESTFN)
979 raise
980 else:
Andrew Svetlov5b898402012-12-18 21:26:36 +0200981 posix.stat(support.TESTFN) # should not raise exception
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000982 finally:
983 posix.close(f)
984
Larry Hastings9cf065c2012-06-22 16:30:09 -0700985 @unittest.skipUnless(os.symlink in os.supports_dir_fd, "test needs dir_fd support in os.symlink()")
986 def test_symlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000987 f = posix.open(posix.getcwd(), posix.O_RDONLY)
988 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700989 posix.symlink(support.TESTFN, support.TESTFN + 'link', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000990 self.assertEqual(posix.readlink(support.TESTFN + 'link'), support.TESTFN)
991 finally:
992 posix.close(f)
993 support.unlink(support.TESTFN + 'link')
994
Larry Hastings9cf065c2012-06-22 16:30:09 -0700995 @unittest.skipUnless(os.unlink in os.supports_dir_fd, "test needs dir_fd support in os.unlink()")
996 def test_unlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000997 f = posix.open(posix.getcwd(), posix.O_RDONLY)
Victor Stinnerbf816222011-06-30 23:25:47 +0200998 support.create_empty_file(support.TESTFN + 'del')
Andrew Svetlov5b898402012-12-18 21:26:36 +0200999 posix.stat(support.TESTFN + 'del') # should not raise exception
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001000 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001001 posix.unlink(support.TESTFN + 'del', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001002 except:
1003 support.unlink(support.TESTFN + 'del')
1004 raise
1005 else:
1006 self.assertRaises(OSError, posix.stat, support.TESTFN + 'link')
1007 finally:
1008 posix.close(f)
1009
Larry Hastings9cf065c2012-06-22 16:30:09 -07001010 @unittest.skipUnless(os.mkfifo in os.supports_dir_fd, "test needs dir_fd support in os.mkfifo()")
1011 def test_mkfifo_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001012 support.unlink(support.TESTFN)
1013 f = posix.open(posix.getcwd(), posix.O_RDONLY)
1014 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001015 posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001016 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
1017 finally:
1018 posix.close(f)
1019
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001020 requires_sched_h = unittest.skipUnless(hasattr(posix, 'sched_yield'),
1021 "don't have scheduling support")
Antoine Pitrou84869872012-08-04 16:16:35 +02001022 requires_sched_affinity = unittest.skipUnless(hasattr(posix, 'sched_setaffinity'),
Benjamin Peterson50ba2712011-08-02 22:15:40 -05001023 "don't have sched affinity support")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001024
1025 @requires_sched_h
1026 def test_sched_yield(self):
1027 # This has no error conditions (at least on Linux).
1028 posix.sched_yield()
1029
1030 @requires_sched_h
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02001031 @unittest.skipUnless(hasattr(posix, 'sched_get_priority_max'),
1032 "requires sched_get_priority_max()")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001033 def test_sched_priority(self):
1034 # Round-robin usually has interesting priorities.
1035 pol = posix.SCHED_RR
1036 lo = posix.sched_get_priority_min(pol)
1037 hi = posix.sched_get_priority_max(pol)
1038 self.assertIsInstance(lo, int)
1039 self.assertIsInstance(hi, int)
1040 self.assertGreaterEqual(hi, lo)
Benjamin Peterson539b6c42011-08-02 22:09:37 -05001041 # OSX evidently just returns 15 without checking the argument.
1042 if sys.platform != "darwin":
Benjamin Petersonc1581582011-08-02 22:10:55 -05001043 self.assertRaises(OSError, posix.sched_get_priority_min, -23)
1044 self.assertRaises(OSError, posix.sched_get_priority_max, -23)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001045
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05001046 @unittest.skipUnless(hasattr(posix, 'sched_setscheduler'), "can't change scheduler")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001047 def test_get_and_set_scheduler_and_param(self):
1048 possible_schedulers = [sched for name, sched in posix.__dict__.items()
1049 if name.startswith("SCHED_")]
1050 mine = posix.sched_getscheduler(0)
1051 self.assertIn(mine, possible_schedulers)
1052 try:
Jesus Ceaceb5d162011-09-10 01:16:55 +02001053 parent = posix.sched_getscheduler(os.getppid())
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001054 except OSError as e:
Jesus Ceaceb5d162011-09-10 01:16:55 +02001055 if e.errno != errno.EPERM:
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001056 raise
1057 else:
Jesus Ceaceb5d162011-09-10 01:16:55 +02001058 self.assertIn(parent, possible_schedulers)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001059 self.assertRaises(OSError, posix.sched_getscheduler, -1)
1060 self.assertRaises(OSError, posix.sched_getparam, -1)
1061 param = posix.sched_getparam(0)
1062 self.assertIsInstance(param.sched_priority, int)
Charles-François Natali7b911cb2011-08-21 12:41:43 +02001063
Charles-François Natalib402a5c2013-01-13 14:13:25 +01001064 # POSIX states that calling sched_setparam() or sched_setscheduler() on
1065 # a process with a scheduling policy other than SCHED_FIFO or SCHED_RR
1066 # is implementation-defined: NetBSD and FreeBSD can return EINVAL.
1067 if not sys.platform.startswith(('freebsd', 'netbsd')):
1068 try:
1069 posix.sched_setscheduler(0, mine, param)
1070 posix.sched_setparam(0, param)
1071 except OSError as e:
1072 if e.errno != errno.EPERM:
1073 raise
Charles-François Natali7b911cb2011-08-21 12:41:43 +02001074 self.assertRaises(OSError, posix.sched_setparam, -1, param)
1075
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001076 self.assertRaises(OSError, posix.sched_setscheduler, -1, mine, param)
1077 self.assertRaises(TypeError, posix.sched_setscheduler, 0, mine, None)
1078 self.assertRaises(TypeError, posix.sched_setparam, 0, 43)
1079 param = posix.sched_param(None)
1080 self.assertRaises(TypeError, posix.sched_setparam, 0, param)
1081 large = 214748364700
1082 param = posix.sched_param(large)
1083 self.assertRaises(OverflowError, posix.sched_setparam, 0, param)
1084 param = posix.sched_param(sched_priority=-large)
1085 self.assertRaises(OverflowError, posix.sched_setparam, 0, param)
1086
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05001087 @unittest.skipUnless(hasattr(posix, "sched_rr_get_interval"), "no function")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001088 def test_sched_rr_get_interval(self):
Benjamin Peterson43234ab2011-08-02 22:19:14 -05001089 try:
1090 interval = posix.sched_rr_get_interval(0)
1091 except OSError as e:
1092 # This likely means that sched_rr_get_interval is only valid for
1093 # processes with the SCHED_RR scheduler in effect.
1094 if e.errno != errno.EINVAL:
1095 raise
1096 self.skipTest("only works on SCHED_RR processes")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001097 self.assertIsInstance(interval, float)
1098 # Reasonable constraints, I think.
1099 self.assertGreaterEqual(interval, 0.)
1100 self.assertLess(interval, 1.)
1101
Benjamin Peterson2740af82011-08-02 17:41:34 -05001102 @requires_sched_affinity
Antoine Pitrou84869872012-08-04 16:16:35 +02001103 def test_sched_getaffinity(self):
1104 mask = posix.sched_getaffinity(0)
1105 self.assertIsInstance(mask, set)
1106 self.assertGreaterEqual(len(mask), 1)
1107 self.assertRaises(OSError, posix.sched_getaffinity, -1)
1108 for cpu in mask:
1109 self.assertIsInstance(cpu, int)
1110 self.assertGreaterEqual(cpu, 0)
1111 self.assertLess(cpu, 1 << 32)
1112
1113 @requires_sched_affinity
1114 def test_sched_setaffinity(self):
1115 mask = posix.sched_getaffinity(0)
1116 if len(mask) > 1:
1117 # Empty masks are forbidden
1118 mask.pop()
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001119 posix.sched_setaffinity(0, mask)
Antoine Pitrou84869872012-08-04 16:16:35 +02001120 self.assertEqual(posix.sched_getaffinity(0), mask)
1121 self.assertRaises(OSError, posix.sched_setaffinity, 0, [])
1122 self.assertRaises(ValueError, posix.sched_setaffinity, 0, [-10])
1123 self.assertRaises(OverflowError, posix.sched_setaffinity, 0, [1<<128])
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001124 self.assertRaises(OSError, posix.sched_setaffinity, -1, mask)
1125
Victor Stinner8b905bd2011-10-25 13:34:04 +02001126 def test_rtld_constants(self):
1127 # check presence of major RTLD_* constants
1128 posix.RTLD_LAZY
1129 posix.RTLD_NOW
1130 posix.RTLD_GLOBAL
1131 posix.RTLD_LOCAL
1132
Jesus Cea60c13dd2012-06-23 02:58:14 +02001133 @unittest.skipUnless(hasattr(os, 'SEEK_HOLE'),
1134 "test needs an OS that reports file holes")
Hynek Schlawackf841e422012-06-24 09:51:46 +02001135 def test_fs_holes(self):
Jesus Cea94363612012-06-22 18:32:07 +02001136 # Even if the filesystem doesn't report holes,
1137 # if the OS supports it the SEEK_* constants
1138 # will be defined and will have a consistent
1139 # behaviour:
1140 # os.SEEK_DATA = current position
1141 # os.SEEK_HOLE = end of file position
Hynek Schlawackf841e422012-06-24 09:51:46 +02001142 with open(support.TESTFN, 'r+b') as fp:
Jesus Cea94363612012-06-22 18:32:07 +02001143 fp.write(b"hello")
1144 fp.flush()
1145 size = fp.tell()
1146 fno = fp.fileno()
Jesus Cead46f7d22012-07-07 14:56:04 +02001147 try :
1148 for i in range(size):
1149 self.assertEqual(i, os.lseek(fno, i, os.SEEK_DATA))
1150 self.assertLessEqual(size, os.lseek(fno, i, os.SEEK_HOLE))
1151 self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_DATA)
1152 self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_HOLE)
1153 except OSError :
1154 # Some OSs claim to support SEEK_HOLE/SEEK_DATA
1155 # but it is not true.
1156 # For instance:
1157 # http://lists.freebsd.org/pipermail/freebsd-amd64/2012-January/014332.html
1158 raise unittest.SkipTest("OSError raised!")
Jesus Cea94363612012-06-22 18:32:07 +02001159
Larry Hastingsb0827312014-02-09 22:05:19 -08001160 def test_path_error2(self):
1161 """
1162 Test functions that call path_error2(), providing two filenames in their exceptions.
1163 """
Victor Stinner047b7ae2014-10-05 17:37:41 +02001164 for name in ("rename", "replace", "link"):
Larry Hastingsb0827312014-02-09 22:05:19 -08001165 function = getattr(os, name, None)
Victor Stinnerbed04a72014-10-05 17:37:59 +02001166 if function is None:
1167 continue
Larry Hastingsb0827312014-02-09 22:05:19 -08001168
Victor Stinnerbed04a72014-10-05 17:37:59 +02001169 for dst in ("noodly2", support.TESTFN):
1170 try:
1171 function('doesnotexistfilename', dst)
1172 except OSError as e:
1173 self.assertIn("'doesnotexistfilename' -> '{}'".format(dst), str(e))
1174 break
1175 else:
1176 self.fail("No valid path_error2() test for os." + name)
Larry Hastingsb0827312014-02-09 22:05:19 -08001177
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001178 def test_path_with_null_character(self):
1179 fn = support.TESTFN
1180 fn_with_NUL = fn + '\0'
1181 self.addCleanup(support.unlink, fn)
1182 support.unlink(fn)
1183 fd = None
1184 try:
Serhiy Storchaka7e9d1d12015-04-20 10:12:28 +03001185 with self.assertRaises(ValueError):
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001186 fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # raises
1187 finally:
1188 if fd is not None:
1189 os.close(fd)
1190 self.assertFalse(os.path.exists(fn))
Serhiy Storchaka7e9d1d12015-04-20 10:12:28 +03001191 self.assertRaises(ValueError, os.mkdir, fn_with_NUL)
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001192 self.assertFalse(os.path.exists(fn))
1193 open(fn, 'wb').close()
Serhiy Storchaka7e9d1d12015-04-20 10:12:28 +03001194 self.assertRaises(ValueError, os.stat, fn_with_NUL)
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001195
1196 def test_path_with_null_byte(self):
1197 fn = os.fsencode(support.TESTFN)
1198 fn_with_NUL = fn + b'\0'
1199 self.addCleanup(support.unlink, fn)
1200 support.unlink(fn)
1201 fd = None
1202 try:
1203 with self.assertRaises(ValueError):
1204 fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # raises
1205 finally:
1206 if fd is not None:
1207 os.close(fd)
1208 self.assertFalse(os.path.exists(fn))
1209 self.assertRaises(ValueError, os.mkdir, fn_with_NUL)
1210 self.assertFalse(os.path.exists(fn))
1211 open(fn, 'wb').close()
1212 self.assertRaises(ValueError, os.stat, fn_with_NUL)
1213
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001214class PosixGroupsTester(unittest.TestCase):
1215
1216 def setUp(self):
1217 if posix.getuid() != 0:
1218 raise unittest.SkipTest("not enough privileges")
1219 if not hasattr(posix, 'getgroups'):
1220 raise unittest.SkipTest("need posix.getgroups")
1221 if sys.platform == 'darwin':
1222 raise unittest.SkipTest("getgroups(2) is broken on OSX")
1223 self.saved_groups = posix.getgroups()
1224
1225 def tearDown(self):
1226 if hasattr(posix, 'setgroups'):
1227 posix.setgroups(self.saved_groups)
1228 elif hasattr(posix, 'initgroups'):
1229 name = pwd.getpwuid(posix.getuid()).pw_name
1230 posix.initgroups(name, self.saved_groups[0])
1231
1232 @unittest.skipUnless(hasattr(posix, 'initgroups'),
1233 "test needs posix.initgroups()")
1234 def test_initgroups(self):
1235 # find missing group
1236
Benjamin Peterson659a6f52014-03-01 19:14:12 -05001237 g = max(self.saved_groups or [0]) + 1
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001238 name = pwd.getpwuid(posix.getuid()).pw_name
1239 posix.initgroups(name, g)
1240 self.assertIn(g, posix.getgroups())
1241
1242 @unittest.skipUnless(hasattr(posix, 'setgroups'),
1243 "test needs posix.setgroups()")
1244 def test_setgroups(self):
Antoine Pitroue5a91012010-09-04 17:32:06 +00001245 for groups in [[0], list(range(16))]:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001246 posix.setgroups(groups)
1247 self.assertListEqual(groups, posix.getgroups())
1248
Neal Norwitze241ce82003-02-17 18:17:05 +00001249def test_main():
Antoine Pitrou68c95922011-03-20 17:33:57 +01001250 try:
1251 support.run_unittest(PosixTester, PosixGroupsTester)
1252 finally:
1253 support.reap_children()
Neal Norwitze241ce82003-02-17 18:17:05 +00001254
1255if __name__ == '__main__':
1256 test_main()