Debian Codegraph @

lib-python/3/test/test_posix.py

raw symbols SCIP
1 "Test posix functions"
2
3 from test import support
4 from test.support import import_helper
5 from test.support import os_helper
6 from test.support import warnings_helper
7 from test.support.script_helper import assert_python_ok
8
9 import errno
10 import sys
11 import signal
12 import time
13 import os
14 import platform
15 import stat
16 import tempfile
17 import unittest
18 import warnings
19 import textwrap
20 from contextlib import contextmanager
21
22 try:
23 import posix
24 except ImportError:
25 import nt as posix
26
27 try:
28 import pwd
29 except ImportError:
30 pwd = None
31
32 _DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(),
33 os_helper.TESTFN + '-dummy-symlink')
34
35 requires_32b = unittest.skipUnless(
36 # Emscripten/WASI have 32 bits pointers, but support 64 bits syscall args.
37 sys.maxsize < 2**32 and not (support.is_emscripten or support.is_wasi),
38 'test is only meaningful on 32-bit builds'
39 )
40
41 def _supports_sched():
42 if not hasattr(posix, 'sched_getscheduler'):
43 return False
44 try:
45 posix.sched_getscheduler(0)
46 except OSError as e:
47 if e.errno == errno.ENOSYS:
48 return False
49 return True
50
51 requires_sched = unittest.skipUnless(_supports_sched(), 'requires POSIX scheduler API')
52
53
54 class PosixTester(unittest.TestCase):
55
56 def setUp(self):
57 # create empty file
58 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
59 with open(os_helper.TESTFN, "wb"):
60 pass
61 self.enterContext(warnings_helper.check_warnings())
62 warnings.filterwarnings('ignore', '.* potential security risk .*',
63 RuntimeWarning)
64
65 def testNoArgFunctions(self):
66 # test posix functions which take no arguments and have
67 # no side-effects which we need to cleanup (e.g., fork, wait, abort)
68 NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdb", "uname",
69 "times", "getloadavg",
70 "getegid", "geteuid", "getgid", "getgroups",
71 "getpid", "getpgrp", "getppid", "getuid", "sync",
72 ]
73
74 for name in NO_ARG_FUNCTIONS:
75 posix_func = getattr(posix, name, None)
76 if posix_func is not None:
77 with self.subTest(name):
78 posix_func()
79 self.assertRaises(TypeError, posix_func, 1)
80
81 @unittest.skipUnless(hasattr(posix, 'getresuid'),
82 'test needs posix.getresuid()')
83 def test_getresuid(self):
84 user_ids = posix.getresuid()
85 self.assertEqual(len(user_ids), 3)
86 for val in user_ids:
87 self.assertGreaterEqual(val, 0)
88
89 @unittest.skipUnless(hasattr(posix, 'getresgid'),
90 'test needs posix.getresgid()')
91 def test_getresgid(self):
92 group_ids = posix.getresgid()
93 self.assertEqual(len(group_ids), 3)
94 for val in group_ids:
95 self.assertGreaterEqual(val, 0)
96
97 @unittest.skipUnless(hasattr(posix, 'setresuid'),
98 'test needs posix.setresuid()')
99 def test_setresuid(self):
100 current_user_ids = posix.getresuid()
101 self.assertIsNone(posix.setresuid(*current_user_ids))
102 # -1 means don't change that value.
103 self.assertIsNone(posix.setresuid(-1, -1, -1))
104
105 @unittest.skipUnless(hasattr(posix, 'setresuid'),
106 'test needs posix.setresuid()')
107 def test_setresuid_exception(self):
108 # Don't do this test if someone is silly enough to run us as root.
109 current_user_ids = posix.getresuid()
110 if 0 not in current_user_ids:
111 new_user_ids = (current_user_ids[0]+1, -1, -1)
112 self.assertRaises(OSError, posix.setresuid, *new_user_ids)
113
114 @unittest.skipUnless(hasattr(posix, 'setresgid'),
115 'test needs posix.setresgid()')
116 def test_setresgid(self):
117 current_group_ids = posix.getresgid()
118 self.assertIsNone(posix.setresgid(*current_group_ids))
119 # -1 means don't change that value.
120 self.assertIsNone(posix.setresgid(-1, -1, -1))
121
122 @unittest.skipUnless(hasattr(posix, 'setresgid'),
123 'test needs posix.setresgid()')
124 def test_setresgid_exception(self):
125 # Don't do this test if someone is silly enough to run us as root.
126 current_group_ids = posix.getresgid()
127 if 0 not in current_group_ids:
128 new_group_ids = (current_group_ids[0]+1, -1, -1)
129 self.assertRaises(OSError, posix.setresgid, *new_group_ids)
130
131 @unittest.skipUnless(hasattr(posix, 'initgroups'),
132 "test needs os.initgroups()")
133 @unittest.skipUnless(hasattr(pwd, 'getpwuid'), "test needs pwd.getpwuid()")
134 def test_initgroups(self):
135 # It takes a string and an integer; check that it raises a TypeError
136 # for other argument lists.
137 self.assertRaises(TypeError, posix.initgroups)
138 self.assertRaises(TypeError, posix.initgroups, None)
139 self.assertRaises(TypeError, posix.initgroups, 3, "foo")
140 self.assertRaises(TypeError, posix.initgroups, "foo", 3, object())
141
142 # If a non-privileged user invokes it, it should fail with OSError
143 # EPERM.
144 if os.getuid() != 0:
145 try:
146 name = pwd.getpwuid(posix.getuid()).pw_name
147 except KeyError:
148 # the current UID may not have a pwd entry
149 raise unittest.SkipTest("need a pwd entry")
150 try:
151 posix.initgroups(name, 13)
152 except OSError as e:
153 self.assertEqual(e.errno, errno.EPERM)
154 else:
155 self.fail("Expected OSError to be raised by initgroups")
156
157 @unittest.skipUnless(hasattr(posix, 'statvfs'),
158 'test needs posix.statvfs()')
159 def test_statvfs(self):
160 self.assertTrue(posix.statvfs(os.curdir))
161
162 @unittest.skipUnless(hasattr(posix, 'fstatvfs'),
163 'test needs posix.fstatvfs()')
164 def test_fstatvfs(self):
165 fp = open(os_helper.TESTFN)
166 try:
167 self.assertTrue(posix.fstatvfs(fp.fileno()))
168 self.assertTrue(posix.statvfs(fp.fileno()))
169 finally:
170 fp.close()
171
172 @unittest.skipUnless(hasattr(posix, 'ftruncate'),
173 'test needs posix.ftruncate()')
174 def test_ftruncate(self):
175 fp = open(os_helper.TESTFN, 'w+')
176 try:
177 # we need to have some data to truncate
178 fp.write('test')
179 fp.flush()
180 posix.ftruncate(fp.fileno(), 0)
181 finally:
182 fp.close()
183
184 @unittest.skipUnless(hasattr(posix, 'truncate'), "test needs posix.truncate()")
185 def test_truncate(self):
186 with open(os_helper.TESTFN, 'w') as fp:
187 fp.write('test')
188 fp.flush()
189 posix.truncate(os_helper.TESTFN, 0)
190
191 @unittest.skipUnless(getattr(os, 'execve', None) in os.supports_fd, "test needs execve() to support the fd parameter")
192 @support.requires_fork()
193 def test_fexecve(self):
194 fp = os.open(sys.executable, os.O_RDONLY)
195 try:
196 pid = os.fork()
197 if pid == 0:
198 os.chdir(os.path.split(sys.executable)[0])
199 posix.execve(fp, [sys.executable, '-c', 'pass'], os.environ)
200 else:
201 support.wait_process(pid, exitcode=0)
202 finally:
203 os.close(fp)
204
205
206 @unittest.skipUnless(hasattr(posix, 'waitid'), "test needs posix.waitid()")
207 @support.requires_fork()
208 def test_waitid(self):
209 pid = os.fork()
210 if pid == 0:
211 os.chdir(os.path.split(sys.executable)[0])
212 posix.execve(sys.executable, [sys.executable, '-c', 'pass'], os.environ)
213 else:
214 res = posix.waitid(posix.P_PID, pid, posix.WEXITED)
215 self.assertEqual(pid, res.si_pid)
216
217 @support.requires_fork()
218 def test_register_at_fork(self):
219 with self.assertRaises(TypeError, msg="Positional args not allowed"):
220 os.register_at_fork(lambda: None)
221 with self.assertRaises(TypeError, msg="Args must be callable"):
222 os.register_at_fork(before=2)
223 with self.assertRaises(TypeError, msg="Args must be callable"):
224 os.register_at_fork(after_in_child="three")
225 with self.assertRaises(TypeError, msg="Args must be callable"):
226 os.register_at_fork(after_in_parent=b"Five")
227 with self.assertRaises(TypeError, msg="Args must not be None"):
228 os.register_at_fork(before=None)
229 with self.assertRaises(TypeError, msg="Args must not be None"):
230 os.register_at_fork(after_in_child=None)
231 with self.assertRaises(TypeError, msg="Args must not be None"):
232 os.register_at_fork(after_in_parent=None)
233 with self.assertRaises(TypeError, msg="Invalid arg was allowed"):
234 # Ensure a combination of valid and invalid is an error.
235 os.register_at_fork(before=None, after_in_parent=lambda: 3)
236 with self.assertRaises(TypeError, msg="Invalid arg was allowed"):
237 # Ensure a combination of valid and invalid is an error.
238 os.register_at_fork(before=lambda: None, after_in_child='')
239 # We test actual registrations in their own process so as not to
240 # pollute this one. There is no way to unregister for cleanup.
241 code = """if 1:
242 import os
243
244 r, w = os.pipe()
245 fin_r, fin_w = os.pipe()
246
247 os.register_at_fork(before=lambda: os.write(w, b'A'))
248 os.register_at_fork(after_in_parent=lambda: os.write(w, b'C'))
249 os.register_at_fork(after_in_child=lambda: os.write(w, b'E'))
250 os.register_at_fork(before=lambda: os.write(w, b'B'),
251 after_in_parent=lambda: os.write(w, b'D'),
252 after_in_child=lambda: os.write(w, b'F'))
253
254 pid = os.fork()
255 if pid == 0:
256 # At this point, after-forkers have already been executed
257 os.close(w)
258 # Wait for parent to tell us to exit
259 os.read(fin_r, 1)
260 os._exit(0)
261 else:
262 try:
263 os.close(w)
264 with open(r, "rb") as f:
265 data = f.read()
266 assert len(data) == 6, data
267 # Check before-fork callbacks
268 assert data[:2] == b'BA', data
269 # Check after-fork callbacks
270 assert sorted(data[2:]) == list(b'CDEF'), data
271 assert data.index(b'C') < data.index(b'D'), data
272 assert data.index(b'E') < data.index(b'F'), data
273 finally:
274 os.write(fin_w, b'!')
275 """
276 assert_python_ok('-c', code)
277
278 @unittest.skipUnless(hasattr(posix, 'lockf'), "test needs posix.lockf()")
279 def test_lockf(self):
280 fd = os.open(os_helper.TESTFN, os.O_WRONLY | os.O_CREAT)
281 try:
282 os.write(fd, b'test')
283 os.lseek(fd, 0, os.SEEK_SET)
284 posix.lockf(fd, posix.F_LOCK, 4)
285 # section is locked
286 posix.lockf(fd, posix.F_ULOCK, 4)
287 finally:
288 os.close(fd)
289
290 @unittest.skipUnless(hasattr(posix, 'pread'), "test needs posix.pread()")
291 def test_pread(self):
292 fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
293 try:
294 os.write(fd, b'test')
295 os.lseek(fd, 0, os.SEEK_SET)
296 self.assertEqual(b'es', posix.pread(fd, 2, 1))
297 # the first pread() shouldn't disturb the file offset
298 self.assertEqual(b'te', posix.read(fd, 2))
299 finally:
300 os.close(fd)
301
302 @unittest.skipUnless(hasattr(posix, 'preadv'), "test needs posix.preadv()")
303 def test_preadv(self):
304 fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
305 try:
306 os.write(fd, b'test1tt2t3t5t6t6t8')
307 buf = [bytearray(i) for i in [5, 3, 2]]
308 self.assertEqual(posix.preadv(fd, buf, 3), 10)
309 self.assertEqual([b't1tt2', b't3t', b'5t'], list(buf))
310 finally:
311 os.close(fd)
312
313 @unittest.skipUnless(hasattr(posix, 'preadv'), "test needs posix.preadv()")
314 @unittest.skipUnless(hasattr(posix, 'RWF_HIPRI'), "test needs posix.RWF_HIPRI")
315 def test_preadv_flags(self):
316 fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
317 try:
318 os.write(fd, b'test1tt2t3t5t6t6t8')
319 buf = [bytearray(i) for i in [5, 3, 2]]
320 self.assertEqual(posix.preadv(fd, buf, 3, os.RWF_HIPRI), 10)
321 self.assertEqual([b't1tt2', b't3t', b'5t'], list(buf))
322 except NotImplementedError:
323 self.skipTest("preadv2 not available")
324 except OSError as inst:
325 # Is possible that the macro RWF_HIPRI was defined at compilation time
326 # but the option is not supported by the kernel or the runtime libc shared
327 # library.
328 if inst.errno in {errno.EINVAL, errno.ENOTSUP}:
329 raise unittest.SkipTest("RWF_HIPRI is not supported by the current system")
330 else:
331 raise
332 finally:
333 os.close(fd)
334
335 @unittest.skipUnless(hasattr(posix, 'preadv'), "test needs posix.preadv()")
336 @requires_32b
337 def test_preadv_overflow_32bits(self):
338 fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
339 try:
340 buf = [bytearray(2**16)] * 2**15
341 with self.assertRaises(OSError) as cm:
342 os.preadv(fd, buf, 0)
343 self.assertEqual(cm.exception.errno, errno.EINVAL)
344 self.assertEqual(bytes(buf[0]), b'\0'* 2**16)
345 finally:
346 os.close(fd)
347
348 @unittest.skipUnless(hasattr(posix, 'pwrite'), "test needs posix.pwrite()")
349 def test_pwrite(self):
350 fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
351 try:
352 os.write(fd, b'test')
353 os.lseek(fd, 0, os.SEEK_SET)
354 posix.pwrite(fd, b'xx', 1)
355 self.assertEqual(b'txxt', posix.read(fd, 4))
356 finally:
357 os.close(fd)
358
359 @unittest.skipUnless(hasattr(posix, 'pwritev'), "test needs posix.pwritev()")
360 def test_pwritev(self):
361 fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
362 try:
363 os.write(fd, b"xx")
364 os.lseek(fd, 0, os.SEEK_SET)
365 n = os.pwritev(fd, [b'test1', b'tt2', b't3'], 2)
366 self.assertEqual(n, 10)
367
368 os.lseek(fd, 0, os.SEEK_SET)
369 self.assertEqual(b'xxtest1tt2t3', posix.read(fd, 100))
370 finally:
371 os.close(fd)
372
373 @unittest.skipUnless(hasattr(posix, 'pwritev'), "test needs posix.pwritev()")
374 @unittest.skipUnless(hasattr(posix, 'os.RWF_SYNC'), "test needs os.RWF_SYNC")
375 def test_pwritev_flags(self):
376 fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
377 try:
378 os.write(fd,b"xx")
379 os.lseek(fd, 0, os.SEEK_SET)
380 n = os.pwritev(fd, [b'test1', b'tt2', b't3'], 2, os.RWF_SYNC)
381 self.assertEqual(n, 10)
382
383 os.lseek(fd, 0, os.SEEK_SET)
384 self.assertEqual(b'xxtest1tt2', posix.read(fd, 100))
385 finally:
386 os.close(fd)
387
388 @unittest.skipUnless(hasattr(posix, 'pwritev'), "test needs posix.pwritev()")
389 @requires_32b
390 def test_pwritev_overflow_32bits(self):
391 fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
392 try:
393 with self.assertRaises(OSError) as cm:
394 os.pwritev(fd, [b"x" * 2**16] * 2**15, 0)
395 self.assertEqual(cm.exception.errno, errno.EINVAL)
396 finally:
397 os.close(fd)
398
399 @unittest.skipUnless(hasattr(posix, 'posix_fallocate'),
400 "test needs posix.posix_fallocate()")
401 def test_posix_fallocate(self):
402 fd = os.open(os_helper.TESTFN, os.O_WRONLY | os.O_CREAT)
403 try:
404 posix.posix_fallocate(fd, 0, 10)
405 except OSError as inst:
406 # issue10812, ZFS doesn't appear to support posix_fallocate,
407 # so skip Solaris-based since they are likely to have ZFS.
408 # issue33655: Also ignore EINVAL on *BSD since ZFS is also
409 # often used there.
410 if inst.errno == errno.EINVAL and sys.platform.startswith(
411 ('sunos', 'freebsd', 'netbsd', 'openbsd', 'gnukfreebsd')):
412 raise unittest.SkipTest("test may fail on ZFS filesystems")
413 else:
414 raise
415 finally:
416 os.close(fd)
417
418 # issue31106 - posix_fallocate() does not set error in errno.
419 @unittest.skipUnless(hasattr(posix, 'posix_fallocate'),
420 "test needs posix.posix_fallocate()")
421 def test_posix_fallocate_errno(self):
422 try:
423 posix.posix_fallocate(-42, 0, 10)
424 except OSError as inst:
425 if inst.errno != errno.EBADF:
426 raise
427
428 @unittest.skipUnless(hasattr(posix, 'posix_fadvise'),
429 "test needs posix.posix_fadvise()")
430 def test_posix_fadvise(self):
431 fd = os.open(os_helper.TESTFN, os.O_RDONLY)
432 try:
433 posix.posix_fadvise(fd, 0, 0, posix.POSIX_FADV_WILLNEED)
434 finally:
435 os.close(fd)
436
437 @unittest.skipUnless(hasattr(posix, 'posix_fadvise'),
438 "test needs posix.posix_fadvise()")
439 def test_posix_fadvise_errno(self):
440 try:
441 posix.posix_fadvise(-42, 0, 0, posix.POSIX_FADV_WILLNEED)
442 except OSError as inst:
443 if inst.errno != errno.EBADF:
444 raise
445
446 @unittest.skipUnless(os.utime in os.supports_fd, "test needs fd support in os.utime")
447 def test_utime_with_fd(self):
448 now = time.time()
449 fd = os.open(os_helper.TESTFN, os.O_RDONLY)
450 try:
451 posix.utime(fd)
452 posix.utime(fd, None)
453 self.assertRaises(TypeError, posix.utime, fd, (None, None))
454 self.assertRaises(TypeError, posix.utime, fd, (now, None))
455 self.assertRaises(TypeError, posix.utime, fd, (None, now))
456 posix.utime(fd, (int(now), int(now)))
457 posix.utime(fd, (now, now))
458 self.assertRaises(ValueError, posix.utime, fd, (now, now), ns=(now, now))
459 self.assertRaises(ValueError, posix.utime, fd, (now, 0), ns=(None, None))
460 self.assertRaises(ValueError, posix.utime, fd, (None, None), ns=(now, 0))
461 posix.utime(fd, (int(now), int((now - int(now)) * 1e9)))
462 posix.utime(fd, ns=(int(now), int((now - int(now)) * 1e9)))
463
464 finally:
465 os.close(fd)
466
467 @unittest.skipUnless(os.utime in os.supports_follow_symlinks, "test needs follow_symlinks support in os.utime")
468 def test_utime_nofollow_symlinks(self):
469 now = time.time()
470 posix.utime(os_helper.TESTFN, None, follow_symlinks=False)
471 self.assertRaises(TypeError, posix.utime, os_helper.TESTFN,
472 (None, None), follow_symlinks=False)
473 self.assertRaises(TypeError, posix.utime, os_helper.TESTFN,
474 (now, None), follow_symlinks=False)
475 self.assertRaises(TypeError, posix.utime, os_helper.TESTFN,
476 (None, now), follow_symlinks=False)
477 posix.utime(os_helper.TESTFN, (int(now), int(now)),
478 follow_symlinks=False)
479 posix.utime(os_helper.TESTFN, (now, now), follow_symlinks=False)
480 posix.utime(os_helper.TESTFN, follow_symlinks=False)
481
482 @unittest.skipUnless(hasattr(posix, 'writev'), "test needs posix.writev()")
483 def test_writev(self):
484 fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
485 try:
486 n = os.writev(fd, (b'test1', b'tt2', b't3'))
487 self.assertEqual(n, 10)
488
489 os.lseek(fd, 0, os.SEEK_SET)
490 self.assertEqual(b'test1tt2t3', posix.read(fd, 10))
491
492 # Issue #20113: empty list of buffers should not crash
493 try:
494 size = posix.writev(fd, [])
495 except OSError:
496 # writev(fd, []) raises OSError(22, "Invalid argument")
497 # on OpenIndiana
498 pass
499 else:
500 self.assertEqual(size, 0)
501 finally:
502 os.close(fd)
503
504 @unittest.skipUnless(hasattr(posix, 'writev'), "test needs posix.writev()")
505 @requires_32b
506 def test_writev_overflow_32bits(self):
507 fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
508 try:
509 with self.assertRaises(OSError) as cm:
510 os.writev(fd, [b"x" * 2**16] * 2**15)
511 self.assertEqual(cm.exception.errno, errno.EINVAL)
512 finally:
513 os.close(fd)
514
515 @unittest.skipUnless(hasattr(posix, 'readv'), "test needs posix.readv()")
516 def test_readv(self):
517 fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
518 try:
519 os.write(fd, b'test1tt2t3')
520 os.lseek(fd, 0, os.SEEK_SET)
521 buf = [bytearray(i) for i in [5, 3, 2]]
522 self.assertEqual(posix.readv(fd, buf), 10)
523 self.assertEqual([b'test1', b'tt2', b't3'], [bytes(i) for i in buf])
524
525 # Issue #20113: empty list of buffers should not crash
526 try:
527 size = posix.readv(fd, [])
528 except OSError:
529 # readv(fd, []) raises OSError(22, "Invalid argument")
530 # on OpenIndiana
531 pass
532 else:
533 self.assertEqual(size, 0)
534 finally:
535 os.close(fd)
536
537 @unittest.skipUnless(hasattr(posix, 'readv'), "test needs posix.readv()")
538 @requires_32b
539 def test_readv_overflow_32bits(self):
540 fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
541 try:
542 buf = [bytearray(2**16)] * 2**15
543 with self.assertRaises(OSError) as cm:
544 os.readv(fd, buf)
545 self.assertEqual(cm.exception.errno, errno.EINVAL)
546 self.assertEqual(bytes(buf[0]), b'\0'* 2**16)
547 finally:
548 os.close(fd)
549
550 @unittest.skipUnless(hasattr(posix, 'dup'),
551 'test needs posix.dup()')
552 @unittest.skipIf(support.is_wasi, "WASI does not have dup()")
553 def test_dup(self):
554 fp = open(os_helper.TESTFN)
555 try:
556 fd = posix.dup(fp.fileno())
557 self.assertIsInstance(fd, int)
558 os.close(fd)
559 finally:
560 fp.close()
561
562 @unittest.skipUnless(hasattr(posix, 'confstr'),
563 'test needs posix.confstr()')
564 def test_confstr(self):
565 self.assertRaises(ValueError, posix.confstr, "CS_garbage")
566 self.assertEqual(len(posix.confstr("CS_PATH")) > 0, True)
567
568 @unittest.skipUnless(hasattr(posix, 'dup2'),
569 'test needs posix.dup2()')
570 @unittest.skipIf(support.is_wasi, "WASI does not have dup2()")
571 def test_dup2(self):
572 fp1 = open(os_helper.TESTFN)
573 fp2 = open(os_helper.TESTFN)
574 try:
575 posix.dup2(fp1.fileno(), fp2.fileno())
576 finally:
577 fp1.close()
578 fp2.close()
579
580 @unittest.skipUnless(hasattr(os, 'O_CLOEXEC'), "needs os.O_CLOEXEC")
581 @support.requires_linux_version(2, 6, 23)
582 @support.requires_subprocess()
583 def test_oscloexec(self):
584 fd = os.open(os_helper.TESTFN, os.O_RDONLY|os.O_CLOEXEC)
585 self.addCleanup(os.close, fd)
586 self.assertFalse(os.get_inheritable(fd))
587
588 @unittest.skipUnless(hasattr(posix, 'O_EXLOCK'),
589 'test needs posix.O_EXLOCK')
590 def test_osexlock(self):
591 fd = os.open(os_helper.TESTFN,
592 os.O_WRONLY|os.O_EXLOCK|os.O_CREAT)
593 self.assertRaises(OSError, os.open, os_helper.TESTFN,
594 os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
595 os.close(fd)
596
597 if hasattr(posix, "O_SHLOCK"):
598 fd = os.open(os_helper.TESTFN,
599 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
600 self.assertRaises(OSError, os.open, os_helper.TESTFN,
601 os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
602 os.close(fd)
603
604 @unittest.skipUnless(hasattr(posix, 'O_SHLOCK'),
605 'test needs posix.O_SHLOCK')
606 def test_osshlock(self):
607 fd1 = os.open(os_helper.TESTFN,
608 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
609 fd2 = os.open(os_helper.TESTFN,
610 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
611 os.close(fd2)
612 os.close(fd1)
613
614 if hasattr(posix, "O_EXLOCK"):
615 fd = os.open(os_helper.TESTFN,
616 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
617 self.assertRaises(OSError, os.open, os_helper.TESTFN,
618 os.O_RDONLY|os.O_EXLOCK|os.O_NONBLOCK)
619 os.close(fd)
620
621 @unittest.skipUnless(hasattr(posix, 'fstat'),
622 'test needs posix.fstat()')
623 def test_fstat(self):
624 fp = open(os_helper.TESTFN)
625 try:
626 self.assertTrue(posix.fstat(fp.fileno()))
627 self.assertTrue(posix.stat(fp.fileno()))
628
629 self.assertRaisesRegex(TypeError,
630 'should be string, bytes, os.PathLike or integer, not',
631 posix.stat, float(fp.fileno()))
632 finally:
633 fp.close()
634
635 def test_stat(self):
636 self.assertTrue(posix.stat(os_helper.TESTFN))
637 self.assertTrue(posix.stat(os.fsencode(os_helper.TESTFN)))
638
639 self.assertWarnsRegex(DeprecationWarning,
640 'should be string, bytes, os.PathLike or integer, not',
641 posix.stat, bytearray(os.fsencode(os_helper.TESTFN)))
642 self.assertRaisesRegex(TypeError,
643 'should be string, bytes, os.PathLike or integer, not',
644 posix.stat, None)
645 self.assertRaisesRegex(TypeError,
646 'should be string, bytes, os.PathLike or integer, not',
647 posix.stat, list(os_helper.TESTFN))
648 self.assertRaisesRegex(TypeError,
649 'should be string, bytes, os.PathLike or integer, not',
650 posix.stat, list(os.fsencode(os_helper.TESTFN)))
651
652 @unittest.skipUnless(hasattr(posix, 'mkfifo'), "don't have mkfifo()")
653 def test_mkfifo(self):
654 if sys.platform == "vxworks":
655 fifo_path = os.path.join("/fifos/", os_helper.TESTFN)
656 else:
657 fifo_path = os_helper.TESTFN
658 os_helper.unlink(fifo_path)
659 self.addCleanup(os_helper.unlink, fifo_path)
660 try:
661 posix.mkfifo(fifo_path, stat.S_IRUSR | stat.S_IWUSR)
662 except PermissionError as e:
663 self.skipTest('posix.mkfifo(): %s' % e)
664 self.assertTrue(stat.S_ISFIFO(posix.stat(fifo_path).st_mode))
665
666 @unittest.skipUnless(hasattr(posix, 'mknod') and hasattr(stat, 'S_IFIFO'),
667 "don't have mknod()/S_IFIFO")
668 def test_mknod(self):
669 # Test using mknod() to create a FIFO (the only use specified
670 # by POSIX).
671 os_helper.unlink(os_helper.TESTFN)
672 mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
673 try:
674 posix.mknod(os_helper.TESTFN, mode, 0)
675 except OSError as e:
676 # Some old systems don't allow unprivileged users to use
677 # mknod(), or only support creating device nodes.
678 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL, errno.EACCES))
679 else:
680 self.assertTrue(stat.S_ISFIFO(posix.stat(os_helper.TESTFN).st_mode))
681
682 # Keyword arguments are also supported
683 os_helper.unlink(os_helper.TESTFN)
684 try:
685 posix.mknod(path=os_helper.TESTFN, mode=mode, device=0,
686 dir_fd=None)
687 except OSError as e:
688 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL, errno.EACCES))
689
690 @unittest.skipUnless(hasattr(posix, 'makedev'), 'test needs posix.makedev()')
691 def test_makedev(self):
692 st = posix.stat(os_helper.TESTFN)
693 dev = st.st_dev
694 self.assertIsInstance(dev, int)
695 self.assertGreaterEqual(dev, 0)
696
697 major = posix.major(dev)
698 self.assertIsInstance(major, int)
699 self.assertGreaterEqual(major, 0)
700 self.assertEqual(posix.major(dev), major)
701 self.assertRaises(TypeError, posix.major, float(dev))
702 self.assertRaises(TypeError, posix.major)
703 self.assertRaises((ValueError, OverflowError), posix.major, -1)
704
705 minor = posix.minor(dev)
706 self.assertIsInstance(minor, int)
707 self.assertGreaterEqual(minor, 0)
708 self.assertEqual(posix.minor(dev), minor)
709 self.assertRaises(TypeError, posix.minor, float(dev))
710 self.assertRaises(TypeError, posix.minor)
711 self.assertRaises((ValueError, OverflowError), posix.minor, -1)
712
713 self.assertEqual(posix.makedev(major, minor), dev)
714 self.assertRaises(TypeError, posix.makedev, float(major), minor)
715 self.assertRaises(TypeError, posix.makedev, major, float(minor))
716 self.assertRaises(TypeError, posix.makedev, major)
717 self.assertRaises(TypeError, posix.makedev)
718
719 def _test_all_chown_common(self, chown_func, first_param, stat_func):
720 """Common code for chown, fchown and lchown tests."""
721 def check_stat(uid, gid):
722 if stat_func is not None:
723 stat = stat_func(first_param)
724 self.assertEqual(stat.st_uid, uid)
725 self.assertEqual(stat.st_gid, gid)
726 uid = os.getuid()
727 gid = os.getgid()
728 # test a successful chown call
729 chown_func(first_param, uid, gid)
730 check_stat(uid, gid)
731 chown_func(first_param, -1, gid)
732 check_stat(uid, gid)
733 chown_func(first_param, uid, -1)
734 check_stat(uid, gid)
735
736 if sys.platform == "vxworks":
737 # On VxWorks, root user id is 1 and 0 means no login user:
738 # both are super users.
739 is_root = (uid in (0, 1))
740 else:
741 is_root = (uid == 0)
742 if support.is_emscripten:
743 # Emscripten getuid() / geteuid() always return 0 (root), but
744 # cannot chown uid/gid to random value.
745 pass
746 elif is_root:
747 # Try an amusingly large uid/gid to make sure we handle
748 # large unsigned values. (chown lets you use any
749 # uid/gid you like, even if they aren't defined.)
750 #
751 # On VxWorks uid_t is defined as unsigned short. A big
752 # value greater than 65535 will result in underflow error.
753 #
754 # This problem keeps coming up:
755 # http://bugs.python.org/issue1747858
756 # http://bugs.python.org/issue4591
757 # http://bugs.python.org/issue15301
758 # Hopefully the fix in 4591 fixes it for good!
759 #
760 # This part of the test only runs when run as root.
761 # Only scary people run their tests as root.
762
763 big_value = (2**31 if sys.platform != "vxworks" else 2**15)
764 chown_func(first_param, big_value, big_value)
765 check_stat(big_value, big_value)
766 chown_func(first_param, -1, -1)
767 check_stat(big_value, big_value)
768 chown_func(first_param, uid, gid)
769 check_stat(uid, gid)
770 elif platform.system() in ('HP-UX', 'SunOS'):
771 # HP-UX and Solaris can allow a non-root user to chown() to root
772 # (issue #5113)
773 raise unittest.SkipTest("Skipping because of non-standard chown() "
774 "behavior")
775 else:
776 # non-root cannot chown to root, raises OSError
777 self.assertRaises(OSError, chown_func, first_param, 0, 0)
778 check_stat(uid, gid)
779 self.assertRaises(OSError, chown_func, first_param, 0, -1)
780 check_stat(uid, gid)
781 if 0 not in os.getgroups():
782 self.assertRaises(OSError, chown_func, first_param, -1, 0)
783 check_stat(uid, gid)
784 # test illegal types
785 for t in str, float:
786 self.assertRaises(TypeError, chown_func, first_param, t(uid), gid)
787 check_stat(uid, gid)
788 self.assertRaises(TypeError, chown_func, first_param, uid, t(gid))
789 check_stat(uid, gid)
790
791 @unittest.skipUnless(hasattr(os, "chown"), "requires os.chown()")
792 @unittest.skipIf(support.is_emscripten, "getgid() is a stub")
793 def test_chown(self):
794 # raise an OSError if the file does not exist
795 os.unlink(os_helper.TESTFN)
796 self.assertRaises(OSError, posix.chown, os_helper.TESTFN, -1, -1)
797
798 # re-create the file
799 os_helper.create_empty_file(os_helper.TESTFN)
800 self._test_all_chown_common(posix.chown, os_helper.TESTFN, posix.stat)
801
802 @os_helper.skip_unless_working_chmod
803 @unittest.skipUnless(hasattr(posix, 'fchown'), "test needs os.fchown()")
804 @unittest.skipIf(support.is_emscripten, "getgid() is a stub")
805 def test_fchown(self):
806 os.unlink(os_helper.TESTFN)
807
808 # re-create the file
809 test_file = open(os_helper.TESTFN, 'w')
810 try:
811 fd = test_file.fileno()
812 self._test_all_chown_common(posix.fchown, fd,
813 getattr(posix, 'fstat', None))
814 finally:
815 test_file.close()
816
817 @os_helper.skip_unless_working_chmod
818 @unittest.skipUnless(hasattr(posix, 'lchown'), "test needs os.lchown()")
819 def test_lchown(self):
820 os.unlink(os_helper.TESTFN)
821 # create a symlink
822 os.symlink(_DUMMY_SYMLINK, os_helper.TESTFN)
823 self._test_all_chown_common(posix.lchown, os_helper.TESTFN,
824 getattr(posix, 'lstat', None))
825
826 @unittest.skipUnless(hasattr(posix, 'chdir'), 'test needs posix.chdir()')
827 def test_chdir(self):
828 posix.chdir(os.curdir)
829 self.assertRaises(OSError, posix.chdir, os_helper.TESTFN)
830
831 def test_listdir(self):
832 self.assertIn(os_helper.TESTFN, posix.listdir(os.curdir))
833
834 def test_listdir_default(self):
835 # When listdir is called without argument,
836 # it's the same as listdir(os.curdir).
837 self.assertIn(os_helper.TESTFN, posix.listdir())
838
839 def test_listdir_bytes(self):
840 # When listdir is called with a bytes object,
841 # the returned strings are of type bytes.
842 self.assertIn(os.fsencode(os_helper.TESTFN), posix.listdir(b'.'))
843
844 def test_listdir_bytes_like(self):
845 for cls in bytearray, memoryview:
846 with self.assertWarns(DeprecationWarning):
847 names = posix.listdir(cls(b'.'))
848 self.assertIn(os.fsencode(os_helper.TESTFN), names)
849 for name in names:
850 self.assertIs(type(name), bytes)
851
852 @unittest.skipUnless(posix.listdir in os.supports_fd,
853 "test needs fd support for posix.listdir()")
854 def test_listdir_fd(self):
855 f = posix.open(posix.getcwd(), posix.O_RDONLY)
856 self.addCleanup(posix.close, f)
857 self.assertEqual(
858 sorted(posix.listdir('.')),
859 sorted(posix.listdir(f))
860 )
861 # Check that the fd offset was reset (issue #13739)
862 self.assertEqual(
863 sorted(posix.listdir('.')),
864 sorted(posix.listdir(f))
865 )
866
867 @unittest.skipUnless(hasattr(posix, 'access'), 'test needs posix.access()')
868 def test_access(self):
869 self.assertTrue(posix.access(os_helper.TESTFN, os.R_OK))
870
871 @unittest.skipUnless(hasattr(posix, 'umask'), 'test needs posix.umask()')
872 def test_umask(self):
873 old_mask = posix.umask(0)
874 self.assertIsInstance(old_mask, int)
875 posix.umask(old_mask)
876
877 @unittest.skipUnless(hasattr(posix, 'strerror'),
878 'test needs posix.strerror()')
879 def test_strerror(self):
880 self.assertTrue(posix.strerror(0))
881
882 @unittest.skipUnless(hasattr(posix, 'pipe'), 'test needs posix.pipe()')
883 def test_pipe(self):
884 reader, writer = posix.pipe()
885 os.close(reader)
886 os.close(writer)
887
888 @unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()")
889 @support.requires_linux_version(2, 6, 27)
890 def test_pipe2(self):
891 self.assertRaises(TypeError, os.pipe2, 'DEADBEEF')
892 self.assertRaises(TypeError, os.pipe2, 0, 0)
893
894 # try calling with flags = 0, like os.pipe()
895 r, w = os.pipe2(0)
896 os.close(r)
897 os.close(w)
898
899 # test flags
900 r, w = os.pipe2(os.O_CLOEXEC|os.O_NONBLOCK)
901 self.addCleanup(os.close, r)
902 self.addCleanup(os.close, w)
903 self.assertFalse(os.get_inheritable(r))
904 self.assertFalse(os.get_inheritable(w))
905 self.assertFalse(os.get_blocking(r))
906 self.assertFalse(os.get_blocking(w))
907 # try reading from an empty pipe: this should fail, not block
908 self.assertRaises(OSError, os.read, r, 1)
909 # try a write big enough to fill-up the pipe: this should either
910 # fail or perform a partial write, not block
911 try:
912 os.write(w, b'x' * support.PIPE_MAX_SIZE)
913 except OSError:
914 pass
915
916 @support.cpython_only
917 @unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()")
918 @support.requires_linux_version(2, 6, 27)
919 def test_pipe2_c_limits(self):
920 # Issue 15989
921 import _testcapi
922 self.assertRaises(OverflowError, os.pipe2, _testcapi.INT_MAX + 1)
923 self.assertRaises(OverflowError, os.pipe2, _testcapi.UINT_MAX + 1)
924
925 @unittest.skipUnless(hasattr(posix, 'utime'), 'test needs posix.utime()')
926 def test_utime(self):
927 now = time.time()
928 posix.utime(os_helper.TESTFN, None)
929 self.assertRaises(TypeError, posix.utime,
930 os_helper.TESTFN, (None, None))
931 self.assertRaises(TypeError, posix.utime,
932 os_helper.TESTFN, (now, None))
933 self.assertRaises(TypeError, posix.utime,
934 os_helper.TESTFN, (None, now))
935 posix.utime(os_helper.TESTFN, (int(now), int(now)))
936 posix.utime(os_helper.TESTFN, (now, now))
937
938 def check_chmod(self, chmod_func, target, **kwargs):
939 mode = os.stat(target).st_mode
940 try:
941 new_mode = mode & ~(stat.S_IWOTH | stat.S_IWGRP | stat.S_IWUSR)
942 chmod_func(target, new_mode, **kwargs)
943 self.assertEqual(os.stat(target).st_mode, new_mode)
944 if stat.S_ISREG(mode):
945 try:
946 with open(target, 'wb+'):
947 pass
948 except PermissionError:
949 pass
950 new_mode = mode | (stat.S_IWOTH | stat.S_IWGRP | stat.S_IWUSR)
951 chmod_func(target, new_mode, **kwargs)
952 self.assertEqual(os.stat(target).st_mode, new_mode)
953 if stat.S_ISREG(mode):
954 with open(target, 'wb+'):
955 pass
956 finally:
957 posix.chmod(target, mode)
958
959 @os_helper.skip_unless_working_chmod
960 def test_chmod_file(self):
961 self.check_chmod(posix.chmod, os_helper.TESTFN)
962
963 def tempdir(self):
964 target = os_helper.TESTFN + 'd'
965 posix.mkdir(target)
966 self.addCleanup(posix.rmdir, target)
967 return target
968
969 @os_helper.skip_unless_working_chmod
970 def test_chmod_dir(self):
971 target = self.tempdir()
972 self.check_chmod(posix.chmod, target)
973
974 @unittest.skipUnless(hasattr(posix, 'lchmod'), 'test needs os.lchmod()')
975 def test_lchmod_file(self):
976 self.check_chmod(posix.lchmod, os_helper.TESTFN)
977 self.check_chmod(posix.chmod, os_helper.TESTFN, follow_symlinks=False)
978
979 @unittest.skipUnless(hasattr(posix, 'lchmod'), 'test needs os.lchmod()')
980 def test_lchmod_dir(self):
981 target = self.tempdir()
982 self.check_chmod(posix.lchmod, target)
983 self.check_chmod(posix.chmod, target, follow_symlinks=False)
984
985 def check_chmod_link(self, chmod_func, target, link, **kwargs):
986 target_mode = os.stat(target).st_mode
987 link_mode = os.lstat(link).st_mode
988 try:
989 new_mode = target_mode & ~(stat.S_IWOTH | stat.S_IWGRP | stat.S_IWUSR)
990 chmod_func(link, new_mode, **kwargs)
991 self.assertEqual(os.stat(target).st_mode, new_mode)
992 self.assertEqual(os.lstat(link).st_mode, link_mode)
993 new_mode = target_mode | (stat.S_IWOTH | stat.S_IWGRP | stat.S_IWUSR)
994 chmod_func(link, new_mode, **kwargs)
995 self.assertEqual(os.stat(target).st_mode, new_mode)
996 self.assertEqual(os.lstat(link).st_mode, link_mode)
997 finally:
998 posix.chmod(target, target_mode)
999
1000 def check_lchmod_link(self, chmod_func, target, link, **kwargs):
1001 target_mode = os.stat(target).st_mode
1002 link_mode = os.lstat(link).st_mode
1003 new_mode = link_mode & ~(stat.S_IWOTH | stat.S_IWGRP | stat.S_IWUSR)
1004 chmod_func(link, new_mode, **kwargs)
1005 self.assertEqual(os.stat(target).st_mode, target_mode)
1006 self.assertEqual(os.lstat(link).st_mode, new_mode)
1007 new_mode = link_mode | (stat.S_IWOTH | stat.S_IWGRP | stat.S_IWUSR)
1008 chmod_func(link, new_mode, **kwargs)
1009 self.assertEqual(os.stat(target).st_mode, target_mode)
1010 self.assertEqual(os.lstat(link).st_mode, new_mode)
1011
1012 @os_helper.skip_unless_symlink
1013 def test_chmod_file_symlink(self):
1014 target = os_helper.TESTFN
1015 link = os_helper.TESTFN + '-link'
1016 os.symlink(target, link)
1017 self.addCleanup(posix.unlink, link)
1018 if os.name == 'nt':
1019 self.check_lchmod_link(posix.chmod, target, link)
1020 else:
1021 self.check_chmod_link(posix.chmod, target, link)
1022 self.check_chmod_link(posix.chmod, target, link, follow_symlinks=True)
1023
1024 @os_helper.skip_unless_symlink
1025 def test_chmod_dir_symlink(self):
1026 target = self.tempdir()
1027 link = os_helper.TESTFN + '-link'
1028 os.symlink(target, link, target_is_directory=True)
1029 self.addCleanup(posix.unlink, link)
1030 if os.name == 'nt':
1031 self.check_lchmod_link(posix.chmod, target, link)
1032 else:
1033 self.check_chmod_link(posix.chmod, target, link)
1034 self.check_chmod_link(posix.chmod, target, link, follow_symlinks=True)
1035
1036 @unittest.skipUnless(hasattr(posix, 'lchmod'), 'test needs os.lchmod()')
1037 @os_helper.skip_unless_symlink
1038 def test_lchmod_file_symlink(self):
1039 target = os_helper.TESTFN
1040 link = os_helper.TESTFN + '-link'
1041 os.symlink(target, link)
1042 self.addCleanup(posix.unlink, link)
1043 self.check_lchmod_link(posix.chmod, target, link, follow_symlinks=False)
1044 self.check_lchmod_link(posix.lchmod, target, link)
1045
1046 @unittest.skipUnless(hasattr(posix, 'lchmod'), 'test needs os.lchmod()')
1047 @os_helper.skip_unless_symlink
1048 def test_lchmod_dir_symlink(self):
1049 target = self.tempdir()
1050 link = os_helper.TESTFN + '-link'
1051 os.symlink(target, link)
1052 self.addCleanup(posix.unlink, link)
1053 self.check_lchmod_link(posix.chmod, target, link, follow_symlinks=False)
1054 self.check_lchmod_link(posix.lchmod, target, link)
1055
1056 def _test_chflags_regular_file(self, chflags_func, target_file, **kwargs):
1057 st = os.stat(target_file)
1058 self.assertTrue(hasattr(st, 'st_flags'))
1059
1060 # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
1061 flags = st.st_flags | stat.UF_IMMUTABLE
1062 try:
1063 chflags_func(target_file, flags, **kwargs)
1064 except OSError as err:
1065 if err.errno != errno.EOPNOTSUPP:
1066 raise
1067 msg = 'chflag UF_IMMUTABLE not supported by underlying fs'
1068 self.skipTest(msg)
1069
1070 try:
1071 new_st = os.stat(target_file)
1072 self.assertEqual(st.st_flags | stat.UF_IMMUTABLE, new_st.st_flags)
1073 try:
1074 fd = open(target_file, 'w+')
1075 except OSError as e:
1076 self.assertEqual(e.errno, errno.EPERM)
1077 finally:
1078 posix.chflags(target_file, st.st_flags)
1079
1080 @unittest.skipUnless(hasattr(posix, 'chflags'), 'test needs os.chflags()')
1081 def test_chflags(self):
1082 self._test_chflags_regular_file(posix.chflags, os_helper.TESTFN)
1083
1084 @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
1085 def test_lchflags_regular_file(self):
1086 self._test_chflags_regular_file(posix.lchflags, os_helper.TESTFN)
1087 self._test_chflags_regular_file(posix.chflags, os_helper.TESTFN,
1088 follow_symlinks=False)
1089
1090 @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
1091 def test_lchflags_symlink(self):
1092 testfn_st = os.stat(os_helper.TESTFN)
1093
1094 self.assertTrue(hasattr(testfn_st, 'st_flags'))
1095
1096 self.addCleanup(os_helper.unlink, _DUMMY_SYMLINK)
1097 os.symlink(os_helper.TESTFN, _DUMMY_SYMLINK)
1098 dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
1099
1100 def chflags_nofollow(path, flags):
1101 return posix.chflags(path, flags, follow_symlinks=False)
1102
1103 for fn in (posix.lchflags, chflags_nofollow):
1104 # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
1105 flags = dummy_symlink_st.st_flags | stat.UF_IMMUTABLE
1106 try:
1107 fn(_DUMMY_SYMLINK, flags)
1108 except OSError as err:
1109 if err.errno != errno.EOPNOTSUPP:
1110 raise
1111 msg = 'chflag UF_IMMUTABLE not supported by underlying fs'
1112 self.skipTest(msg)
1113 try:
1114 new_testfn_st = os.stat(os_helper.TESTFN)
1115 new_dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
1116
1117 self.assertEqual(testfn_st.st_flags, new_testfn_st.st_flags)
1118 self.assertEqual(dummy_symlink_st.st_flags | stat.UF_IMMUTABLE,
1119 new_dummy_symlink_st.st_flags)
1120 finally:
1121 fn(_DUMMY_SYMLINK, dummy_symlink_st.st_flags)
1122
1123 def test_environ(self):
1124 if os.name == "nt":
1125 item_type = str
1126 else:
1127 item_type = bytes
1128 for k, v in posix.environ.items():
1129 self.assertEqual(type(k), item_type)
1130 self.assertEqual(type(v), item_type)
1131
1132 def test_putenv(self):
1133 with self.assertRaises(ValueError):
1134 os.putenv('FRUIT\0VEGETABLE', 'cabbage')
1135 with self.assertRaises(ValueError):
1136 os.putenv('FRUIT', 'orange\0VEGETABLE=cabbage')
1137 with self.assertRaises(ValueError):
1138 os.putenv('FRUIT=ORANGE', 'lemon')
1139 if os.name == 'posix':
1140 with self.assertRaises(ValueError):
1141 os.putenv(b'FRUIT\0VEGETABLE', b'cabbage')
1142 with self.assertRaises(ValueError):
1143 os.putenv(b'FRUIT', b'orange\0VEGETABLE=cabbage')
1144 with self.assertRaises(ValueError):
1145 os.putenv(b'FRUIT=ORANGE', b'lemon')
1146
1147 @unittest.skipUnless(hasattr(posix, 'getcwd'), 'test needs posix.getcwd()')
1148 def test_getcwd_long_pathnames(self):
1149 dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
1150 curdir = os.getcwd()
1151 base_path = os.path.abspath(os_helper.TESTFN) + '.getcwd'
1152
1153 try:
1154 os.mkdir(base_path)
1155 os.chdir(base_path)
1156 except:
1157 # Just returning nothing instead of the SkipTest exception, because
1158 # the test results in Error in that case. Is that ok?
1159 # raise unittest.SkipTest("cannot create directory for testing")
1160 return
1161
1162 def _create_and_do_getcwd(dirname, current_path_length = 0):
1163 try:
1164 os.mkdir(dirname)
1165 except:
1166 raise unittest.SkipTest("mkdir cannot create directory sufficiently deep for getcwd test")
1167
1168 os.chdir(dirname)
1169 try:
1170 os.getcwd()
1171 if current_path_length < 1027:
1172 _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1)
1173 finally:
1174 os.chdir('..')
1175 os.rmdir(dirname)
1176
1177 _create_and_do_getcwd(dirname)
1178
1179 finally:
1180 os.chdir(curdir)
1181 os_helper.rmtree(base_path)
1182
1183 @unittest.skipUnless(hasattr(posix, 'getgrouplist'), "test needs posix.getgrouplist()")
1184 @unittest.skipUnless(hasattr(pwd, 'getpwuid'), "test needs pwd.getpwuid()")
1185 @unittest.skipUnless(hasattr(os, 'getuid'), "test needs os.getuid()")
1186 def test_getgrouplist(self):
1187 user = pwd.getpwuid(os.getuid())[0]
1188 group = pwd.getpwuid(os.getuid())[3]
1189 self.assertIn(group, posix.getgrouplist(user, group))
1190
1191
1192 @unittest.skipUnless(hasattr(os, 'getegid'), "test needs os.getegid()")
1193 @unittest.skipUnless(hasattr(os, 'popen'), "test needs os.popen()")
1194 @support.requires_subprocess()
1195 def test_getgroups(self):
1196 with os.popen('id -G 2>/dev/null') as idg:
1197 groups = idg.read().strip()
1198 ret = idg.close()
1199
1200 try:
1201 idg_groups = set(int(g) for g in groups.split())
1202 except ValueError:
1203 idg_groups = set()
1204 if ret is not None or not idg_groups:
1205 raise unittest.SkipTest("need working 'id -G'")
1206
1207 # Issues 16698: OS X ABIs prior to 10.6 have limits on getgroups()
1208 if sys.platform == 'darwin':
1209 import sysconfig
1210 dt = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') or '10.3'
1211 if tuple(int(n) for n in dt.split('.')[0:2]) < (10, 6):
1212 raise unittest.SkipTest("getgroups(2) is broken prior to 10.6")
1213
1214 # 'id -G' and 'os.getgroups()' should return the same
1215 # groups, ignoring order, duplicates, and the effective gid.
1216 # #10822/#26944 - It is implementation defined whether
1217 # posix.getgroups() includes the effective gid.
1218 symdiff = idg_groups.symmetric_difference(posix.getgroups())
1219 self.assertTrue(not symdiff or symdiff == {posix.getegid()})
1220
1221 @unittest.skipUnless(hasattr(signal, 'SIGCHLD'), 'CLD_XXXX be placed in si_code for a SIGCHLD signal')
1222 @unittest.skipUnless(hasattr(os, 'waitid_result'), "test needs os.waitid_result")
1223 def test_cld_xxxx_constants(self):
1224 os.CLD_EXITED
1225 os.CLD_KILLED
1226 os.CLD_DUMPED
1227 os.CLD_TRAPPED
1228 os.CLD_STOPPED
1229 os.CLD_CONTINUED
1230
1231 requires_sched_h = unittest.skipUnless(hasattr(posix, 'sched_yield'),
1232 "don't have scheduling support")
1233 requires_sched_affinity = unittest.skipUnless(hasattr(posix, 'sched_setaffinity'),
1234 "don't have sched affinity support")
1235
1236 @requires_sched_h
1237 def test_sched_yield(self):
1238 # This has no error conditions (at least on Linux).
1239 posix.sched_yield()
1240
1241 @requires_sched_h
1242 @unittest.skipUnless(hasattr(posix, 'sched_get_priority_max'),
1243 "requires sched_get_priority_max()")
1244 def test_sched_priority(self):
1245 # Round-robin usually has interesting priorities.
1246 pol = posix.SCHED_RR
1247 lo = posix.sched_get_priority_min(pol)
1248 hi = posix.sched_get_priority_max(pol)
1249 self.assertIsInstance(lo, int)
1250 self.assertIsInstance(hi, int)
1251 self.assertGreaterEqual(hi, lo)
1252 # OSX evidently just returns 15 without checking the argument.
1253 if sys.platform != "darwin":
1254 self.assertRaises(OSError, posix.sched_get_priority_min, -23)
1255 self.assertRaises(OSError, posix.sched_get_priority_max, -23)
1256
1257 @requires_sched
1258 def test_get_and_set_scheduler_and_param(self):
1259 possible_schedulers = [sched for name, sched in posix.__dict__.items()
1260 if name.startswith("SCHED_")]
1261 mine = posix.sched_getscheduler(0)
1262 self.assertIn(mine, possible_schedulers)
1263 try:
1264 parent = posix.sched_getscheduler(os.getppid())
1265 except OSError as e:
1266 if e.errno != errno.EPERM:
1267 raise
1268 else:
1269 self.assertIn(parent, possible_schedulers)
1270 self.assertRaises(OSError, posix.sched_getscheduler, -1)
1271 self.assertRaises(OSError, posix.sched_getparam, -1)
1272 param = posix.sched_getparam(0)
1273 self.assertIsInstance(param.sched_priority, int)
1274
1275 # POSIX states that calling sched_setparam() or sched_setscheduler() on
1276 # a process with a scheduling policy other than SCHED_FIFO or SCHED_RR
1277 # is implementation-defined: NetBSD and FreeBSD can return EINVAL.
1278 if not sys.platform.startswith(('freebsd', 'netbsd')):
1279 try:
1280 posix.sched_setscheduler(0, mine, param)
1281 posix.sched_setparam(0, param)
1282 except OSError as e:
1283 if e.errno != errno.EPERM:
1284 raise
1285 self.assertRaises(OSError, posix.sched_setparam, -1, param)
1286
1287 self.assertRaises(OSError, posix.sched_setscheduler, -1, mine, param)
1288 self.assertRaises(TypeError, posix.sched_setscheduler, 0, mine, None)
1289 self.assertRaises(TypeError, posix.sched_setparam, 0, 43)
1290 param = posix.sched_param(None)
1291 self.assertRaises(TypeError, posix.sched_setparam, 0, param)
1292 large = 214748364700
1293 param = posix.sched_param(large)
1294 self.assertRaises(OverflowError, posix.sched_setparam, 0, param)
1295 param = posix.sched_param(sched_priority=-large)
1296 self.assertRaises(OverflowError, posix.sched_setparam, 0, param)
1297
1298 @unittest.skipUnless(hasattr(posix, "sched_rr_get_interval"), "no function")
1299 def test_sched_rr_get_interval(self):
1300 try:
1301 interval = posix.sched_rr_get_interval(0)
1302 except OSError as e:
1303 # This likely means that sched_rr_get_interval is only valid for
1304 # processes with the SCHED_RR scheduler in effect.
1305 if e.errno != errno.EINVAL:
1306 raise
1307 self.skipTest("only works on SCHED_RR processes")
1308 self.assertIsInstance(interval, float)
1309 # Reasonable constraints, I think.
1310 self.assertGreaterEqual(interval, 0.)
1311 self.assertLess(interval, 1.)
1312
1313 @requires_sched_affinity
1314 def test_sched_getaffinity(self):
1315 mask = posix.sched_getaffinity(0)
1316 self.assertIsInstance(mask, set)
1317 self.assertGreaterEqual(len(mask), 1)
1318 if not sys.platform.startswith("freebsd"):
1319 # bpo-47205: does not raise OSError on FreeBSD
1320 self.assertRaises(OSError, posix.sched_getaffinity, -1)
1321 for cpu in mask:
1322 self.assertIsInstance(cpu, int)
1323 self.assertGreaterEqual(cpu, 0)
1324 self.assertLess(cpu, 1 << 32)
1325
1326 @requires_sched_affinity
1327 def test_sched_setaffinity(self):
1328 mask = posix.sched_getaffinity(0)
1329 self.addCleanup(posix.sched_setaffinity, 0, list(mask))
1330
1331 if len(mask) > 1:
1332 # Empty masks are forbidden
1333 mask.pop()
1334 posix.sched_setaffinity(0, mask)
1335 self.assertEqual(posix.sched_getaffinity(0), mask)
1336
1337 try:
1338 posix.sched_setaffinity(0, [])
1339 # gh-117061: On RHEL9, sched_setaffinity(0, []) does not fail
1340 except OSError:
1341 # sched_setaffinity() manual page documents EINVAL error
1342 # when the mask is empty.
1343 pass
1344
1345 self.assertRaises(ValueError, posix.sched_setaffinity, 0, [-10])
1346 self.assertRaises(ValueError, posix.sched_setaffinity, 0, map(int, "0X"))
1347 self.assertRaises(OverflowError, posix.sched_setaffinity, 0, [1<<128])
1348 if not sys.platform.startswith("freebsd"):
1349 # bpo-47205: does not raise OSError on FreeBSD
1350 self.assertRaises(OSError, posix.sched_setaffinity, -1, mask)
1351
1352 @unittest.skipIf(support.is_wasi, "No dynamic linking on WASI")
1353 @unittest.skipUnless(os.name == 'posix', "POSIX-only test")
1354 def test_rtld_constants(self):
1355 # check presence of major RTLD_* constants
1356 posix.RTLD_LAZY
1357 posix.RTLD_NOW
1358 posix.RTLD_GLOBAL
1359 posix.RTLD_LOCAL
1360
1361 @unittest.skipUnless(hasattr(os, 'SEEK_HOLE'),
1362 "test needs an OS that reports file holes")
1363 def test_fs_holes(self):
1364 # Even if the filesystem doesn't report holes,
1365 # if the OS supports it the SEEK_* constants
1366 # will be defined and will have a consistent
1367 # behaviour:
1368 # os.SEEK_DATA = current position
1369 # os.SEEK_HOLE = end of file position
1370 with open(os_helper.TESTFN, 'r+b') as fp:
1371 fp.write(b"hello")
1372 fp.flush()
1373 size = fp.tell()
1374 fno = fp.fileno()
1375 try :
1376 for i in range(size):
1377 self.assertEqual(i, os.lseek(fno, i, os.SEEK_DATA))
1378 self.assertLessEqual(size, os.lseek(fno, i, os.SEEK_HOLE))
1379 self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_DATA)
1380 self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_HOLE)
1381 except OSError :
1382 # Some OSs claim to support SEEK_HOLE/SEEK_DATA
1383 # but it is not true.
1384 # For instance:
1385 # http://lists.freebsd.org/pipermail/freebsd-amd64/2012-January/014332.html
1386 raise unittest.SkipTest("OSError raised!")
1387
1388 def test_path_error2(self):
1389 """
1390 Test functions that call path_error2(), providing two filenames in their exceptions.
1391 """
1392 for name in ("rename", "replace", "link"):
1393 function = getattr(os, name, None)
1394 if function is None:
1395 continue
1396
1397 for dst in ("noodly2", os_helper.TESTFN):
1398 try:
1399 function('doesnotexistfilename', dst)
1400 except OSError as e:
1401 self.assertIn("'doesnotexistfilename' -> '{}'".format(dst), str(e))
1402 break
1403 else:
1404 self.fail("No valid path_error2() test for os." + name)
1405
1406 def test_path_with_null_character(self):
1407 fn = os_helper.TESTFN
1408 fn_with_NUL = fn + '\0'
1409 self.addCleanup(os_helper.unlink, fn)
1410 os_helper.unlink(fn)
1411 fd = None
1412 try:
1413 with self.assertRaises(ValueError):
1414 fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # raises
1415 finally:
1416 if fd is not None:
1417 os.close(fd)
1418 self.assertFalse(os.path.exists(fn))
1419 self.assertRaises(ValueError, os.mkdir, fn_with_NUL)
1420 self.assertFalse(os.path.exists(fn))
1421 open(fn, 'wb').close()
1422 self.assertRaises(ValueError, os.stat, fn_with_NUL)
1423
1424 def test_path_with_null_byte(self):
1425 fn = os.fsencode(os_helper.TESTFN)
1426 fn_with_NUL = fn + b'\0'
1427 self.addCleanup(os_helper.unlink, fn)
1428 os_helper.unlink(fn)
1429 fd = None
1430 try:
1431 with self.assertRaises(ValueError):
1432 fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # raises
1433 finally:
1434 if fd is not None:
1435 os.close(fd)
1436 self.assertFalse(os.path.exists(fn))
1437 self.assertRaises(ValueError, os.mkdir, fn_with_NUL)
1438 self.assertFalse(os.path.exists(fn))
1439 open(fn, 'wb').close()
1440 self.assertRaises(ValueError, os.stat, fn_with_NUL)
1441
1442 @unittest.skipUnless(hasattr(os, "pidfd_open"), "pidfd_open unavailable")
1443 def test_pidfd_open(self):
1444 with self.assertRaises(OSError) as cm:
1445 os.pidfd_open(-1)
1446 if cm.exception.errno == errno.ENOSYS:
1447 self.skipTest("system does not support pidfd_open")
1448 if isinstance(cm.exception, PermissionError):
1449 self.skipTest(f"pidfd_open syscall blocked: {cm.exception!r}")
1450 self.assertEqual(cm.exception.errno, errno.EINVAL)
1451 os.close(os.pidfd_open(os.getpid(), 0))
1452
1453
1454 # tests for the posix *at functions follow
1455 class TestPosixDirFd(unittest.TestCase):
1456 count = 0
1457
1458 @contextmanager
1459 def prepare(self):
1460 TestPosixDirFd.count += 1
1461 name = f'{os_helper.TESTFN}_{self.count}'
1462 base_dir = f'{os_helper.TESTFN}_{self.count}base'
1463 posix.mkdir(base_dir)
1464 self.addCleanup(posix.rmdir, base_dir)
1465 fullname = os.path.join(base_dir, name)
1466 assert not os.path.exists(fullname)
1467 with os_helper.open_dir_fd(base_dir) as dir_fd:
1468 yield (dir_fd, name, fullname)
1469
1470 @contextmanager
1471 def prepare_file(self):
1472 with self.prepare() as (dir_fd, name, fullname):
1473 os_helper.create_empty_file(fullname)
1474 self.addCleanup(posix.unlink, fullname)
1475 yield (dir_fd, name, fullname)
1476
1477 @unittest.skipUnless(os.access in os.supports_dir_fd, "test needs dir_fd support for os.access()")
1478 def test_access_dir_fd(self):
1479 with self.prepare_file() as (dir_fd, name, fullname):
1480 self.assertTrue(posix.access(name, os.R_OK, dir_fd=dir_fd))
1481
1482 @unittest.skipUnless(os.chmod in os.supports_dir_fd, "test needs dir_fd support in os.chmod()")
1483 def test_chmod_dir_fd(self):
1484 with self.prepare_file() as (dir_fd, name, fullname):
1485 posix.chmod(fullname, stat.S_IRUSR)
1486 posix.chmod(name, stat.S_IRUSR | stat.S_IWUSR, dir_fd=dir_fd)
1487 s = posix.stat(fullname)
1488 self.assertEqual(s.st_mode & stat.S_IRWXU,
1489 stat.S_IRUSR | stat.S_IWUSR)
1490
1491 @unittest.skipUnless(hasattr(os, 'chown') and (os.chown in os.supports_dir_fd),
1492 "test needs dir_fd support in os.chown()")
1493 @unittest.skipIf(support.is_emscripten, "getgid() is a stub")
1494 def test_chown_dir_fd(self):
1495 with self.prepare_file() as (dir_fd, name, fullname):
1496 posix.chown(name, os.getuid(), os.getgid(), dir_fd=dir_fd)
1497
1498 @unittest.skipUnless(os.stat in os.supports_dir_fd, "test needs dir_fd support in os.stat()")
1499 def test_stat_dir_fd(self):
1500 with self.prepare() as (dir_fd, name, fullname):
1501 with open(fullname, 'w') as outfile:
1502 outfile.write("testline\n")
1503 self.addCleanup(posix.unlink, fullname)
1504
1505 s1 = posix.stat(fullname)
1506 s2 = posix.stat(name, dir_fd=dir_fd)
1507 self.assertEqual(s1, s2)
1508 s2 = posix.stat(fullname, dir_fd=None)
1509 self.assertEqual(s1, s2)
1510
1511 self.assertRaisesRegex(TypeError, 'should be integer or None, not',
1512 posix.stat, name, dir_fd=posix.getcwd())
1513 self.assertRaisesRegex(TypeError, 'should be integer or None, not',
1514 posix.stat, name, dir_fd=float(dir_fd))
1515 self.assertRaises(OverflowError,
1516 posix.stat, name, dir_fd=10**20)
1517
1518 @unittest.skipUnless(os.utime in os.supports_dir_fd, "test needs dir_fd support in os.utime()")
1519 def test_utime_dir_fd(self):
1520 with self.prepare_file() as (dir_fd, name, fullname):
1521 now = time.time()
1522 posix.utime(name, None, dir_fd=dir_fd)
1523 posix.utime(name, dir_fd=dir_fd)
1524 self.assertRaises(TypeError, posix.utime, name,
1525 now, dir_fd=dir_fd)
1526 self.assertRaises(TypeError, posix.utime, name,
1527 (None, None), dir_fd=dir_fd)
1528 self.assertRaises(TypeError, posix.utime, name,
1529 (now, None), dir_fd=dir_fd)
1530 self.assertRaises(TypeError, posix.utime, name,
1531 (None, now), dir_fd=dir_fd)
1532 self.assertRaises(TypeError, posix.utime, name,
1533 (now, "x"), dir_fd=dir_fd)
1534 posix.utime(name, (int(now), int(now)), dir_fd=dir_fd)
1535 posix.utime(name, (now, now), dir_fd=dir_fd)
1536 posix.utime(name,
1537 (int(now), int((now - int(now)) * 1e9)), dir_fd=dir_fd)
1538 posix.utime(name, dir_fd=dir_fd,
1539 times=(int(now), int((now - int(now)) * 1e9)))
1540
1541 # try dir_fd and follow_symlinks together
1542 if os.utime in os.supports_follow_symlinks:
1543 try:
1544 posix.utime(name, follow_symlinks=False, dir_fd=dir_fd)
1545 except ValueError:
1546 # whoops! using both together not supported on this platform.
1547 pass
1548
1549 @unittest.skipIf(
1550 support.is_wasi,
1551 "WASI: symlink following on path_link is not supported"
1552 )
1553 @unittest.skipUnless(
1554 hasattr(os, "link") and os.link in os.supports_dir_fd,
1555 "test needs dir_fd support in os.link()"
1556 )
1557 def test_link_dir_fd(self):
1558 with self.prepare_file() as (dir_fd, name, fullname), \
1559 self.prepare() as (dir_fd2, linkname, fulllinkname):
1560 try:
1561 posix.link(name, linkname, src_dir_fd=dir_fd, dst_dir_fd=dir_fd2)
1562 except PermissionError as e:
1563 self.skipTest('posix.link(): %s' % e)
1564 self.addCleanup(posix.unlink, fulllinkname)
1565 # should have same inodes
1566 self.assertEqual(posix.stat(fullname)[1],
1567 posix.stat(fulllinkname)[1])
1568
1569 @unittest.skipUnless(os.mkdir in os.supports_dir_fd, "test needs dir_fd support in os.mkdir()")
1570 def test_mkdir_dir_fd(self):
1571 with self.prepare() as (dir_fd, name, fullname):
1572 posix.mkdir(name, dir_fd=dir_fd)
1573 self.addCleanup(posix.rmdir, fullname)
1574 posix.stat(fullname) # should not raise exception
1575
1576 @unittest.skipUnless(hasattr(os, 'mknod')
1577 and (os.mknod in os.supports_dir_fd)
1578 and hasattr(stat, 'S_IFIFO'),
1579 "test requires both stat.S_IFIFO and dir_fd support for os.mknod()")
1580 def test_mknod_dir_fd(self):
1581 # Test using mknodat() to create a FIFO (the only use specified
1582 # by POSIX).
1583 with self.prepare() as (dir_fd, name, fullname):
1584 mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
1585 try:
1586 posix.mknod(name, mode, 0, dir_fd=dir_fd)
1587 except OSError as e:
1588 # Some old systems don't allow unprivileged users to use
1589 # mknod(), or only support creating device nodes.
1590 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL, errno.EACCES))
1591 else:
1592 self.addCleanup(posix.unlink, fullname)
1593 self.assertTrue(stat.S_ISFIFO(posix.stat(fullname).st_mode))
1594
1595 @unittest.skipUnless(os.open in os.supports_dir_fd, "test needs dir_fd support in os.open()")
1596 def test_open_dir_fd(self):
1597 with self.prepare() as (dir_fd, name, fullname):
1598 with open(fullname, 'wb') as outfile:
1599 outfile.write(b"testline\n")
1600 self.addCleanup(posix.unlink, fullname)
1601 fd = posix.open(name, posix.O_RDONLY, dir_fd=dir_fd)
1602 try:
1603 res = posix.read(fd, 9)
1604 self.assertEqual(b"testline\n", res)
1605 finally:
1606 posix.close(fd)
1607
1608 @unittest.skipUnless(hasattr(os, 'readlink') and (os.readlink in os.supports_dir_fd),
1609 "test needs dir_fd support in os.readlink()")
1610 def test_readlink_dir_fd(self):
1611 with self.prepare() as (dir_fd, name, fullname):
1612 os.symlink('symlink', fullname)
1613 self.addCleanup(posix.unlink, fullname)
1614 self.assertEqual(posix.readlink(name, dir_fd=dir_fd), 'symlink')
1615
1616 @unittest.skipUnless(os.rename in os.supports_dir_fd, "test needs dir_fd support in os.rename()")
1617 def test_rename_dir_fd(self):
1618 with self.prepare_file() as (dir_fd, name, fullname), \
1619 self.prepare() as (dir_fd2, name2, fullname2):
1620 posix.rename(name, name2,
1621 src_dir_fd=dir_fd, dst_dir_fd=dir_fd2)
1622 posix.stat(fullname2) # should not raise exception
1623 posix.rename(fullname2, fullname)
1624
1625 @unittest.skipUnless(os.symlink in os.supports_dir_fd, "test needs dir_fd support in os.symlink()")
1626 def test_symlink_dir_fd(self):
1627 with self.prepare() as (dir_fd, name, fullname):
1628 posix.symlink('symlink', name, dir_fd=dir_fd)
1629 self.addCleanup(posix.unlink, fullname)
1630 self.assertEqual(posix.readlink(fullname), 'symlink')
1631
1632 @unittest.skipUnless(os.unlink in os.supports_dir_fd, "test needs dir_fd support in os.unlink()")
1633 def test_unlink_dir_fd(self):
1634 with self.prepare() as (dir_fd, name, fullname):
1635 os_helper.create_empty_file(fullname)
1636 posix.stat(fullname) # should not raise exception
1637 try:
1638 posix.unlink(name, dir_fd=dir_fd)
1639 self.assertRaises(OSError, posix.stat, fullname)
1640 except:
1641 self.addCleanup(posix.unlink, fullname)
1642 raise
1643
1644 @unittest.skipUnless(hasattr(os, 'mkfifo') and os.mkfifo in os.supports_dir_fd, "test needs dir_fd support in os.mkfifo()")
1645 def test_mkfifo_dir_fd(self):
1646 with self.prepare() as (dir_fd, name, fullname):
1647 try:
1648 posix.mkfifo(name, stat.S_IRUSR | stat.S_IWUSR, dir_fd=dir_fd)
1649 except PermissionError as e:
1650 self.skipTest('posix.mkfifo(): %s' % e)
1651 self.addCleanup(posix.unlink, fullname)
1652 self.assertTrue(stat.S_ISFIFO(posix.stat(fullname).st_mode))
1653
1654
1655 class PosixGroupsTester(unittest.TestCase):
1656
1657 def setUp(self):
1658 if posix.getuid() != 0:
1659 raise unittest.SkipTest("not enough privileges")
1660 if not hasattr(posix, 'getgroups'):
1661 raise unittest.SkipTest("need posix.getgroups")
1662 if sys.platform == 'darwin':
1663 raise unittest.SkipTest("getgroups(2) is broken on OSX")
1664 self.saved_groups = posix.getgroups()
1665
1666 def tearDown(self):
1667 if hasattr(posix, 'setgroups'):
1668 posix.setgroups(self.saved_groups)
1669 elif hasattr(posix, 'initgroups'):
1670 name = pwd.getpwuid(posix.getuid()).pw_name
1671 posix.initgroups(name, self.saved_groups[0])
1672
1673 @unittest.skipUnless(hasattr(posix, 'initgroups'),
1674 "test needs posix.initgroups()")
1675 def test_initgroups(self):
1676 # find missing group
1677
1678 g = max(self.saved_groups or [0]) + 1
1679 name = pwd.getpwuid(posix.getuid()).pw_name
1680 posix.initgroups(name, g)
1681 self.assertIn(g, posix.getgroups())
1682
1683 @unittest.skipUnless(hasattr(posix, 'setgroups'),
1684 "test needs posix.setgroups()")
1685 def test_setgroups(self):
1686 for groups in [[0], list(range(16))]:
1687 posix.setgroups(groups)
1688 self.assertListEqual(groups, posix.getgroups())
1689
1690
1691 class _PosixSpawnMixin:
1692 # Program which does nothing and exits with status 0 (success)
1693 NOOP_PROGRAM = (sys.executable, '-I', '-S', '-c', 'pass')
1694 spawn_func = None
1695
1696 def python_args(self, *args):
1697 # Disable site module to avoid side effects. For example,
1698 # on Fedora 28, if the HOME environment variable is not set,
1699 # site._getuserbase() calls pwd.getpwuid() which opens
1700 # /var/lib/sss/mc/passwd but then leaves the file open which makes
1701 # test_close_file() to fail.
1702 return (sys.executable, '-I', '-S', *args)
1703
1704 def test_returns_pid(self):
1705 pidfile = os_helper.TESTFN
1706 self.addCleanup(os_helper.unlink, pidfile)
1707 script = f"""if 1:
1708 import os
1709 with open({pidfile!r}, "w") as pidfile:
1710 pidfile.write(str(os.getpid()))
1711 """
1712 args = self.python_args('-c', script)
1713 pid = self.spawn_func(args[0], args, os.environ)
1714 support.wait_process(pid, exitcode=0)
1715 with open(pidfile, encoding="utf-8") as f:
1716 self.assertEqual(f.read(), str(pid))
1717
1718 def test_no_such_executable(self):
1719 no_such_executable = 'no_such_executable'
1720 try:
1721 pid = self.spawn_func(no_such_executable,
1722 [no_such_executable],
1723 os.environ)
1724 # bpo-35794: PermissionError can be raised if there are
1725 # directories in the $PATH that are not accessible.
1726 except (FileNotFoundError, PermissionError) as exc:
1727 self.assertEqual(exc.filename, no_such_executable)
1728 else:
1729 pid2, status = os.waitpid(pid, 0)
1730 self.assertEqual(pid2, pid)
1731 self.assertNotEqual(status, 0)
1732
1733 def test_specify_environment(self):
1734 envfile = os_helper.TESTFN
1735 self.addCleanup(os_helper.unlink, envfile)
1736 script = f"""if 1:
1737 import os
1738 with open({envfile!r}, "w", encoding="utf-8") as envfile:
1739 envfile.write(os.environ['foo'])
1740 """
1741 args = self.python_args('-c', script)
1742 pid = self.spawn_func(args[0], args,
1743 {**os.environ, 'foo': 'bar'})
1744 support.wait_process(pid, exitcode=0)
1745 with open(envfile, encoding="utf-8") as f:
1746 self.assertEqual(f.read(), 'bar')
1747
1748 def test_none_file_actions(self):
1749 pid = self.spawn_func(
1750 self.NOOP_PROGRAM[0],
1751 self.NOOP_PROGRAM,
1752 os.environ,
1753 file_actions=None
1754 )
1755 support.wait_process(pid, exitcode=0)
1756
1757 def test_empty_file_actions(self):
1758 pid = self.spawn_func(
1759 self.NOOP_PROGRAM[0],
1760 self.NOOP_PROGRAM,
1761 os.environ,
1762 file_actions=[]
1763 )
1764 support.wait_process(pid, exitcode=0)
1765
1766 def test_resetids_explicit_default(self):
1767 pid = self.spawn_func(
1768 sys.executable,
1769 [sys.executable, '-c', 'pass'],
1770 os.environ,
1771 resetids=False
1772 )
1773 support.wait_process(pid, exitcode=0)
1774
1775 def test_resetids(self):
1776 pid = self.spawn_func(
1777 sys.executable,
1778 [sys.executable, '-c', 'pass'],
1779 os.environ,
1780 resetids=True
1781 )
1782 support.wait_process(pid, exitcode=0)
1783
1784 def test_resetids_wrong_type(self):
1785 with self.assertRaises(TypeError):
1786 self.spawn_func(sys.executable,
1787 [sys.executable, "-c", "pass"],
1788 os.environ, resetids=None)
1789
1790 def test_setpgroup(self):
1791 pid = self.spawn_func(
1792 sys.executable,
1793 [sys.executable, '-c', 'pass'],
1794 os.environ,
1795 setpgroup=os.getpgrp()
1796 )
1797 support.wait_process(pid, exitcode=0)
1798
1799 def test_setpgroup_wrong_type(self):
1800 with self.assertRaises(TypeError):
1801 self.spawn_func(sys.executable,
1802 [sys.executable, "-c", "pass"],
1803 os.environ, setpgroup="023")
1804
1805 @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'),
1806 'need signal.pthread_sigmask()')
1807 def test_setsigmask(self):
1808 code = textwrap.dedent("""\
1809 import signal
1810 signal.raise_signal(signal.SIGUSR1)""")
1811
1812 pid = self.spawn_func(
1813 sys.executable,
1814 [sys.executable, '-c', code],
1815 os.environ,
1816 setsigmask=[signal.SIGUSR1]
1817 )
1818 support.wait_process(pid, exitcode=0)
1819
1820 def test_setsigmask_wrong_type(self):
1821 with self.assertRaises(TypeError):
1822 self.spawn_func(sys.executable,
1823 [sys.executable, "-c", "pass"],
1824 os.environ, setsigmask=34)
1825 with self.assertRaises(TypeError):
1826 self.spawn_func(sys.executable,
1827 [sys.executable, "-c", "pass"],
1828 os.environ, setsigmask=["j"])
1829 with self.assertRaises(ValueError):
1830 self.spawn_func(sys.executable,
1831 [sys.executable, "-c", "pass"],
1832 os.environ, setsigmask=[signal.NSIG,
1833 signal.NSIG+1])
1834
1835 def test_setsid(self):
1836 rfd, wfd = os.pipe()
1837 self.addCleanup(os.close, rfd)
1838 try:
1839 os.set_inheritable(wfd, True)
1840
1841 code = textwrap.dedent(f"""
1842 import os
1843 fd = {wfd}
1844 sid = os.getsid(0)
1845 os.write(fd, str(sid).encode())
1846 """)
1847
1848 try:
1849 pid = self.spawn_func(sys.executable,
1850 [sys.executable, "-c", code],
1851 os.environ, setsid=True)
1852 except NotImplementedError as exc:
1853 self.skipTest(f"setsid is not supported: {exc!r}")
1854 except PermissionError as exc:
1855 self.skipTest(f"setsid failed with: {exc!r}")
1856 finally:
1857 os.close(wfd)
1858
1859 support.wait_process(pid, exitcode=0)
1860
1861 output = os.read(rfd, 100)
1862 child_sid = int(output)
1863 parent_sid = os.getsid(os.getpid())
1864 self.assertNotEqual(parent_sid, child_sid)
1865
1866 @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'),
1867 'need signal.pthread_sigmask()')
1868 def test_setsigdef(self):
1869 original_handler = signal.signal(signal.SIGUSR1, signal.SIG_IGN)
1870 code = textwrap.dedent("""\
1871 import signal
1872 signal.raise_signal(signal.SIGUSR1)""")
1873 try:
1874 pid = self.spawn_func(
1875 sys.executable,
1876 [sys.executable, '-c', code],
1877 os.environ,
1878 setsigdef=[signal.SIGUSR1]
1879 )
1880 finally:
1881 signal.signal(signal.SIGUSR1, original_handler)
1882
1883 support.wait_process(pid, exitcode=-signal.SIGUSR1)
1884
1885 def test_setsigdef_wrong_type(self):
1886 with self.assertRaises(TypeError):
1887 self.spawn_func(sys.executable,
1888 [sys.executable, "-c", "pass"],
1889 os.environ, setsigdef=34)
1890 with self.assertRaises(TypeError):
1891 self.spawn_func(sys.executable,
1892 [sys.executable, "-c", "pass"],
1893 os.environ, setsigdef=["j"])
1894 with self.assertRaises(ValueError):
1895 self.spawn_func(sys.executable,
1896 [sys.executable, "-c", "pass"],
1897 os.environ, setsigdef=[signal.NSIG, signal.NSIG+1])
1898
1899 @requires_sched
1900 @unittest.skipIf(sys.platform.startswith(('freebsd', 'netbsd')),
1901 "bpo-34685: test can fail on BSD")
1902 def test_setscheduler_only_param(self):
1903 policy = os.sched_getscheduler(0)
1904 priority = os.sched_get_priority_min(policy)
1905 code = textwrap.dedent(f"""\
1906 import os, sys
1907 if os.sched_getscheduler(0) != {policy}:
1908 sys.exit(101)
1909 if os.sched_getparam(0).sched_priority != {priority}:
1910 sys.exit(102)""")
1911 pid = self.spawn_func(
1912 sys.executable,
1913 [sys.executable, '-c', code],
1914 os.environ,
1915 scheduler=(None, os.sched_param(priority))
1916 )
1917 support.wait_process(pid, exitcode=0)
1918
1919 @requires_sched
1920 @unittest.skipIf(sys.platform.startswith(('freebsd', 'netbsd')),
1921 "bpo-34685: test can fail on BSD")
1922 def test_setscheduler_with_policy(self):
1923 policy = os.sched_getscheduler(0)
1924 priority = os.sched_get_priority_min(policy)
1925 code = textwrap.dedent(f"""\
1926 import os, sys
1927 if os.sched_getscheduler(0) != {policy}:
1928 sys.exit(101)
1929 if os.sched_getparam(0).sched_priority != {priority}:
1930 sys.exit(102)""")
1931 pid = self.spawn_func(
1932 sys.executable,
1933 [sys.executable, '-c', code],
1934 os.environ,
1935 scheduler=(policy, os.sched_param(priority))
1936 )
1937 support.wait_process(pid, exitcode=0)
1938
1939 def test_multiple_file_actions(self):
1940 file_actions = [
1941 (os.POSIX_SPAWN_OPEN, 3, os.path.realpath(__file__), os.O_RDONLY, 0),
1942 (os.POSIX_SPAWN_CLOSE, 0),
1943 (os.POSIX_SPAWN_DUP2, 1, 4),
1944 ]
1945 pid = self.spawn_func(self.NOOP_PROGRAM[0],
1946 self.NOOP_PROGRAM,
1947 os.environ,
1948 file_actions=file_actions)
1949 support.wait_process(pid, exitcode=0)
1950
1951 def test_bad_file_actions(self):
1952 args = self.NOOP_PROGRAM
1953 with self.assertRaises(TypeError):
1954 self.spawn_func(args[0], args, os.environ,
1955 file_actions=[None])
1956 with self.assertRaises(TypeError):
1957 self.spawn_func(args[0], args, os.environ,
1958 file_actions=[()])
1959 with self.assertRaises(TypeError):
1960 self.spawn_func(args[0], args, os.environ,
1961 file_actions=[(None,)])
1962 with self.assertRaises(TypeError):
1963 self.spawn_func(args[0], args, os.environ,
1964 file_actions=[(12345,)])
1965 with self.assertRaises(TypeError):
1966 self.spawn_func(args[0], args, os.environ,
1967 file_actions=[(os.POSIX_SPAWN_CLOSE,)])
1968 with self.assertRaises(TypeError):
1969 self.spawn_func(args[0], args, os.environ,
1970 file_actions=[(os.POSIX_SPAWN_CLOSE, 1, 2)])
1971 with self.assertRaises(TypeError):
1972 self.spawn_func(args[0], args, os.environ,
1973 file_actions=[(os.POSIX_SPAWN_CLOSE, None)])
1974 with self.assertRaises(ValueError):
1975 self.spawn_func(args[0], args, os.environ,
1976 file_actions=[(os.POSIX_SPAWN_OPEN,
1977 3, __file__ + '\0',
1978 os.O_RDONLY, 0)])
1979
1980 def test_open_file(self):
1981 outfile = os_helper.TESTFN
1982 self.addCleanup(os_helper.unlink, outfile)
1983 script = """if 1:
1984 import sys
1985 sys.stdout.write("hello")
1986 """
1987 file_actions = [
1988 (os.POSIX_SPAWN_OPEN, 1, outfile,
1989 os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
1990 stat.S_IRUSR | stat.S_IWUSR),
1991 ]
1992 args = self.python_args('-c', script)
1993 pid = self.spawn_func(args[0], args, os.environ,
1994 file_actions=file_actions)
1995
1996 support.wait_process(pid, exitcode=0)
1997 with open(outfile, encoding="utf-8") as f:
1998 self.assertEqual(f.read(), 'hello')
1999
2000 def test_close_file(self):
2001 closefile = os_helper.TESTFN
2002 self.addCleanup(os_helper.unlink, closefile)
2003 script = f"""if 1:
2004 import os
2005 try:
2006 os.fstat(0)
2007 except OSError as e:
2008 with open({closefile!r}, 'w', encoding='utf-8') as closefile:
2009 closefile.write('is closed %d' % e.errno)
2010 """
2011 args = self.python_args('-c', script)
2012 pid = self.spawn_func(args[0], args, os.environ,
2013 file_actions=[(os.POSIX_SPAWN_CLOSE, 0)])
2014
2015 support.wait_process(pid, exitcode=0)
2016 with open(closefile, encoding="utf-8") as f:
2017 self.assertEqual(f.read(), 'is closed %d' % errno.EBADF)
2018
2019 def test_dup2(self):
2020 dupfile = os_helper.TESTFN
2021 self.addCleanup(os_helper.unlink, dupfile)
2022 script = """if 1:
2023 import sys
2024 sys.stdout.write("hello")
2025 """
2026 with open(dupfile, "wb") as childfile:
2027 file_actions = [
2028 (os.POSIX_SPAWN_DUP2, childfile.fileno(), 1),
2029 ]
2030 args = self.python_args('-c', script)
2031 pid = self.spawn_func(args[0], args, os.environ,
2032 file_actions=file_actions)
2033 support.wait_process(pid, exitcode=0)
2034 with open(dupfile, encoding="utf-8") as f:
2035 self.assertEqual(f.read(), 'hello')
2036
2037
2038 @unittest.skipUnless(hasattr(os, 'posix_spawn'), "test needs os.posix_spawn")
2039 class TestPosixSpawn(unittest.TestCase, _PosixSpawnMixin):
2040 spawn_func = getattr(posix, 'posix_spawn', None)
2041
2042
2043 @unittest.skipUnless(hasattr(os, 'posix_spawnp'), "test needs os.posix_spawnp")
2044 class TestPosixSpawnP(unittest.TestCase, _PosixSpawnMixin):
2045 spawn_func = getattr(posix, 'posix_spawnp', None)
2046
2047 @os_helper.skip_unless_symlink
2048 def test_posix_spawnp(self):
2049 # Use a symlink to create a program in its own temporary directory
2050 temp_dir = tempfile.mkdtemp()
2051 self.addCleanup(os_helper.rmtree, temp_dir)
2052
2053 program = 'posix_spawnp_test_program.exe'
2054 program_fullpath = os.path.join(temp_dir, program)
2055 os.symlink(sys.executable, program_fullpath)
2056
2057 try:
2058 path = os.pathsep.join((temp_dir, os.environ['PATH']))
2059 except KeyError:
2060 path = temp_dir # PATH is not set
2061
2062 spawn_args = (program, '-I', '-S', '-c', 'pass')
2063 code = textwrap.dedent("""
2064 import os
2065 from test import support
2066
2067 args = %a
2068 pid = os.posix_spawnp(args[0], args, os.environ)
2069
2070 support.wait_process(pid, exitcode=0)
2071 """ % (spawn_args,))
2072
2073 # Use a subprocess to test os.posix_spawnp() with a modified PATH
2074 # environment variable: posix_spawnp() uses the current environment
2075 # to locate the program, not its environment argument.
2076 args = ('-c', code)
2077 assert_python_ok(*args, PATH=path)
2078
2079
2080 @unittest.skipUnless(sys.platform == "darwin", "test weak linking on macOS")
2081 class TestPosixWeaklinking(unittest.TestCase):
2082 # These test cases verify that weak linking support on macOS works
2083 # as expected. These cases only test new behaviour introduced by weak linking,
2084 # regular behaviour is tested by the normal test cases.
2085 #
2086 # See the section on Weak Linking in Mac/README.txt for more information.
2087 def setUp(self):
2088 import sysconfig
2089 import platform
2090
2091 config_vars = sysconfig.get_config_vars()
2092 self.available = { nm for nm in config_vars if nm.startswith("HAVE_") and config_vars[nm] }
2093 self.mac_ver = tuple(int(part) for part in platform.mac_ver()[0].split("."))
2094
2095 def _verify_available(self, name):
2096 if name not in self.available:
2097 raise unittest.SkipTest(f"{name} not weak-linked")
2098
2099 def test_pwritev(self):
2100 self._verify_available("HAVE_PWRITEV")
2101 if self.mac_ver >= (10, 16):
2102 self.assertTrue(hasattr(os, "pwritev"), "os.pwritev is not available")
2103 self.assertTrue(hasattr(os, "preadv"), "os.readv is not available")
2104
2105 else:
2106 self.assertFalse(hasattr(os, "pwritev"), "os.pwritev is available")
2107 self.assertFalse(hasattr(os, "preadv"), "os.readv is available")
2108
2109 def test_stat(self):
2110 self._verify_available("HAVE_FSTATAT")
2111 if self.mac_ver >= (10, 10):
2112 self.assertIn("HAVE_FSTATAT", posix._have_functions)
2113
2114 else:
2115 self.assertNotIn("HAVE_FSTATAT", posix._have_functions)
2116
2117 with self.assertRaisesRegex(NotImplementedError, "dir_fd unavailable"):
2118 os.stat("file", dir_fd=0)
2119
2120 def test_access(self):
2121 self._verify_available("HAVE_FACCESSAT")
2122 if self.mac_ver >= (10, 10):
2123 self.assertIn("HAVE_FACCESSAT", posix._have_functions)
2124
2125 else:
2126 self.assertNotIn("HAVE_FACCESSAT", posix._have_functions)
2127
2128 with self.assertRaisesRegex(NotImplementedError, "dir_fd unavailable"):
2129 os.access("file", os.R_OK, dir_fd=0)
2130
2131 with self.assertRaisesRegex(NotImplementedError, "follow_symlinks unavailable"):
2132 os.access("file", os.R_OK, follow_symlinks=False)
2133
2134 with self.assertRaisesRegex(NotImplementedError, "effective_ids unavailable"):
2135 os.access("file", os.R_OK, effective_ids=True)
2136
2137 def test_chmod(self):
2138 self._verify_available("HAVE_FCHMODAT")
2139 if self.mac_ver >= (10, 10):
2140 self.assertIn("HAVE_FCHMODAT", posix._have_functions)
2141
2142 else:
2143 self.assertNotIn("HAVE_FCHMODAT", posix._have_functions)
2144 self.assertIn("HAVE_LCHMOD", posix._have_functions)
2145
2146 with self.assertRaisesRegex(NotImplementedError, "dir_fd unavailable"):
2147 os.chmod("file", 0o644, dir_fd=0)
2148
2149 def test_chown(self):
2150 self._verify_available("HAVE_FCHOWNAT")
2151 if self.mac_ver >= (10, 10):
2152 self.assertIn("HAVE_FCHOWNAT", posix._have_functions)
2153
2154 else:
2155 self.assertNotIn("HAVE_FCHOWNAT", posix._have_functions)
2156 self.assertIn("HAVE_LCHOWN", posix._have_functions)
2157
2158 with self.assertRaisesRegex(NotImplementedError, "dir_fd unavailable"):
2159 os.chown("file", 0, 0, dir_fd=0)
2160
2161 def test_link(self):
2162 self._verify_available("HAVE_LINKAT")
2163 if self.mac_ver >= (10, 10):
2164 self.assertIn("HAVE_LINKAT", posix._have_functions)
2165
2166 else:
2167 self.assertNotIn("HAVE_LINKAT", posix._have_functions)
2168
2169 with self.assertRaisesRegex(NotImplementedError, "src_dir_fd unavailable"):
2170 os.link("source", "target", src_dir_fd=0)
2171
2172 with self.assertRaisesRegex(NotImplementedError, "dst_dir_fd unavailable"):
2173 os.link("source", "target", dst_dir_fd=0)
2174
2175 with self.assertRaisesRegex(NotImplementedError, "src_dir_fd unavailable"):
2176 os.link("source", "target", src_dir_fd=0, dst_dir_fd=0)
2177
2178 # issue 41355: !HAVE_LINKAT code path ignores the follow_symlinks flag
2179 with os_helper.temp_dir() as base_path:
2180 link_path = os.path.join(base_path, "link")
2181 target_path = os.path.join(base_path, "target")
2182 source_path = os.path.join(base_path, "source")
2183
2184 with open(source_path, "w") as fp:
2185 fp.write("data")
2186
2187 os.symlink("target", link_path)
2188
2189 # Calling os.link should fail in the link(2) call, and
2190 # should not reject *follow_symlinks* (to match the
2191 # behaviour you'd get when building on a platform without
2192 # linkat)
2193 with self.assertRaises(FileExistsError):
2194 os.link(source_path, link_path, follow_symlinks=True)
2195
2196 with self.assertRaises(FileExistsError):
2197 os.link(source_path, link_path, follow_symlinks=False)
2198
2199
2200 def test_listdir_scandir(self):
2201 self._verify_available("HAVE_FDOPENDIR")
2202 if self.mac_ver >= (10, 10):
2203 self.assertIn("HAVE_FDOPENDIR", posix._have_functions)
2204
2205 else:
2206 self.assertNotIn("HAVE_FDOPENDIR", posix._have_functions)
2207
2208 with self.assertRaisesRegex(TypeError, "listdir: path should be string, bytes, os.PathLike or None, not int"):
2209 os.listdir(0)
2210
2211 with self.assertRaisesRegex(TypeError, "scandir: path should be string, bytes, os.PathLike or None, not int"):
2212 os.scandir(0)
2213
2214 def test_mkdir(self):
2215 self._verify_available("HAVE_MKDIRAT")
2216 if self.mac_ver >= (10, 10):
2217 self.assertIn("HAVE_MKDIRAT", posix._have_functions)
2218
2219 else:
2220 self.assertNotIn("HAVE_MKDIRAT", posix._have_functions)
2221
2222 with self.assertRaisesRegex(NotImplementedError, "dir_fd unavailable"):
2223 os.mkdir("dir", dir_fd=0)
2224
2225 def test_mkfifo(self):
2226 self._verify_available("HAVE_MKFIFOAT")
2227 if self.mac_ver >= (13, 0):
2228 self.assertIn("HAVE_MKFIFOAT", posix._have_functions)
2229
2230 else:
2231 self.assertNotIn("HAVE_MKFIFOAT", posix._have_functions)
2232
2233 with self.assertRaisesRegex(NotImplementedError, "dir_fd unavailable"):
2234 os.mkfifo("path", dir_fd=0)
2235
2236 def test_mknod(self):
2237 self._verify_available("HAVE_MKNODAT")
2238 if self.mac_ver >= (13, 0):
2239 self.assertIn("HAVE_MKNODAT", posix._have_functions)
2240
2241 else:
2242 self.assertNotIn("HAVE_MKNODAT", posix._have_functions)
2243
2244 with self.assertRaisesRegex(NotImplementedError, "dir_fd unavailable"):
2245 os.mknod("path", dir_fd=0)
2246
2247 def test_rename_replace(self):
2248 self._verify_available("HAVE_RENAMEAT")
2249 if self.mac_ver >= (10, 10):
2250 self.assertIn("HAVE_RENAMEAT", posix._have_functions)
2251
2252 else:
2253 self.assertNotIn("HAVE_RENAMEAT", posix._have_functions)
2254
2255 with self.assertRaisesRegex(NotImplementedError, "src_dir_fd and dst_dir_fd unavailable"):
2256 os.rename("a", "b", src_dir_fd=0)
2257
2258 with self.assertRaisesRegex(NotImplementedError, "src_dir_fd and dst_dir_fd unavailable"):
2259 os.rename("a", "b", dst_dir_fd=0)
2260
2261 with self.assertRaisesRegex(NotImplementedError, "src_dir_fd and dst_dir_fd unavailable"):
2262 os.replace("a", "b", src_dir_fd=0)
2263
2264 with self.assertRaisesRegex(NotImplementedError, "src_dir_fd and dst_dir_fd unavailable"):
2265 os.replace("a", "b", dst_dir_fd=0)
2266
2267 def test_unlink_rmdir(self):
2268 self._verify_available("HAVE_UNLINKAT")
2269 if self.mac_ver >= (10, 10):
2270 self.assertIn("HAVE_UNLINKAT", posix._have_functions)
2271
2272 else:
2273 self.assertNotIn("HAVE_UNLINKAT", posix._have_functions)
2274
2275 with self.assertRaisesRegex(NotImplementedError, "dir_fd unavailable"):
2276 os.unlink("path", dir_fd=0)
2277
2278 with self.assertRaisesRegex(NotImplementedError, "dir_fd unavailable"):
2279 os.rmdir("path", dir_fd=0)
2280
2281 def test_open(self):
2282 self._verify_available("HAVE_OPENAT")
2283 if self.mac_ver >= (10, 10):
2284 self.assertIn("HAVE_OPENAT", posix._have_functions)
2285
2286 else:
2287 self.assertNotIn("HAVE_OPENAT", posix._have_functions)
2288
2289 with self.assertRaisesRegex(NotImplementedError, "dir_fd unavailable"):
2290 os.open("path", os.O_RDONLY, dir_fd=0)
2291
2292 def test_readlink(self):
2293 self._verify_available("HAVE_READLINKAT")
2294 if self.mac_ver >= (10, 10):
2295 self.assertIn("HAVE_READLINKAT", posix._have_functions)
2296
2297 else:
2298 self.assertNotIn("HAVE_READLINKAT", posix._have_functions)
2299
2300 with self.assertRaisesRegex(NotImplementedError, "dir_fd unavailable"):
2301 os.readlink("path", dir_fd=0)
2302
2303 def test_symlink(self):
2304 self._verify_available("HAVE_SYMLINKAT")
2305 if self.mac_ver >= (10, 10):
2306 self.assertIn("HAVE_SYMLINKAT", posix._have_functions)
2307
2308 else:
2309 self.assertNotIn("HAVE_SYMLINKAT", posix._have_functions)
2310
2311 with self.assertRaisesRegex(NotImplementedError, "dir_fd unavailable"):
2312 os.symlink("a", "b", dir_fd=0)
2313
2314 def test_utime(self):
2315 self._verify_available("HAVE_FUTIMENS")
2316 self._verify_available("HAVE_UTIMENSAT")
2317 if self.mac_ver >= (10, 13):
2318 self.assertIn("HAVE_FUTIMENS", posix._have_functions)
2319 self.assertIn("HAVE_UTIMENSAT", posix._have_functions)
2320
2321 else:
2322 self.assertNotIn("HAVE_FUTIMENS", posix._have_functions)
2323 self.assertNotIn("HAVE_UTIMENSAT", posix._have_functions)
2324
2325 with self.assertRaisesRegex(NotImplementedError, "dir_fd unavailable"):
2326 os.utime("path", dir_fd=0)
2327
2328
2329 def tearDownModule():
2330 support.reap_children()
2331
2332
2333 if __name__ == '__main__':
2334 unittest.main()