blob: 63c74cd80da7a336f03ec0afd2d708da116bd416 [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,
Brett Cannon3f9183b2016-08-26 14:44:48 -0700400 'should be string, bytes, os.PathLike or integer, not',
Serhiy Storchaka43767632013-11-03 21:31:38 +0200401 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)))
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200410
Serhiy Storchakad73c3182016-08-06 23:22:08 +0300411 self.assertWarnsRegex(DeprecationWarning,
Brett Cannon3f9183b2016-08-26 14:44:48 -0700412 'should be string, bytes, os.PathLike or integer, not',
Serhiy Storchakad73c3182016-08-06 23:22:08 +0300413 posix.stat, bytearray(os.fsencode(support.TESTFN)))
Serhiy Storchaka43767632013-11-03 21:31:38 +0200414 self.assertRaisesRegex(TypeError,
Brett Cannon3f9183b2016-08-26 14:44:48 -0700415 'should be string, bytes, os.PathLike or integer, not',
Serhiy Storchaka43767632013-11-03 21:31:38 +0200416 posix.stat, None)
417 self.assertRaisesRegex(TypeError,
Brett Cannon3f9183b2016-08-26 14:44:48 -0700418 'should be string, bytes, os.PathLike or integer, not',
Serhiy Storchaka43767632013-11-03 21:31:38 +0200419 posix.stat, list(support.TESTFN))
420 self.assertRaisesRegex(TypeError,
Brett Cannon3f9183b2016-08-26 14:44:48 -0700421 'should be string, bytes, os.PathLike or integer, not',
Serhiy Storchaka43767632013-11-03 21:31:38 +0200422 posix.stat, list(os.fsencode(support.TESTFN)))
Neal Norwitze241ce82003-02-17 18:17:05 +0000423
Benjamin Peterson052a02b2010-08-17 01:27:09 +0000424 @unittest.skipUnless(hasattr(posix, 'mkfifo'), "don't have mkfifo()")
425 def test_mkfifo(self):
426 support.unlink(support.TESTFN)
427 posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR)
428 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
429
430 @unittest.skipUnless(hasattr(posix, 'mknod') and hasattr(stat, 'S_IFIFO'),
431 "don't have mknod()/S_IFIFO")
432 def test_mknod(self):
433 # Test using mknod() to create a FIFO (the only use specified
434 # by POSIX).
435 support.unlink(support.TESTFN)
436 mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
437 try:
438 posix.mknod(support.TESTFN, mode, 0)
439 except OSError as e:
440 # Some old systems don't allow unprivileged users to use
441 # mknod(), or only support creating device nodes.
442 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
443 else:
444 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
445
Martin Panterbf19d162015-09-09 01:01:13 +0000446 # Keyword arguments are also supported
447 support.unlink(support.TESTFN)
448 try:
449 posix.mknod(path=support.TESTFN, mode=mode, device=0,
450 dir_fd=None)
451 except OSError as e:
452 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
453
Serhiy Storchaka16b2e4f2015-04-20 09:22:13 +0300454 @unittest.skipUnless(hasattr(posix, 'stat'), 'test needs posix.stat()')
455 @unittest.skipUnless(hasattr(posix, 'makedev'), 'test needs posix.makedev()')
456 def test_makedev(self):
457 st = posix.stat(support.TESTFN)
458 dev = st.st_dev
459 self.assertIsInstance(dev, int)
460 self.assertGreaterEqual(dev, 0)
461
462 major = posix.major(dev)
463 self.assertIsInstance(major, int)
464 self.assertGreaterEqual(major, 0)
465 self.assertEqual(posix.major(dev), major)
466 self.assertRaises(TypeError, posix.major, float(dev))
467 self.assertRaises(TypeError, posix.major)
468 self.assertRaises((ValueError, OverflowError), posix.major, -1)
469
470 minor = posix.minor(dev)
471 self.assertIsInstance(minor, int)
472 self.assertGreaterEqual(minor, 0)
473 self.assertEqual(posix.minor(dev), minor)
474 self.assertRaises(TypeError, posix.minor, float(dev))
475 self.assertRaises(TypeError, posix.minor)
476 self.assertRaises((ValueError, OverflowError), posix.minor, -1)
477
478 self.assertEqual(posix.makedev(major, minor), dev)
479 self.assertRaises(TypeError, posix.makedev, float(major), minor)
480 self.assertRaises(TypeError, posix.makedev, major, float(minor))
481 self.assertRaises(TypeError, posix.makedev, major)
482 self.assertRaises(TypeError, posix.makedev)
483
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200484 def _test_all_chown_common(self, chown_func, first_param, stat_func):
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000485 """Common code for chown, fchown and lchown tests."""
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200486 def check_stat(uid, gid):
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200487 if stat_func is not None:
488 stat = stat_func(first_param)
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200489 self.assertEqual(stat.st_uid, uid)
490 self.assertEqual(stat.st_gid, gid)
491 uid = os.getuid()
492 gid = os.getgid()
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200493 # test a successful chown call
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200494 chown_func(first_param, uid, gid)
495 check_stat(uid, gid)
496 chown_func(first_param, -1, gid)
497 check_stat(uid, gid)
498 chown_func(first_param, uid, -1)
499 check_stat(uid, gid)
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200500
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200501 if uid == 0:
502 # Try an amusingly large uid/gid to make sure we handle
503 # large unsigned values. (chown lets you use any
504 # uid/gid you like, even if they aren't defined.)
505 #
506 # This problem keeps coming up:
507 # http://bugs.python.org/issue1747858
508 # http://bugs.python.org/issue4591
509 # http://bugs.python.org/issue15301
510 # Hopefully the fix in 4591 fixes it for good!
511 #
512 # This part of the test only runs when run as root.
513 # Only scary people run their tests as root.
514
515 big_value = 2**31
516 chown_func(first_param, big_value, big_value)
517 check_stat(big_value, big_value)
518 chown_func(first_param, -1, -1)
519 check_stat(big_value, big_value)
520 chown_func(first_param, uid, gid)
521 check_stat(uid, gid)
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200522 elif platform.system() in ('HP-UX', 'SunOS'):
523 # HP-UX and Solaris can allow a non-root user to chown() to root
524 # (issue #5113)
525 raise unittest.SkipTest("Skipping because of non-standard chown() "
526 "behavior")
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000527 else:
528 # non-root cannot chown to root, raises OSError
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200529 self.assertRaises(OSError, chown_func, first_param, 0, 0)
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200530 check_stat(uid, gid)
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200531 self.assertRaises(OSError, chown_func, first_param, 0, -1)
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200532 check_stat(uid, gid)
Serhiy Storchakaa2964b32013-02-21 14:34:36 +0200533 if 0 not in os.getgroups():
Serhiy Storchakab3d62ce2013-02-20 19:48:22 +0200534 self.assertRaises(OSError, chown_func, first_param, -1, 0)
535 check_stat(uid, gid)
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200536 # test illegal types
537 for t in str, float:
538 self.assertRaises(TypeError, chown_func, first_param, t(uid), gid)
539 check_stat(uid, gid)
540 self.assertRaises(TypeError, chown_func, first_param, uid, t(gid))
541 check_stat(uid, gid)
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000542
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000543 @unittest.skipUnless(hasattr(posix, 'chown'), "test needs os.chown()")
544 def test_chown(self):
545 # raise an OSError if the file does not exist
546 os.unlink(support.TESTFN)
547 self.assertRaises(OSError, posix.chown, support.TESTFN, -1, -1)
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000548
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000549 # re-create the file
Victor Stinnerbf816222011-06-30 23:25:47 +0200550 support.create_empty_file(support.TESTFN)
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200551 self._test_all_chown_common(posix.chown, support.TESTFN,
552 getattr(posix, 'stat', None))
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000553
554 @unittest.skipUnless(hasattr(posix, 'fchown'), "test needs os.fchown()")
555 def test_fchown(self):
556 os.unlink(support.TESTFN)
557
558 # re-create the file
559 test_file = open(support.TESTFN, 'w')
560 try:
561 fd = test_file.fileno()
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200562 self._test_all_chown_common(posix.fchown, fd,
563 getattr(posix, 'fstat', None))
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000564 finally:
565 test_file.close()
566
567 @unittest.skipUnless(hasattr(posix, 'lchown'), "test needs os.lchown()")
568 def test_lchown(self):
569 os.unlink(support.TESTFN)
570 # create a symlink
Ned Deily3eb67d52011-06-28 00:00:28 -0700571 os.symlink(_DUMMY_SYMLINK, support.TESTFN)
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200572 self._test_all_chown_common(posix.lchown, support.TESTFN,
573 getattr(posix, 'lstat', None))
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000574
Serhiy Storchaka43767632013-11-03 21:31:38 +0200575 @unittest.skipUnless(hasattr(posix, 'chdir'), 'test needs posix.chdir()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000576 def test_chdir(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200577 posix.chdir(os.curdir)
578 self.assertRaises(OSError, posix.chdir, support.TESTFN)
Neal Norwitze241ce82003-02-17 18:17:05 +0000579
Martin v. Löwisc9e1c7d2010-07-23 12:16:41 +0000580 def test_listdir(self):
Larry Hastingsfdaea062012-06-25 04:42:23 -0700581 self.assertTrue(support.TESTFN in posix.listdir(os.curdir))
Martin v. Löwisc9e1c7d2010-07-23 12:16:41 +0000582
583 def test_listdir_default(self):
Larry Hastingsfdaea062012-06-25 04:42:23 -0700584 # When listdir is called without argument,
585 # it's the same as listdir(os.curdir).
586 self.assertTrue(support.TESTFN in posix.listdir())
Neal Norwitze241ce82003-02-17 18:17:05 +0000587
Larry Hastingsfdaea062012-06-25 04:42:23 -0700588 def test_listdir_bytes(self):
589 # When listdir is called with a bytes object,
590 # the returned strings are of type bytes.
591 self.assertTrue(os.fsencode(support.TESTFN) in posix.listdir(b'.'))
592
593 @unittest.skipUnless(posix.listdir in os.supports_fd,
594 "test needs fd support for posix.listdir()")
595 def test_listdir_fd(self):
Antoine Pitrou8250e232011-02-25 23:41:16 +0000596 f = posix.open(posix.getcwd(), posix.O_RDONLY)
Charles-François Natali7546ad32012-01-08 18:34:06 +0100597 self.addCleanup(posix.close, f)
Antoine Pitrou8250e232011-02-25 23:41:16 +0000598 self.assertEqual(
599 sorted(posix.listdir('.')),
Larry Hastings9cf065c2012-06-22 16:30:09 -0700600 sorted(posix.listdir(f))
Antoine Pitrou8250e232011-02-25 23:41:16 +0000601 )
Charles-François Natali7546ad32012-01-08 18:34:06 +0100602 # Check that the fd offset was reset (issue #13739)
Charles-François Natali7546ad32012-01-08 18:34:06 +0100603 self.assertEqual(
604 sorted(posix.listdir('.')),
Larry Hastings9cf065c2012-06-22 16:30:09 -0700605 sorted(posix.listdir(f))
Charles-François Natali7546ad32012-01-08 18:34:06 +0100606 )
Antoine Pitrou8250e232011-02-25 23:41:16 +0000607
Serhiy Storchaka43767632013-11-03 21:31:38 +0200608 @unittest.skipUnless(hasattr(posix, 'access'), 'test needs posix.access()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000609 def test_access(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200610 self.assertTrue(posix.access(support.TESTFN, os.R_OK))
Neal Norwitze241ce82003-02-17 18:17:05 +0000611
Serhiy Storchaka43767632013-11-03 21:31:38 +0200612 @unittest.skipUnless(hasattr(posix, 'umask'), 'test needs posix.umask()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000613 def test_umask(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200614 old_mask = posix.umask(0)
615 self.assertIsInstance(old_mask, int)
616 posix.umask(old_mask)
Neal Norwitze241ce82003-02-17 18:17:05 +0000617
Serhiy Storchaka43767632013-11-03 21:31:38 +0200618 @unittest.skipUnless(hasattr(posix, 'strerror'),
619 'test needs posix.strerror()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000620 def test_strerror(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200621 self.assertTrue(posix.strerror(0))
Neal Norwitze241ce82003-02-17 18:17:05 +0000622
Serhiy Storchaka43767632013-11-03 21:31:38 +0200623 @unittest.skipUnless(hasattr(posix, 'pipe'), 'test needs posix.pipe()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000624 def test_pipe(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200625 reader, writer = posix.pipe()
626 os.close(reader)
627 os.close(writer)
Neal Norwitze241ce82003-02-17 18:17:05 +0000628
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200629 @unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()")
Charles-François Natali239bb962011-06-03 12:55:15 +0200630 @support.requires_linux_version(2, 6, 27)
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200631 def test_pipe2(self):
632 self.assertRaises(TypeError, os.pipe2, 'DEADBEEF')
633 self.assertRaises(TypeError, os.pipe2, 0, 0)
634
Charles-François Natali368f34b2011-06-06 19:49:47 +0200635 # try calling with flags = 0, like os.pipe()
636 r, w = os.pipe2(0)
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200637 os.close(r)
638 os.close(w)
639
640 # test flags
641 r, w = os.pipe2(os.O_CLOEXEC|os.O_NONBLOCK)
642 self.addCleanup(os.close, r)
643 self.addCleanup(os.close, w)
Victor Stinnerbff989e2013-08-28 12:25:40 +0200644 self.assertFalse(os.get_inheritable(r))
645 self.assertFalse(os.get_inheritable(w))
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200646 self.assertFalse(os.get_blocking(r))
647 self.assertFalse(os.get_blocking(w))
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200648 # try reading from an empty pipe: this should fail, not block
649 self.assertRaises(OSError, os.read, r, 1)
650 # try a write big enough to fill-up the pipe: this should either
651 # fail or perform a partial write, not block
652 try:
653 os.write(w, b'x' * support.PIPE_MAX_SIZE)
654 except OSError:
655 pass
656
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200657 @support.cpython_only
658 @unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()")
659 @support.requires_linux_version(2, 6, 27)
660 def test_pipe2_c_limits(self):
Serhiy Storchaka78980432013-01-15 01:12:17 +0200661 # Issue 15989
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200662 import _testcapi
Serhiy Storchaka78980432013-01-15 01:12:17 +0200663 self.assertRaises(OverflowError, os.pipe2, _testcapi.INT_MAX + 1)
664 self.assertRaises(OverflowError, os.pipe2, _testcapi.UINT_MAX + 1)
665
Serhiy Storchaka43767632013-11-03 21:31:38 +0200666 @unittest.skipUnless(hasattr(posix, 'utime'), 'test needs posix.utime()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000667 def test_utime(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200668 now = time.time()
669 posix.utime(support.TESTFN, None)
670 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None))
671 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None))
672 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now))
673 posix.utime(support.TESTFN, (int(now), int(now)))
674 posix.utime(support.TESTFN, (now, now))
Neal Norwitze241ce82003-02-17 18:17:05 +0000675
Larry Hastings9cf065c2012-06-22 16:30:09 -0700676 def _test_chflags_regular_file(self, chflags_func, target_file, **kwargs):
Ned Deily3eb67d52011-06-28 00:00:28 -0700677 st = os.stat(target_file)
678 self.assertTrue(hasattr(st, 'st_flags'))
Trent Nelson75959cf2012-08-21 23:59:31 +0000679
680 # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
681 flags = st.st_flags | stat.UF_IMMUTABLE
682 try:
683 chflags_func(target_file, flags, **kwargs)
684 except OSError as err:
685 if err.errno != errno.EOPNOTSUPP:
686 raise
687 msg = 'chflag UF_IMMUTABLE not supported by underlying fs'
688 self.skipTest(msg)
689
Ned Deily3eb67d52011-06-28 00:00:28 -0700690 try:
691 new_st = os.stat(target_file)
692 self.assertEqual(st.st_flags | stat.UF_IMMUTABLE, new_st.st_flags)
693 try:
694 fd = open(target_file, 'w+')
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200695 except OSError as e:
Ned Deily3eb67d52011-06-28 00:00:28 -0700696 self.assertEqual(e.errno, errno.EPERM)
697 finally:
698 posix.chflags(target_file, st.st_flags)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000699
Ned Deily3eb67d52011-06-28 00:00:28 -0700700 @unittest.skipUnless(hasattr(posix, 'chflags'), 'test needs os.chflags()')
701 def test_chflags(self):
702 self._test_chflags_regular_file(posix.chflags, support.TESTFN)
703
704 @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
705 def test_lchflags_regular_file(self):
706 self._test_chflags_regular_file(posix.lchflags, support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700707 self._test_chflags_regular_file(posix.chflags, support.TESTFN, follow_symlinks=False)
Ned Deily3eb67d52011-06-28 00:00:28 -0700708
709 @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
710 def test_lchflags_symlink(self):
711 testfn_st = os.stat(support.TESTFN)
712
713 self.assertTrue(hasattr(testfn_st, 'st_flags'))
714
715 os.symlink(support.TESTFN, _DUMMY_SYMLINK)
716 self.teardown_files.append(_DUMMY_SYMLINK)
717 dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
718
Larry Hastings9cf065c2012-06-22 16:30:09 -0700719 def chflags_nofollow(path, flags):
720 return posix.chflags(path, flags, follow_symlinks=False)
Ned Deily3eb67d52011-06-28 00:00:28 -0700721
Larry Hastings9cf065c2012-06-22 16:30:09 -0700722 for fn in (posix.lchflags, chflags_nofollow):
Trent Nelson75959cf2012-08-21 23:59:31 +0000723 # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
724 flags = dummy_symlink_st.st_flags | stat.UF_IMMUTABLE
725 try:
726 fn(_DUMMY_SYMLINK, flags)
727 except OSError as err:
728 if err.errno != errno.EOPNOTSUPP:
729 raise
730 msg = 'chflag UF_IMMUTABLE not supported by underlying fs'
731 self.skipTest(msg)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700732 try:
733 new_testfn_st = os.stat(support.TESTFN)
734 new_dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
735
736 self.assertEqual(testfn_st.st_flags, new_testfn_st.st_flags)
737 self.assertEqual(dummy_symlink_st.st_flags | stat.UF_IMMUTABLE,
738 new_dummy_symlink_st.st_flags)
739 finally:
740 fn(_DUMMY_SYMLINK, dummy_symlink_st.st_flags)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000741
Guido van Rossum98297ee2007-11-06 21:34:58 +0000742 def test_environ(self):
Victor Stinner17b490d2010-05-06 22:19:30 +0000743 if os.name == "nt":
744 item_type = str
745 else:
746 item_type = bytes
Guido van Rossum98297ee2007-11-06 21:34:58 +0000747 for k, v in posix.environ.items():
Victor Stinner17b490d2010-05-06 22:19:30 +0000748 self.assertEqual(type(k), item_type)
749 self.assertEqual(type(v), item_type)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000750
Serhiy Storchaka43767632013-11-03 21:31:38 +0200751 @unittest.skipUnless(hasattr(posix, 'getcwd'), 'test needs posix.getcwd()')
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000752 def test_getcwd_long_pathnames(self):
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500753 dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
754 curdir = os.getcwd()
755 base_path = os.path.abspath(support.TESTFN) + '.getcwd'
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000756
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500757 try:
758 os.mkdir(base_path)
759 os.chdir(base_path)
760 except:
761 # Just returning nothing instead of the SkipTest exception, because
762 # the test results in Error in that case. Is that ok?
763 # raise unittest.SkipTest("cannot create directory for testing")
764 return
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000765
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500766 def _create_and_do_getcwd(dirname, current_path_length = 0):
767 try:
768 os.mkdir(dirname)
769 except:
770 raise unittest.SkipTest("mkdir cannot create directory sufficiently deep for getcwd test")
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000771
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500772 os.chdir(dirname)
773 try:
774 os.getcwd()
775 if current_path_length < 1027:
776 _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1)
777 finally:
778 os.chdir('..')
779 os.rmdir(dirname)
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000780
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500781 _create_and_do_getcwd(dirname)
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000782
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500783 finally:
784 os.chdir(curdir)
785 support.rmtree(base_path)
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000786
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200787 @unittest.skipUnless(hasattr(posix, 'getgrouplist'), "test needs posix.getgrouplist()")
788 @unittest.skipUnless(hasattr(pwd, 'getpwuid'), "test needs pwd.getpwuid()")
789 @unittest.skipUnless(hasattr(os, 'getuid'), "test needs os.getuid()")
790 def test_getgrouplist(self):
Ross Lagerwalla0b315f2012-12-13 15:20:26 +0000791 user = pwd.getpwuid(os.getuid())[0]
792 group = pwd.getpwuid(os.getuid())[3]
793 self.assertIn(group, posix.getgrouplist(user, group))
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200794
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200795
Antoine Pitrou318b8f32011-01-12 18:45:27 +0000796 @unittest.skipUnless(hasattr(os, 'getegid'), "test needs os.getegid()")
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000797 def test_getgroups(self):
Jesus Cea61f32cb2014-06-28 18:39:35 +0200798 with os.popen('id -G 2>/dev/null') as idg:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000799 groups = idg.read().strip()
Charles-François Natalie8a255a2012-05-02 20:01:38 +0200800 ret = idg.close()
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000801
Xavier de Gaye24c3b492016-10-19 11:00:26 +0200802 try:
803 idg_groups = set(int(g) for g in groups.split())
804 except ValueError:
805 idg_groups = set()
806 if ret is not None or not idg_groups:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000807 raise unittest.SkipTest("need working 'id -G'")
808
Ned Deily028915e2013-02-02 15:08:52 -0800809 # Issues 16698: OS X ABIs prior to 10.6 have limits on getgroups()
810 if sys.platform == 'darwin':
811 import sysconfig
812 dt = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') or '10.0'
Ned Deily04cdfa12014-06-25 13:36:14 -0700813 if tuple(int(n) for n in dt.split('.')[0:2]) < (10, 6):
Ned Deily028915e2013-02-02 15:08:52 -0800814 raise unittest.SkipTest("getgroups(2) is broken prior to 10.6")
815
Ronald Oussoren7fb6f512010-08-01 19:18:13 +0000816 # 'id -G' and 'os.getgroups()' should return the same
Xavier de Gaye24c3b492016-10-19 11:00:26 +0200817 # groups, ignoring order, duplicates, and the effective gid.
818 # #10822/#26944 - It is implementation defined whether
819 # posix.getgroups() includes the effective gid.
820 symdiff = idg_groups.symmetric_difference(posix.getgroups())
821 self.assertTrue(not symdiff or symdiff == {posix.getegid()})
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000822
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000823 # tests for the posix *at functions follow
824
Larry Hastings9cf065c2012-06-22 16:30:09 -0700825 @unittest.skipUnless(os.access in os.supports_dir_fd, "test needs dir_fd support for os.access()")
826 def test_access_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000827 f = posix.open(posix.getcwd(), posix.O_RDONLY)
828 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700829 self.assertTrue(posix.access(support.TESTFN, os.R_OK, dir_fd=f))
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000830 finally:
831 posix.close(f)
832
Larry Hastings9cf065c2012-06-22 16:30:09 -0700833 @unittest.skipUnless(os.chmod in os.supports_dir_fd, "test needs dir_fd support in os.chmod()")
834 def test_chmod_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000835 os.chmod(support.TESTFN, stat.S_IRUSR)
836
837 f = posix.open(posix.getcwd(), posix.O_RDONLY)
838 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700839 posix.chmod(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000840
841 s = posix.stat(support.TESTFN)
842 self.assertEqual(s[0] & stat.S_IRWXU, stat.S_IRUSR | stat.S_IWUSR)
843 finally:
844 posix.close(f)
845
Larry Hastings9cf065c2012-06-22 16:30:09 -0700846 @unittest.skipUnless(os.chown in os.supports_dir_fd, "test needs dir_fd support in os.chown()")
847 def test_chown_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000848 support.unlink(support.TESTFN)
Victor Stinnerbf816222011-06-30 23:25:47 +0200849 support.create_empty_file(support.TESTFN)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000850
851 f = posix.open(posix.getcwd(), posix.O_RDONLY)
852 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700853 posix.chown(support.TESTFN, os.getuid(), os.getgid(), dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000854 finally:
855 posix.close(f)
856
Larry Hastings9cf065c2012-06-22 16:30:09 -0700857 @unittest.skipUnless(os.stat in os.supports_dir_fd, "test needs dir_fd support in os.stat()")
858 def test_stat_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000859 support.unlink(support.TESTFN)
860 with open(support.TESTFN, 'w') as outfile:
861 outfile.write("testline\n")
862
863 f = posix.open(posix.getcwd(), posix.O_RDONLY)
864 try:
865 s1 = posix.stat(support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700866 s2 = posix.stat(support.TESTFN, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000867 self.assertEqual(s1, s2)
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200868 s2 = posix.stat(support.TESTFN, dir_fd=None)
869 self.assertEqual(s1, s2)
Serhiy Storchaka7155b882016-04-08 08:48:20 +0300870 self.assertRaisesRegex(TypeError, 'should be integer or None, not',
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200871 posix.stat, support.TESTFN, dir_fd=posix.getcwd())
Serhiy Storchaka7155b882016-04-08 08:48:20 +0300872 self.assertRaisesRegex(TypeError, 'should be integer or None, not',
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200873 posix.stat, support.TESTFN, dir_fd=float(f))
874 self.assertRaises(OverflowError,
875 posix.stat, support.TESTFN, dir_fd=10**20)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000876 finally:
877 posix.close(f)
878
Larry Hastings9cf065c2012-06-22 16:30:09 -0700879 @unittest.skipUnless(os.utime in os.supports_dir_fd, "test needs dir_fd support in os.utime()")
880 def test_utime_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000881 f = posix.open(posix.getcwd(), posix.O_RDONLY)
882 try:
883 now = time.time()
Larry Hastings9cf065c2012-06-22 16:30:09 -0700884 posix.utime(support.TESTFN, None, dir_fd=f)
885 posix.utime(support.TESTFN, dir_fd=f)
886 self.assertRaises(TypeError, posix.utime, support.TESTFN, now, dir_fd=f)
887 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None), dir_fd=f)
888 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None), dir_fd=f)
889 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now), dir_fd=f)
890 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, "x"), dir_fd=f)
891 posix.utime(support.TESTFN, (int(now), int(now)), dir_fd=f)
892 posix.utime(support.TESTFN, (now, now), dir_fd=f)
893 posix.utime(support.TESTFN,
894 (int(now), int((now - int(now)) * 1e9)), dir_fd=f)
895 posix.utime(support.TESTFN, dir_fd=f,
896 times=(int(now), int((now - int(now)) * 1e9)))
897
Larry Hastings90867a52012-06-22 17:01:41 -0700898 # try dir_fd and follow_symlinks together
Larry Hastings9cf065c2012-06-22 16:30:09 -0700899 if os.utime in os.supports_follow_symlinks:
Larry Hastings90867a52012-06-22 17:01:41 -0700900 try:
901 posix.utime(support.TESTFN, follow_symlinks=False, dir_fd=f)
Georg Brandl969288e2012-06-26 09:25:44 +0200902 except ValueError:
Larry Hastings90867a52012-06-22 17:01:41 -0700903 # whoops! using both together not supported on this platform.
904 pass
Larry Hastings9cf065c2012-06-22 16:30:09 -0700905
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000906 finally:
907 posix.close(f)
908
Larry Hastings9cf065c2012-06-22 16:30:09 -0700909 @unittest.skipUnless(os.link in os.supports_dir_fd, "test needs dir_fd support in os.link()")
910 def test_link_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000911 f = posix.open(posix.getcwd(), posix.O_RDONLY)
912 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700913 posix.link(support.TESTFN, support.TESTFN + 'link', src_dir_fd=f, dst_dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000914 # should have same inodes
915 self.assertEqual(posix.stat(support.TESTFN)[1],
916 posix.stat(support.TESTFN + 'link')[1])
917 finally:
918 posix.close(f)
919 support.unlink(support.TESTFN + 'link')
920
Larry Hastings9cf065c2012-06-22 16:30:09 -0700921 @unittest.skipUnless(os.mkdir in os.supports_dir_fd, "test needs dir_fd support in os.mkdir()")
922 def test_mkdir_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000923 f = posix.open(posix.getcwd(), posix.O_RDONLY)
924 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700925 posix.mkdir(support.TESTFN + 'dir', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000926 posix.stat(support.TESTFN + 'dir') # should not raise exception
927 finally:
928 posix.close(f)
929 support.rmtree(support.TESTFN + 'dir')
930
Larry Hastings9cf065c2012-06-22 16:30:09 -0700931 @unittest.skipUnless((os.mknod in os.supports_dir_fd) and hasattr(stat, 'S_IFIFO'),
932 "test requires both stat.S_IFIFO and dir_fd support for os.mknod()")
933 def test_mknod_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000934 # Test using mknodat() to create a FIFO (the only use specified
935 # by POSIX).
936 support.unlink(support.TESTFN)
937 mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
938 f = posix.open(posix.getcwd(), posix.O_RDONLY)
939 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700940 posix.mknod(support.TESTFN, mode, 0, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000941 except OSError as e:
942 # Some old systems don't allow unprivileged users to use
943 # mknod(), or only support creating device nodes.
944 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
945 else:
946 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
947 finally:
948 posix.close(f)
949
Larry Hastings9cf065c2012-06-22 16:30:09 -0700950 @unittest.skipUnless(os.open in os.supports_dir_fd, "test needs dir_fd support in os.open()")
951 def test_open_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000952 support.unlink(support.TESTFN)
953 with open(support.TESTFN, 'w') as outfile:
954 outfile.write("testline\n")
955 a = posix.open(posix.getcwd(), posix.O_RDONLY)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700956 b = posix.open(support.TESTFN, posix.O_RDONLY, dir_fd=a)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000957 try:
958 res = posix.read(b, 9).decode(encoding="utf-8")
959 self.assertEqual("testline\n", res)
960 finally:
961 posix.close(a)
962 posix.close(b)
963
Larry Hastings9cf065c2012-06-22 16:30:09 -0700964 @unittest.skipUnless(os.readlink in os.supports_dir_fd, "test needs dir_fd support in os.readlink()")
965 def test_readlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000966 os.symlink(support.TESTFN, support.TESTFN + 'link')
967 f = posix.open(posix.getcwd(), posix.O_RDONLY)
968 try:
969 self.assertEqual(posix.readlink(support.TESTFN + 'link'),
Larry Hastings9cf065c2012-06-22 16:30:09 -0700970 posix.readlink(support.TESTFN + 'link', dir_fd=f))
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000971 finally:
972 support.unlink(support.TESTFN + 'link')
973 posix.close(f)
974
Larry Hastings9cf065c2012-06-22 16:30:09 -0700975 @unittest.skipUnless(os.rename in os.supports_dir_fd, "test needs dir_fd support in os.rename()")
976 def test_rename_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000977 support.unlink(support.TESTFN)
Victor Stinnerbf816222011-06-30 23:25:47 +0200978 support.create_empty_file(support.TESTFN + 'ren')
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000979 f = posix.open(posix.getcwd(), posix.O_RDONLY)
980 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700981 posix.rename(support.TESTFN + 'ren', support.TESTFN, src_dir_fd=f, dst_dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000982 except:
983 posix.rename(support.TESTFN + 'ren', support.TESTFN)
984 raise
985 else:
Andrew Svetlov5b898402012-12-18 21:26:36 +0200986 posix.stat(support.TESTFN) # should not raise exception
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000987 finally:
988 posix.close(f)
989
Larry Hastings9cf065c2012-06-22 16:30:09 -0700990 @unittest.skipUnless(os.symlink in os.supports_dir_fd, "test needs dir_fd support in os.symlink()")
991 def test_symlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000992 f = posix.open(posix.getcwd(), posix.O_RDONLY)
993 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700994 posix.symlink(support.TESTFN, support.TESTFN + 'link', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000995 self.assertEqual(posix.readlink(support.TESTFN + 'link'), support.TESTFN)
996 finally:
997 posix.close(f)
998 support.unlink(support.TESTFN + 'link')
999
Larry Hastings9cf065c2012-06-22 16:30:09 -07001000 @unittest.skipUnless(os.unlink in os.supports_dir_fd, "test needs dir_fd support in os.unlink()")
1001 def test_unlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001002 f = posix.open(posix.getcwd(), posix.O_RDONLY)
Victor Stinnerbf816222011-06-30 23:25:47 +02001003 support.create_empty_file(support.TESTFN + 'del')
Andrew Svetlov5b898402012-12-18 21:26:36 +02001004 posix.stat(support.TESTFN + 'del') # should not raise exception
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001005 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001006 posix.unlink(support.TESTFN + 'del', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001007 except:
1008 support.unlink(support.TESTFN + 'del')
1009 raise
1010 else:
1011 self.assertRaises(OSError, posix.stat, support.TESTFN + 'link')
1012 finally:
1013 posix.close(f)
1014
Larry Hastings9cf065c2012-06-22 16:30:09 -07001015 @unittest.skipUnless(os.mkfifo in os.supports_dir_fd, "test needs dir_fd support in os.mkfifo()")
1016 def test_mkfifo_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001017 support.unlink(support.TESTFN)
1018 f = posix.open(posix.getcwd(), posix.O_RDONLY)
1019 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001020 posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001021 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
1022 finally:
1023 posix.close(f)
1024
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001025 requires_sched_h = unittest.skipUnless(hasattr(posix, 'sched_yield'),
1026 "don't have scheduling support")
Antoine Pitrou84869872012-08-04 16:16:35 +02001027 requires_sched_affinity = unittest.skipUnless(hasattr(posix, 'sched_setaffinity'),
Benjamin Peterson50ba2712011-08-02 22:15:40 -05001028 "don't have sched affinity support")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001029
1030 @requires_sched_h
1031 def test_sched_yield(self):
1032 # This has no error conditions (at least on Linux).
1033 posix.sched_yield()
1034
1035 @requires_sched_h
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02001036 @unittest.skipUnless(hasattr(posix, 'sched_get_priority_max'),
1037 "requires sched_get_priority_max()")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001038 def test_sched_priority(self):
1039 # Round-robin usually has interesting priorities.
1040 pol = posix.SCHED_RR
1041 lo = posix.sched_get_priority_min(pol)
1042 hi = posix.sched_get_priority_max(pol)
1043 self.assertIsInstance(lo, int)
1044 self.assertIsInstance(hi, int)
1045 self.assertGreaterEqual(hi, lo)
Benjamin Peterson539b6c42011-08-02 22:09:37 -05001046 # OSX evidently just returns 15 without checking the argument.
1047 if sys.platform != "darwin":
Benjamin Petersonc1581582011-08-02 22:10:55 -05001048 self.assertRaises(OSError, posix.sched_get_priority_min, -23)
1049 self.assertRaises(OSError, posix.sched_get_priority_max, -23)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001050
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05001051 @unittest.skipUnless(hasattr(posix, 'sched_setscheduler'), "can't change scheduler")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001052 def test_get_and_set_scheduler_and_param(self):
1053 possible_schedulers = [sched for name, sched in posix.__dict__.items()
1054 if name.startswith("SCHED_")]
1055 mine = posix.sched_getscheduler(0)
1056 self.assertIn(mine, possible_schedulers)
1057 try:
Jesus Ceaceb5d162011-09-10 01:16:55 +02001058 parent = posix.sched_getscheduler(os.getppid())
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001059 except OSError as e:
Jesus Ceaceb5d162011-09-10 01:16:55 +02001060 if e.errno != errno.EPERM:
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001061 raise
1062 else:
Jesus Ceaceb5d162011-09-10 01:16:55 +02001063 self.assertIn(parent, possible_schedulers)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001064 self.assertRaises(OSError, posix.sched_getscheduler, -1)
1065 self.assertRaises(OSError, posix.sched_getparam, -1)
1066 param = posix.sched_getparam(0)
1067 self.assertIsInstance(param.sched_priority, int)
Charles-François Natali7b911cb2011-08-21 12:41:43 +02001068
Charles-François Natalib402a5c2013-01-13 14:13:25 +01001069 # POSIX states that calling sched_setparam() or sched_setscheduler() on
1070 # a process with a scheduling policy other than SCHED_FIFO or SCHED_RR
1071 # is implementation-defined: NetBSD and FreeBSD can return EINVAL.
1072 if not sys.platform.startswith(('freebsd', 'netbsd')):
1073 try:
1074 posix.sched_setscheduler(0, mine, param)
1075 posix.sched_setparam(0, param)
1076 except OSError as e:
1077 if e.errno != errno.EPERM:
1078 raise
Charles-François Natali7b911cb2011-08-21 12:41:43 +02001079 self.assertRaises(OSError, posix.sched_setparam, -1, param)
1080
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001081 self.assertRaises(OSError, posix.sched_setscheduler, -1, mine, param)
1082 self.assertRaises(TypeError, posix.sched_setscheduler, 0, mine, None)
1083 self.assertRaises(TypeError, posix.sched_setparam, 0, 43)
1084 param = posix.sched_param(None)
1085 self.assertRaises(TypeError, posix.sched_setparam, 0, param)
1086 large = 214748364700
1087 param = posix.sched_param(large)
1088 self.assertRaises(OverflowError, posix.sched_setparam, 0, param)
1089 param = posix.sched_param(sched_priority=-large)
1090 self.assertRaises(OverflowError, posix.sched_setparam, 0, param)
1091
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05001092 @unittest.skipUnless(hasattr(posix, "sched_rr_get_interval"), "no function")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001093 def test_sched_rr_get_interval(self):
Benjamin Peterson43234ab2011-08-02 22:19:14 -05001094 try:
1095 interval = posix.sched_rr_get_interval(0)
1096 except OSError as e:
1097 # This likely means that sched_rr_get_interval is only valid for
1098 # processes with the SCHED_RR scheduler in effect.
1099 if e.errno != errno.EINVAL:
1100 raise
1101 self.skipTest("only works on SCHED_RR processes")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001102 self.assertIsInstance(interval, float)
1103 # Reasonable constraints, I think.
1104 self.assertGreaterEqual(interval, 0.)
1105 self.assertLess(interval, 1.)
1106
Benjamin Peterson2740af82011-08-02 17:41:34 -05001107 @requires_sched_affinity
Antoine Pitrou84869872012-08-04 16:16:35 +02001108 def test_sched_getaffinity(self):
1109 mask = posix.sched_getaffinity(0)
1110 self.assertIsInstance(mask, set)
1111 self.assertGreaterEqual(len(mask), 1)
1112 self.assertRaises(OSError, posix.sched_getaffinity, -1)
1113 for cpu in mask:
1114 self.assertIsInstance(cpu, int)
1115 self.assertGreaterEqual(cpu, 0)
1116 self.assertLess(cpu, 1 << 32)
1117
1118 @requires_sched_affinity
1119 def test_sched_setaffinity(self):
1120 mask = posix.sched_getaffinity(0)
1121 if len(mask) > 1:
1122 # Empty masks are forbidden
1123 mask.pop()
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001124 posix.sched_setaffinity(0, mask)
Antoine Pitrou84869872012-08-04 16:16:35 +02001125 self.assertEqual(posix.sched_getaffinity(0), mask)
1126 self.assertRaises(OSError, posix.sched_setaffinity, 0, [])
1127 self.assertRaises(ValueError, posix.sched_setaffinity, 0, [-10])
1128 self.assertRaises(OverflowError, posix.sched_setaffinity, 0, [1<<128])
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001129 self.assertRaises(OSError, posix.sched_setaffinity, -1, mask)
1130
Victor Stinner8b905bd2011-10-25 13:34:04 +02001131 def test_rtld_constants(self):
1132 # check presence of major RTLD_* constants
1133 posix.RTLD_LAZY
1134 posix.RTLD_NOW
1135 posix.RTLD_GLOBAL
1136 posix.RTLD_LOCAL
1137
Jesus Cea60c13dd2012-06-23 02:58:14 +02001138 @unittest.skipUnless(hasattr(os, 'SEEK_HOLE'),
1139 "test needs an OS that reports file holes")
Hynek Schlawackf841e422012-06-24 09:51:46 +02001140 def test_fs_holes(self):
Jesus Cea94363612012-06-22 18:32:07 +02001141 # Even if the filesystem doesn't report holes,
1142 # if the OS supports it the SEEK_* constants
1143 # will be defined and will have a consistent
1144 # behaviour:
1145 # os.SEEK_DATA = current position
1146 # os.SEEK_HOLE = end of file position
Hynek Schlawackf841e422012-06-24 09:51:46 +02001147 with open(support.TESTFN, 'r+b') as fp:
Jesus Cea94363612012-06-22 18:32:07 +02001148 fp.write(b"hello")
1149 fp.flush()
1150 size = fp.tell()
1151 fno = fp.fileno()
Jesus Cead46f7d22012-07-07 14:56:04 +02001152 try :
1153 for i in range(size):
1154 self.assertEqual(i, os.lseek(fno, i, os.SEEK_DATA))
1155 self.assertLessEqual(size, os.lseek(fno, i, os.SEEK_HOLE))
1156 self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_DATA)
1157 self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_HOLE)
1158 except OSError :
1159 # Some OSs claim to support SEEK_HOLE/SEEK_DATA
1160 # but it is not true.
1161 # For instance:
1162 # http://lists.freebsd.org/pipermail/freebsd-amd64/2012-January/014332.html
1163 raise unittest.SkipTest("OSError raised!")
Jesus Cea94363612012-06-22 18:32:07 +02001164
Larry Hastingsb0827312014-02-09 22:05:19 -08001165 def test_path_error2(self):
1166 """
1167 Test functions that call path_error2(), providing two filenames in their exceptions.
1168 """
Victor Stinner047b7ae2014-10-05 17:37:41 +02001169 for name in ("rename", "replace", "link"):
Larry Hastingsb0827312014-02-09 22:05:19 -08001170 function = getattr(os, name, None)
Victor Stinnerbed04a72014-10-05 17:37:59 +02001171 if function is None:
1172 continue
Larry Hastingsb0827312014-02-09 22:05:19 -08001173
Victor Stinnerbed04a72014-10-05 17:37:59 +02001174 for dst in ("noodly2", support.TESTFN):
1175 try:
1176 function('doesnotexistfilename', dst)
1177 except OSError as e:
1178 self.assertIn("'doesnotexistfilename' -> '{}'".format(dst), str(e))
1179 break
1180 else:
1181 self.fail("No valid path_error2() test for os." + name)
Larry Hastingsb0827312014-02-09 22:05:19 -08001182
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001183 def test_path_with_null_character(self):
1184 fn = support.TESTFN
1185 fn_with_NUL = fn + '\0'
1186 self.addCleanup(support.unlink, fn)
1187 support.unlink(fn)
1188 fd = None
1189 try:
Serhiy Storchaka7e9d1d12015-04-20 10:12:28 +03001190 with self.assertRaises(ValueError):
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001191 fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # raises
1192 finally:
1193 if fd is not None:
1194 os.close(fd)
1195 self.assertFalse(os.path.exists(fn))
Serhiy Storchaka7e9d1d12015-04-20 10:12:28 +03001196 self.assertRaises(ValueError, os.mkdir, fn_with_NUL)
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001197 self.assertFalse(os.path.exists(fn))
1198 open(fn, 'wb').close()
Serhiy Storchaka7e9d1d12015-04-20 10:12:28 +03001199 self.assertRaises(ValueError, os.stat, fn_with_NUL)
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001200
1201 def test_path_with_null_byte(self):
1202 fn = os.fsencode(support.TESTFN)
1203 fn_with_NUL = fn + b'\0'
1204 self.addCleanup(support.unlink, fn)
1205 support.unlink(fn)
1206 fd = None
1207 try:
1208 with self.assertRaises(ValueError):
1209 fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # raises
1210 finally:
1211 if fd is not None:
1212 os.close(fd)
1213 self.assertFalse(os.path.exists(fn))
1214 self.assertRaises(ValueError, os.mkdir, fn_with_NUL)
1215 self.assertFalse(os.path.exists(fn))
1216 open(fn, 'wb').close()
1217 self.assertRaises(ValueError, os.stat, fn_with_NUL)
1218
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001219class PosixGroupsTester(unittest.TestCase):
1220
1221 def setUp(self):
1222 if posix.getuid() != 0:
1223 raise unittest.SkipTest("not enough privileges")
1224 if not hasattr(posix, 'getgroups'):
1225 raise unittest.SkipTest("need posix.getgroups")
1226 if sys.platform == 'darwin':
1227 raise unittest.SkipTest("getgroups(2) is broken on OSX")
1228 self.saved_groups = posix.getgroups()
1229
1230 def tearDown(self):
1231 if hasattr(posix, 'setgroups'):
1232 posix.setgroups(self.saved_groups)
1233 elif hasattr(posix, 'initgroups'):
1234 name = pwd.getpwuid(posix.getuid()).pw_name
1235 posix.initgroups(name, self.saved_groups[0])
1236
1237 @unittest.skipUnless(hasattr(posix, 'initgroups'),
1238 "test needs posix.initgroups()")
1239 def test_initgroups(self):
1240 # find missing group
1241
Benjamin Peterson659a6f52014-03-01 19:14:12 -05001242 g = max(self.saved_groups or [0]) + 1
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001243 name = pwd.getpwuid(posix.getuid()).pw_name
1244 posix.initgroups(name, g)
1245 self.assertIn(g, posix.getgroups())
1246
1247 @unittest.skipUnless(hasattr(posix, 'setgroups'),
1248 "test needs posix.setgroups()")
1249 def test_setgroups(self):
Antoine Pitroue5a91012010-09-04 17:32:06 +00001250 for groups in [[0], list(range(16))]:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001251 posix.setgroups(groups)
1252 self.assertListEqual(groups, posix.getgroups())
1253
Neal Norwitze241ce82003-02-17 18:17:05 +00001254def test_main():
Antoine Pitrou68c95922011-03-20 17:33:57 +01001255 try:
1256 support.run_unittest(PosixTester, PosixGroupsTester)
1257 finally:
1258 support.reap_children()
Neal Norwitze241ce82003-02-17 18:17:05 +00001259
1260if __name__ == '__main__':
1261 test_main()