blob: 22b050d4d723c81c630078009dc92a4d5c04fd67 [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
Antoine Pitrou346cbd32017-05-27 17:50:54 +02004from test.support.script_helper import assert_python_ok
Xavier de Gaye3a4e9892016-12-13 10:00:01 +01005android_not_root = support.android_not_root
R. David Murrayeb3615d2009-04-22 02:24:39 +00006
7# Skip these tests if there is no posix module.
8posix = support.import_module('posix')
Neal Norwitze241ce82003-02-17 18:17:05 +00009
Antoine Pitroub7572f02009-12-02 20:46:48 +000010import errno
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +000011import sys
Neal Norwitze241ce82003-02-17 18:17:05 +000012import time
13import os
Charles-François Nataliab2d58e2012-04-17 19:48:35 +020014import platform
Christian Heimesd5e2b6f2008-03-19 21:50:51 +000015import pwd
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
R. David Murraya21e4ca2009-03-31 23:16:50 +000020
Ned Deilyba2eab22011-07-26 13:53:55 -070021_DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(),
22 support.TESTFN + '-dummy-symlink')
Neal Norwitze241ce82003-02-17 18:17:05 +000023
24class PosixTester(unittest.TestCase):
25
26 def setUp(self):
27 # create empty file
Benjamin Petersonee8712c2008-05-20 21:35:26 +000028 fp = open(support.TESTFN, 'w+')
Neal Norwitze241ce82003-02-17 18:17:05 +000029 fp.close()
Ned Deily3eb67d52011-06-28 00:00:28 -070030 self.teardown_files = [ support.TESTFN ]
Brett Cannonc8d502e2010-03-20 21:53:28 +000031 self._warnings_manager = support.check_warnings()
32 self._warnings_manager.__enter__()
33 warnings.filterwarnings('ignore', '.* potential security risk .*',
34 RuntimeWarning)
Neal Norwitze241ce82003-02-17 18:17:05 +000035
36 def tearDown(self):
Ned Deily3eb67d52011-06-28 00:00:28 -070037 for teardown_file in self.teardown_files:
38 support.unlink(teardown_file)
Brett Cannonc8d502e2010-03-20 21:53:28 +000039 self._warnings_manager.__exit__(None, None, None)
Neal Norwitze241ce82003-02-17 18:17:05 +000040
41 def testNoArgFunctions(self):
42 # test posix functions which take no arguments and have
43 # no side-effects which we need to cleanup (e.g., fork, wait, abort)
Guido van Rossumf0af3e32008-10-02 18:55:37 +000044 NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdb", "uname",
Guido van Rossum687b9c02007-10-25 23:18:51 +000045 "times", "getloadavg",
Neal Norwitze241ce82003-02-17 18:17:05 +000046 "getegid", "geteuid", "getgid", "getgroups",
Ross Lagerwall7807c352011-03-17 20:20:30 +020047 "getpid", "getpgrp", "getppid", "getuid", "sync",
Neal Norwitze241ce82003-02-17 18:17:05 +000048 ]
Neal Norwitz71b13e82003-02-23 22:12:24 +000049
Neal Norwitze241ce82003-02-17 18:17:05 +000050 for name in NO_ARG_FUNCTIONS:
51 posix_func = getattr(posix, name, None)
52 if posix_func is not None:
53 posix_func()
Neal Norwitz2ff51a82003-02-17 22:40:31 +000054 self.assertRaises(TypeError, posix_func, 1)
Neal Norwitze241ce82003-02-17 18:17:05 +000055
Serhiy Storchaka43767632013-11-03 21:31:38 +020056 @unittest.skipUnless(hasattr(posix, 'getresuid'),
57 'test needs 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)
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000063
Serhiy Storchaka43767632013-11-03 21:31:38 +020064 @unittest.skipUnless(hasattr(posix, 'getresgid'),
65 'test needs posix.getresgid()')
66 def test_getresgid(self):
67 group_ids = posix.getresgid()
68 self.assertEqual(len(group_ids), 3)
69 for val in group_ids:
70 self.assertGreaterEqual(val, 0)
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000071
Serhiy Storchaka43767632013-11-03 21:31:38 +020072 @unittest.skipUnless(hasattr(posix, 'setresuid'),
73 'test needs posix.setresuid()')
74 def test_setresuid(self):
75 current_user_ids = posix.getresuid()
76 self.assertIsNone(posix.setresuid(*current_user_ids))
77 # -1 means don't change that value.
78 self.assertIsNone(posix.setresuid(-1, -1, -1))
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000079
Serhiy Storchaka43767632013-11-03 21:31:38 +020080 @unittest.skipUnless(hasattr(posix, 'setresuid'),
81 'test needs posix.setresuid()')
82 def test_setresuid_exception(self):
83 # Don't do this test if someone is silly enough to run us as root.
84 current_user_ids = posix.getresuid()
85 if 0 not in current_user_ids:
86 new_user_ids = (current_user_ids[0]+1, -1, -1)
87 self.assertRaises(OSError, posix.setresuid, *new_user_ids)
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000088
Serhiy Storchaka43767632013-11-03 21:31:38 +020089 @unittest.skipUnless(hasattr(posix, 'setresgid'),
90 'test needs posix.setresgid()')
91 def test_setresgid(self):
92 current_group_ids = posix.getresgid()
93 self.assertIsNone(posix.setresgid(*current_group_ids))
94 # -1 means don't change that value.
95 self.assertIsNone(posix.setresgid(-1, -1, -1))
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000096
Serhiy Storchaka43767632013-11-03 21:31:38 +020097 @unittest.skipUnless(hasattr(posix, 'setresgid'),
98 'test needs posix.setresgid()')
99 def test_setresgid_exception(self):
100 # Don't do this test if someone is silly enough to run us as root.
101 current_group_ids = posix.getresgid()
102 if 0 not in current_group_ids:
103 new_group_ids = (current_group_ids[0]+1, -1, -1)
104 self.assertRaises(OSError, posix.setresgid, *new_group_ids)
Martin v. Löwis7aed61a2009-11-27 14:09:49 +0000105
Antoine Pitroub7572f02009-12-02 20:46:48 +0000106 @unittest.skipUnless(hasattr(posix, 'initgroups'),
107 "test needs os.initgroups()")
108 def test_initgroups(self):
109 # It takes a string and an integer; check that it raises a TypeError
110 # for other argument lists.
111 self.assertRaises(TypeError, posix.initgroups)
112 self.assertRaises(TypeError, posix.initgroups, None)
113 self.assertRaises(TypeError, posix.initgroups, 3, "foo")
114 self.assertRaises(TypeError, posix.initgroups, "foo", 3, object())
115
116 # If a non-privileged user invokes it, it should fail with OSError
117 # EPERM.
118 if os.getuid() != 0:
Charles-François Natalie8a255a2012-05-02 20:01:38 +0200119 try:
120 name = pwd.getpwuid(posix.getuid()).pw_name
121 except KeyError:
122 # the current UID may not have a pwd entry
123 raise unittest.SkipTest("need a pwd entry")
Antoine Pitroub7572f02009-12-02 20:46:48 +0000124 try:
125 posix.initgroups(name, 13)
126 except OSError as e:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000127 self.assertEqual(e.errno, errno.EPERM)
Antoine Pitroub7572f02009-12-02 20:46:48 +0000128 else:
129 self.fail("Expected OSError to be raised by initgroups")
130
Serhiy Storchaka43767632013-11-03 21:31:38 +0200131 @unittest.skipUnless(hasattr(posix, 'statvfs'),
132 'test needs posix.statvfs()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000133 def test_statvfs(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200134 self.assertTrue(posix.statvfs(os.curdir))
Neal Norwitze241ce82003-02-17 18:17:05 +0000135
Serhiy Storchaka43767632013-11-03 21:31:38 +0200136 @unittest.skipUnless(hasattr(posix, 'fstatvfs'),
137 'test needs posix.fstatvfs()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000138 def test_fstatvfs(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200139 fp = open(support.TESTFN)
140 try:
141 self.assertTrue(posix.fstatvfs(fp.fileno()))
142 self.assertTrue(posix.statvfs(fp.fileno()))
143 finally:
144 fp.close()
Neal Norwitze241ce82003-02-17 18:17:05 +0000145
Serhiy Storchaka43767632013-11-03 21:31:38 +0200146 @unittest.skipUnless(hasattr(posix, 'ftruncate'),
147 'test needs posix.ftruncate()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000148 def test_ftruncate(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200149 fp = open(support.TESTFN, 'w+')
150 try:
151 # we need to have some data to truncate
152 fp.write('test')
153 fp.flush()
154 posix.ftruncate(fp.fileno(), 0)
155 finally:
156 fp.close()
Neal Norwitze241ce82003-02-17 18:17:05 +0000157
Ross Lagerwall7807c352011-03-17 20:20:30 +0200158 @unittest.skipUnless(hasattr(posix, 'truncate'), "test needs posix.truncate()")
159 def test_truncate(self):
160 with open(support.TESTFN, 'w') as fp:
161 fp.write('test')
162 fp.flush()
163 posix.truncate(support.TESTFN, 0)
164
Larry Hastings9cf065c2012-06-22 16:30:09 -0700165 @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 +0200166 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
Ross Lagerwalldedf6cf2011-03-20 18:27:05 +0200167 @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
Ross Lagerwall7807c352011-03-17 20:20:30 +0200168 def test_fexecve(self):
169 fp = os.open(sys.executable, os.O_RDONLY)
170 try:
171 pid = os.fork()
172 if pid == 0:
173 os.chdir(os.path.split(sys.executable)[0])
Larry Hastings9cf065c2012-06-22 16:30:09 -0700174 posix.execve(fp, [sys.executable, '-c', 'pass'], os.environ)
Ross Lagerwall7807c352011-03-17 20:20:30 +0200175 else:
Ross Lagerwalldedf6cf2011-03-20 18:27:05 +0200176 self.assertEqual(os.waitpid(pid, 0), (pid, 0))
Ross Lagerwall7807c352011-03-17 20:20:30 +0200177 finally:
178 os.close(fp)
179
180 @unittest.skipUnless(hasattr(posix, 'waitid'), "test needs posix.waitid()")
181 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
182 def test_waitid(self):
183 pid = os.fork()
184 if pid == 0:
185 os.chdir(os.path.split(sys.executable)[0])
186 posix.execve(sys.executable, [sys.executable, '-c', 'pass'], os.environ)
187 else:
188 res = posix.waitid(posix.P_PID, pid, posix.WEXITED)
189 self.assertEqual(pid, res.si_pid)
190
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200191 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
Gregory P. Smith163468a2017-05-29 10:03:41 -0700192 def test_register_at_fork(self):
193 with self.assertRaises(TypeError, msg="Positional args not allowed"):
194 os.register_at_fork(lambda: None)
195 with self.assertRaises(TypeError, msg="Args must be callable"):
196 os.register_at_fork(before=2)
197 with self.assertRaises(TypeError, msg="Args must be callable"):
198 os.register_at_fork(after_in_child="three")
199 with self.assertRaises(TypeError, msg="Args must be callable"):
200 os.register_at_fork(after_in_parent=b"Five")
201 with self.assertRaises(TypeError, msg="Args must not be None"):
202 os.register_at_fork(before=None)
203 with self.assertRaises(TypeError, msg="Args must not be None"):
204 os.register_at_fork(after_in_child=None)
205 with self.assertRaises(TypeError, msg="Args must not be None"):
206 os.register_at_fork(after_in_parent=None)
207 with self.assertRaises(TypeError, msg="Invalid arg was allowed"):
208 # Ensure a combination of valid and invalid is an error.
209 os.register_at_fork(before=None, after_in_parent=lambda: 3)
210 with self.assertRaises(TypeError, msg="Invalid arg was allowed"):
211 # Ensure a combination of valid and invalid is an error.
212 os.register_at_fork(before=lambda: None, after_in_child='')
213 # We test actual registrations in their own process so as not to
214 # pollute this one. There is no way to unregister for cleanup.
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200215 code = """if 1:
216 import os
217
218 r, w = os.pipe()
219 fin_r, fin_w = os.pipe()
220
Gregory P. Smith163468a2017-05-29 10:03:41 -0700221 os.register_at_fork(before=lambda: os.write(w, b'A'))
222 os.register_at_fork(after_in_parent=lambda: os.write(w, b'C'))
223 os.register_at_fork(after_in_child=lambda: os.write(w, b'E'))
224 os.register_at_fork(before=lambda: os.write(w, b'B'),
225 after_in_parent=lambda: os.write(w, b'D'),
226 after_in_child=lambda: os.write(w, b'F'))
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200227
228 pid = os.fork()
229 if pid == 0:
230 # At this point, after-forkers have already been executed
231 os.close(w)
232 # Wait for parent to tell us to exit
233 os.read(fin_r, 1)
234 os._exit(0)
235 else:
236 try:
237 os.close(w)
238 with open(r, "rb") as f:
239 data = f.read()
240 assert len(data) == 6, data
241 # Check before-fork callbacks
242 assert data[:2] == b'BA', data
243 # Check after-fork callbacks
244 assert sorted(data[2:]) == list(b'CDEF'), data
245 assert data.index(b'C') < data.index(b'D'), data
246 assert data.index(b'E') < data.index(b'F'), data
247 finally:
248 os.write(fin_w, b'!')
249 """
250 assert_python_ok('-c', code)
251
Ross Lagerwall7807c352011-03-17 20:20:30 +0200252 @unittest.skipUnless(hasattr(posix, 'lockf'), "test needs posix.lockf()")
253 def test_lockf(self):
254 fd = os.open(support.TESTFN, os.O_WRONLY | os.O_CREAT)
255 try:
256 os.write(fd, b'test')
257 os.lseek(fd, 0, os.SEEK_SET)
258 posix.lockf(fd, posix.F_LOCK, 4)
259 # section is locked
260 posix.lockf(fd, posix.F_ULOCK, 4)
261 finally:
262 os.close(fd)
263
264 @unittest.skipUnless(hasattr(posix, 'pread'), "test needs posix.pread()")
265 def test_pread(self):
266 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
267 try:
268 os.write(fd, b'test')
269 os.lseek(fd, 0, os.SEEK_SET)
270 self.assertEqual(b'es', posix.pread(fd, 2, 1))
Florent Xiclunae41f0de2011-11-11 19:39:25 +0100271 # the first pread() shouldn't disturb the file offset
Ross Lagerwall7807c352011-03-17 20:20:30 +0200272 self.assertEqual(b'te', posix.read(fd, 2))
273 finally:
274 os.close(fd)
275
276 @unittest.skipUnless(hasattr(posix, 'pwrite'), "test needs posix.pwrite()")
277 def test_pwrite(self):
278 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
279 try:
280 os.write(fd, b'test')
281 os.lseek(fd, 0, os.SEEK_SET)
282 posix.pwrite(fd, b'xx', 1)
283 self.assertEqual(b'txxt', posix.read(fd, 4))
284 finally:
285 os.close(fd)
286
287 @unittest.skipUnless(hasattr(posix, 'posix_fallocate'),
288 "test needs posix.posix_fallocate()")
289 def test_posix_fallocate(self):
290 fd = os.open(support.TESTFN, os.O_WRONLY | os.O_CREAT)
291 try:
292 posix.posix_fallocate(fd, 0, 10)
293 except OSError as inst:
294 # issue10812, ZFS doesn't appear to support posix_fallocate,
295 # so skip Solaris-based since they are likely to have ZFS.
296 if inst.errno != errno.EINVAL or not sys.platform.startswith("sunos"):
297 raise
298 finally:
299 os.close(fd)
300
301 @unittest.skipUnless(hasattr(posix, 'posix_fadvise'),
302 "test needs posix.posix_fadvise()")
303 def test_posix_fadvise(self):
304 fd = os.open(support.TESTFN, os.O_RDONLY)
305 try:
306 posix.posix_fadvise(fd, 0, 0, posix.POSIX_FADV_WILLNEED)
307 finally:
308 os.close(fd)
309
Larry Hastings9cf065c2012-06-22 16:30:09 -0700310 @unittest.skipUnless(os.utime in os.supports_fd, "test needs fd support in os.utime")
311 def test_utime_with_fd(self):
Ross Lagerwall7807c352011-03-17 20:20:30 +0200312 now = time.time()
313 fd = os.open(support.TESTFN, os.O_RDONLY)
314 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700315 posix.utime(fd)
316 posix.utime(fd, None)
317 self.assertRaises(TypeError, posix.utime, fd, (None, None))
318 self.assertRaises(TypeError, posix.utime, fd, (now, None))
319 self.assertRaises(TypeError, posix.utime, fd, (None, now))
320 posix.utime(fd, (int(now), int(now)))
321 posix.utime(fd, (now, now))
322 self.assertRaises(ValueError, posix.utime, fd, (now, now), ns=(now, now))
323 self.assertRaises(ValueError, posix.utime, fd, (now, 0), ns=(None, None))
324 self.assertRaises(ValueError, posix.utime, fd, (None, None), ns=(now, 0))
325 posix.utime(fd, (int(now), int((now - int(now)) * 1e9)))
326 posix.utime(fd, ns=(int(now), int((now - int(now)) * 1e9)))
327
Ross Lagerwall7807c352011-03-17 20:20:30 +0200328 finally:
329 os.close(fd)
330
Larry Hastings9cf065c2012-06-22 16:30:09 -0700331 @unittest.skipUnless(os.utime in os.supports_follow_symlinks, "test needs follow_symlinks support in os.utime")
332 def test_utime_nofollow_symlinks(self):
Ross Lagerwall7807c352011-03-17 20:20:30 +0200333 now = time.time()
Larry Hastings9cf065c2012-06-22 16:30:09 -0700334 posix.utime(support.TESTFN, None, follow_symlinks=False)
335 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None), follow_symlinks=False)
336 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None), follow_symlinks=False)
337 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now), follow_symlinks=False)
338 posix.utime(support.TESTFN, (int(now), int(now)), follow_symlinks=False)
339 posix.utime(support.TESTFN, (now, now), follow_symlinks=False)
340 posix.utime(support.TESTFN, follow_symlinks=False)
Ross Lagerwall7807c352011-03-17 20:20:30 +0200341
342 @unittest.skipUnless(hasattr(posix, 'writev'), "test needs posix.writev()")
343 def test_writev(self):
344 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
345 try:
Victor Stinner57ddf782014-01-08 15:21:28 +0100346 n = os.writev(fd, (b'test1', b'tt2', b't3'))
347 self.assertEqual(n, 10)
348
Ross Lagerwall7807c352011-03-17 20:20:30 +0200349 os.lseek(fd, 0, os.SEEK_SET)
350 self.assertEqual(b'test1tt2t3', posix.read(fd, 10))
Victor Stinner57ddf782014-01-08 15:21:28 +0100351
352 # Issue #20113: empty list of buffers should not crash
Victor Stinnercd5ca6a2014-01-08 16:01:31 +0100353 try:
354 size = posix.writev(fd, [])
355 except OSError:
356 # writev(fd, []) raises OSError(22, "Invalid argument")
357 # on OpenIndiana
358 pass
359 else:
360 self.assertEqual(size, 0)
Ross Lagerwall7807c352011-03-17 20:20:30 +0200361 finally:
362 os.close(fd)
363
364 @unittest.skipUnless(hasattr(posix, 'readv'), "test needs posix.readv()")
365 def test_readv(self):
366 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
367 try:
368 os.write(fd, b'test1tt2t3')
369 os.lseek(fd, 0, os.SEEK_SET)
370 buf = [bytearray(i) for i in [5, 3, 2]]
371 self.assertEqual(posix.readv(fd, buf), 10)
372 self.assertEqual([b'test1', b'tt2', b't3'], [bytes(i) for i in buf])
Victor Stinner57ddf782014-01-08 15:21:28 +0100373
374 # Issue #20113: empty list of buffers should not crash
Victor Stinnercd5ca6a2014-01-08 16:01:31 +0100375 try:
376 size = posix.readv(fd, [])
377 except OSError:
378 # readv(fd, []) raises OSError(22, "Invalid argument")
379 # on OpenIndiana
380 pass
381 else:
382 self.assertEqual(size, 0)
Ross Lagerwall7807c352011-03-17 20:20:30 +0200383 finally:
384 os.close(fd)
385
Serhiy Storchaka43767632013-11-03 21:31:38 +0200386 @unittest.skipUnless(hasattr(posix, 'dup'),
387 'test needs posix.dup()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000388 def test_dup(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200389 fp = open(support.TESTFN)
390 try:
391 fd = posix.dup(fp.fileno())
392 self.assertIsInstance(fd, int)
393 os.close(fd)
394 finally:
395 fp.close()
Neal Norwitze241ce82003-02-17 18:17:05 +0000396
Serhiy Storchaka43767632013-11-03 21:31:38 +0200397 @unittest.skipUnless(hasattr(posix, 'confstr'),
398 'test needs posix.confstr()')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000399 def test_confstr(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200400 self.assertRaises(ValueError, posix.confstr, "CS_garbage")
401 self.assertEqual(len(posix.confstr("CS_PATH")) > 0, True)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000402
Serhiy Storchaka43767632013-11-03 21:31:38 +0200403 @unittest.skipUnless(hasattr(posix, 'dup2'),
404 'test needs posix.dup2()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000405 def test_dup2(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200406 fp1 = open(support.TESTFN)
407 fp2 = open(support.TESTFN)
408 try:
409 posix.dup2(fp1.fileno(), fp2.fileno())
410 finally:
411 fp1.close()
412 fp2.close()
Neal Norwitze241ce82003-02-17 18:17:05 +0000413
Charles-François Natali1e045b12011-05-22 20:42:32 +0200414 @unittest.skipUnless(hasattr(os, 'O_CLOEXEC'), "needs os.O_CLOEXEC")
Charles-François Natali239bb962011-06-03 12:55:15 +0200415 @support.requires_linux_version(2, 6, 23)
Charles-François Natali1e045b12011-05-22 20:42:32 +0200416 def test_oscloexec(self):
417 fd = os.open(support.TESTFN, os.O_RDONLY|os.O_CLOEXEC)
418 self.addCleanup(os.close, fd)
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200419 self.assertFalse(os.get_inheritable(fd))
Charles-François Natali1e045b12011-05-22 20:42:32 +0200420
Serhiy Storchaka43767632013-11-03 21:31:38 +0200421 @unittest.skipUnless(hasattr(posix, 'O_EXLOCK'),
422 'test needs posix.O_EXLOCK')
Skip Montanaro98470002005-06-17 01:14:49 +0000423 def test_osexlock(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200424 fd = os.open(support.TESTFN,
425 os.O_WRONLY|os.O_EXLOCK|os.O_CREAT)
426 self.assertRaises(OSError, os.open, support.TESTFN,
427 os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
428 os.close(fd)
429
430 if hasattr(posix, "O_SHLOCK"):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000431 fd = os.open(support.TESTFN,
Serhiy Storchaka43767632013-11-03 21:31:38 +0200432 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000433 self.assertRaises(OSError, os.open, support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000434 os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
435 os.close(fd)
436
Serhiy Storchaka43767632013-11-03 21:31:38 +0200437 @unittest.skipUnless(hasattr(posix, 'O_SHLOCK'),
438 'test needs posix.O_SHLOCK')
Skip Montanaro98470002005-06-17 01:14:49 +0000439 def test_osshlock(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200440 fd1 = os.open(support.TESTFN,
441 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
442 fd2 = os.open(support.TESTFN,
443 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
444 os.close(fd2)
445 os.close(fd1)
446
447 if hasattr(posix, "O_EXLOCK"):
448 fd = os.open(support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000449 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
Serhiy Storchaka43767632013-11-03 21:31:38 +0200450 self.assertRaises(OSError, os.open, support.TESTFN,
451 os.O_RDONLY|os.O_EXLOCK|os.O_NONBLOCK)
452 os.close(fd)
Skip Montanaro98470002005-06-17 01:14:49 +0000453
Serhiy Storchaka43767632013-11-03 21:31:38 +0200454 @unittest.skipUnless(hasattr(posix, 'fstat'),
455 'test needs posix.fstat()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000456 def test_fstat(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200457 fp = open(support.TESTFN)
458 try:
459 self.assertTrue(posix.fstat(fp.fileno()))
460 self.assertTrue(posix.stat(fp.fileno()))
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200461
Serhiy Storchaka43767632013-11-03 21:31:38 +0200462 self.assertRaisesRegex(TypeError,
Brett Cannon3f9183b2016-08-26 14:44:48 -0700463 'should be string, bytes, os.PathLike or integer, not',
Serhiy Storchaka43767632013-11-03 21:31:38 +0200464 posix.stat, float(fp.fileno()))
465 finally:
466 fp.close()
Neal Norwitze241ce82003-02-17 18:17:05 +0000467
Serhiy Storchaka43767632013-11-03 21:31:38 +0200468 @unittest.skipUnless(hasattr(posix, 'stat'),
469 'test needs posix.stat()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000470 def test_stat(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200471 self.assertTrue(posix.stat(support.TESTFN))
472 self.assertTrue(posix.stat(os.fsencode(support.TESTFN)))
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200473
Serhiy Storchakad73c3182016-08-06 23:22:08 +0300474 self.assertWarnsRegex(DeprecationWarning,
Brett Cannon3f9183b2016-08-26 14:44:48 -0700475 'should be string, bytes, os.PathLike or integer, not',
Serhiy Storchakad73c3182016-08-06 23:22:08 +0300476 posix.stat, bytearray(os.fsencode(support.TESTFN)))
Serhiy Storchaka43767632013-11-03 21:31:38 +0200477 self.assertRaisesRegex(TypeError,
Brett Cannon3f9183b2016-08-26 14:44:48 -0700478 'should be string, bytes, os.PathLike or integer, not',
Serhiy Storchaka43767632013-11-03 21:31:38 +0200479 posix.stat, None)
480 self.assertRaisesRegex(TypeError,
Brett Cannon3f9183b2016-08-26 14:44:48 -0700481 'should be string, bytes, os.PathLike or integer, not',
Serhiy Storchaka43767632013-11-03 21:31:38 +0200482 posix.stat, list(support.TESTFN))
483 self.assertRaisesRegex(TypeError,
Brett Cannon3f9183b2016-08-26 14:44:48 -0700484 'should be string, bytes, os.PathLike or integer, not',
Serhiy Storchaka43767632013-11-03 21:31:38 +0200485 posix.stat, list(os.fsencode(support.TESTFN)))
Neal Norwitze241ce82003-02-17 18:17:05 +0000486
Benjamin Peterson052a02b2010-08-17 01:27:09 +0000487 @unittest.skipUnless(hasattr(posix, 'mkfifo'), "don't have mkfifo()")
Xavier de Gaye3a4e9892016-12-13 10:00:01 +0100488 @unittest.skipIf(android_not_root, "mkfifo not allowed, non root user")
Benjamin Peterson052a02b2010-08-17 01:27:09 +0000489 def test_mkfifo(self):
490 support.unlink(support.TESTFN)
491 posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR)
492 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
493
494 @unittest.skipUnless(hasattr(posix, 'mknod') and hasattr(stat, 'S_IFIFO'),
495 "don't have mknod()/S_IFIFO")
Xavier de Gaye3a4e9892016-12-13 10:00:01 +0100496 @unittest.skipIf(android_not_root, "mknod not allowed, non root user")
Benjamin Peterson052a02b2010-08-17 01:27:09 +0000497 def test_mknod(self):
498 # Test using mknod() to create a FIFO (the only use specified
499 # by POSIX).
500 support.unlink(support.TESTFN)
501 mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
502 try:
503 posix.mknod(support.TESTFN, mode, 0)
504 except OSError as e:
505 # Some old systems don't allow unprivileged users to use
506 # mknod(), or only support creating device nodes.
507 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
508 else:
509 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
510
Martin Panterbf19d162015-09-09 01:01:13 +0000511 # Keyword arguments are also supported
512 support.unlink(support.TESTFN)
513 try:
514 posix.mknod(path=support.TESTFN, mode=mode, device=0,
515 dir_fd=None)
516 except OSError as e:
517 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
518
Serhiy Storchaka16b2e4f2015-04-20 09:22:13 +0300519 @unittest.skipUnless(hasattr(posix, 'stat'), 'test needs posix.stat()')
520 @unittest.skipUnless(hasattr(posix, 'makedev'), 'test needs posix.makedev()')
521 def test_makedev(self):
522 st = posix.stat(support.TESTFN)
523 dev = st.st_dev
524 self.assertIsInstance(dev, int)
525 self.assertGreaterEqual(dev, 0)
526
527 major = posix.major(dev)
528 self.assertIsInstance(major, int)
529 self.assertGreaterEqual(major, 0)
530 self.assertEqual(posix.major(dev), major)
531 self.assertRaises(TypeError, posix.major, float(dev))
532 self.assertRaises(TypeError, posix.major)
533 self.assertRaises((ValueError, OverflowError), posix.major, -1)
534
535 minor = posix.minor(dev)
536 self.assertIsInstance(minor, int)
537 self.assertGreaterEqual(minor, 0)
538 self.assertEqual(posix.minor(dev), minor)
539 self.assertRaises(TypeError, posix.minor, float(dev))
540 self.assertRaises(TypeError, posix.minor)
541 self.assertRaises((ValueError, OverflowError), posix.minor, -1)
542
543 self.assertEqual(posix.makedev(major, minor), dev)
544 self.assertRaises(TypeError, posix.makedev, float(major), minor)
545 self.assertRaises(TypeError, posix.makedev, major, float(minor))
546 self.assertRaises(TypeError, posix.makedev, major)
547 self.assertRaises(TypeError, posix.makedev)
548
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200549 def _test_all_chown_common(self, chown_func, first_param, stat_func):
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000550 """Common code for chown, fchown and lchown tests."""
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200551 def check_stat(uid, gid):
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200552 if stat_func is not None:
553 stat = stat_func(first_param)
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200554 self.assertEqual(stat.st_uid, uid)
555 self.assertEqual(stat.st_gid, gid)
556 uid = os.getuid()
557 gid = os.getgid()
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200558 # test a successful chown call
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200559 chown_func(first_param, uid, gid)
560 check_stat(uid, gid)
561 chown_func(first_param, -1, gid)
562 check_stat(uid, gid)
563 chown_func(first_param, uid, -1)
564 check_stat(uid, gid)
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200565
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200566 if uid == 0:
567 # Try an amusingly large uid/gid to make sure we handle
568 # large unsigned values. (chown lets you use any
569 # uid/gid you like, even if they aren't defined.)
570 #
571 # This problem keeps coming up:
572 # http://bugs.python.org/issue1747858
573 # http://bugs.python.org/issue4591
574 # http://bugs.python.org/issue15301
575 # Hopefully the fix in 4591 fixes it for good!
576 #
577 # This part of the test only runs when run as root.
578 # Only scary people run their tests as root.
579
580 big_value = 2**31
581 chown_func(first_param, big_value, big_value)
582 check_stat(big_value, big_value)
583 chown_func(first_param, -1, -1)
584 check_stat(big_value, big_value)
585 chown_func(first_param, uid, gid)
586 check_stat(uid, gid)
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200587 elif platform.system() in ('HP-UX', 'SunOS'):
588 # HP-UX and Solaris can allow a non-root user to chown() to root
589 # (issue #5113)
590 raise unittest.SkipTest("Skipping because of non-standard chown() "
591 "behavior")
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000592 else:
593 # non-root cannot chown to root, raises OSError
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200594 self.assertRaises(OSError, chown_func, first_param, 0, 0)
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200595 check_stat(uid, gid)
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200596 self.assertRaises(OSError, chown_func, first_param, 0, -1)
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200597 check_stat(uid, gid)
Serhiy Storchakaa2964b32013-02-21 14:34:36 +0200598 if 0 not in os.getgroups():
Serhiy Storchakab3d62ce2013-02-20 19:48:22 +0200599 self.assertRaises(OSError, chown_func, first_param, -1, 0)
600 check_stat(uid, gid)
Serhiy Storchaka54db2fd2013-02-20 19:40:25 +0200601 # test illegal types
602 for t in str, float:
603 self.assertRaises(TypeError, chown_func, first_param, t(uid), gid)
604 check_stat(uid, gid)
605 self.assertRaises(TypeError, chown_func, first_param, uid, t(gid))
606 check_stat(uid, gid)
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000607
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000608 @unittest.skipUnless(hasattr(posix, 'chown'), "test needs os.chown()")
609 def test_chown(self):
610 # raise an OSError if the file does not exist
611 os.unlink(support.TESTFN)
612 self.assertRaises(OSError, posix.chown, support.TESTFN, -1, -1)
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000613
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000614 # re-create the file
Victor Stinnerbf816222011-06-30 23:25:47 +0200615 support.create_empty_file(support.TESTFN)
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200616 self._test_all_chown_common(posix.chown, support.TESTFN,
617 getattr(posix, 'stat', None))
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000618
619 @unittest.skipUnless(hasattr(posix, 'fchown'), "test needs os.fchown()")
620 def test_fchown(self):
621 os.unlink(support.TESTFN)
622
623 # re-create the file
624 test_file = open(support.TESTFN, 'w')
625 try:
626 fd = test_file.fileno()
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200627 self._test_all_chown_common(posix.fchown, fd,
628 getattr(posix, 'fstat', None))
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000629 finally:
630 test_file.close()
631
632 @unittest.skipUnless(hasattr(posix, 'lchown'), "test needs os.lchown()")
633 def test_lchown(self):
634 os.unlink(support.TESTFN)
635 # create a symlink
Ned Deily3eb67d52011-06-28 00:00:28 -0700636 os.symlink(_DUMMY_SYMLINK, support.TESTFN)
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200637 self._test_all_chown_common(posix.lchown, support.TESTFN,
638 getattr(posix, 'lstat', None))
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000639
Serhiy Storchaka43767632013-11-03 21:31:38 +0200640 @unittest.skipUnless(hasattr(posix, 'chdir'), 'test needs posix.chdir()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000641 def test_chdir(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200642 posix.chdir(os.curdir)
643 self.assertRaises(OSError, posix.chdir, support.TESTFN)
Neal Norwitze241ce82003-02-17 18:17:05 +0000644
Martin v. Löwisc9e1c7d2010-07-23 12:16:41 +0000645 def test_listdir(self):
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +0300646 self.assertIn(support.TESTFN, posix.listdir(os.curdir))
Martin v. Löwisc9e1c7d2010-07-23 12:16:41 +0000647
648 def test_listdir_default(self):
Larry Hastingsfdaea062012-06-25 04:42:23 -0700649 # When listdir is called without argument,
650 # it's the same as listdir(os.curdir).
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +0300651 self.assertIn(support.TESTFN, posix.listdir())
Neal Norwitze241ce82003-02-17 18:17:05 +0000652
Larry Hastingsfdaea062012-06-25 04:42:23 -0700653 def test_listdir_bytes(self):
654 # When listdir is called with a bytes object,
655 # the returned strings are of type bytes.
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +0300656 self.assertIn(os.fsencode(support.TESTFN), posix.listdir(b'.'))
657
658 def test_listdir_bytes_like(self):
659 for cls in bytearray, memoryview:
660 with self.assertWarns(DeprecationWarning):
661 names = posix.listdir(cls(b'.'))
662 self.assertIn(os.fsencode(support.TESTFN), names)
663 for name in names:
664 self.assertIs(type(name), bytes)
Larry Hastingsfdaea062012-06-25 04:42:23 -0700665
666 @unittest.skipUnless(posix.listdir in os.supports_fd,
667 "test needs fd support for posix.listdir()")
668 def test_listdir_fd(self):
Antoine Pitrou8250e232011-02-25 23:41:16 +0000669 f = posix.open(posix.getcwd(), posix.O_RDONLY)
Charles-François Natali7546ad32012-01-08 18:34:06 +0100670 self.addCleanup(posix.close, f)
Antoine Pitrou8250e232011-02-25 23:41:16 +0000671 self.assertEqual(
672 sorted(posix.listdir('.')),
Larry Hastings9cf065c2012-06-22 16:30:09 -0700673 sorted(posix.listdir(f))
Antoine Pitrou8250e232011-02-25 23:41:16 +0000674 )
Charles-François Natali7546ad32012-01-08 18:34:06 +0100675 # Check that the fd offset was reset (issue #13739)
Charles-François Natali7546ad32012-01-08 18:34:06 +0100676 self.assertEqual(
677 sorted(posix.listdir('.')),
Larry Hastings9cf065c2012-06-22 16:30:09 -0700678 sorted(posix.listdir(f))
Charles-François Natali7546ad32012-01-08 18:34:06 +0100679 )
Antoine Pitrou8250e232011-02-25 23:41:16 +0000680
Serhiy Storchaka43767632013-11-03 21:31:38 +0200681 @unittest.skipUnless(hasattr(posix, 'access'), 'test needs posix.access()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000682 def test_access(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200683 self.assertTrue(posix.access(support.TESTFN, os.R_OK))
Neal Norwitze241ce82003-02-17 18:17:05 +0000684
Serhiy Storchaka43767632013-11-03 21:31:38 +0200685 @unittest.skipUnless(hasattr(posix, 'umask'), 'test needs posix.umask()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000686 def test_umask(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200687 old_mask = posix.umask(0)
688 self.assertIsInstance(old_mask, int)
689 posix.umask(old_mask)
Neal Norwitze241ce82003-02-17 18:17:05 +0000690
Serhiy Storchaka43767632013-11-03 21:31:38 +0200691 @unittest.skipUnless(hasattr(posix, 'strerror'),
692 'test needs posix.strerror()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000693 def test_strerror(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200694 self.assertTrue(posix.strerror(0))
Neal Norwitze241ce82003-02-17 18:17:05 +0000695
Serhiy Storchaka43767632013-11-03 21:31:38 +0200696 @unittest.skipUnless(hasattr(posix, 'pipe'), 'test needs posix.pipe()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000697 def test_pipe(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200698 reader, writer = posix.pipe()
699 os.close(reader)
700 os.close(writer)
Neal Norwitze241ce82003-02-17 18:17:05 +0000701
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200702 @unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()")
Charles-François Natali239bb962011-06-03 12:55:15 +0200703 @support.requires_linux_version(2, 6, 27)
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200704 def test_pipe2(self):
705 self.assertRaises(TypeError, os.pipe2, 'DEADBEEF')
706 self.assertRaises(TypeError, os.pipe2, 0, 0)
707
Charles-François Natali368f34b2011-06-06 19:49:47 +0200708 # try calling with flags = 0, like os.pipe()
709 r, w = os.pipe2(0)
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200710 os.close(r)
711 os.close(w)
712
713 # test flags
714 r, w = os.pipe2(os.O_CLOEXEC|os.O_NONBLOCK)
715 self.addCleanup(os.close, r)
716 self.addCleanup(os.close, w)
Victor Stinnerbff989e2013-08-28 12:25:40 +0200717 self.assertFalse(os.get_inheritable(r))
718 self.assertFalse(os.get_inheritable(w))
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200719 self.assertFalse(os.get_blocking(r))
720 self.assertFalse(os.get_blocking(w))
Charles-François Natalidaafdd52011-05-29 20:07:40 +0200721 # try reading from an empty pipe: this should fail, not block
722 self.assertRaises(OSError, os.read, r, 1)
723 # try a write big enough to fill-up the pipe: this should either
724 # fail or perform a partial write, not block
725 try:
726 os.write(w, b'x' * support.PIPE_MAX_SIZE)
727 except OSError:
728 pass
729
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200730 @support.cpython_only
731 @unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()")
732 @support.requires_linux_version(2, 6, 27)
733 def test_pipe2_c_limits(self):
Serhiy Storchaka78980432013-01-15 01:12:17 +0200734 # Issue 15989
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200735 import _testcapi
Serhiy Storchaka78980432013-01-15 01:12:17 +0200736 self.assertRaises(OverflowError, os.pipe2, _testcapi.INT_MAX + 1)
737 self.assertRaises(OverflowError, os.pipe2, _testcapi.UINT_MAX + 1)
738
Serhiy Storchaka43767632013-11-03 21:31:38 +0200739 @unittest.skipUnless(hasattr(posix, 'utime'), 'test needs posix.utime()')
Neal Norwitze241ce82003-02-17 18:17:05 +0000740 def test_utime(self):
Serhiy Storchaka43767632013-11-03 21:31:38 +0200741 now = time.time()
742 posix.utime(support.TESTFN, None)
743 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None))
744 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None))
745 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now))
746 posix.utime(support.TESTFN, (int(now), int(now)))
747 posix.utime(support.TESTFN, (now, now))
Neal Norwitze241ce82003-02-17 18:17:05 +0000748
Larry Hastings9cf065c2012-06-22 16:30:09 -0700749 def _test_chflags_regular_file(self, chflags_func, target_file, **kwargs):
Ned Deily3eb67d52011-06-28 00:00:28 -0700750 st = os.stat(target_file)
751 self.assertTrue(hasattr(st, 'st_flags'))
Trent Nelson75959cf2012-08-21 23:59:31 +0000752
753 # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
754 flags = st.st_flags | stat.UF_IMMUTABLE
755 try:
756 chflags_func(target_file, flags, **kwargs)
757 except OSError as err:
758 if err.errno != errno.EOPNOTSUPP:
759 raise
760 msg = 'chflag UF_IMMUTABLE not supported by underlying fs'
761 self.skipTest(msg)
762
Ned Deily3eb67d52011-06-28 00:00:28 -0700763 try:
764 new_st = os.stat(target_file)
765 self.assertEqual(st.st_flags | stat.UF_IMMUTABLE, new_st.st_flags)
766 try:
767 fd = open(target_file, 'w+')
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200768 except OSError as e:
Ned Deily3eb67d52011-06-28 00:00:28 -0700769 self.assertEqual(e.errno, errno.EPERM)
770 finally:
771 posix.chflags(target_file, st.st_flags)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000772
Ned Deily3eb67d52011-06-28 00:00:28 -0700773 @unittest.skipUnless(hasattr(posix, 'chflags'), 'test needs os.chflags()')
774 def test_chflags(self):
775 self._test_chflags_regular_file(posix.chflags, support.TESTFN)
776
777 @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
778 def test_lchflags_regular_file(self):
779 self._test_chflags_regular_file(posix.lchflags, support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700780 self._test_chflags_regular_file(posix.chflags, support.TESTFN, follow_symlinks=False)
Ned Deily3eb67d52011-06-28 00:00:28 -0700781
782 @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
783 def test_lchflags_symlink(self):
784 testfn_st = os.stat(support.TESTFN)
785
786 self.assertTrue(hasattr(testfn_st, 'st_flags'))
787
788 os.symlink(support.TESTFN, _DUMMY_SYMLINK)
789 self.teardown_files.append(_DUMMY_SYMLINK)
790 dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
791
Larry Hastings9cf065c2012-06-22 16:30:09 -0700792 def chflags_nofollow(path, flags):
793 return posix.chflags(path, flags, follow_symlinks=False)
Ned Deily3eb67d52011-06-28 00:00:28 -0700794
Larry Hastings9cf065c2012-06-22 16:30:09 -0700795 for fn in (posix.lchflags, chflags_nofollow):
Trent Nelson75959cf2012-08-21 23:59:31 +0000796 # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
797 flags = dummy_symlink_st.st_flags | stat.UF_IMMUTABLE
798 try:
799 fn(_DUMMY_SYMLINK, flags)
800 except OSError as err:
801 if err.errno != errno.EOPNOTSUPP:
802 raise
803 msg = 'chflag UF_IMMUTABLE not supported by underlying fs'
804 self.skipTest(msg)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700805 try:
806 new_testfn_st = os.stat(support.TESTFN)
807 new_dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
808
809 self.assertEqual(testfn_st.st_flags, new_testfn_st.st_flags)
810 self.assertEqual(dummy_symlink_st.st_flags | stat.UF_IMMUTABLE,
811 new_dummy_symlink_st.st_flags)
812 finally:
813 fn(_DUMMY_SYMLINK, dummy_symlink_st.st_flags)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000814
Guido van Rossum98297ee2007-11-06 21:34:58 +0000815 def test_environ(self):
Victor Stinner17b490d2010-05-06 22:19:30 +0000816 if os.name == "nt":
817 item_type = str
818 else:
819 item_type = bytes
Guido van Rossum98297ee2007-11-06 21:34:58 +0000820 for k, v in posix.environ.items():
Victor Stinner17b490d2010-05-06 22:19:30 +0000821 self.assertEqual(type(k), item_type)
822 self.assertEqual(type(v), item_type)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000823
Serhiy Storchaka77703942017-06-25 07:33:01 +0300824 @unittest.skipUnless(hasattr(os, "putenv"), "requires os.putenv()")
825 def test_putenv(self):
826 with self.assertRaises(ValueError):
827 os.putenv('FRUIT\0VEGETABLE', 'cabbage')
828 with self.assertRaises(ValueError):
829 os.putenv(b'FRUIT\0VEGETABLE', b'cabbage')
830 with self.assertRaises(ValueError):
831 os.putenv('FRUIT', 'orange\0VEGETABLE=cabbage')
832 with self.assertRaises(ValueError):
833 os.putenv(b'FRUIT', b'orange\0VEGETABLE=cabbage')
834 with self.assertRaises(ValueError):
835 os.putenv('FRUIT=ORANGE', 'lemon')
836 with self.assertRaises(ValueError):
837 os.putenv(b'FRUIT=ORANGE', b'lemon')
838
Serhiy Storchaka43767632013-11-03 21:31:38 +0200839 @unittest.skipUnless(hasattr(posix, 'getcwd'), 'test needs posix.getcwd()')
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000840 def test_getcwd_long_pathnames(self):
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500841 dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
842 curdir = os.getcwd()
843 base_path = os.path.abspath(support.TESTFN) + '.getcwd'
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000844
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500845 try:
846 os.mkdir(base_path)
847 os.chdir(base_path)
848 except:
849 # Just returning nothing instead of the SkipTest exception, because
850 # the test results in Error in that case. Is that ok?
851 # raise unittest.SkipTest("cannot create directory for testing")
852 return
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000853
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500854 def _create_and_do_getcwd(dirname, current_path_length = 0):
855 try:
856 os.mkdir(dirname)
857 except:
858 raise unittest.SkipTest("mkdir cannot create directory sufficiently deep for getcwd test")
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000859
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500860 os.chdir(dirname)
861 try:
862 os.getcwd()
863 if current_path_length < 1027:
864 _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1)
865 finally:
866 os.chdir('..')
867 os.rmdir(dirname)
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000868
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500869 _create_and_do_getcwd(dirname)
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000870
Benjamin Peterson3a7dffa2013-08-23 21:01:48 -0500871 finally:
872 os.chdir(curdir)
873 support.rmtree(base_path)
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000874
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200875 @unittest.skipUnless(hasattr(posix, 'getgrouplist'), "test needs posix.getgrouplist()")
876 @unittest.skipUnless(hasattr(pwd, 'getpwuid'), "test needs pwd.getpwuid()")
877 @unittest.skipUnless(hasattr(os, 'getuid'), "test needs os.getuid()")
878 def test_getgrouplist(self):
Ross Lagerwalla0b315f2012-12-13 15:20:26 +0000879 user = pwd.getpwuid(os.getuid())[0]
880 group = pwd.getpwuid(os.getuid())[3]
881 self.assertIn(group, posix.getgrouplist(user, group))
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200882
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +0200883
Antoine Pitrou318b8f32011-01-12 18:45:27 +0000884 @unittest.skipUnless(hasattr(os, 'getegid'), "test needs os.getegid()")
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000885 def test_getgroups(self):
Jesus Cea61f32cb2014-06-28 18:39:35 +0200886 with os.popen('id -G 2>/dev/null') as idg:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000887 groups = idg.read().strip()
Charles-François Natalie8a255a2012-05-02 20:01:38 +0200888 ret = idg.close()
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000889
Xavier de Gaye24c3b492016-10-19 11:00:26 +0200890 try:
891 idg_groups = set(int(g) for g in groups.split())
892 except ValueError:
893 idg_groups = set()
894 if ret is not None or not idg_groups:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000895 raise unittest.SkipTest("need working 'id -G'")
896
Ned Deily028915e2013-02-02 15:08:52 -0800897 # Issues 16698: OS X ABIs prior to 10.6 have limits on getgroups()
898 if sys.platform == 'darwin':
899 import sysconfig
900 dt = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') or '10.0'
Ned Deily04cdfa12014-06-25 13:36:14 -0700901 if tuple(int(n) for n in dt.split('.')[0:2]) < (10, 6):
Ned Deily028915e2013-02-02 15:08:52 -0800902 raise unittest.SkipTest("getgroups(2) is broken prior to 10.6")
903
Ronald Oussoren7fb6f512010-08-01 19:18:13 +0000904 # 'id -G' and 'os.getgroups()' should return the same
Xavier de Gaye24c3b492016-10-19 11:00:26 +0200905 # groups, ignoring order, duplicates, and the effective gid.
906 # #10822/#26944 - It is implementation defined whether
907 # posix.getgroups() includes the effective gid.
908 symdiff = idg_groups.symmetric_difference(posix.getgroups())
909 self.assertTrue(not symdiff or symdiff == {posix.getegid()})
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000910
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000911 # tests for the posix *at functions follow
912
Larry Hastings9cf065c2012-06-22 16:30:09 -0700913 @unittest.skipUnless(os.access in os.supports_dir_fd, "test needs dir_fd support for os.access()")
914 def test_access_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000915 f = posix.open(posix.getcwd(), posix.O_RDONLY)
916 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700917 self.assertTrue(posix.access(support.TESTFN, os.R_OK, dir_fd=f))
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000918 finally:
919 posix.close(f)
920
Larry Hastings9cf065c2012-06-22 16:30:09 -0700921 @unittest.skipUnless(os.chmod in os.supports_dir_fd, "test needs dir_fd support in os.chmod()")
922 def test_chmod_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000923 os.chmod(support.TESTFN, stat.S_IRUSR)
924
925 f = posix.open(posix.getcwd(), posix.O_RDONLY)
926 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700927 posix.chmod(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000928
929 s = posix.stat(support.TESTFN)
930 self.assertEqual(s[0] & stat.S_IRWXU, stat.S_IRUSR | stat.S_IWUSR)
931 finally:
932 posix.close(f)
933
Larry Hastings9cf065c2012-06-22 16:30:09 -0700934 @unittest.skipUnless(os.chown in os.supports_dir_fd, "test needs dir_fd support in os.chown()")
935 def test_chown_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000936 support.unlink(support.TESTFN)
Victor Stinnerbf816222011-06-30 23:25:47 +0200937 support.create_empty_file(support.TESTFN)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000938
939 f = posix.open(posix.getcwd(), posix.O_RDONLY)
940 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700941 posix.chown(support.TESTFN, os.getuid(), os.getgid(), dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000942 finally:
943 posix.close(f)
944
Larry Hastings9cf065c2012-06-22 16:30:09 -0700945 @unittest.skipUnless(os.stat in os.supports_dir_fd, "test needs dir_fd support in os.stat()")
946 def test_stat_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000947 support.unlink(support.TESTFN)
948 with open(support.TESTFN, 'w') as outfile:
949 outfile.write("testline\n")
950
951 f = posix.open(posix.getcwd(), posix.O_RDONLY)
952 try:
953 s1 = posix.stat(support.TESTFN)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700954 s2 = posix.stat(support.TESTFN, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000955 self.assertEqual(s1, s2)
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200956 s2 = posix.stat(support.TESTFN, dir_fd=None)
957 self.assertEqual(s1, s2)
Serhiy Storchaka7155b882016-04-08 08:48:20 +0300958 self.assertRaisesRegex(TypeError, 'should be integer or None, not',
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200959 posix.stat, support.TESTFN, dir_fd=posix.getcwd())
Serhiy Storchaka7155b882016-04-08 08:48:20 +0300960 self.assertRaisesRegex(TypeError, 'should be integer or None, not',
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200961 posix.stat, support.TESTFN, dir_fd=float(f))
962 self.assertRaises(OverflowError,
963 posix.stat, support.TESTFN, dir_fd=10**20)
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000964 finally:
965 posix.close(f)
966
Larry Hastings9cf065c2012-06-22 16:30:09 -0700967 @unittest.skipUnless(os.utime in os.supports_dir_fd, "test needs dir_fd support in os.utime()")
968 def test_utime_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000969 f = posix.open(posix.getcwd(), posix.O_RDONLY)
970 try:
971 now = time.time()
Larry Hastings9cf065c2012-06-22 16:30:09 -0700972 posix.utime(support.TESTFN, None, dir_fd=f)
973 posix.utime(support.TESTFN, dir_fd=f)
974 self.assertRaises(TypeError, posix.utime, support.TESTFN, now, dir_fd=f)
975 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None), dir_fd=f)
976 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None), dir_fd=f)
977 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now), dir_fd=f)
978 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, "x"), dir_fd=f)
979 posix.utime(support.TESTFN, (int(now), int(now)), dir_fd=f)
980 posix.utime(support.TESTFN, (now, now), dir_fd=f)
981 posix.utime(support.TESTFN,
982 (int(now), int((now - int(now)) * 1e9)), dir_fd=f)
983 posix.utime(support.TESTFN, dir_fd=f,
984 times=(int(now), int((now - int(now)) * 1e9)))
985
Larry Hastings90867a52012-06-22 17:01:41 -0700986 # try dir_fd and follow_symlinks together
Larry Hastings9cf065c2012-06-22 16:30:09 -0700987 if os.utime in os.supports_follow_symlinks:
Larry Hastings90867a52012-06-22 17:01:41 -0700988 try:
989 posix.utime(support.TESTFN, follow_symlinks=False, dir_fd=f)
Georg Brandl969288e2012-06-26 09:25:44 +0200990 except ValueError:
Larry Hastings90867a52012-06-22 17:01:41 -0700991 # whoops! using both together not supported on this platform.
992 pass
Larry Hastings9cf065c2012-06-22 16:30:09 -0700993
Antoine Pitrouf65132d2011-02-25 23:25:17 +0000994 finally:
995 posix.close(f)
996
Larry Hastings9cf065c2012-06-22 16:30:09 -0700997 @unittest.skipUnless(os.link in os.supports_dir_fd, "test needs dir_fd support in os.link()")
Xavier de Gaye3a4e9892016-12-13 10:00:01 +0100998 @unittest.skipIf(android_not_root, "hard link not allowed, non root user")
Larry Hastings9cf065c2012-06-22 16:30:09 -0700999 def test_link_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001000 f = posix.open(posix.getcwd(), posix.O_RDONLY)
1001 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001002 posix.link(support.TESTFN, support.TESTFN + 'link', src_dir_fd=f, dst_dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001003 # should have same inodes
1004 self.assertEqual(posix.stat(support.TESTFN)[1],
1005 posix.stat(support.TESTFN + 'link')[1])
1006 finally:
1007 posix.close(f)
1008 support.unlink(support.TESTFN + 'link')
1009
Larry Hastings9cf065c2012-06-22 16:30:09 -07001010 @unittest.skipUnless(os.mkdir in os.supports_dir_fd, "test needs dir_fd support in os.mkdir()")
1011 def test_mkdir_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001012 f = posix.open(posix.getcwd(), posix.O_RDONLY)
1013 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001014 posix.mkdir(support.TESTFN + 'dir', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001015 posix.stat(support.TESTFN + 'dir') # should not raise exception
1016 finally:
1017 posix.close(f)
1018 support.rmtree(support.TESTFN + 'dir')
1019
Larry Hastings9cf065c2012-06-22 16:30:09 -07001020 @unittest.skipUnless((os.mknod in os.supports_dir_fd) and hasattr(stat, 'S_IFIFO'),
1021 "test requires both stat.S_IFIFO and dir_fd support for os.mknod()")
Xavier de Gaye3a4e9892016-12-13 10:00:01 +01001022 @unittest.skipIf(android_not_root, "mknod not allowed, non root user")
Larry Hastings9cf065c2012-06-22 16:30:09 -07001023 def test_mknod_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001024 # Test using mknodat() to create a FIFO (the only use specified
1025 # by POSIX).
1026 support.unlink(support.TESTFN)
1027 mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
1028 f = posix.open(posix.getcwd(), posix.O_RDONLY)
1029 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001030 posix.mknod(support.TESTFN, mode, 0, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001031 except OSError as e:
1032 # Some old systems don't allow unprivileged users to use
1033 # mknod(), or only support creating device nodes.
1034 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
1035 else:
1036 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
1037 finally:
1038 posix.close(f)
1039
Larry Hastings9cf065c2012-06-22 16:30:09 -07001040 @unittest.skipUnless(os.open in os.supports_dir_fd, "test needs dir_fd support in os.open()")
1041 def test_open_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001042 support.unlink(support.TESTFN)
1043 with open(support.TESTFN, 'w') as outfile:
1044 outfile.write("testline\n")
1045 a = posix.open(posix.getcwd(), posix.O_RDONLY)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001046 b = posix.open(support.TESTFN, posix.O_RDONLY, dir_fd=a)
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001047 try:
1048 res = posix.read(b, 9).decode(encoding="utf-8")
1049 self.assertEqual("testline\n", res)
1050 finally:
1051 posix.close(a)
1052 posix.close(b)
1053
Larry Hastings9cf065c2012-06-22 16:30:09 -07001054 @unittest.skipUnless(os.readlink in os.supports_dir_fd, "test needs dir_fd support in os.readlink()")
1055 def test_readlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001056 os.symlink(support.TESTFN, support.TESTFN + 'link')
1057 f = posix.open(posix.getcwd(), posix.O_RDONLY)
1058 try:
1059 self.assertEqual(posix.readlink(support.TESTFN + 'link'),
Larry Hastings9cf065c2012-06-22 16:30:09 -07001060 posix.readlink(support.TESTFN + 'link', dir_fd=f))
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001061 finally:
1062 support.unlink(support.TESTFN + 'link')
1063 posix.close(f)
1064
Larry Hastings9cf065c2012-06-22 16:30:09 -07001065 @unittest.skipUnless(os.rename in os.supports_dir_fd, "test needs dir_fd support in os.rename()")
1066 def test_rename_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001067 support.unlink(support.TESTFN)
Victor Stinnerbf816222011-06-30 23:25:47 +02001068 support.create_empty_file(support.TESTFN + 'ren')
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001069 f = posix.open(posix.getcwd(), posix.O_RDONLY)
1070 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001071 posix.rename(support.TESTFN + 'ren', support.TESTFN, src_dir_fd=f, dst_dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001072 except:
1073 posix.rename(support.TESTFN + 'ren', support.TESTFN)
1074 raise
1075 else:
Andrew Svetlov5b898402012-12-18 21:26:36 +02001076 posix.stat(support.TESTFN) # should not raise exception
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001077 finally:
1078 posix.close(f)
1079
Larry Hastings9cf065c2012-06-22 16:30:09 -07001080 @unittest.skipUnless(os.symlink in os.supports_dir_fd, "test needs dir_fd support in os.symlink()")
1081 def test_symlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001082 f = posix.open(posix.getcwd(), posix.O_RDONLY)
1083 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001084 posix.symlink(support.TESTFN, support.TESTFN + 'link', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001085 self.assertEqual(posix.readlink(support.TESTFN + 'link'), support.TESTFN)
1086 finally:
1087 posix.close(f)
1088 support.unlink(support.TESTFN + 'link')
1089
Larry Hastings9cf065c2012-06-22 16:30:09 -07001090 @unittest.skipUnless(os.unlink in os.supports_dir_fd, "test needs dir_fd support in os.unlink()")
1091 def test_unlink_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001092 f = posix.open(posix.getcwd(), posix.O_RDONLY)
Victor Stinnerbf816222011-06-30 23:25:47 +02001093 support.create_empty_file(support.TESTFN + 'del')
Andrew Svetlov5b898402012-12-18 21:26:36 +02001094 posix.stat(support.TESTFN + 'del') # should not raise exception
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001095 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001096 posix.unlink(support.TESTFN + 'del', dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001097 except:
1098 support.unlink(support.TESTFN + 'del')
1099 raise
1100 else:
1101 self.assertRaises(OSError, posix.stat, support.TESTFN + 'link')
1102 finally:
1103 posix.close(f)
1104
Larry Hastings9cf065c2012-06-22 16:30:09 -07001105 @unittest.skipUnless(os.mkfifo in os.supports_dir_fd, "test needs dir_fd support in os.mkfifo()")
Xavier de Gaye3a4e9892016-12-13 10:00:01 +01001106 @unittest.skipIf(android_not_root, "mkfifo not allowed, non root user")
Larry Hastings9cf065c2012-06-22 16:30:09 -07001107 def test_mkfifo_dir_fd(self):
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001108 support.unlink(support.TESTFN)
1109 f = posix.open(posix.getcwd(), posix.O_RDONLY)
1110 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -07001111 posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)
Antoine Pitrouf65132d2011-02-25 23:25:17 +00001112 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
1113 finally:
1114 posix.close(f)
1115
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001116 requires_sched_h = unittest.skipUnless(hasattr(posix, 'sched_yield'),
1117 "don't have scheduling support")
Antoine Pitrou84869872012-08-04 16:16:35 +02001118 requires_sched_affinity = unittest.skipUnless(hasattr(posix, 'sched_setaffinity'),
Benjamin Peterson50ba2712011-08-02 22:15:40 -05001119 "don't have sched affinity support")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001120
1121 @requires_sched_h
1122 def test_sched_yield(self):
1123 # This has no error conditions (at least on Linux).
1124 posix.sched_yield()
1125
1126 @requires_sched_h
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02001127 @unittest.skipUnless(hasattr(posix, 'sched_get_priority_max'),
1128 "requires sched_get_priority_max()")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001129 def test_sched_priority(self):
1130 # Round-robin usually has interesting priorities.
1131 pol = posix.SCHED_RR
1132 lo = posix.sched_get_priority_min(pol)
1133 hi = posix.sched_get_priority_max(pol)
1134 self.assertIsInstance(lo, int)
1135 self.assertIsInstance(hi, int)
1136 self.assertGreaterEqual(hi, lo)
Benjamin Peterson539b6c42011-08-02 22:09:37 -05001137 # OSX evidently just returns 15 without checking the argument.
1138 if sys.platform != "darwin":
Benjamin Petersonc1581582011-08-02 22:10:55 -05001139 self.assertRaises(OSError, posix.sched_get_priority_min, -23)
1140 self.assertRaises(OSError, posix.sched_get_priority_max, -23)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001141
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05001142 @unittest.skipUnless(hasattr(posix, 'sched_setscheduler'), "can't change scheduler")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001143 def test_get_and_set_scheduler_and_param(self):
1144 possible_schedulers = [sched for name, sched in posix.__dict__.items()
1145 if name.startswith("SCHED_")]
1146 mine = posix.sched_getscheduler(0)
1147 self.assertIn(mine, possible_schedulers)
1148 try:
Jesus Ceaceb5d162011-09-10 01:16:55 +02001149 parent = posix.sched_getscheduler(os.getppid())
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001150 except OSError as e:
Jesus Ceaceb5d162011-09-10 01:16:55 +02001151 if e.errno != errno.EPERM:
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001152 raise
1153 else:
Jesus Ceaceb5d162011-09-10 01:16:55 +02001154 self.assertIn(parent, possible_schedulers)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001155 self.assertRaises(OSError, posix.sched_getscheduler, -1)
1156 self.assertRaises(OSError, posix.sched_getparam, -1)
1157 param = posix.sched_getparam(0)
1158 self.assertIsInstance(param.sched_priority, int)
Charles-François Natali7b911cb2011-08-21 12:41:43 +02001159
Charles-François Natalib402a5c2013-01-13 14:13:25 +01001160 # POSIX states that calling sched_setparam() or sched_setscheduler() on
1161 # a process with a scheduling policy other than SCHED_FIFO or SCHED_RR
1162 # is implementation-defined: NetBSD and FreeBSD can return EINVAL.
1163 if not sys.platform.startswith(('freebsd', 'netbsd')):
1164 try:
1165 posix.sched_setscheduler(0, mine, param)
1166 posix.sched_setparam(0, param)
1167 except OSError as e:
1168 if e.errno != errno.EPERM:
1169 raise
Charles-François Natali7b911cb2011-08-21 12:41:43 +02001170 self.assertRaises(OSError, posix.sched_setparam, -1, param)
1171
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001172 self.assertRaises(OSError, posix.sched_setscheduler, -1, mine, param)
1173 self.assertRaises(TypeError, posix.sched_setscheduler, 0, mine, None)
1174 self.assertRaises(TypeError, posix.sched_setparam, 0, 43)
1175 param = posix.sched_param(None)
1176 self.assertRaises(TypeError, posix.sched_setparam, 0, param)
1177 large = 214748364700
1178 param = posix.sched_param(large)
1179 self.assertRaises(OverflowError, posix.sched_setparam, 0, param)
1180 param = posix.sched_param(sched_priority=-large)
1181 self.assertRaises(OverflowError, posix.sched_setparam, 0, param)
1182
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05001183 @unittest.skipUnless(hasattr(posix, "sched_rr_get_interval"), "no function")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001184 def test_sched_rr_get_interval(self):
Benjamin Peterson43234ab2011-08-02 22:19:14 -05001185 try:
1186 interval = posix.sched_rr_get_interval(0)
1187 except OSError as e:
1188 # This likely means that sched_rr_get_interval is only valid for
1189 # processes with the SCHED_RR scheduler in effect.
1190 if e.errno != errno.EINVAL:
1191 raise
1192 self.skipTest("only works on SCHED_RR processes")
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001193 self.assertIsInstance(interval, float)
1194 # Reasonable constraints, I think.
1195 self.assertGreaterEqual(interval, 0.)
1196 self.assertLess(interval, 1.)
1197
Benjamin Peterson2740af82011-08-02 17:41:34 -05001198 @requires_sched_affinity
Antoine Pitrou84869872012-08-04 16:16:35 +02001199 def test_sched_getaffinity(self):
1200 mask = posix.sched_getaffinity(0)
1201 self.assertIsInstance(mask, set)
1202 self.assertGreaterEqual(len(mask), 1)
1203 self.assertRaises(OSError, posix.sched_getaffinity, -1)
1204 for cpu in mask:
1205 self.assertIsInstance(cpu, int)
1206 self.assertGreaterEqual(cpu, 0)
1207 self.assertLess(cpu, 1 << 32)
1208
1209 @requires_sched_affinity
1210 def test_sched_setaffinity(self):
1211 mask = posix.sched_getaffinity(0)
1212 if len(mask) > 1:
1213 # Empty masks are forbidden
1214 mask.pop()
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001215 posix.sched_setaffinity(0, mask)
Antoine Pitrou84869872012-08-04 16:16:35 +02001216 self.assertEqual(posix.sched_getaffinity(0), mask)
1217 self.assertRaises(OSError, posix.sched_setaffinity, 0, [])
1218 self.assertRaises(ValueError, posix.sched_setaffinity, 0, [-10])
1219 self.assertRaises(OverflowError, posix.sched_setaffinity, 0, [1<<128])
Benjamin Peterson94b580d2011-08-02 17:30:04 -05001220 self.assertRaises(OSError, posix.sched_setaffinity, -1, mask)
1221
Victor Stinner8b905bd2011-10-25 13:34:04 +02001222 def test_rtld_constants(self):
1223 # check presence of major RTLD_* constants
1224 posix.RTLD_LAZY
1225 posix.RTLD_NOW
1226 posix.RTLD_GLOBAL
1227 posix.RTLD_LOCAL
1228
Jesus Cea60c13dd2012-06-23 02:58:14 +02001229 @unittest.skipUnless(hasattr(os, 'SEEK_HOLE'),
1230 "test needs an OS that reports file holes")
Hynek Schlawackf841e422012-06-24 09:51:46 +02001231 def test_fs_holes(self):
Jesus Cea94363612012-06-22 18:32:07 +02001232 # Even if the filesystem doesn't report holes,
1233 # if the OS supports it the SEEK_* constants
1234 # will be defined and will have a consistent
1235 # behaviour:
1236 # os.SEEK_DATA = current position
1237 # os.SEEK_HOLE = end of file position
Hynek Schlawackf841e422012-06-24 09:51:46 +02001238 with open(support.TESTFN, 'r+b') as fp:
Jesus Cea94363612012-06-22 18:32:07 +02001239 fp.write(b"hello")
1240 fp.flush()
1241 size = fp.tell()
1242 fno = fp.fileno()
Jesus Cead46f7d22012-07-07 14:56:04 +02001243 try :
1244 for i in range(size):
1245 self.assertEqual(i, os.lseek(fno, i, os.SEEK_DATA))
1246 self.assertLessEqual(size, os.lseek(fno, i, os.SEEK_HOLE))
1247 self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_DATA)
1248 self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_HOLE)
1249 except OSError :
1250 # Some OSs claim to support SEEK_HOLE/SEEK_DATA
1251 # but it is not true.
1252 # For instance:
1253 # http://lists.freebsd.org/pipermail/freebsd-amd64/2012-January/014332.html
1254 raise unittest.SkipTest("OSError raised!")
Jesus Cea94363612012-06-22 18:32:07 +02001255
Larry Hastingsb0827312014-02-09 22:05:19 -08001256 def test_path_error2(self):
1257 """
1258 Test functions that call path_error2(), providing two filenames in their exceptions.
1259 """
Victor Stinner047b7ae2014-10-05 17:37:41 +02001260 for name in ("rename", "replace", "link"):
Larry Hastingsb0827312014-02-09 22:05:19 -08001261 function = getattr(os, name, None)
Victor Stinnerbed04a72014-10-05 17:37:59 +02001262 if function is None:
1263 continue
Larry Hastingsb0827312014-02-09 22:05:19 -08001264
Victor Stinnerbed04a72014-10-05 17:37:59 +02001265 for dst in ("noodly2", support.TESTFN):
1266 try:
1267 function('doesnotexistfilename', dst)
1268 except OSError as e:
1269 self.assertIn("'doesnotexistfilename' -> '{}'".format(dst), str(e))
1270 break
1271 else:
1272 self.fail("No valid path_error2() test for os." + name)
Larry Hastingsb0827312014-02-09 22:05:19 -08001273
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001274 def test_path_with_null_character(self):
1275 fn = support.TESTFN
1276 fn_with_NUL = fn + '\0'
1277 self.addCleanup(support.unlink, fn)
1278 support.unlink(fn)
1279 fd = None
1280 try:
Serhiy Storchaka7e9d1d12015-04-20 10:12:28 +03001281 with self.assertRaises(ValueError):
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001282 fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # raises
1283 finally:
1284 if fd is not None:
1285 os.close(fd)
1286 self.assertFalse(os.path.exists(fn))
Serhiy Storchaka7e9d1d12015-04-20 10:12:28 +03001287 self.assertRaises(ValueError, os.mkdir, fn_with_NUL)
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001288 self.assertFalse(os.path.exists(fn))
1289 open(fn, 'wb').close()
Serhiy Storchaka7e9d1d12015-04-20 10:12:28 +03001290 self.assertRaises(ValueError, os.stat, fn_with_NUL)
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001291
1292 def test_path_with_null_byte(self):
1293 fn = os.fsencode(support.TESTFN)
1294 fn_with_NUL = fn + b'\0'
1295 self.addCleanup(support.unlink, fn)
1296 support.unlink(fn)
1297 fd = None
1298 try:
1299 with self.assertRaises(ValueError):
1300 fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # raises
1301 finally:
1302 if fd is not None:
1303 os.close(fd)
1304 self.assertFalse(os.path.exists(fn))
1305 self.assertRaises(ValueError, os.mkdir, fn_with_NUL)
1306 self.assertFalse(os.path.exists(fn))
1307 open(fn, 'wb').close()
1308 self.assertRaises(ValueError, os.stat, fn_with_NUL)
1309
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001310class PosixGroupsTester(unittest.TestCase):
1311
1312 def setUp(self):
1313 if posix.getuid() != 0:
1314 raise unittest.SkipTest("not enough privileges")
1315 if not hasattr(posix, 'getgroups'):
1316 raise unittest.SkipTest("need posix.getgroups")
1317 if sys.platform == 'darwin':
1318 raise unittest.SkipTest("getgroups(2) is broken on OSX")
1319 self.saved_groups = posix.getgroups()
1320
1321 def tearDown(self):
1322 if hasattr(posix, 'setgroups'):
1323 posix.setgroups(self.saved_groups)
1324 elif hasattr(posix, 'initgroups'):
1325 name = pwd.getpwuid(posix.getuid()).pw_name
1326 posix.initgroups(name, self.saved_groups[0])
1327
1328 @unittest.skipUnless(hasattr(posix, 'initgroups'),
1329 "test needs posix.initgroups()")
1330 def test_initgroups(self):
1331 # find missing group
1332
Benjamin Peterson659a6f52014-03-01 19:14:12 -05001333 g = max(self.saved_groups or [0]) + 1
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001334 name = pwd.getpwuid(posix.getuid()).pw_name
1335 posix.initgroups(name, g)
1336 self.assertIn(g, posix.getgroups())
1337
1338 @unittest.skipUnless(hasattr(posix, 'setgroups'),
1339 "test needs posix.setgroups()")
1340 def test_setgroups(self):
Antoine Pitroue5a91012010-09-04 17:32:06 +00001341 for groups in [[0], list(range(16))]:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00001342 posix.setgroups(groups)
1343 self.assertListEqual(groups, posix.getgroups())
1344
Neal Norwitze241ce82003-02-17 18:17:05 +00001345def test_main():
Antoine Pitrou68c95922011-03-20 17:33:57 +01001346 try:
1347 support.run_unittest(PosixTester, PosixGroupsTester)
1348 finally:
1349 support.reap_children()
Neal Norwitze241ce82003-02-17 18:17:05 +00001350
1351if __name__ == '__main__':
1352 test_main()