blob: d83440de4ac1453d5473262d0aca798ca8cb0f14 [file] [log] [blame]
Neal Norwitze241ce82003-02-17 18:17:05 +00001"Test posix functions"
2
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
R. David Murrayeb3615d2009-04-22 02:24:39 +00004
5# Skip these tests if there is no posix module.
6posix = support.import_module('posix')
Neal Norwitze241ce82003-02-17 18:17:05 +00007
Antoine Pitroub7572f02009-12-02 20:46:48 +00008import errno
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00009import sys
Neal Norwitze241ce82003-02-17 18:17:05 +000010import time
11import os
Charles-François Natali1e045b12011-05-22 20:42:32 +020012import fcntl
Charles-François Nataliab2d58e2012-04-17 19:48:35 +020013import platform
Christian Heimesd5e2b6f2008-03-19 21:50:51 +000014import pwd
Benjamin Petersondcf97b92008-07-02 17:30:14 +000015import shutil
Benjamin Peterson052a02b2010-08-17 01:27:09 +000016import stat
Ned Deilyba2eab22011-07-26 13:53:55 -070017import tempfile
Neal Norwitze241ce82003-02-17 18:17:05 +000018import unittest
19import warnings
Serhiy Storchaka9101e232013-01-19 12:41:45 +020020import _testcapi
R. David Murraya21e4ca2009-03-31 23:16:50 +000021
Ned Deilyba2eab22011-07-26 13:53:55 -070022_DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(),
23 support.TESTFN + '-dummy-symlink')
Neal Norwitze241ce82003-02-17 18:17:05 +000024
25class PosixTester(unittest.TestCase):
26
27 def setUp(self):
28 # create empty file
Benjamin Petersonee8712c2008-05-20 21:35:26 +000029 fp = open(support.TESTFN, 'w+')
Neal Norwitze241ce82003-02-17 18:17:05 +000030 fp.close()
Ned Deily3eb67d52011-06-28 00:00:28 -070031 self.teardown_files = [ support.TESTFN ]
Brett Cannonc8d502e2010-03-20 21:53:28 +000032 self._warnings_manager = support.check_warnings()
33 self._warnings_manager.__enter__()
34 warnings.filterwarnings('ignore', '.* potential security risk .*',
35 RuntimeWarning)
Neal Norwitze241ce82003-02-17 18:17:05 +000036
37 def tearDown(self):
Ned Deily3eb67d52011-06-28 00:00:28 -070038 for teardown_file in self.teardown_files:
39 support.unlink(teardown_file)
Brett Cannonc8d502e2010-03-20 21:53:28 +000040 self._warnings_manager.__exit__(None, None, None)
Neal Norwitze241ce82003-02-17 18:17:05 +000041
42 def testNoArgFunctions(self):
43 # test posix functions which take no arguments and have
44 # no side-effects which we need to cleanup (e.g., fork, wait, abort)
Guido van Rossumf0af3e32008-10-02 18:55:37 +000045 NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdb", "uname",
Guido van Rossum687b9c02007-10-25 23:18:51 +000046 "times", "getloadavg",
Neal Norwitze241ce82003-02-17 18:17:05 +000047 "getegid", "geteuid", "getgid", "getgroups",
Ross Lagerwall7807c352011-03-17 20:20:30 +020048 "getpid", "getpgrp", "getppid", "getuid", "sync",
Neal Norwitze241ce82003-02-17 18:17:05 +000049 ]
Neal Norwitz71b13e82003-02-23 22:12:24 +000050
Neal Norwitze241ce82003-02-17 18:17:05 +000051 for name in NO_ARG_FUNCTIONS:
52 posix_func = getattr(posix, name, None)
53 if posix_func is not None:
54 posix_func()
Neal Norwitz2ff51a82003-02-17 22:40:31 +000055 self.assertRaises(TypeError, posix_func, 1)
Neal Norwitze241ce82003-02-17 18:17:05 +000056
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000057 if hasattr(posix, 'getresuid'):
58 def test_getresuid(self):
59 user_ids = posix.getresuid()
60 self.assertEqual(len(user_ids), 3)
61 for val in user_ids:
62 self.assertGreaterEqual(val, 0)
63
64 if hasattr(posix, 'getresgid'):
65 def test_getresgid(self):
66 group_ids = posix.getresgid()
67 self.assertEqual(len(group_ids), 3)
68 for val in group_ids:
69 self.assertGreaterEqual(val, 0)
70
71 if hasattr(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))
77
78 def test_setresuid_exception(self):
79 # Don't do this test if someone is silly enough to run us as root.
80 current_user_ids = posix.getresuid()
81 if 0 not in current_user_ids:
82 new_user_ids = (current_user_ids[0]+1, -1, -1)
83 self.assertRaises(OSError, posix.setresuid, *new_user_ids)
84
85 if hasattr(posix, 'setresgid'):
86 def test_setresgid(self):
87 current_group_ids = posix.getresgid()
88 self.assertIsNone(posix.setresgid(*current_group_ids))
89 # -1 means don't change that value.
90 self.assertIsNone(posix.setresgid(-1, -1, -1))
91
92 def test_setresgid_exception(self):
93 # Don't do this test if someone is silly enough to run us as root.
94 current_group_ids = posix.getresgid()
95 if 0 not in current_group_ids:
96 new_group_ids = (current_group_ids[0]+1, -1, -1)
97 self.assertRaises(OSError, posix.setresgid, *new_group_ids)
98
Antoine Pitroub7572f02009-12-02 20:46:48 +000099 @unittest.skipUnless(hasattr(posix, 'initgroups'),
100 "test needs os.initgroups()")
101 def test_initgroups(self):
102 # It takes a string and an integer; check that it raises a TypeError
103 # for other argument lists.
104 self.assertRaises(TypeError, posix.initgroups)
105 self.assertRaises(TypeError, posix.initgroups, None)
106 self.assertRaises(TypeError, posix.initgroups, 3, "foo")
107 self.assertRaises(TypeError, posix.initgroups, "foo", 3, object())
108
109 # If a non-privileged user invokes it, it should fail with OSError
110 # EPERM.
111 if os.getuid() != 0:
Charles-François Natalie8a255a2012-05-02 20:01:38 +0200112 try:
113 name = pwd.getpwuid(posix.getuid()).pw_name
114 except KeyError:
115 # the current UID may not have a pwd entry
116 raise unittest.SkipTest("need a pwd entry")
Antoine Pitroub7572f02009-12-02 20:46:48 +0000117 try:
118 posix.initgroups(name, 13)
119 except OSError as e:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000120 self.assertEqual(e.errno, errno.EPERM)
Antoine Pitroub7572f02009-12-02 20:46:48 +0000121 else:
122 self.fail("Expected OSError to be raised by initgroups")
123
Neal Norwitze241ce82003-02-17 18:17:05 +0000124 def test_statvfs(self):
125 if hasattr(posix, 'statvfs'):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000126 self.assertTrue(posix.statvfs(os.curdir))
Neal Norwitze241ce82003-02-17 18:17:05 +0000127
128 def test_fstatvfs(self):
129 if hasattr(posix, 'fstatvfs'):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000130 fp = open(support.TESTFN)
Neal Norwitze241ce82003-02-17 18:17:05 +0000131 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000132 self.assertTrue(posix.fstatvfs(fp.fileno()))
Larry Hastings9cf065c2012-06-22 16:30:09 -0700133 self.assertTrue(posix.statvfs(fp.fileno()))
Neal Norwitze241ce82003-02-17 18:17:05 +0000134 finally:
135 fp.close()
136
137 def test_ftruncate(self):
138 if hasattr(posix, 'ftruncate'):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000139 fp = open(support.TESTFN, 'w+')
Neal Norwitze241ce82003-02-17 18:17:05 +0000140 try:
141 # we need to have some data to truncate
142 fp.write('test')
143 fp.flush()
144 posix.ftruncate(fp.fileno(), 0)
145 finally:
146 fp.close()
147
Ross Lagerwall7807c352011-03-17 20:20:30 +0200148 @unittest.skipUnless(hasattr(posix, 'truncate'), "test needs posix.truncate()")
149 def test_truncate(self):
150 with open(support.TESTFN, 'w') as fp:
151 fp.write('test')
152 fp.flush()
153 posix.truncate(support.TESTFN, 0)
154
Larry Hastings9cf065c2012-06-22 16:30:09 -0700155 @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 +0200156 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
Ross Lagerwalldedf6cf2011-03-20 18:27:05 +0200157 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
Ross Lagerwall7807c352011-03-17 20:20:30 +0200158 def test_fexecve(self):
159 fp = os.open(sys.executable, os.O_RDONLY)
160 try:
161 pid = os.fork()
162 if pid == 0:
163 os.chdir(os.path.split(sys.executable)[0])
Larry Hastings9cf065c2012-06-22 16:30:09 -0700164 posix.execve(fp, [sys.executable, '-c', 'pass'], os.environ)
Ross Lagerwall7807c352011-03-17 20:20:30 +0200165 else:
Ross Lagerwalldedf6cf2011-03-20 18:27:05 +0200166 self.assertEqual(os.waitpid(pid, 0), (pid, 0))
Ross Lagerwall7807c352011-03-17 20:20:30 +0200167 finally:
168 os.close(fp)
169
170 @unittest.skipUnless(hasattr(posix, 'waitid'), "test needs posix.waitid()")
171 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
172 def test_waitid(self):
173 pid = os.fork()
174 if pid == 0:
175 os.chdir(os.path.split(sys.executable)[0])
176 posix.execve(sys.executable, [sys.executable, '-c', 'pass'], os.environ)
177 else:
178 res = posix.waitid(posix.P_PID, pid, posix.WEXITED)
179 self.assertEqual(pid, res.si_pid)
180
181 @unittest.skipUnless(hasattr(posix, 'lockf'), "test needs posix.lockf()")
182 def test_lockf(self):
183 fd = os.open(support.TESTFN, os.O_WRONLY | os.O_CREAT)
184 try:
185 os.write(fd, b'test')
186 os.lseek(fd, 0, os.SEEK_SET)
187 posix.lockf(fd, posix.F_LOCK, 4)
188 # section is locked
189 posix.lockf(fd, posix.F_ULOCK, 4)
190 finally:
191 os.close(fd)
192
193 @unittest.skipUnless(hasattr(posix, 'pread'), "test needs posix.pread()")
194 def test_pread(self):
195 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
196 try:
197 os.write(fd, b'test')
198 os.lseek(fd, 0, os.SEEK_SET)
199 self.assertEqual(b'es', posix.pread(fd, 2, 1))
Florent Xiclunae41f0de2011-11-11 19:39:25 +0100200 # the first pread() shouldn't disturb the file offset
Ross Lagerwall7807c352011-03-17 20:20:30 +0200201 self.assertEqual(b'te', posix.read(fd, 2))
202 finally:
203 os.close(fd)
204
205 @unittest.skipUnless(hasattr(posix, 'pwrite'), "test needs posix.pwrite()")
206 def test_pwrite(self):
207 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
208 try:
209 os.write(fd, b'test')
210 os.lseek(fd, 0, os.SEEK_SET)
211 posix.pwrite(fd, b'xx', 1)
212 self.assertEqual(b'txxt', posix.read(fd, 4))
213 finally:
214 os.close(fd)
215
216 @unittest.skipUnless(hasattr(posix, 'posix_fallocate'),
217 "test needs posix.posix_fallocate()")
218 def test_posix_fallocate(self):
219 fd = os.open(support.TESTFN, os.O_WRONLY | os.O_CREAT)
220 try:
221 posix.posix_fallocate(fd, 0, 10)
222 except OSError as inst:
223 # issue10812, ZFS doesn't appear to support posix_fallocate,
224 # so skip Solaris-based since they are likely to have ZFS.
225 if inst.errno != errno.EINVAL or not sys.platform.startswith("sunos"):
226 raise
227 finally:
228 os.close(fd)
229
230 @unittest.skipUnless(hasattr(posix, 'posix_fadvise'),
231 "test needs posix.posix_fadvise()")
232 def test_posix_fadvise(self):
233 fd = os.open(support.TESTFN, os.O_RDONLY)
234 try:
235 posix.posix_fadvise(fd, 0, 0, posix.POSIX_FADV_WILLNEED)
236 finally:
237 os.close(fd)
238
Larry Hastings9cf065c2012-06-22 16:30:09 -0700239 @unittest.skipUnless(os.utime in os.supports_fd, "test needs fd support in os.utime")
240 def test_utime_with_fd(self):
Ross Lagerwall7807c352011-03-17 20:20:30 +0200241 now = time.time()
242 fd = os.open(support.TESTFN, os.O_RDONLY)
243 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700244 posix.utime(fd)
245 posix.utime(fd, None)
246 self.assertRaises(TypeError, posix.utime, fd, (None, None))
247 self.assertRaises(TypeError, posix.utime, fd, (now, None))
248 self.assertRaises(TypeError, posix.utime, fd, (None, now))
249 posix.utime(fd, (int(now), int(now)))
250 posix.utime(fd, (now, now))
251 self.assertRaises(ValueError, posix.utime, fd, (now, now), ns=(now, now))
252 self.assertRaises(ValueError, posix.utime, fd, (now, 0), ns=(None, None))
253 self.assertRaises(ValueError, posix.utime, fd, (None, None), ns=(now, 0))
254 posix.utime(fd, (int(now), int((now - int(now)) * 1e9)))
255 posix.utime(fd, ns=(int(now), int((now - int(now)) * 1e9)))
256
Ross Lagerwall7807c352011-03-17 20:20:30 +0200257 finally:
258 os.close(fd)
259
Larry Hastings9cf065c2012-06-22 16:30:09 -0700260 @unittest.skipUnless(os.utime in os.supports_follow_symlinks, "test needs follow_symlinks support in os.utime")
261 def test_utime_nofollow_symlinks(self):
Ross Lagerwall7807c352011-03-17 20:20:30 +0200262 now = time.time()
Larry Hastings9cf065c2012-06-22 16:30:09 -0700263 posix.utime(support.TESTFN, None, follow_symlinks=False)
264 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None), follow_symlinks=False)
265 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None), follow_symlinks=False)
266 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now), follow_symlinks=False)
267 posix.utime(support.TESTFN, (int(now), int(now)), follow_symlinks=False)
268 posix.utime(support.TESTFN, (now, now), follow_symlinks=False)
269 posix.utime(support.TESTFN, follow_symlinks=False)
Ross Lagerwall7807c352011-03-17 20:20:30 +0200270
271 @unittest.skipUnless(hasattr(posix, 'writev'), "test needs posix.writev()")
272 def test_writev(self):
273 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
274 try:
275 os.writev(fd, (b'test1', b'tt2', b't3'))
276 os.lseek(fd, 0, os.SEEK_SET)
277 self.assertEqual(b'test1tt2t3', posix.read(fd, 10))
278 finally:
279 os.close(fd)
280
281 @unittest.skipUnless(hasattr(posix, 'readv'), "test needs posix.readv()")
282 def test_readv(self):
283 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
284 try:
285 os.write(fd, b'test1tt2t3')
286 os.lseek(fd, 0, os.SEEK_SET)
287 buf = [bytearray(i) for i in [5, 3, 2]]
288 self.assertEqual(posix.readv(fd, buf), 10)
289 self.assertEqual([b'test1', b'tt2', b't3'], [bytes(i) for i in buf])
290 finally:
291 os.close(fd)
292
Neal Norwitze241ce82003-02-17 18:17:05 +0000293 def test_dup(self):
294 if hasattr(posix, 'dup'):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000295 fp = open(support.TESTFN)
Neal Norwitze241ce82003-02-17 18:17:05 +0000296 try:
297 fd = posix.dup(fp.fileno())
Ezio Melottie9615932010-01-24 19:26:24 +0000298 self.assertIsInstance(fd, int)
Neal Norwitze241ce82003-02-17 18:17:05 +0000299 os.close(fd)
300 finally:
301 fp.close()
302
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000303 def test_confstr(self):
304 if hasattr(posix, 'confstr'):
305 self.assertRaises(ValueError, posix.confstr, "CS_garbage")
306 self.assertEqual(len(posix.confstr("CS_PATH")) > 0, True)
307
Neal Norwitze241ce82003-02-17 18:17:05 +0000308 def test_dup2(self):
309 if hasattr(posix, 'dup2'):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000310 fp1 = open(support.TESTFN)
311 fp2 = open(support.TESTFN)
Neal Norwitze241ce82003-02-17 18:17:05 +0000312 try:
313 posix.dup2(fp1.fileno(), fp2.fileno())
314 finally:
315 fp1.close()
316 fp2.close()
317
Charles-François Natali1e045b12011-05-22 20:42:32 +0200318 @unittest.skipUnless(hasattr(os, 'O_CLOEXEC'), "needs os.O_CLOEXEC")
Charles-François Natali239bb962011-06-03 12:55:15 +0200319 @support.requires_linux_version(2, 6, 23)
Charles-François Natali1e045b12011-05-22 20:42:32 +0200320 def test_oscloexec(self):
321 fd = os.open(support.TESTFN, os.O_RDONLY|os.O_CLOEXEC)
322 self.addCleanup(os.close, fd)
Victor Stinnere36f3752011-05-24 00:29:43 +0200323 self.assertTrue(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC)
Charles-François Natali1e045b12011-05-22 20:42:32 +0200324
Skip Montanaro98470002005-06-17 01:14:49 +0000325 def test_osexlock(self):
326 if hasattr(posix, "O_EXLOCK"):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000327 fd = os.open(support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000328 os.O_WRONLY|os.O_EXLOCK|os.O_CREAT)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000329 self.assertRaises(OSError, os.open, support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000330 os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
331 os.close(fd)
332
333 if hasattr(posix, "O_SHLOCK"):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000334 fd = os.open(support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000335 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000336 self.assertRaises(OSError, os.open, support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000337 os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
338 os.close(fd)
339
340 def test_osshlock(self):
341 if hasattr(posix, "O_SHLOCK"):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000342 fd1 = os.open(support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000343 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000344 fd2 = os.open(support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000345 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
346 os.close(fd2)
347 os.close(fd1)
348
349 if hasattr(posix, "O_EXLOCK"):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000350 fd = os.open(support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000351 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000352 self.assertRaises(OSError, os.open, support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000353 os.O_RDONLY|os.O_EXLOCK|os.O_NONBLOCK)
354 os.close(fd)
355
Neal Norwitze241ce82003-02-17 18:17:05 +0000356 def test_fstat(self):
357 if hasattr(posix, 'fstat'):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000358 fp = open(support.TESTFN)
Neal Norwitze241ce82003-02-17 18:17:05 +0000359 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000360 self.assertTrue(posix.fstat(fp.fileno()))
Larry Hastings9cf065c2012-06-22 16:30:09 -0700361 self.assertTrue(posix.stat(fp.fileno()))
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200362
363 self.assertRaisesRegex(TypeError,
364 'should be string, bytes or integer, not',
365 posix.stat, float(fp.fileno()))
Neal Norwitze241ce82003-02-17 18:17:05 +0000366 finally:
367 fp.close()
368
369 def test_stat(self):
370 if hasattr(posix, 'stat'):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000371 self.assertTrue(posix.stat(support.TESTFN))
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200372 self.assertTrue(posix.stat(os.fsencode(support.TESTFN)))
373 self.assertTrue(posix.stat(bytearray(os.fsencode(support.TESTFN))))
374
375 self.assertRaisesRegex(TypeError,
376 'can\'t specify None for path argument',
377 posix.stat, None)
378 self.assertRaisesRegex(TypeError,
379 'should be string, bytes or integer, not',
380 posix.stat, list(support.TESTFN))
381 self.assertRaisesRegex(TypeError,
382 'should be string, bytes or integer, not',
383 posix.stat, list(os.fsencode(support.TESTFN)))
Neal Norwitze241ce82003-02-17 18:17:05 +0000384
Benjamin Peterson052a02b2010-08-17 01:27:09 +0000385 @unittest.skipUnless(hasattr(posix, 'mkfifo'), "don't have mkfifo()")
386 def test_mkfifo(self):
387 support.unlink(support.TESTFN)
388 posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR)
389 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
390
391 @unittest.skipUnless(hasattr(posix, 'mknod') and hasattr(stat, 'S_IFIFO'),
392 "don't have mknod()/S_IFIFO")
393 def test_mknod(self):
394 # Test using mknod() to create a FIFO (the only use specified
395 # by POSIX).
396 support.unlink(support.TESTFN)
397 mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
398 try:
399 posix.mknod(support.TESTFN, mode, 0)
400 except OSError as e:
401 # Some old systems don't allow unprivileged users to use
402 # mknod(), or only support creating device nodes.
403 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
404 else:
405 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
406
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200407 def _test_all_chown_common(self, chown_func, first_param, stat_func):
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000408 """Common code for chown, fchown and lchown tests."""
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200409 def check_stat():
410 if stat_func is not None:
411 stat = stat_func(first_param)
412 self.assertEqual(stat.st_uid, os.getuid())
413 self.assertEqual(stat.st_gid, os.getgid())
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200414 # test a successful chown call
415 chown_func(first_param, os.getuid(), os.getgid())
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200416 check_stat()
417 chown_func(first_param, -1, os.getgid())
418 check_stat()
419 chown_func(first_param, os.getuid(), -1)
420 check_stat()
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200421
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000422 if os.getuid() == 0:
423 try:
424 # Many linux distros have a nfsnobody user as MAX_UID-2
425 # that makes a good test case for signedness issues.
426 # http://bugs.python.org/issue1747858
427 # This part of the test only runs when run as root.
428 # Only scary people run their tests as root.
429 ent = pwd.getpwnam('nfsnobody')
430 chown_func(first_param, ent.pw_uid, ent.pw_gid)
431 except KeyError:
432 pass
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200433 elif platform.system() in ('HP-UX', 'SunOS'):
434 # HP-UX and Solaris can allow a non-root user to chown() to root
435 # (issue #5113)
436 raise unittest.SkipTest("Skipping because of non-standard chown() "
437 "behavior")
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000438 else:
439 # non-root cannot chown to root, raises OSError
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200440 self.assertRaises(OSError, chown_func, first_param, 0, 0)
441 check_stat()
442 self.assertRaises(OSError, chown_func, first_param, -1, 0)
443 check_stat()
444 self.assertRaises(OSError, chown_func, first_param, 0, -1)
445 check_stat()
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000446
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000447 @unittest.skipUnless(hasattr(posix, 'chown'), "test needs os.chown()")
448 def test_chown(self):
449 # raise an OSError if the file does not exist
450 os.unlink(support.TESTFN)
451 self.assertRaises(OSError, posix.chown, support.TESTFN, -1, -1)
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000452
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000453 # re-create the file
Victor Stinnerbf816222011-06-30 23:25:47 +0200454 support.create_empty_file(support.TESTFN)
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200455 self._test_all_chown_common(posix.chown, support.TESTFN,
456 getattr(posix, 'stat', None))
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000457
458 @unittest.skipUnless(hasattr(posix, 'fchown'), "test needs os.fchown()")
459 def test_fchown(self):
460 os.unlink(support.TESTFN)
461
462 # re-create the file
463 test_file = open(support.TESTFN, 'w')
464 try:
465 fd = test_file.fileno()
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200466 self._test_all_chown_common(posix.fchown, fd,
467 getattr(posix, 'fstat', None))
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000468 finally:
469 test_file.close()
470
471 @unittest.skipUnless(hasattr(posix, 'lchown'), "test needs os.lchown()")
472 def test_lchown(self):
473 os.unlink(support.TESTFN)
474 # create a symlink
Ned Deily3eb67d52011-06-28 00:00:28 -0700475 os.symlink(_DUMMY_SYMLINK, support.TESTFN)
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200476 self._test_all_chown_common(posix.lchown, support.TESTFN,
477 getattr(posix, 'lstat', None))
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000478
Neal Norwitze241ce82003-02-17 18:17:05 +0000479 def test_chdir(self):
480 if hasattr(posix, 'chdir'):
481 posix.chdir(os.curdir)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000482 self.assertRaises(OSError, posix.chdir, support.TESTFN)
Neal Norwitze241ce82003-02-17 18:17:05 +0000483
Martin v. Löwisc9e1c7d2010-07-23 12:16:41 +0000484 def test_listdir(self):
Larry Hastingsfdaea062012-06-25 04:42:23 -0700485 self.assertTrue(support.TESTFN in posix.listdir(os.curdir))
Martin v. Löwisc9e1c7d2010-07-23 12:16:41 +0000486
487 def test_listdir_default(self):
Larry Hastingsfdaea062012-06-25 04:42:23 -0700488 # When listdir is called without argument,
489 # it's the same as listdir(os.curdir).
490 self.assertTrue(support.TESTFN in posix.listdir())
Neal Norwitze241ce82003-02-17 18:17:05 +0000491
Larry Hastingsfdaea062012-06-25 04:42:23 -0700492 def test_listdir_bytes(self):
493 # When listdir is called with a bytes object,
494 # the returned strings are of type bytes.
495 self.assertTrue(os.fsencode(support.TESTFN) in posix.listdir(b'.'))
496
497 @unittest.skipUnless(posix.listdir in os.supports_fd,
498 "test needs fd support for posix.listdir()")
499 def test_listdir_fd(self):
Antoine Pitrou8250e232011-02-25 23:41:16 +0000500 f = posix.open(posix.getcwd(), posix.O_RDONLY)
Charles-François Natali7546ad32012-01-08 18:34:06 +0100501 self.addCleanup(posix.close, f)
Antoine Pitrou8250e232011-02-25 23:41:16 +0000502 self.assertEqual(
503 sorted(posix.listdir('.')),
Larry Hastings9cf065c2012-06-22 16:30:09 -0700504 sorted(posix.listdir(f))
Antoine Pitrou8250e232011-02-25 23:41:16 +0000505 )
Charles-François Natali7546ad32012-01-08 18:34:06 +0100506 # Check that the fd offset was reset (issue #13739)
Charles-François Natali7546ad32012-01-08 18:34:06 +0100507 self.assertEqual(
508 sorted(posix.listdir('.')),
Larry Hastings9cf065c2012-06-22 16:30:09 -0700509 sorted(posix.listdir(f))
Charles-François Natali7546ad32012-01-08 18:34:06 +0100510 )
Antoine Pitrou8250e232011-02-25 23:41:16 +0000511
Neal Norwitze241ce82003-02-17 18:17:05 +0000512 def test_access(self):
513 if hasattr(posix, 'access'):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000514 self.assertTrue(posix.access(support.TESTFN, os.R_OK))
Neal Norwitze241ce82003-02-17 18:17:05 +0000515
516 def test_umask(self):
517 if hasattr(posix, 'umask'):
518 old_mask = posix.umask(0)
Ezio Melottie9615932010-01-24 19:26:24 +0000519 self.assertIsInstance(old_mask, int)
Neal Norwitze241ce82003-02-17 18:17:05 +0000520 posix.umask(old_mask)
521
522 def test_strerror(self):
523 if hasattr(posix, 'strerror'):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000524 self.assertTrue(posix.strerror(0))
Neal Norwitze241ce82003-02-17 18:17:05 +0000525
526 def test_pipe(self):
527 if hasattr(posix, 'pipe'):
528 reader, writer = posix.pipe()
529 os.close(reader)
530 os.close(writer)
531
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200532 @unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()")
Charles-François Natali239bb962011-06-03 12:55:15 +0200533 @support.requires_linux_version(2, 6, 27)
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200534 def test_pipe2(self):
535 self.assertRaises(TypeError, os.pipe2, 'DEADBEEF')
536 self.assertRaises(TypeError, os.pipe2, 0, 0)
537
Charles-François Natali368f34b2011-06-06 19:49:47 +0200538 # try calling with flags = 0, like os.pipe()
539 r, w = os.pipe2(0)
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200540 os.close(r)
541 os.close(w)
542
543 # test flags
544 r, w = os.pipe2(os.O_CLOEXEC|os.O_NONBLOCK)
545 self.addCleanup(os.close, r)
546 self.addCleanup(os.close, w)
547 self.assertTrue(fcntl.fcntl(r, fcntl.F_GETFD) & fcntl.FD_CLOEXEC)
548 self.assertTrue(fcntl.fcntl(w, fcntl.F_GETFD) & fcntl.FD_CLOEXEC)
549 # try reading from an empty pipe: this should fail, not block
550 self.assertRaises(OSError, os.read, r, 1)
551 # try a write big enough to fill-up the pipe: this should either
552 # fail or perform a partial write, not block
553 try:
554 os.write(w, b'x' * support.PIPE_MAX_SIZE)
555 except OSError:
556 pass
557
Serhiy Storchaka9101e232013-01-19 12:41:45 +0200558 # Issue 15989
559 self.assertRaises(OverflowError, os.pipe2, _testcapi.INT_MAX + 1)
560 self.assertRaises(OverflowError, os.pipe2, _testcapi.UINT_MAX + 1)
561
Neal Norwitze241ce82003-02-17 18:17:05 +0000562 def test_utime(self):
563 if hasattr(posix, 'utime'):
564 now = time.time()
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000565 posix.utime(support.TESTFN, None)
566 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None))
567 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None))
568 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now))
569 posix.utime(support.TESTFN, (int(now), int(now)))
570 posix.utime(support.TESTFN, (now, now))
Neal Norwitze241ce82003-02-17 18:17:05 +0000571
Larry Hastings9cf065c2012-06-22 16:30:09 -0700572 def _test_chflags_regular_file(self, chflags_func, target_file, **kwargs):
Ned Deily3eb67d52011-06-28 00:00:28 -0700573 st = os.stat(target_file)
574 self.assertTrue(hasattr(st, 'st_flags'))
Trent Nelson75959cf2012-08-21 23:59:31 +0000575
576 # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
577 flags = st.st_flags | stat.UF_IMMUTABLE
578 try:
579 chflags_func(target_file, flags, **kwargs)
580 except OSError as err:
581 if err.errno != errno.EOPNOTSUPP:
582 raise
583 msg = 'chflag UF_IMMUTABLE not supported by underlying fs'
584 self.skipTest(msg)
585
Ned Deily3eb67d52011-06-28 00:00:28 -0700586 try:
587 new_st = os.stat(target_file)
588 self.assertEqual(st.st_flags | stat.UF_IMMUTABLE, new_st.st_flags)
589 try:
590 fd = open(target_file, 'w+')
591 except IOError as e:
592 self.assertEqual(e.errno, errno.EPERM)
593 finally:
594 posix.chflags(target_file, st.st_flags)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000595
Ned Deily3eb67d52011-06-28 00:00:28 -0700596 @unittest.skipUnless(hasattr(posix, 'chflags'), 'test needs os.chflags()')
597 def test_chflags(self):
598 self._test_chflags_regular_file(posix.chflags, support.TESTFN)
599
600 @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
601 def test_lchflags_regular_file(self):
602 self._test_chflags_regular_file(posix.lchflags, support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700603 self._test_chflags_regular_file(posix.chflags, support.TESTFN, follow_symlinks=False)
Ned Deily3eb67d52011-06-28 00:00:28 -0700604
605 @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
606 def test_lchflags_symlink(self):
607 testfn_st = os.stat(support.TESTFN)
608
609 self.assertTrue(hasattr(testfn_st, 'st_flags'))
610
611 os.symlink(support.TESTFN, _DUMMY_SYMLINK)
612 self.teardown_files.append(_DUMMY_SYMLINK)
613 dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
614
Larry Hastings9cf065c2012-06-22 16:30:09 -0700615 def chflags_nofollow(path, flags):
616 return posix.chflags(path, flags, follow_symlinks=False)
Ned Deily3eb67d52011-06-28 00:00:28 -0700617
Larry Hastings9cf065c2012-06-22 16:30:09 -0700618 for fn in (posix.lchflags, chflags_nofollow):
Trent Nelson75959cf2012-08-21 23:59:31 +0000619 # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
620 flags = dummy_symlink_st.st_flags | stat.UF_IMMUTABLE
621 try:
622 fn(_DUMMY_SYMLINK, flags)
623 except OSError as err:
624 if err.errno != errno.EOPNOTSUPP:
625 raise
626 msg = 'chflag UF_IMMUTABLE not supported by underlying fs'
627 self.skipTest(msg)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700628 try:
629 new_testfn_st = os.stat(support.TESTFN)
630 new_dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
631
632 self.assertEqual(testfn_st.st_flags, new_testfn_st.st_flags)
633 self.assertEqual(dummy_symlink_st.st_flags | stat.UF_IMMUTABLE,
634 new_dummy_symlink_st.st_flags)
635 finally:
636 fn(_DUMMY_SYMLINK, dummy_symlink_st.st_flags)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000637
Guido van Rossum98297ee2007-11-06 21:34:58 +0000638 def test_environ(self):
Victor Stinner17b490d2010-05-06 22:19:30 +0000639 if os.name == "nt":
640 item_type = str
641 else:
642 item_type = bytes
Guido van Rossum98297ee2007-11-06 21:34:58 +0000643 for k, v in posix.environ.items():
Victor Stinner17b490d2010-05-06 22:19:30 +0000644 self.assertEqual(type(k), item_type)
645 self.assertEqual(type(v), item_type)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000646
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000647 def test_getcwd_long_pathnames(self):
648 if hasattr(posix, 'getcwd'):
649 dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
650 curdir = os.getcwd()
651 base_path = os.path.abspath(support.TESTFN) + '.getcwd'
652
653 try:
654 os.mkdir(base_path)
655 os.chdir(base_path)
656 except:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000657# Just returning nothing instead of the SkipTest exception,
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000658# because the test results in Error in that case.
659# Is that ok?
Benjamin Petersone549ead2009-03-28 21:42:05 +0000660# raise unittest.SkipTest("cannot create directory for testing")
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000661 return
662
663 def _create_and_do_getcwd(dirname, current_path_length = 0):
664 try:
665 os.mkdir(dirname)
666 except:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000667 raise unittest.SkipTest("mkdir cannot create directory sufficiently deep for getcwd test")
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000668
669 os.chdir(dirname)
670 try:
671 os.getcwd()
672 if current_path_length < 1027:
673 _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1)
674 finally:
675 os.chdir('..')
676 os.rmdir(dirname)
677
678 _create_and_do_getcwd(dirname)
679
680 finally:
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000681 os.chdir(curdir)
R. David Murray414c91f2009-07-09 20:12:31 +0000682 support.rmtree(base_path)
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000683
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200684 @unittest.skipUnless(hasattr(posix, 'getgrouplist'), "test needs posix.getgrouplist()")
685 @unittest.skipUnless(hasattr(pwd, 'getpwuid'), "test needs pwd.getpwuid()")
686 @unittest.skipUnless(hasattr(os, 'getuid'), "test needs os.getuid()")
687 def test_getgrouplist(self):
Ross Lagerwalla0b315f2012-12-13 15:20:26 +0000688 user = pwd.getpwuid(os.getuid())[0]
689 group = pwd.getpwuid(os.getuid())[3]
690 self.assertIn(group, posix.getgrouplist(user, group))
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200691
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200692
Antoine Pitrou318b8f32011-01-12 18:45:27 +0000693 @unittest.skipUnless(hasattr(os, 'getegid'), "test needs os.getegid()")
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000694 def test_getgroups(self):
695 with os.popen('id -G') as idg:
696 groups = idg.read().strip()
Charles-François Natalie8a255a2012-05-02 20:01:38 +0200697 ret = idg.close()
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000698
Benjamin Petersonb29614e2012-10-09 11:16:03 -0400699 if ret is not None or not groups:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000700 raise unittest.SkipTest("need working 'id -G'")
701
Ned Deily028915e2013-02-02 15:08:52 -0800702 # Issues 16698: OS X ABIs prior to 10.6 have limits on getgroups()
703 if sys.platform == 'darwin':
704 import sysconfig
705 dt = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') or '10.0'
706 if float(dt) < 10.6:
707 raise unittest.SkipTest("getgroups(2) is broken prior to 10.6")
708
Ronald Oussoren7fb6f512010-08-01 19:18:13 +0000709 # 'id -G' and 'os.getgroups()' should return the same
710 # groups, ignoring order and duplicates.
Antoine Pitrou318b8f32011-01-12 18:45:27 +0000711 # #10822 - it is implementation defined whether posix.getgroups()
712 # includes the effective gid so we include it anyway, since id -G does
Ronald Oussorencb615e62010-07-24 14:15:19 +0000713 self.assertEqual(
Ronald Oussoren7fb6f512010-08-01 19:18:13 +0000714 set([int(x) for x in groups.split()]),
Antoine Pitrou318b8f32011-01-12 18:45:27 +0000715 set(posix.getgroups() + [posix.getegid()]))
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000716
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000717 # tests for the posix *at functions follow
718
Larry Hastings9cf065c2012-06-22 16:30:09 -0700719 @unittest.skipUnless(os.access in os.supports_dir_fd, "test needs dir_fd support for os.access()")
720 def test_access_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000721 f = posix.open(posix.getcwd(), posix.O_RDONLY)
722 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700723 self.assertTrue(posix.access(support.TESTFN, os.R_OK, dir_fd=f))
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000724 finally:
725 posix.close(f)
726
Larry Hastings9cf065c2012-06-22 16:30:09 -0700727 @unittest.skipUnless(os.chmod in os.supports_dir_fd, "test needs dir_fd support in os.chmod()")
728 def test_chmod_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000729 os.chmod(support.TESTFN, stat.S_IRUSR)
730
731 f = posix.open(posix.getcwd(), posix.O_RDONLY)
732 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700733 posix.chmod(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000734
735 s = posix.stat(support.TESTFN)
736 self.assertEqual(s[0] & stat.S_IRWXU, stat.S_IRUSR | stat.S_IWUSR)
737 finally:
738 posix.close(f)
739
Larry Hastings9cf065c2012-06-22 16:30:09 -0700740 @unittest.skipUnless(os.chown in os.supports_dir_fd, "test needs dir_fd support in os.chown()")
741 def test_chown_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000742 support.unlink(support.TESTFN)
Victor Stinnerbf816222011-06-30 23:25:47 +0200743 support.create_empty_file(support.TESTFN)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000744
745 f = posix.open(posix.getcwd(), posix.O_RDONLY)
746 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700747 posix.chown(support.TESTFN, os.getuid(), os.getgid(), dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000748 finally:
749 posix.close(f)
750
Larry Hastings9cf065c2012-06-22 16:30:09 -0700751 @unittest.skipUnless(os.stat in os.supports_dir_fd, "test needs dir_fd support in os.stat()")
752 def test_stat_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000753 support.unlink(support.TESTFN)
754 with open(support.TESTFN, 'w') as outfile:
755 outfile.write("testline\n")
756
757 f = posix.open(posix.getcwd(), posix.O_RDONLY)
758 try:
759 s1 = posix.stat(support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700760 s2 = posix.stat(support.TESTFN, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000761 self.assertEqual(s1, s2)
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200762 s2 = posix.stat(support.TESTFN, dir_fd=None)
763 self.assertEqual(s1, s2)
764 self.assertRaisesRegex(TypeError, 'should be integer, not',
765 posix.stat, support.TESTFN, dir_fd=posix.getcwd())
766 self.assertRaisesRegex(TypeError, 'should be integer, not',
767 posix.stat, support.TESTFN, dir_fd=float(f))
768 self.assertRaises(OverflowError,
769 posix.stat, support.TESTFN, dir_fd=10**20)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000770 finally:
771 posix.close(f)
772
Larry Hastings9cf065c2012-06-22 16:30:09 -0700773 @unittest.skipUnless(os.utime in os.supports_dir_fd, "test needs dir_fd support in os.utime()")
774 def test_utime_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000775 f = posix.open(posix.getcwd(), posix.O_RDONLY)
776 try:
777 now = time.time()
Larry Hastings9cf065c2012-06-22 16:30:09 -0700778 posix.utime(support.TESTFN, None, dir_fd=f)
779 posix.utime(support.TESTFN, dir_fd=f)
780 self.assertRaises(TypeError, posix.utime, support.TESTFN, now, dir_fd=f)
781 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None), dir_fd=f)
782 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None), dir_fd=f)
783 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now), dir_fd=f)
784 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, "x"), dir_fd=f)
785 posix.utime(support.TESTFN, (int(now), int(now)), dir_fd=f)
786 posix.utime(support.TESTFN, (now, now), dir_fd=f)
787 posix.utime(support.TESTFN,
788 (int(now), int((now - int(now)) * 1e9)), dir_fd=f)
789 posix.utime(support.TESTFN, dir_fd=f,
790 times=(int(now), int((now - int(now)) * 1e9)))
791
Larry Hastings90867a52012-06-22 17:01:41 -0700792 # try dir_fd and follow_symlinks together
Larry Hastings9cf065c2012-06-22 16:30:09 -0700793 if os.utime in os.supports_follow_symlinks:
Larry Hastings90867a52012-06-22 17:01:41 -0700794 try:
795 posix.utime(support.TESTFN, follow_symlinks=False, dir_fd=f)
Georg Brandl969288e2012-06-26 09:25:44 +0200796 except ValueError:
Larry Hastings90867a52012-06-22 17:01:41 -0700797 # whoops! using both together not supported on this platform.
798 pass
Larry Hastings9cf065c2012-06-22 16:30:09 -0700799
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000800 finally:
801 posix.close(f)
802
Larry Hastings9cf065c2012-06-22 16:30:09 -0700803 @unittest.skipUnless(os.link in os.supports_dir_fd, "test needs dir_fd support in os.link()")
804 def test_link_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000805 f = posix.open(posix.getcwd(), posix.O_RDONLY)
806 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700807 posix.link(support.TESTFN, support.TESTFN + 'link', src_dir_fd=f, dst_dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000808 # should have same inodes
809 self.assertEqual(posix.stat(support.TESTFN)[1],
810 posix.stat(support.TESTFN + 'link')[1])
811 finally:
812 posix.close(f)
813 support.unlink(support.TESTFN + 'link')
814
Larry Hastings9cf065c2012-06-22 16:30:09 -0700815 @unittest.skipUnless(os.mkdir in os.supports_dir_fd, "test needs dir_fd support in os.mkdir()")
816 def test_mkdir_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000817 f = posix.open(posix.getcwd(), posix.O_RDONLY)
818 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700819 posix.mkdir(support.TESTFN + 'dir', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000820 posix.stat(support.TESTFN + 'dir') # should not raise exception
821 finally:
822 posix.close(f)
823 support.rmtree(support.TESTFN + 'dir')
824
Larry Hastings9cf065c2012-06-22 16:30:09 -0700825 @unittest.skipUnless((os.mknod in os.supports_dir_fd) and hasattr(stat, 'S_IFIFO'),
826 "test requires both stat.S_IFIFO and dir_fd support for os.mknod()")
827 def test_mknod_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000828 # Test using mknodat() to create a FIFO (the only use specified
829 # by POSIX).
830 support.unlink(support.TESTFN)
831 mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
832 f = posix.open(posix.getcwd(), posix.O_RDONLY)
833 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700834 posix.mknod(support.TESTFN, mode, 0, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000835 except OSError as e:
836 # Some old systems don't allow unprivileged users to use
837 # mknod(), or only support creating device nodes.
838 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
839 else:
840 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
841 finally:
842 posix.close(f)
843
Larry Hastings9cf065c2012-06-22 16:30:09 -0700844 @unittest.skipUnless(os.open in os.supports_dir_fd, "test needs dir_fd support in os.open()")
845 def test_open_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000846 support.unlink(support.TESTFN)
847 with open(support.TESTFN, 'w') as outfile:
848 outfile.write("testline\n")
849 a = posix.open(posix.getcwd(), posix.O_RDONLY)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700850 b = posix.open(support.TESTFN, posix.O_RDONLY, dir_fd=a)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000851 try:
852 res = posix.read(b, 9).decode(encoding="utf-8")
853 self.assertEqual("testline\n", res)
854 finally:
855 posix.close(a)
856 posix.close(b)
857
Larry Hastings9cf065c2012-06-22 16:30:09 -0700858 @unittest.skipUnless(os.readlink in os.supports_dir_fd, "test needs dir_fd support in os.readlink()")
859 def test_readlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000860 os.symlink(support.TESTFN, support.TESTFN + 'link')
861 f = posix.open(posix.getcwd(), posix.O_RDONLY)
862 try:
863 self.assertEqual(posix.readlink(support.TESTFN + 'link'),
Larry Hastings9cf065c2012-06-22 16:30:09 -0700864 posix.readlink(support.TESTFN + 'link', dir_fd=f))
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000865 finally:
866 support.unlink(support.TESTFN + 'link')
867 posix.close(f)
868
Larry Hastings9cf065c2012-06-22 16:30:09 -0700869 @unittest.skipUnless(os.rename in os.supports_dir_fd, "test needs dir_fd support in os.rename()")
870 def test_rename_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000871 support.unlink(support.TESTFN)
Victor Stinnerbf816222011-06-30 23:25:47 +0200872 support.create_empty_file(support.TESTFN + 'ren')
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000873 f = posix.open(posix.getcwd(), posix.O_RDONLY)
874 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700875 posix.rename(support.TESTFN + 'ren', support.TESTFN, src_dir_fd=f, dst_dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000876 except:
877 posix.rename(support.TESTFN + 'ren', support.TESTFN)
878 raise
879 else:
Andrew Svetlov5b898402012-12-18 21:26:36 +0200880 posix.stat(support.TESTFN) # should not raise exception
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000881 finally:
882 posix.close(f)
883
Larry Hastings9cf065c2012-06-22 16:30:09 -0700884 @unittest.skipUnless(os.symlink in os.supports_dir_fd, "test needs dir_fd support in os.symlink()")
885 def test_symlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000886 f = posix.open(posix.getcwd(), posix.O_RDONLY)
887 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700888 posix.symlink(support.TESTFN, support.TESTFN + 'link', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000889 self.assertEqual(posix.readlink(support.TESTFN + 'link'), support.TESTFN)
890 finally:
891 posix.close(f)
892 support.unlink(support.TESTFN + 'link')
893
Larry Hastings9cf065c2012-06-22 16:30:09 -0700894 @unittest.skipUnless(os.unlink in os.supports_dir_fd, "test needs dir_fd support in os.unlink()")
895 def test_unlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000896 f = posix.open(posix.getcwd(), posix.O_RDONLY)
Victor Stinnerbf816222011-06-30 23:25:47 +0200897 support.create_empty_file(support.TESTFN + 'del')
Andrew Svetlov5b898402012-12-18 21:26:36 +0200898 posix.stat(support.TESTFN + 'del') # should not raise exception
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000899 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700900 posix.unlink(support.TESTFN + 'del', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000901 except:
902 support.unlink(support.TESTFN + 'del')
903 raise
904 else:
905 self.assertRaises(OSError, posix.stat, support.TESTFN + 'link')
906 finally:
907 posix.close(f)
908
Larry Hastings9cf065c2012-06-22 16:30:09 -0700909 @unittest.skipUnless(os.mkfifo in os.supports_dir_fd, "test needs dir_fd support in os.mkfifo()")
910 def test_mkfifo_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000911 support.unlink(support.TESTFN)
912 f = posix.open(posix.getcwd(), posix.O_RDONLY)
913 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700914 posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000915 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
916 finally:
917 posix.close(f)
918
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500919 requires_sched_h = unittest.skipUnless(hasattr(posix, 'sched_yield'),
920 "don't have scheduling support")
Antoine Pitrou84869872012-08-04 16:16:35 +0200921 requires_sched_affinity = unittest.skipUnless(hasattr(posix, 'sched_setaffinity'),
Benjamin Peterson50ba2712011-08-02 22:15:40 -0500922 "don't have sched affinity support")
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500923
924 @requires_sched_h
925 def test_sched_yield(self):
926 # This has no error conditions (at least on Linux).
927 posix.sched_yield()
928
929 @requires_sched_h
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +0200930 @unittest.skipUnless(hasattr(posix, 'sched_get_priority_max'),
931 "requires sched_get_priority_max()")
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500932 def test_sched_priority(self):
933 # Round-robin usually has interesting priorities.
934 pol = posix.SCHED_RR
935 lo = posix.sched_get_priority_min(pol)
936 hi = posix.sched_get_priority_max(pol)
937 self.assertIsInstance(lo, int)
938 self.assertIsInstance(hi, int)
939 self.assertGreaterEqual(hi, lo)
Benjamin Peterson539b6c42011-08-02 22:09:37 -0500940 # OSX evidently just returns 15 without checking the argument.
941 if sys.platform != "darwin":
Benjamin Petersonc1581582011-08-02 22:10:55 -0500942 self.assertRaises(OSError, posix.sched_get_priority_min, -23)
943 self.assertRaises(OSError, posix.sched_get_priority_max, -23)
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500944
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -0500945 @unittest.skipUnless(hasattr(posix, 'sched_setscheduler'), "can't change scheduler")
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500946 def test_get_and_set_scheduler_and_param(self):
947 possible_schedulers = [sched for name, sched in posix.__dict__.items()
948 if name.startswith("SCHED_")]
949 mine = posix.sched_getscheduler(0)
950 self.assertIn(mine, possible_schedulers)
951 try:
Jesus Ceaceb5d162011-09-10 01:16:55 +0200952 parent = posix.sched_getscheduler(os.getppid())
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500953 except OSError as e:
Jesus Ceaceb5d162011-09-10 01:16:55 +0200954 if e.errno != errno.EPERM:
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500955 raise
956 else:
Jesus Ceaceb5d162011-09-10 01:16:55 +0200957 self.assertIn(parent, possible_schedulers)
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500958 self.assertRaises(OSError, posix.sched_getscheduler, -1)
959 self.assertRaises(OSError, posix.sched_getparam, -1)
960 param = posix.sched_getparam(0)
961 self.assertIsInstance(param.sched_priority, int)
Charles-François Natali7b911cb2011-08-21 12:41:43 +0200962
Charles-François Natalic78de462013-01-13 14:10:37 +0100963 # POSIX states that calling sched_setparam() or sched_setscheduler() on
964 # a process with a scheduling policy other than SCHED_FIFO or SCHED_RR
965 # is implementation-defined: NetBSD and FreeBSD can return EINVAL.
966 if not sys.platform.startswith(('freebsd', 'netbsd')):
967 try:
968 posix.sched_setscheduler(0, mine, param)
969 posix.sched_setparam(0, param)
970 except OSError as e:
971 if e.errno != errno.EPERM:
972 raise
Charles-François Natali7b911cb2011-08-21 12:41:43 +0200973 self.assertRaises(OSError, posix.sched_setparam, -1, param)
974
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500975 self.assertRaises(OSError, posix.sched_setscheduler, -1, mine, param)
976 self.assertRaises(TypeError, posix.sched_setscheduler, 0, mine, None)
977 self.assertRaises(TypeError, posix.sched_setparam, 0, 43)
978 param = posix.sched_param(None)
979 self.assertRaises(TypeError, posix.sched_setparam, 0, param)
980 large = 214748364700
981 param = posix.sched_param(large)
982 self.assertRaises(OverflowError, posix.sched_setparam, 0, param)
983 param = posix.sched_param(sched_priority=-large)
984 self.assertRaises(OverflowError, posix.sched_setparam, 0, param)
985
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -0500986 @unittest.skipUnless(hasattr(posix, "sched_rr_get_interval"), "no function")
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500987 def test_sched_rr_get_interval(self):
Benjamin Peterson43234ab2011-08-02 22:19:14 -0500988 try:
989 interval = posix.sched_rr_get_interval(0)
990 except OSError as e:
991 # This likely means that sched_rr_get_interval is only valid for
992 # processes with the SCHED_RR scheduler in effect.
993 if e.errno != errno.EINVAL:
994 raise
995 self.skipTest("only works on SCHED_RR processes")
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500996 self.assertIsInstance(interval, float)
997 # Reasonable constraints, I think.
998 self.assertGreaterEqual(interval, 0.)
999 self.assertLess(interval, 1.)
1000
Benjamin Peterson2740af82011-08-02 17:41:34 -05001001 @requires_sched_affinity
Antoine Pitrou84869872012-08-04 16:16:35 +02001002 def test_sched_getaffinity(self):
1003 mask = posix.sched_getaffinity(0)
1004 self.assertIsInstance(mask, set)
1005 self.assertGreaterEqual(len(mask), 1)
1006 self.assertRaises(OSError, posix.sched_getaffinity, -1)
1007 for cpu in mask:
1008 self.assertIsInstance(cpu, int)
1009 self.assertGreaterEqual(cpu, 0)
1010 self.assertLess(cpu, 1 << 32)
1011
1012 @requires_sched_affinity
1013 def test_sched_setaffinity(self):
1014 mask = posix.sched_getaffinity(0)
1015 if len(mask) > 1:
1016 # Empty masks are forbidden
1017 mask.pop()
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001018 posix.sched_setaffinity(0, mask)
Antoine Pitrou84869872012-08-04 16:16:35 +02001019 self.assertEqual(posix.sched_getaffinity(0), mask)
1020 self.assertRaises(OSError, posix.sched_setaffinity, 0, [])
1021 self.assertRaises(ValueError, posix.sched_setaffinity, 0, [-10])
1022 self.assertRaises(OverflowError, posix.sched_setaffinity, 0, [1<<128])
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001023 self.assertRaises(OSError, posix.sched_setaffinity, -1, mask)
1024
Victor Stinner8b905bd2011-10-25 13:34:04 +02001025 def test_rtld_constants(self):
1026 # check presence of major RTLD_* constants
1027 posix.RTLD_LAZY
1028 posix.RTLD_NOW
1029 posix.RTLD_GLOBAL
1030 posix.RTLD_LOCAL
1031
Jesus Cea60c13dd2012-06-23 02:58:14 +02001032 @unittest.skipUnless(hasattr(os, 'SEEK_HOLE'),
1033 "test needs an OS that reports file holes")
Hynek Schlawackf841e422012-06-24 09:51:46 +02001034 def test_fs_holes(self):
Jesus Cea94363612012-06-22 18:32:07 +02001035 # Even if the filesystem doesn't report holes,
1036 # if the OS supports it the SEEK_* constants
1037 # will be defined and will have a consistent
1038 # behaviour:
1039 # os.SEEK_DATA = current position
1040 # os.SEEK_HOLE = end of file position
Hynek Schlawackf841e422012-06-24 09:51:46 +02001041 with open(support.TESTFN, 'r+b') as fp:
Jesus Cea94363612012-06-22 18:32:07 +02001042 fp.write(b"hello")
1043 fp.flush()
1044 size = fp.tell()
1045 fno = fp.fileno()
Jesus Cead46f7d22012-07-07 14:56:04 +02001046 try :
1047 for i in range(size):
1048 self.assertEqual(i, os.lseek(fno, i, os.SEEK_DATA))
1049 self.assertLessEqual(size, os.lseek(fno, i, os.SEEK_HOLE))
1050 self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_DATA)
1051 self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_HOLE)
1052 except OSError :
1053 # Some OSs claim to support SEEK_HOLE/SEEK_DATA
1054 # but it is not true.
1055 # For instance:
1056 # http://lists.freebsd.org/pipermail/freebsd-amd64/2012-January/014332.html
1057 raise unittest.SkipTest("OSError raised!")
Jesus Cea94363612012-06-22 18:32:07 +02001058
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001059class PosixGroupsTester(unittest.TestCase):
1060
1061 def setUp(self):
1062 if posix.getuid() != 0:
1063 raise unittest.SkipTest("not enough privileges")
1064 if not hasattr(posix, 'getgroups'):
1065 raise unittest.SkipTest("need posix.getgroups")
1066 if sys.platform == 'darwin':
1067 raise unittest.SkipTest("getgroups(2) is broken on OSX")
1068 self.saved_groups = posix.getgroups()
1069
1070 def tearDown(self):
1071 if hasattr(posix, 'setgroups'):
1072 posix.setgroups(self.saved_groups)
1073 elif hasattr(posix, 'initgroups'):
1074 name = pwd.getpwuid(posix.getuid()).pw_name
1075 posix.initgroups(name, self.saved_groups[0])
1076
1077 @unittest.skipUnless(hasattr(posix, 'initgroups'),
1078 "test needs posix.initgroups()")
1079 def test_initgroups(self):
1080 # find missing group
1081
Antoine Pitroue5a91012010-09-04 17:32:06 +00001082 g = max(self.saved_groups) + 1
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001083 name = pwd.getpwuid(posix.getuid()).pw_name
1084 posix.initgroups(name, g)
1085 self.assertIn(g, posix.getgroups())
1086
1087 @unittest.skipUnless(hasattr(posix, 'setgroups'),
1088 "test needs posix.setgroups()")
1089 def test_setgroups(self):
Antoine Pitroue5a91012010-09-04 17:32:06 +00001090 for groups in [[0], list(range(16))]:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001091 posix.setgroups(groups)
1092 self.assertListEqual(groups, posix.getgroups())
1093
Neal Norwitze241ce82003-02-17 18:17:05 +00001094def test_main():
Antoine Pitrou68c95922011-03-20 17:33:57 +01001095 try:
1096 support.run_unittest(PosixTester, PosixGroupsTester)
1097 finally:
1098 support.reap_children()
Neal Norwitze241ce82003-02-17 18:17:05 +00001099
1100if __name__ == '__main__':
1101 test_main()