blob: d2f58baae6b6d2b89e1f64c36adfeaa4cd53106f [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
Benjamin Petersonb29614e2012-10-09 11:16:03 -0400802 if ret is not None or not groups:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000803 raise unittest.SkipTest("need working 'id -G'")
804
Ned Deily028915e2013-02-02 15:08:52 -0800805 # Issues 16698: OS X ABIs prior to 10.6 have limits on getgroups()
806 if sys.platform == 'darwin':
807 import sysconfig
808 dt = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') or '10.0'
Ned Deily04cdfa12014-06-25 13:36:14 -0700809 if tuple(int(n) for n in dt.split('.')[0:2]) < (10, 6):
Ned Deily028915e2013-02-02 15:08:52 -0800810 raise unittest.SkipTest("getgroups(2) is broken prior to 10.6")
811
Ronald Oussoren7fb6f512010-08-01 19:18:13 +0000812 # 'id -G' and 'os.getgroups()' should return the same
813 # groups, ignoring order and duplicates.
Antoine Pitrou318b8f32011-01-12 18:45:27 +0000814 # #10822 - it is implementation defined whether posix.getgroups()
815 # includes the effective gid so we include it anyway, since id -G does
Ronald Oussorencb615e62010-07-24 14:15:19 +0000816 self.assertEqual(
Ronald Oussoren7fb6f512010-08-01 19:18:13 +0000817 set([int(x) for x in groups.split()]),
Antoine Pitrou318b8f32011-01-12 18:45:27 +0000818 set(posix.getgroups() + [posix.getegid()]))
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000819
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000820 # tests for the posix *at functions follow
821
Larry Hastings9cf065c2012-06-22 16:30:09 -0700822 @unittest.skipUnless(os.access in os.supports_dir_fd, "test needs dir_fd support for os.access()")
823 def test_access_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000824 f = posix.open(posix.getcwd(), posix.O_RDONLY)
825 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700826 self.assertTrue(posix.access(support.TESTFN, os.R_OK, dir_fd=f))
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000827 finally:
828 posix.close(f)
829
Larry Hastings9cf065c2012-06-22 16:30:09 -0700830 @unittest.skipUnless(os.chmod in os.supports_dir_fd, "test needs dir_fd support in os.chmod()")
831 def test_chmod_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000832 os.chmod(support.TESTFN, stat.S_IRUSR)
833
834 f = posix.open(posix.getcwd(), posix.O_RDONLY)
835 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700836 posix.chmod(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000837
838 s = posix.stat(support.TESTFN)
839 self.assertEqual(s[0] & stat.S_IRWXU, stat.S_IRUSR | stat.S_IWUSR)
840 finally:
841 posix.close(f)
842
Larry Hastings9cf065c2012-06-22 16:30:09 -0700843 @unittest.skipUnless(os.chown in os.supports_dir_fd, "test needs dir_fd support in os.chown()")
844 def test_chown_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000845 support.unlink(support.TESTFN)
Victor Stinnerbf816222011-06-30 23:25:47 +0200846 support.create_empty_file(support.TESTFN)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000847
848 f = posix.open(posix.getcwd(), posix.O_RDONLY)
849 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700850 posix.chown(support.TESTFN, os.getuid(), os.getgid(), dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000851 finally:
852 posix.close(f)
853
Larry Hastings9cf065c2012-06-22 16:30:09 -0700854 @unittest.skipUnless(os.stat in os.supports_dir_fd, "test needs dir_fd support in os.stat()")
855 def test_stat_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000856 support.unlink(support.TESTFN)
857 with open(support.TESTFN, 'w') as outfile:
858 outfile.write("testline\n")
859
860 f = posix.open(posix.getcwd(), posix.O_RDONLY)
861 try:
862 s1 = posix.stat(support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700863 s2 = posix.stat(support.TESTFN, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000864 self.assertEqual(s1, s2)
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200865 s2 = posix.stat(support.TESTFN, dir_fd=None)
866 self.assertEqual(s1, s2)
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=posix.getcwd())
Serhiy Storchaka7155b882016-04-08 08:48:20 +0300869 self.assertRaisesRegex(TypeError, 'should be integer or None, not',
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200870 posix.stat, support.TESTFN, dir_fd=float(f))
871 self.assertRaises(OverflowError,
872 posix.stat, support.TESTFN, dir_fd=10**20)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000873 finally:
874 posix.close(f)
875
Larry Hastings9cf065c2012-06-22 16:30:09 -0700876 @unittest.skipUnless(os.utime in os.supports_dir_fd, "test needs dir_fd support in os.utime()")
877 def test_utime_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000878 f = posix.open(posix.getcwd(), posix.O_RDONLY)
879 try:
880 now = time.time()
Larry Hastings9cf065c2012-06-22 16:30:09 -0700881 posix.utime(support.TESTFN, None, dir_fd=f)
882 posix.utime(support.TESTFN, dir_fd=f)
883 self.assertRaises(TypeError, posix.utime, support.TESTFN, now, dir_fd=f)
884 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None), dir_fd=f)
885 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None), dir_fd=f)
886 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now), dir_fd=f)
887 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, "x"), dir_fd=f)
888 posix.utime(support.TESTFN, (int(now), int(now)), dir_fd=f)
889 posix.utime(support.TESTFN, (now, now), dir_fd=f)
890 posix.utime(support.TESTFN,
891 (int(now), int((now - int(now)) * 1e9)), dir_fd=f)
892 posix.utime(support.TESTFN, dir_fd=f,
893 times=(int(now), int((now - int(now)) * 1e9)))
894
Larry Hastings90867a52012-06-22 17:01:41 -0700895 # try dir_fd and follow_symlinks together
Larry Hastings9cf065c2012-06-22 16:30:09 -0700896 if os.utime in os.supports_follow_symlinks:
Larry Hastings90867a52012-06-22 17:01:41 -0700897 try:
898 posix.utime(support.TESTFN, follow_symlinks=False, dir_fd=f)
Georg Brandl969288e2012-06-26 09:25:44 +0200899 except ValueError:
Larry Hastings90867a52012-06-22 17:01:41 -0700900 # whoops! using both together not supported on this platform.
901 pass
Larry Hastings9cf065c2012-06-22 16:30:09 -0700902
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000903 finally:
904 posix.close(f)
905
Larry Hastings9cf065c2012-06-22 16:30:09 -0700906 @unittest.skipUnless(os.link in os.supports_dir_fd, "test needs dir_fd support in os.link()")
907 def test_link_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000908 f = posix.open(posix.getcwd(), posix.O_RDONLY)
909 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700910 posix.link(support.TESTFN, support.TESTFN + 'link', src_dir_fd=f, dst_dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000911 # should have same inodes
912 self.assertEqual(posix.stat(support.TESTFN)[1],
913 posix.stat(support.TESTFN + 'link')[1])
914 finally:
915 posix.close(f)
916 support.unlink(support.TESTFN + 'link')
917
Larry Hastings9cf065c2012-06-22 16:30:09 -0700918 @unittest.skipUnless(os.mkdir in os.supports_dir_fd, "test needs dir_fd support in os.mkdir()")
919 def test_mkdir_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000920 f = posix.open(posix.getcwd(), posix.O_RDONLY)
921 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700922 posix.mkdir(support.TESTFN + 'dir', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000923 posix.stat(support.TESTFN + 'dir') # should not raise exception
924 finally:
925 posix.close(f)
926 support.rmtree(support.TESTFN + 'dir')
927
Larry Hastings9cf065c2012-06-22 16:30:09 -0700928 @unittest.skipUnless((os.mknod in os.supports_dir_fd) and hasattr(stat, 'S_IFIFO'),
929 "test requires both stat.S_IFIFO and dir_fd support for os.mknod()")
930 def test_mknod_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000931 # Test using mknodat() to create a FIFO (the only use specified
932 # by POSIX).
933 support.unlink(support.TESTFN)
934 mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
935 f = posix.open(posix.getcwd(), posix.O_RDONLY)
936 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700937 posix.mknod(support.TESTFN, mode, 0, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000938 except OSError as e:
939 # Some old systems don't allow unprivileged users to use
940 # mknod(), or only support creating device nodes.
941 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
942 else:
943 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
944 finally:
945 posix.close(f)
946
Larry Hastings9cf065c2012-06-22 16:30:09 -0700947 @unittest.skipUnless(os.open in os.supports_dir_fd, "test needs dir_fd support in os.open()")
948 def test_open_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000949 support.unlink(support.TESTFN)
950 with open(support.TESTFN, 'w') as outfile:
951 outfile.write("testline\n")
952 a = posix.open(posix.getcwd(), posix.O_RDONLY)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700953 b = posix.open(support.TESTFN, posix.O_RDONLY, dir_fd=a)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000954 try:
955 res = posix.read(b, 9).decode(encoding="utf-8")
956 self.assertEqual("testline\n", res)
957 finally:
958 posix.close(a)
959 posix.close(b)
960
Larry Hastings9cf065c2012-06-22 16:30:09 -0700961 @unittest.skipUnless(os.readlink in os.supports_dir_fd, "test needs dir_fd support in os.readlink()")
962 def test_readlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000963 os.symlink(support.TESTFN, support.TESTFN + 'link')
964 f = posix.open(posix.getcwd(), posix.O_RDONLY)
965 try:
966 self.assertEqual(posix.readlink(support.TESTFN + 'link'),
Larry Hastings9cf065c2012-06-22 16:30:09 -0700967 posix.readlink(support.TESTFN + 'link', dir_fd=f))
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000968 finally:
969 support.unlink(support.TESTFN + 'link')
970 posix.close(f)
971
Larry Hastings9cf065c2012-06-22 16:30:09 -0700972 @unittest.skipUnless(os.rename in os.supports_dir_fd, "test needs dir_fd support in os.rename()")
973 def test_rename_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000974 support.unlink(support.TESTFN)
Victor Stinnerbf816222011-06-30 23:25:47 +0200975 support.create_empty_file(support.TESTFN + 'ren')
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000976 f = posix.open(posix.getcwd(), posix.O_RDONLY)
977 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700978 posix.rename(support.TESTFN + 'ren', support.TESTFN, src_dir_fd=f, dst_dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000979 except:
980 posix.rename(support.TESTFN + 'ren', support.TESTFN)
981 raise
982 else:
Andrew Svetlov5b898402012-12-18 21:26:36 +0200983 posix.stat(support.TESTFN) # should not raise exception
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000984 finally:
985 posix.close(f)
986
Larry Hastings9cf065c2012-06-22 16:30:09 -0700987 @unittest.skipUnless(os.symlink in os.supports_dir_fd, "test needs dir_fd support in os.symlink()")
988 def test_symlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000989 f = posix.open(posix.getcwd(), posix.O_RDONLY)
990 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700991 posix.symlink(support.TESTFN, support.TESTFN + 'link', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000992 self.assertEqual(posix.readlink(support.TESTFN + 'link'), support.TESTFN)
993 finally:
994 posix.close(f)
995 support.unlink(support.TESTFN + 'link')
996
Larry Hastings9cf065c2012-06-22 16:30:09 -0700997 @unittest.skipUnless(os.unlink in os.supports_dir_fd, "test needs dir_fd support in os.unlink()")
998 def test_unlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000999 f = posix.open(posix.getcwd(), posix.O_RDONLY)
Victor Stinnerbf816222011-06-30 23:25:47 +02001000 support.create_empty_file(support.TESTFN + 'del')
Andrew Svetlov5b898402012-12-18 21:26:36 +02001001 posix.stat(support.TESTFN + 'del') # should not raise exception
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001002 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001003 posix.unlink(support.TESTFN + 'del', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001004 except:
1005 support.unlink(support.TESTFN + 'del')
1006 raise
1007 else:
1008 self.assertRaises(OSError, posix.stat, support.TESTFN + 'link')
1009 finally:
1010 posix.close(f)
1011
Larry Hastings9cf065c2012-06-22 16:30:09 -07001012 @unittest.skipUnless(os.mkfifo in os.supports_dir_fd, "test needs dir_fd support in os.mkfifo()")
1013 def test_mkfifo_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001014 support.unlink(support.TESTFN)
1015 f = posix.open(posix.getcwd(), posix.O_RDONLY)
1016 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001017 posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001018 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
1019 finally:
1020 posix.close(f)
1021
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001022 requires_sched_h = unittest.skipUnless(hasattr(posix, 'sched_yield'),
1023 "don't have scheduling support")
Antoine Pitrou84869872012-08-04 16:16:35 +02001024 requires_sched_affinity = unittest.skipUnless(hasattr(posix, 'sched_setaffinity'),
Benjamin Peterson50ba2712011-08-02 22:15:40 -05001025 "don't have sched affinity support")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001026
1027 @requires_sched_h
1028 def test_sched_yield(self):
1029 # This has no error conditions (at least on Linux).
1030 posix.sched_yield()
1031
1032 @requires_sched_h
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02001033 @unittest.skipUnless(hasattr(posix, 'sched_get_priority_max'),
1034 "requires sched_get_priority_max()")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001035 def test_sched_priority(self):
1036 # Round-robin usually has interesting priorities.
1037 pol = posix.SCHED_RR
1038 lo = posix.sched_get_priority_min(pol)
1039 hi = posix.sched_get_priority_max(pol)
1040 self.assertIsInstance(lo, int)
1041 self.assertIsInstance(hi, int)
1042 self.assertGreaterEqual(hi, lo)
Benjamin Peterson539b6c42011-08-02 22:09:37 -05001043 # OSX evidently just returns 15 without checking the argument.
1044 if sys.platform != "darwin":
Benjamin Petersonc1581582011-08-02 22:10:55 -05001045 self.assertRaises(OSError, posix.sched_get_priority_min, -23)
1046 self.assertRaises(OSError, posix.sched_get_priority_max, -23)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001047
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05001048 @unittest.skipUnless(hasattr(posix, 'sched_setscheduler'), "can't change scheduler")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001049 def test_get_and_set_scheduler_and_param(self):
1050 possible_schedulers = [sched for name, sched in posix.__dict__.items()
1051 if name.startswith("SCHED_")]
1052 mine = posix.sched_getscheduler(0)
1053 self.assertIn(mine, possible_schedulers)
1054 try:
Jesus Ceaceb5d162011-09-10 01:16:55 +02001055 parent = posix.sched_getscheduler(os.getppid())
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001056 except OSError as e:
Jesus Ceaceb5d162011-09-10 01:16:55 +02001057 if e.errno != errno.EPERM:
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001058 raise
1059 else:
Jesus Ceaceb5d162011-09-10 01:16:55 +02001060 self.assertIn(parent, possible_schedulers)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001061 self.assertRaises(OSError, posix.sched_getscheduler, -1)
1062 self.assertRaises(OSError, posix.sched_getparam, -1)
1063 param = posix.sched_getparam(0)
1064 self.assertIsInstance(param.sched_priority, int)
Charles-François Natali7b911cb2011-08-21 12:41:43 +02001065
Charles-François Natalib402a5c2013-01-13 14:13:25 +01001066 # POSIX states that calling sched_setparam() or sched_setscheduler() on
1067 # a process with a scheduling policy other than SCHED_FIFO or SCHED_RR
1068 # is implementation-defined: NetBSD and FreeBSD can return EINVAL.
1069 if not sys.platform.startswith(('freebsd', 'netbsd')):
1070 try:
1071 posix.sched_setscheduler(0, mine, param)
1072 posix.sched_setparam(0, param)
1073 except OSError as e:
1074 if e.errno != errno.EPERM:
1075 raise
Charles-François Natali7b911cb2011-08-21 12:41:43 +02001076 self.assertRaises(OSError, posix.sched_setparam, -1, param)
1077
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001078 self.assertRaises(OSError, posix.sched_setscheduler, -1, mine, param)
1079 self.assertRaises(TypeError, posix.sched_setscheduler, 0, mine, None)
1080 self.assertRaises(TypeError, posix.sched_setparam, 0, 43)
1081 param = posix.sched_param(None)
1082 self.assertRaises(TypeError, posix.sched_setparam, 0, param)
1083 large = 214748364700
1084 param = posix.sched_param(large)
1085 self.assertRaises(OverflowError, posix.sched_setparam, 0, param)
1086 param = posix.sched_param(sched_priority=-large)
1087 self.assertRaises(OverflowError, posix.sched_setparam, 0, param)
1088
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05001089 @unittest.skipUnless(hasattr(posix, "sched_rr_get_interval"), "no function")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001090 def test_sched_rr_get_interval(self):
Benjamin Peterson43234ab2011-08-02 22:19:14 -05001091 try:
1092 interval = posix.sched_rr_get_interval(0)
1093 except OSError as e:
1094 # This likely means that sched_rr_get_interval is only valid for
1095 # processes with the SCHED_RR scheduler in effect.
1096 if e.errno != errno.EINVAL:
1097 raise
1098 self.skipTest("only works on SCHED_RR processes")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001099 self.assertIsInstance(interval, float)
1100 # Reasonable constraints, I think.
1101 self.assertGreaterEqual(interval, 0.)
1102 self.assertLess(interval, 1.)
1103
Benjamin Peterson2740af82011-08-02 17:41:34 -05001104 @requires_sched_affinity
Antoine Pitrou84869872012-08-04 16:16:35 +02001105 def test_sched_getaffinity(self):
1106 mask = posix.sched_getaffinity(0)
1107 self.assertIsInstance(mask, set)
1108 self.assertGreaterEqual(len(mask), 1)
1109 self.assertRaises(OSError, posix.sched_getaffinity, -1)
1110 for cpu in mask:
1111 self.assertIsInstance(cpu, int)
1112 self.assertGreaterEqual(cpu, 0)
1113 self.assertLess(cpu, 1 << 32)
1114
1115 @requires_sched_affinity
1116 def test_sched_setaffinity(self):
1117 mask = posix.sched_getaffinity(0)
1118 if len(mask) > 1:
1119 # Empty masks are forbidden
1120 mask.pop()
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001121 posix.sched_setaffinity(0, mask)
Antoine Pitrou84869872012-08-04 16:16:35 +02001122 self.assertEqual(posix.sched_getaffinity(0), mask)
1123 self.assertRaises(OSError, posix.sched_setaffinity, 0, [])
1124 self.assertRaises(ValueError, posix.sched_setaffinity, 0, [-10])
1125 self.assertRaises(OverflowError, posix.sched_setaffinity, 0, [1<<128])
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001126 self.assertRaises(OSError, posix.sched_setaffinity, -1, mask)
1127
Victor Stinner8b905bd2011-10-25 13:34:04 +02001128 def test_rtld_constants(self):
1129 # check presence of major RTLD_* constants
1130 posix.RTLD_LAZY
1131 posix.RTLD_NOW
1132 posix.RTLD_GLOBAL
1133 posix.RTLD_LOCAL
1134
Jesus Cea60c13dd2012-06-23 02:58:14 +02001135 @unittest.skipUnless(hasattr(os, 'SEEK_HOLE'),
1136 "test needs an OS that reports file holes")
Hynek Schlawackf841e422012-06-24 09:51:46 +02001137 def test_fs_holes(self):
Jesus Cea94363612012-06-22 18:32:07 +02001138 # Even if the filesystem doesn't report holes,
1139 # if the OS supports it the SEEK_* constants
1140 # will be defined and will have a consistent
1141 # behaviour:
1142 # os.SEEK_DATA = current position
1143 # os.SEEK_HOLE = end of file position
Hynek Schlawackf841e422012-06-24 09:51:46 +02001144 with open(support.TESTFN, 'r+b') as fp:
Jesus Cea94363612012-06-22 18:32:07 +02001145 fp.write(b"hello")
1146 fp.flush()
1147 size = fp.tell()
1148 fno = fp.fileno()
Jesus Cead46f7d22012-07-07 14:56:04 +02001149 try :
1150 for i in range(size):
1151 self.assertEqual(i, os.lseek(fno, i, os.SEEK_DATA))
1152 self.assertLessEqual(size, os.lseek(fno, i, os.SEEK_HOLE))
1153 self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_DATA)
1154 self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_HOLE)
1155 except OSError :
1156 # Some OSs claim to support SEEK_HOLE/SEEK_DATA
1157 # but it is not true.
1158 # For instance:
1159 # http://lists.freebsd.org/pipermail/freebsd-amd64/2012-January/014332.html
1160 raise unittest.SkipTest("OSError raised!")
Jesus Cea94363612012-06-22 18:32:07 +02001161
Larry Hastingsb0827312014-02-09 22:05:19 -08001162 def test_path_error2(self):
1163 """
1164 Test functions that call path_error2(), providing two filenames in their exceptions.
1165 """
Victor Stinner047b7ae2014-10-05 17:37:41 +02001166 for name in ("rename", "replace", "link"):
Larry Hastingsb0827312014-02-09 22:05:19 -08001167 function = getattr(os, name, None)
Victor Stinnerbed04a72014-10-05 17:37:59 +02001168 if function is None:
1169 continue
Larry Hastingsb0827312014-02-09 22:05:19 -08001170
Victor Stinnerbed04a72014-10-05 17:37:59 +02001171 for dst in ("noodly2", support.TESTFN):
1172 try:
1173 function('doesnotexistfilename', dst)
1174 except OSError as e:
1175 self.assertIn("'doesnotexistfilename' -> '{}'".format(dst), str(e))
1176 break
1177 else:
1178 self.fail("No valid path_error2() test for os." + name)
Larry Hastingsb0827312014-02-09 22:05:19 -08001179
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001180 def test_path_with_null_character(self):
1181 fn = support.TESTFN
1182 fn_with_NUL = fn + '\0'
1183 self.addCleanup(support.unlink, fn)
1184 support.unlink(fn)
1185 fd = None
1186 try:
Serhiy Storchaka7e9d1d12015-04-20 10:12:28 +03001187 with self.assertRaises(ValueError):
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001188 fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # raises
1189 finally:
1190 if fd is not None:
1191 os.close(fd)
1192 self.assertFalse(os.path.exists(fn))
Serhiy Storchaka7e9d1d12015-04-20 10:12:28 +03001193 self.assertRaises(ValueError, os.mkdir, fn_with_NUL)
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001194 self.assertFalse(os.path.exists(fn))
1195 open(fn, 'wb').close()
Serhiy Storchaka7e9d1d12015-04-20 10:12:28 +03001196 self.assertRaises(ValueError, os.stat, fn_with_NUL)
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001197
1198 def test_path_with_null_byte(self):
1199 fn = os.fsencode(support.TESTFN)
1200 fn_with_NUL = fn + b'\0'
1201 self.addCleanup(support.unlink, fn)
1202 support.unlink(fn)
1203 fd = None
1204 try:
1205 with self.assertRaises(ValueError):
1206 fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # raises
1207 finally:
1208 if fd is not None:
1209 os.close(fd)
1210 self.assertFalse(os.path.exists(fn))
1211 self.assertRaises(ValueError, os.mkdir, fn_with_NUL)
1212 self.assertFalse(os.path.exists(fn))
1213 open(fn, 'wb').close()
1214 self.assertRaises(ValueError, os.stat, fn_with_NUL)
1215
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001216class PosixGroupsTester(unittest.TestCase):
1217
1218 def setUp(self):
1219 if posix.getuid() != 0:
1220 raise unittest.SkipTest("not enough privileges")
1221 if not hasattr(posix, 'getgroups'):
1222 raise unittest.SkipTest("need posix.getgroups")
1223 if sys.platform == 'darwin':
1224 raise unittest.SkipTest("getgroups(2) is broken on OSX")
1225 self.saved_groups = posix.getgroups()
1226
1227 def tearDown(self):
1228 if hasattr(posix, 'setgroups'):
1229 posix.setgroups(self.saved_groups)
1230 elif hasattr(posix, 'initgroups'):
1231 name = pwd.getpwuid(posix.getuid()).pw_name
1232 posix.initgroups(name, self.saved_groups[0])
1233
1234 @unittest.skipUnless(hasattr(posix, 'initgroups'),
1235 "test needs posix.initgroups()")
1236 def test_initgroups(self):
1237 # find missing group
1238
Benjamin Peterson659a6f52014-03-01 19:14:12 -05001239 g = max(self.saved_groups or [0]) + 1
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001240 name = pwd.getpwuid(posix.getuid()).pw_name
1241 posix.initgroups(name, g)
1242 self.assertIn(g, posix.getgroups())
1243
1244 @unittest.skipUnless(hasattr(posix, 'setgroups'),
1245 "test needs posix.setgroups()")
1246 def test_setgroups(self):
Antoine Pitroue5a91012010-09-04 17:32:06 +00001247 for groups in [[0], list(range(16))]:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001248 posix.setgroups(groups)
1249 self.assertListEqual(groups, posix.getgroups())
1250
Neal Norwitze241ce82003-02-17 18:17:05 +00001251def test_main():
Antoine Pitrou68c95922011-03-20 17:33:57 +01001252 try:
1253 support.run_unittest(PosixTester, PosixGroupsTester)
1254 finally:
1255 support.reap_children()
Neal Norwitze241ce82003-02-17 18:17:05 +00001256
1257if __name__ == '__main__':
1258 test_main()