Lines Matching full:os
1 # As a test suite for the os module, this is woefully inadequate, but this
14 import os
74 if hasattr(os, 'geteuid'):
75 root_in_posix = (os.geteuid() == 0)
87 HAVE_WHEEL_GROUP = sys.platform.startswith('freebsd') and os.getgid() == 0
91 return unittest.skipUnless(hasattr(os, name), 'requires os.%s' % name)
106 cwd = os.getcwd()
112 # longer path if longer paths support is enabled. Internally, the os
135 cwd = os.getcwd()
138 need = min_len - (len(cwd) + len(os.path.sep))
144 path = os.path.join(path, dirname)
146 os.mkdir(path)
149 os.chdir(path)
167 cwd = os.getcwdb()
169 self.assertEqual(os.fsdecode(cwd), os.getcwd())
175 if os.path.lexists(os_helper.TESTFN):
176 os.unlink(os_helper.TESTFN)
180 f = os.open(os_helper.TESTFN, os.O_CREAT|os.O_RDWR)
181 os.close(f)
182 self.assertTrue(os.access(os_helper.TESTFN, os.W_OK))
185 first = os.open(os_helper.TESTFN, os.O_CREAT|os.O_RDWR)
189 second = os.dup(first)
193 os.close(first)
198 first, second = second, os.dup(second)
200 os.close(second)
202 os.closerange(first, first + 2)
203 self.assertRaises(OSError, os.write, first, b"a")
209 self.assertRaises(TypeError, os.rename, path, 0)
218 os.lseek(fd, 0, 0)
219 s = os.read(fd, 4)
233 # Issue #21932: Make sure that os.read() does not raise an
236 data = os.read(fp.fileno(), size)
243 # os.write() accepts bytes- and buffer-like objects but not strings
244 fd = os.open(os_helper.TESTFN, os.O_CREAT | os.O_WRONLY)
245 self.assertRaises(TypeError, os.write, fd, "beans")
246 os.write(fd, b"bacon\n")
247 os.write(fd, bytearray(b"eggs\n"))
248 os.write(fd, memoryview(b"spam\n"))
249 os.close(fd)
274 fd = os.open(os_helper.TESTFN, os.O_RDONLY)
275 f = os.fdopen(fd, *args, encoding="utf-8")
279 fd = os.open(os_helper.TESTFN, os.O_CREAT|os.O_RDWR)
280 os.close(fd)
294 os.replace(os_helper.TESTFN, TESTFN2)
295 self.assertRaises(FileNotFoundError, os.stat, os_helper.TESTFN)
300 f = os.open(path=__file__, flags=os.O_RDONLY, mode=0o777,
302 os.close(f)
305 symlink = support.get_attribute(os, "symlink")
310 pass # No OS support or unprivileged user
312 @unittest.skipUnless(hasattr(os, 'copy_file_range'), 'test needs os.copy_file_range()')
315 os.copy_file_range(0, 1, -10)
317 @unittest.skipUnless(hasattr(os, 'copy_file_range'), 'test needs os.copy_file_range()')
335 i = os.copy_file_range(in_fd, out_fd, 5)
351 @unittest.skipUnless(hasattr(os, 'copy_file_range'), 'test needs os.copy_file_range()')
372 i = os.copy_file_range(in_fd, out_fd, bytes_to_copy,
396 @unittest.skipUnless(hasattr(os, 'splice'), 'test needs os.splice()')
399 os.splice(0, 1, -10)
401 @unittest.skipUnless(hasattr(os, 'splice'), 'test needs os.splice()')
414 read_fd, write_fd = os.pipe()
415 self.addCleanup(lambda: os.close(read_fd))
416 self.addCleanup(lambda: os.close(write_fd))
419 i = os.splice(in_fd, write_fd, 5)
432 self.assertEqual(os.read(read_fd, 100), data[:i])
434 @unittest.skipUnless(hasattr(os, 'splice'), 'test needs os.splice()')
449 read_fd, write_fd = os.pipe()
450 self.addCleanup(lambda: os.close(read_fd))
451 self.addCleanup(lambda: os.close(write_fd))
454 i = os.splice(in_fd, write_fd, bytes_to_copy, offset_src=in_skip)
467 read = os.read(read_fd, 100)
472 @unittest.skipUnless(hasattr(os, 'splice'), 'test needs os.splice()')
483 read_fd, write_fd = os.pipe()
484 self.addCleanup(lambda: os.close(read_fd))
485 self.addCleanup(lambda: os.close(write_fd))
486 os.write(write_fd, data)
494 i = os.splice(read_fd, out_fd, bytes_to_copy, offset_dst=out_seek)
516 # Test attributes on return values from os.*stat* family.
524 result = os.stat(fname)
577 result2 = os.stat_result((10,))
584 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
599 result = os.stat(self.fname)
608 @unittest.skipUnless(hasattr(os, 'statvfs'), 'test needs os.statvfs()')
610 result = os.statvfs(self.fname)
641 result2 = os.statvfs_result((10,))
648 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
652 @unittest.skipUnless(hasattr(os, 'statvfs'),
653 "need os.statvfs()")
655 result = os.statvfs(self.fname)
669 os.stat(r"c:\pagefile.sys")
676 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
679 r, w = os.pipe()
681 os.stat(r) # should not raise error
683 os.close(r)
684 os.close(w)
686 os.stat(r)
698 result = os.stat(self.fname)
706 os.mkdir(dirname)
707 self.addCleanup(os.rmdir, dirname)
709 result = os.stat(dirname)
719 # os.environ['TEMP'] should be located on a volume that
721 fname = os.path.join(os.environ['TEMP'], self.fname)
733 result = os.stat(fname)
738 # bpo-38030: os.stat fails for block devices
740 fname = "//./" + os.path.splitdrive(os.getcwd())[0]
741 result = os.stat(fname)
748 self.fname = os.path.join(self.dirname, "f1")
751 os.mkdir(self.dirname)
757 st = os.stat(filename)
770 # The resolution of the C internal function used by os.utime()
782 st = os.stat(filename)
796 os.utime(filename, ns=ns)
803 # issue, os.utime() rounds towards minus infinity.
814 os.utime(filename, (atime, mtime))
823 os.utime(filename, times=(atime, mtime))
826 @unittest.skipUnless(os.utime in os.supports_follow_symlinks,
833 os.utime(filename, ns=ns, follow_symlinks=False)
836 @unittest.skipUnless(os.utime in os.supports_fd,
843 os.utime(fp.fileno(), ns=ns)
846 @unittest.skipUnless(os.utime in os.supports_dir_fd,
850 dirname, name = os.path.split(filename)
853 os.utime(name, dir_fd=dirfd, ns=ns)
858 # test calling os.utime() on a directory
859 os.utime(filename, ns=ns)
866 # Call os.utime() to set the timestamp to the current system clock
878 st = os.stat(self.fname)
887 os.utime(self.fname)
893 os.utime(self.fname, None)
898 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
916 os.utime(self.fname, (large, large))
917 self.assertEqual(os.stat(self.fname).st_mtime, large)
922 os.utime(self.fname, (5, 5), ns=(5, 5))
924 os.utime(self.fname, [5, 5])
926 os.utime(self.fname, (5,))
928 os.utime(self.fname, (5, 5, 5))
930 os.utime(self.fname, ns=[5, 5])
932 os.utime(self.fname, ns=(5,))
934 os.utime(self.fname, ns=(5, 5, 5))
936 if os.utime not in os.supports_follow_symlinks:
938 os.utime(self.fname, (5, 5), follow_symlinks=False)
939 if os.utime not in os.supports_fd:
942 os.utime(fp.fileno(), (5, 5))
943 if os.utime not in os.supports_dir_fd:
945 os.utime(self.fname, (5, 5), dir_fd=0)
957 os.utime(self.fname, ns=(get_bad_int(42), 1))
959 os.utime(self.fname, ns=(get_bad_int(()), 1))
961 os.utime(self.fname, ns=(get_bad_int((1, 2, 3)), 1))
967 """check that os.environ object conform to mapping protocol"""
971 self.__save = dict(os.environ)
972 if os.supports_bytes_environ:
973 self.__saveb = dict(os.environb)
975 os.environ[key] = value
978 os.environ.clear()
979 os.environ.update(self.__save)
980 if os.supports_bytes_environ:
981 os.environb.clear()
982 os.environb.update(self.__saveb)
988 os.environ.clear()
989 return os.environ
992 @unittest.skipUnless(unix_shell and os.path.exists(unix_shell),
994 @unittest.skipUnless(hasattr(os, 'popen'), "needs os.popen()")
996 os.environ.clear()
997 os.environ.update(HELLO="World")
998 with os.popen("%s -c 'echo $HELLO'" % unix_shell) as popen:
1002 @unittest.skipUnless(unix_shell and os.path.exists(unix_shell),
1004 @unittest.skipUnless(hasattr(os, 'popen'), "needs os.popen()")
1006 with os.popen("%s -c 'echo \"line1\nline2\nline3\"'"
1014 # Verify environ keys and values from the OS are of the
1017 for key, val in os.environ.items():
1023 self.assertEqual(os.environ.get(key), value)
1027 """Check that the repr() of os.environ looks like environ({...})."""
1028 env = os.environ
1034 defpath_list = os.defpath.split(os.pathsep)
1036 test_env = {'PATH': os.pathsep.join(test_path)}
1038 saved_environ = os.environ
1040 os.environ = dict(test_env)
1041 # Test that defaulting to os.environ works.
1042 self.assertSequenceEqual(test_path, os.get_exec_path())
1043 self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
1045 os.environ = saved_environ
1048 self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
1050 self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
1052 self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
1054 if os.supports_bytes_environ:
1064 self.assertRaises(ValueError, os.get_exec_path, mixed_env)
1067 self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}),
1069 self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}),
1071 self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}),
1074 @unittest.skipUnless(os.supports_bytes_environ,
1075 "os.environb required for this test.")
1077 # os.environ -> os.environb
1086 os.environ['unicode'] = value
1087 self.assertEqual(os.environ['unicode'], value)
1088 self.assertEqual(os.environb[b'unicode'], value_bytes)
1090 # os.environb -> os.environ
1092 os.environb[b'bytes'] = value
1093 self.assertEqual(os.environb[b'bytes'], value)
1095 self.assertEqual(os.environ['bytes'], value_str)
1100 code = f'import os; print(repr(os.environ.get({name!r})))'
1105 os.putenv(name, value)
1110 os.unsetenv(name)
1115 # On OS X < 10.6, unsetenv() doesn't return a value (bpo-13415).
1121 self.assertRaises((OSError, ValueError), os.putenv, name, "value")
1122 self.assertRaises((OSError, ValueError), os.unsetenv, name)
1128 self.assertRaises(ValueError, os.putenv, longstr, "1")
1129 self.assertRaises(ValueError, os.putenv, "X", longstr)
1130 self.assertRaises(ValueError, os.unsetenv, longstr)
1134 self.assertNotIn(missing, os.environ)
1137 os.environ[missing]
1142 del os.environ[missing]
1150 next(iterator) # start iteration over os.environ.items
1152 # add a new key in os.environ mapping
1153 os.environ[new_key] = "test_environ_iteration"
1157 self.assertEqual(os.environ[new_key], "test_environ_iteration")
1159 del os.environ[new_key]
1162 self._test_environ_iteration(os.environ)
1165 self._test_environ_iteration(os.environ.items())
1168 self._test_environ_iteration(os.environ.values())
1171 if not (unix_shell and os.path.exists(unix_shell)):
1174 with os.popen(f"{unix_shell} -c 'echo ${var}'") as popen:
1182 os.environ[overridden_key] = original_value
1185 expected = dict(os.environ)
1188 actual = os.environ | new_vars_dict
1193 self.assertIs(NotImplemented, os.environ.__or__(new_vars_items))
1200 os.environ[overridden_key] = 'original_value'
1203 expected = dict(os.environ)
1206 os.environ |= new_vars_dict
1207 self.assertEqual(expected, os.environ)
1208 self.assertEqual('3', os.environ[overridden_key])
1214 os_environ_copy = os.environ.copy()
1217 os.environ |= dict_with_bad_key
1221 os.environ |= dict_with_bad_val
1224 self.assertEqual(os_environ_copy, os.environ)
1228 os.environ[overridden_key] = 'original_value'
1231 expected = dict(os.environ)
1234 os.environ |= new_vars_items
1235 self.assertEqual(expected, os.environ)
1236 self.assertEqual('3', os.environ[overridden_key])
1244 os.environ[overridden_key] = original_value
1248 expected.update(os.environ)
1250 actual = new_vars_dict | os.environ
1255 self.assertIs(NotImplemented, os.environ.__ror__(new_vars_items))
1262 """Tests for os.walk()."""
1264 # Wrapper to hide minor differences between os.walk and os.fwalk
1269 return os.walk(top, **kwargs)
1272 join = os.path.join
1309 os.makedirs(self.sub11_path)
1310 os.makedirs(sub2_path)
1311 os.makedirs(sub21_path)
1312 os.makedirs(t2_path)
1319 os.symlink(os.path.abspath(t2_path), self.link_path)
1320 os.symlink('broken', broken_link_path, True)
1321 os.symlink(join('tmp3', 'broken'), broken_link2_path, True)
1322 os.symlink(join('SUB21', 'tmp5'), broken_link3_path, True)
1329 os.chmod(sub21_path, 0)
1331 os.listdir(sub21_path)
1333 self.addCleanup(os.chmod, sub21_path, stat.S_IRWXU)
1335 os.chmod(sub21_path, stat.S_IRWXU)
1336 os.unlink(tmp5_path)
1337 os.rmdir(sub21_path)
1421 path1 = os.path.join(root, dir1)
1422 path1new = os.path.join(root, dir1 + '.new')
1423 os.rename(path1, path1new)
1431 self.assertIn(os.path.join(root, dir2), roots)
1433 os.rename(path1new, path1)
1437 base = os.path.join(os_helper.TESTFN, 'deep')
1438 p = os.path.join(base, *(['d']*depth))
1439 os.makedirs(p)
1446 p = os.path.dirname(p)
1454 p = os.path.join(p, 'd')
1457 @unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
1459 """Tests for os.fwalk()."""
1466 return os.fwalk(*args, **kwargs)
1479 for root, dirs, files in os.walk(**walk_kwargs):
1492 fd = os.open(".", os.O_RDONLY)
1498 os.close(fd)
1506 os.fstat(rootfd)
1508 os.stat(rootfd)
1510 self.assertEqual(set(os.listdir(rootfd)), set(dirs) | set(files))
1516 minfd = os.dup(1)
1517 os.close(minfd)
1521 newfd = os.dup(1)
1522 self.addCleanup(os.close, newfd)
1530 """Tests for os.walk() with bytes."""
1534 for broot, bdirs, bfiles in os.walk(os.fsencode(top), **kwargs):
1535 root = os.fsdecode(broot)
1536 dirs = list(map(os.fsdecode, bdirs))
1537 files = list(map(os.fsdecode, bfiles))
1539 bdirs[:] = list(map(os.fsencode, dirs))
1540 bfiles[:] = list(map(os.fsencode, files))
1542 @unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
1544 """Tests for os.walk() with bytes."""
1546 for broot, bdirs, bfiles, topfd in os.fwalk(os.fsencode(top), *args, **kwargs):
1547 root = os.fsdecode(broot)
1548 dirs = list(map(os.fsdecode, bdirs))
1549 files = list(map(os.fsdecode, bfiles))
1551 bdirs[:] = list(map(os.fsencode, dirs))
1552 bfiles[:] = list(map(os.fsencode, files))
1557 os.mkdir(os_helper.TESTFN)
1561 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
1562 os.makedirs(path) # Should work
1563 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
1564 os.makedirs(path)
1567 self.assertRaises(OSError, os.makedirs, os.curdir)
1568 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
1569 os.makedirs(path)
1570 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
1572 os.makedirs(path)
1577 parent = os.path.join(base, 'dir1')
1578 path = os.path.join(parent, 'dir2')
1579 os.makedirs(path, 0o555)
1580 self.assertTrue(os.path.exists(path))
1581 self.assertTrue(os.path.isdir(path))
1582 if os.name != 'nt':
1583 self.assertEqual(os.stat(path).st_mode & 0o777, 0o555)
1584 self.assertEqual(os.stat(parent).st_mode & 0o777, 0o775)
1587 path = os.path.join(os_helper.TESTFN, 'dir1')
1589 old_mask = os.umask(0o022)
1590 os.makedirs(path, mode)
1591 self.assertRaises(OSError, os.makedirs, path, mode)
1592 self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
1593 os.makedirs(path, 0o776, exist_ok=True)
1594 os.makedirs(path, mode=mode, exist_ok=True)
1595 os.umask(old_mask)
1598 os.makedirs(os.path.abspath('/'), exist_ok=True)
1601 path = os.path.join(os_helper.TESTFN, 'dir1')
1604 old_mask = os.umask(0o022)
1607 os.lstat(os_helper.TESTFN).st_mode)
1609 os.chmod(os_helper.TESTFN, existing_testfn_mode | S_ISGID)
1612 if (os.lstat(os_helper.TESTFN).st_mode & S_ISGID != S_ISGID):
1614 # The os should apply S_ISGID from the parent dir for us, but
1616 os.makedirs(path, mode | S_ISGID)
1619 os.makedirs(path, mode, exist_ok=True)
1621 os.chmod(path, stat.S_IMODE(os.lstat(path).st_mode) & ~S_ISGID)
1623 os.makedirs(path, mode | S_ISGID, exist_ok=True)
1625 os.umask(old_mask)
1629 path = os.path.join(os_helper.TESTFN, 'dir1')
1632 self.assertRaises(OSError, os.makedirs, path)
1633 self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
1634 self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
1635 os.remove(path)
1638 path = os.path.join(os_helper.TESTFN, 'dir1', 'dir2', 'dir3',
1643 while not os.path.exists(path) and path != os_helper.TESTFN:
1644 path = os.path.dirname(path)
1646 os.removedirs(path)
1649 @unittest.skipUnless(hasattr(os, 'chown'), "Test needs chown")
1654 os.mkdir(os_helper.TESTFN)
1657 stat = os.stat(os_helper.TESTFN)
1661 self.assertRaises(TypeError, os.chown, os_helper.TESTFN, value, gid)
1662 self.assertRaises(TypeError, os.chown, os_helper.TESTFN, uid, value)
1663 self.assertIsNone(os.chown(os_helper.TESTFN, uid, gid))
1664 self.assertIsNone(os.chown(os_helper.TESTFN, -1, -1))
1666 @unittest.skipUnless(hasattr(os, 'getgroups'), 'need os.getgroups')
1668 groups = os.getgroups()
1673 uid = os.stat(os_helper.TESTFN).st_uid
1675 os.chown(os_helper.TESTFN, uid, gid_1)
1676 gid = os.stat(os_helper.TESTFN).st_gid
1679 os.chown(os_helper.TESTFN, uid, gid_2)
1680 gid = os.stat(os_helper.TESTFN).st_gid
1687 gid = os.stat(os_helper.TESTFN).st_gid
1688 os.chown(os_helper.TESTFN, uid_1, gid)
1689 uid = os.stat(os_helper.TESTFN).st_uid
1691 os.chown(os_helper.TESTFN, uid_2, gid)
1692 uid = os.stat(os_helper.TESTFN).st_uid
1699 gid = os.stat(os_helper.TESTFN).st_gid
1701 os.chown(os_helper.TESTFN, uid_1, gid)
1702 os.chown(os_helper.TESTFN, uid_2, gid)
1706 os.rmdir(os_helper.TESTFN)
1711 os.makedirs(os_helper.TESTFN)
1717 dira = os.path.join(os_helper.TESTFN, 'dira')
1718 os.mkdir(dira)
1719 dirb = os.path.join(dira, 'dirb')
1720 os.mkdir(dirb)
1721 os.removedirs(dirb)
1722 self.assertFalse(os.path.exists(dirb))
1723 self.assertFalse(os.path.exists(dira))
1724 self.assertFalse(os.path.exists(os_helper.TESTFN))
1727 dira = os.path.join(os_helper.TESTFN, 'dira')
1728 os.mkdir(dira)
1729 dirb = os.path.join(dira, 'dirb')
1730 os.mkdir(dirb)
1731 create_file(os.path.join(dira, 'file.txt'))
1732 os.removedirs(dirb)
1733 self.assertFalse(os.path.exists(dirb))
1734 self.assertTrue(os.path.exists(dira))
1735 self.assertTrue(os.path.exists(os_helper.TESTFN))
1738 dira = os.path.join(os_helper.TESTFN, 'dira')
1739 os.mkdir(dira)
1740 dirb = os.path.join(dira, 'dirb')
1741 os.mkdir(dirb)
1742 create_file(os.path.join(dirb, 'file.txt'))
1744 os.removedirs(dirb)
1745 self.assertTrue(os.path.exists(dirb))
1746 self.assertTrue(os.path.exists(dira))
1747 self.assertTrue(os.path.exists(os_helper.TESTFN))
1752 with open(os.devnull, 'wb', 0) as f:
1755 with open(os.devnull, 'rb') as f:
1761 self.assertEqual(len(os.urandom(0)), 0)
1762 self.assertEqual(len(os.urandom(1)), 1)
1763 self.assertEqual(len(os.urandom(10)), 10)
1764 self.assertEqual(len(os.urandom(100)), 100)
1765 self.assertEqual(len(os.urandom(1000)), 1000)
1768 data1 = os.urandom(16)
1770 data2 = os.urandom(16)
1775 'import os, sys',
1776 'data = os.urandom(%s)' % count,
1790 @unittest.skipUnless(hasattr(os, 'getrandom'), 'need os.getrandom()')
1795 os.getrandom(1)
1805 data = os.getrandom(16)
1810 empty = os.getrandom(0)
1814 self.assertTrue(hasattr(os, 'GRND_RANDOM'))
1816 # Don't test os.getrandom(1, os.GRND_RANDOM) to not consume the rare
1822 os.getrandom(1, os.GRND_NONBLOCK)
1828 data1 = os.getrandom(16)
1829 data2 = os.getrandom(16)
1833 # os.urandom() doesn't use a file descriptor when it is implemented with the
1841 "os.random() does not use a file descriptor")
1850 # test suite would crash; this actually happened on the OS X Tiger
1854 import os
1860 os.urandom(16)
1872 import os
1875 os.urandom(4)
1877 os.closerange(3, 256)
1878 sys.stdout.buffer.write(os.urandom(4))
1889 import os
1892 os.urandom(4)
1896 os.close(fd)
1902 os.closerange(3, 256)
1909 os.dup2(new_fd, fd)
1910 sys.stdout.buffer.write(os.urandom(4))
1911 sys.stdout.buffer.write(os.urandom(4))
1941 orig_execv = os.execv
1942 orig_execve = os.execve
1943 orig_defpath = os.defpath
1944 os.execv = mock_execv
1945 os.execve = mock_execve
1947 os.defpath = defpath
1950 os.execv = orig_execv
1951 os.execve = orig_execve
1952 os.defpath = orig_defpath
1954 @unittest.skipUnless(hasattr(os, 'execv'),
1955 "need os.execv()")
1960 self.assertRaises(OSError, os.execvpe, 'no such app-',
1964 self.assertRaises(ValueError, os.execv, 'notepad', ())
1965 self.assertRaises(ValueError, os.execv, 'notepad', [])
1966 self.assertRaises(ValueError, os.execv, 'notepad', ('',))
1967 self.assertRaises(ValueError, os.execv, 'notepad', [''])
1970 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
1971 self.assertRaises(ValueError, os.execvpe, 'notepad', [], {})
1972 self.assertRaises(ValueError, os.execvpe, 'notepad', [''], {})
1974 @unittest.skipUnless(hasattr(os, '_execvpe'),
1975 "No internal os._execvpe function to test.")
1977 program_path = os.sep + 'absolutepath'
1980 fullpath = os.path.join(os.fsencode(program_path), program)
1986 fullpath = os.path.join(program_path, program)
1987 if os.name != "nt":
1988 native_fullpath = os.fsencode(fullpath)
1993 # test os._execvpe() with an absolute path
1996 os._execvpe, fullpath, arguments)
2000 # test os._execvpe() with a relative path:
2001 # os.get_exec_path() returns defpath
2004 os._execvpe, program, arguments, env=env)
2009 # test os._execvpe() with a relative path:
2010 # os.get_exec_path() reads the 'PATH' variable
2018 os._execvpe, program, arguments, env=env_path)
2025 if os.name != "nt":
2032 newenv = os.environ.copy()
2035 os.execve(args[0], args, newenv)
2038 newenv = os.environ.copy()
2041 os.execve(args[0], args, newenv)
2044 newenv = os.environ.copy()
2047 os.execve(args[0], args, newenv)
2053 os.execve('', ['arg'], {})
2064 os.stat(os_helper.TESTFN)
2069 self.fail("file %s must not exist; os.stat failed with %s"
2075 self.assertRaises(OSError, os.rename, os_helper.TESTFN, os_helper.TESTFN+".bak")
2078 self.assertRaises(OSError, os.remove, os_helper.TESTFN)
2081 self.assertRaises(OSError, os.chdir, os_helper.TESTFN)
2087 self.assertRaises(OSError, os.mkdir, os_helper.TESTFN)
2090 self.assertRaises(OSError, os.utime, os_helper.TESTFN, None)
2093 self.assertRaises(OSError, os.chmod, os_helper.TESTFN, 0)
2103 if hasattr(os, f):
2104 self.check(getattr(os, f))
2119 self.check(os.fdopen, encoding="utf-8")
2121 @unittest.skipUnless(hasattr(os, 'isatty'), 'test needs os.isatty()')
2123 self.assertEqual(os.isatty(os_helper.make_bad_fd()), False)
2125 @unittest.skipUnless(hasattr(os, 'closerange'), 'test needs os.closerange()')
2131 try: os.fstat(fd+i)
2139 self.assertEqual(os.closerange(fd, fd + i-1), None)
2141 @unittest.skipUnless(hasattr(os, 'dup2'), 'test needs os.dup2()')
2143 self.check(os.dup2, 20)
2145 @unittest.skipUnless(hasattr(os, 'fchmod'), 'test needs os.fchmod()')
2147 self.check(os.fchmod, 0)
2149 @unittest.skipUnless(hasattr(os, 'fchown'), 'test needs os.fchown()')
2151 self.check(os.fchown, -1, -1)
2153 @unittest.skipUnless(hasattr(os, 'fpathconf'), 'test needs os.fpathconf()')
2155 self.check(os.pathconf, "PC_NAME_MAX")
2156 self.check(os.fpathconf, "PC_NAME_MAX")
2158 @unittest.skipUnless(hasattr(os, 'ftruncate'), 'test needs os.ftruncate()')
2160 self.check(os.truncate, 0)
2161 self.check(os.ftruncate, 0)
2163 @unittest.skipUnless(hasattr(os, 'lseek'), 'test needs os.lseek()')
2165 self.check(os.lseek, 0, 0)
2167 @unittest.skipUnless(hasattr(os, 'read'), 'test needs os.read()')
2169 self.check(os.read, 1)
2171 @unittest.skipUnless(hasattr(os, 'readv'), 'test needs os.readv()')
2174 self.check(os.readv, [buf])
2176 @unittest.skipUnless(hasattr(os, 'tcsetpgrp'), 'test needs os.tcsetpgrp()')
2178 self.check(os.tcsetpgrp, 0)
2180 @unittest.skipUnless(hasattr(os, 'write'), 'test needs os.write()')
2182 self.check(os.write, b" ")
2184 @unittest.skipUnless(hasattr(os, 'writev'), 'test needs os.writev()')
2186 self.check(os.writev, [b'abc'])
2189 self.check(os.get_inheritable)
2190 self.check(os.set_inheritable, True)
2192 @unittest.skipUnless(hasattr(os, 'get_blocking'),
2193 'needs os.get_blocking() and os.set_blocking()')
2195 self.check(os.get_blocking)
2196 self.check(os.set_blocking, True)
2202 self.file2 = os.path.join(os_helper.TESTFN + "2")
2206 if os.path.exists(file):
2207 os.unlink(file)
2213 os.link(file1, file2)
2215 self.skipTest('os.link(): %s' % e)
2217 self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
2228 os.fsencode("\xf1")
2242 @unittest.skipUnless(hasattr(os, 'setuid'), 'test needs os.setuid()')
2244 if os.getuid() != 0:
2245 self.assertRaises(OSError, os.setuid, 0)
2246 self.assertRaises(TypeError, os.setuid, 'not an int')
2247 self.assertRaises(OverflowError, os.setuid, self.UID_OVERFLOW)
2249 @unittest.skipUnless(hasattr(os, 'setgid'), 'test needs os.setgid()')
2251 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
2252 self.assertRaises(OSError, os.setgid, 0)
2253 self.assertRaises(TypeError, os.setgid, 'not an int')
2254 self.assertRaises(OverflowError, os.setgid, self.GID_OVERFLOW)
2256 @unittest.skipUnless(hasattr(os, 'seteuid'), 'test needs os.seteuid()')
2258 if os.getuid() != 0:
2259 self.assertRaises(OSError, os.seteuid, 0)
2260 self.assertRaises(TypeError, os.setegid, 'not an int')
2261 self.assertRaises(OverflowError, os.seteuid, self.UID_OVERFLOW)
2263 @unittest.skipUnless(hasattr(os, 'setegid'), 'test needs os.setegid()')
2265 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
2266 self.assertRaises(OSError, os.setegid, 0)
2267 self.assertRaises(TypeError, os.setegid, 'not an int')
2268 self.assertRaises(OverflowError, os.setegid, self.GID_OVERFLOW)
2270 @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
2272 if os.getuid() != 0:
2273 self.assertRaises(OSError, os.setreuid, 0, 0)
2274 self.assertRaises(TypeError, os.setreuid, 'not an int', 0)
2275 self.assertRaises(TypeError, os.setreuid, 0, 'not an int')
2276 self.assertRaises(OverflowError, os.setreuid, self.UID_OVERFLOW, 0)
2277 self.assertRaises(OverflowError, os.setreuid, 0, self.UID_OVERFLOW)
2279 @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
2285 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
2287 @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
2289 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
2290 self.assertRaises(OSError, os.setregid, 0, 0)
2291 self.assertRaises(TypeError, os.setregid, 'not an int', 0)
2292 self.assertRaises(TypeError, os.setregid, 0, 'not an int')
2293 self.assertRaises(OverflowError, os.setregid, self.GID_OVERFLOW, 0)
2294 self.assertRaises(OverflowError, os.setregid, 0, self.GID_OVERFLOW)
2296 @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
2302 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
2313 self.bdir = os.fsencode(self.dir)
2318 fn = os.fsencode(fn)
2331 os.mkdir(self.dir)
2334 os_helper.create_empty_file(os.path.join(self.bdir, fn))
2335 fn = os.fsdecode(fn)
2348 found = set(os.listdir(self.dir))
2351 current_directory = os.getcwd()
2353 os.chdir(os.sep)
2354 self.assertEqual(set(os.listdir()), set(os.listdir(os.sep)))
2356 os.chdir(current_directory)
2360 f = open(os.path.join(self.dir, fn), 'rb')
2363 @unittest.skipUnless(hasattr(os, 'statvfs'),
2364 "need os.statvfs()")
2369 fullname = os.path.join(self.dir, fn)
2370 os.statvfs(fullname)
2374 os.stat(os.path.join(self.dir, fn))
2381 # becomes ready, send *sig* via os.kill to the subprocess and check
2429 os.kill(proc.pid, sig)
2437 # os.kill on Windows can take an int which gets set as the exit code
2446 os.path.join(os.path.dirname(__file__),
2458 os.kill(proc.pid, signal.SIGINT)
2460 os.kill(proc.pid, event)
2466 os.kill(proc.pid, signal.SIGINT)
2500 dir_path = os.path.join(os_helper.TESTFN, dir_name)
2502 file_path = os.path.join(os_helper.TESTFN, file_name)
2503 os.makedirs(dir_path)
2516 sorted(os.listdir(os_helper.TESTFN)),
2521 sorted(os.listdir(os.fsencode(os_helper.TESTFN))),
2522 [os.fsencode(path) for path in self.created_paths])
2528 path = '\\\\?\\' + os.path.abspath(os_helper.TESTFN)
2530 sorted(os.listdir(path)),
2534 path = b'\\\\?\\' + os.fsencode(os.path.abspath(os_helper.TESTFN))
2536 sorted(os.listdir(path)),
2537 [os.fsencode(path) for path in self.created_paths])
2540 @unittest.skipUnless(hasattr(os, 'readlink'), 'needs os.readlink()')
2543 filelink_target = os.path.abspath(__file__)
2544 filelinkb = os.fsencode(filelink)
2545 filelinkb_target = os.fsencode(filelink_target)
2548 left = os.path.normcase(left)
2549 right = os.path.normcase(right)
2562 self.assertTrue(os.path.exists(self.filelink_target))
2563 self.assertTrue(os.path.exists(self.filelinkb_target))
2564 self.assertFalse(os.path.exists(self.filelink))
2565 self.assertFalse(os.path.exists(self.filelinkb))
2569 self.assertRaises(OSError, os.readlink, self.filelink_target)
2570 self.assertRaises(OSError, os.readlink, filelink_target)
2573 self.assertRaises(FileNotFoundError, os.readlink, 'missing-link')
2574 self.assertRaises(FileNotFoundError, os.readlink,
2579 os.symlink(self.filelink_target, self.filelink)
2582 self.assertPathEqual(os.readlink(filelink), self.filelink_target)
2586 os.symlink(self.filelinkb_target, self.filelinkb)
2588 path = os.readlink(FakePath(self.filelinkb))
2594 os.symlink(self.filelinkb_target, self.filelinkb)
2596 path = os.readlink(self.filelinkb)
2605 filelink_target = os.path.abspath(__file__)
2607 dirlink_target = os.path.dirname(filelink_target)
2611 assert os.path.exists(self.dirlink_target)
2612 assert os.path.exists(self.filelink_target)
2613 assert not os.path.exists(self.dirlink)
2614 assert not os.path.exists(self.filelink)
2615 assert not os.path.exists(self.missing_link)
2618 if os.path.exists(self.filelink):
2619 os.remove(self.filelink)
2620 if os.path.exists(self.dirlink):
2621 os.rmdir(self.dirlink)
2622 if os.path.lexists(self.missing_link):
2623 os.remove(self.missing_link)
2626 os.symlink(self.dirlink_target, self.dirlink)
2627 self.assertTrue(os.path.exists(self.dirlink))
2628 self.assertTrue(os.path.isdir(self.dirlink))
2629 self.assertTrue(os.path.islink(self.dirlink))
2633 os.symlink(self.filelink_target, self.filelink)
2634 self.assertTrue(os.path.exists(self.filelink))
2635 self.assertTrue(os.path.isfile(self.filelink))
2636 self.assertTrue(os.path.islink(self.filelink))
2642 if os.path.lexists(linkname):
2643 os.remove(linkname)
2645 assert not os.path.exists(target)
2647 os.symlink(target, linkname, target_is_dir)
2651 # For compatibility with Unix, os.remove will check the
2654 os.remove(self.missing_link)
2658 self.assertFalse(os.path.isdir(self.missing_link))
2662 os.rmdir(self.missing_link)
2665 self.assertEqual(os.stat(link), os.stat(target))
2666 self.assertNotEqual(os.lstat(link), os.stat(link))
2668 bytes_link = os.fsencode(link)
2669 self.assertEqual(os.stat(bytes_link), os.stat(target))
2670 self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link))
2673 level1 = os.path.abspath(os_helper.TESTFN)
2674 level2 = os.path.join(level1, "level2")
2675 level3 = os.path.join(level2, "level3")
2678 os.mkdir(level1)
2679 os.mkdir(level2)
2680 os.mkdir(level3)
2682 file1 = os.path.abspath(os.path.join(level1, "file1"))
2685 orig_dir = os.getcwd()
2687 os.chdir(level2)
2688 link = os.path.join(level2, "link")
2689 os.symlink(os.path.relpath(file1), "link")
2690 self.assertIn("link", os.listdir(os.getcwd()))
2692 # Check os.stat calls from the same dir as the link
2693 self.assertEqual(os.stat(file1), os.stat("link"))
2695 # Check os.stat calls from a dir below the link
2696 os.chdir(level1)
2697 self.assertEqual(os.stat(file1),
2698 os.stat(os.path.relpath(link)))
2700 # Check os.stat calls from a dir above the link
2701 os.chdir(level3)
2702 self.assertEqual(os.stat(file1),
2703 os.stat(os.path.relpath(link)))
2705 os.chdir(orig_dir)
2707 @unittest.skipUnless(os.path.lexists(r'C:\Users\All Users')
2708 and os.path.exists(r'C:\ProgramData'),
2711 # os.symlink() calls CreateSymbolicLink, which creates
2719 target = os.readlink(r'C:\Users\All Users')
2720 self.assertTrue(os.path.samefile(target, r'C:\ProgramData'))
2727 path = os.path.join(*[segment] * 10)
2738 os.symlink(src, dest)
2743 os.remove(dest)
2748 os.symlink(os.fsencode(src), os.fsencode(dest))
2753 os.remove(dest)
2758 root = os.path.expandvars(r'%LOCALAPPDATA%\Microsoft\WindowsApps')
2759 if not os.path.isdir(root):
2762 aliases = [os.path.join(root, a)
2763 for a in fnmatch.filter(os.listdir(root), '*.exe')]
2769 st = os.lstat(alias)
2770 self.assertEqual(st, os.stat(alias))
2781 junction_target = os.path.dirname(os.path.abspath(__file__))
2784 assert os.path.exists(self.junction_target)
2785 assert not os.path.lexists(self.junction)
2788 if os.path.lexists(self.junction):
2789 os.unlink(self.junction)
2793 self.assertTrue(os.path.lexists(self.junction))
2794 self.assertTrue(os.path.exists(self.junction))
2795 self.assertTrue(os.path.isdir(self.junction))
2796 self.assertNotEqual(os.stat(self.junction), os.lstat(self.junction))
2797 self.assertEqual(os.stat(self.junction), os.stat(self.junction_target))
2800 self.assertFalse(os.path.islink(self.junction))
2801 self.assertEqual(os.path.normcase("\\\\?\\" + self.junction_target),
2802 os.path.normcase(os.readlink(self.junction)))
2806 self.assertTrue(os.path.exists(self.junction))
2807 self.assertTrue(os.path.lexists(self.junction))
2809 os.unlink(self.junction)
2810 self.assertFalse(os.path.exists(self.junction))
2851 os.stat(name)
2872 os.makedirs('base/some_dir')
2889 src = os.path.join('base', 'some_link')
2890 os.symlink('some_dir', src)
2891 assert os.path.isdir(src)
2896 self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
2897 self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
2903 bytesfn = os.fsencode(fn)
2906 self.assertEqual(os.fsdecode(bytesfn), fn)
2914 self.assertIsNone(os.device_encoding(123456))
2916 @unittest.skipUnless(os.isatty(0) and not win32_is_iot() and (sys.platform.startswith('win') or
2920 encoding = os.device_encoding(0)
2926 @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid")
2929 'import os; print(os.getppid())'],
2933 self.assertEqual(int(stdout), os.getpid())
2937 # On Windows, os.spawnv() simply joins arguments with spaces:
2942 pid = os.spawnv(os.P_NOWAIT, sys.executable, args)
2947 # don't use support.wait_process() to test directly os.waitpid()
2948 # and os.waitstatus_to_exitcode()
2949 pid2, status = os.waitpid(pid, 0)
2950 self.assertEqual(os.waitstatus_to_exitcode(status), exitcode)
2962 os.waitstatus_to_exitcode(0.0)
2966 # bpo-40138: test os.waitpid() and os.waitstatus_to_exitcode()
2976 self.assertEqual(os.waitstatus_to_exitcode(exitcode << 8),
2981 os.waitstatus_to_exitcode((max_exitcode + 1) << 8)
2983 os.waitstatus_to_exitcode(-1)
2992 os.kill(pid, signum)
3007 self.env = dict(os.environ)
3011 # read the variable from os.environ to check that it exists
3012 code = ('import sys, os; magic = os.environ[%r]; sys.exit(%s)'
3020 args = [os.fsencode(a) for a in args]
3021 self.env = {os.fsencode(k): os.fsencode(v)
3029 exitcode = os.spawnl(os.P_WAIT, args[0], *args)
3035 exitcode = os.spawnle(os.P_WAIT, args[0], *args, self.env)
3041 exitcode = os.spawnlp(os.P_WAIT, args[0], *args)
3047 exitcode = os.spawnlpe(os.P_WAIT, args[0], *args, self.env)
3053 exitcode = os.spawnv(os.P_WAIT, args[0], args)
3057 exitcode = os.spawnv(os.P_WAIT, FakePath(args[0]), args)
3063 exitcode = os.spawnve(os.P_WAIT, args[0], args, self.env)
3069 exitcode = os.spawnvp(os.P_WAIT, args[0], args)
3075 exitcode = os.spawnvpe(os.P_WAIT, args[0], args, self.env)
3081 pid = os.spawnv(os.P_NOWAIT, args[0], args)
3088 exitcode = os.spawnve(os.P_WAIT, args[0], args, self.env)
3094 self.assertRaises(ValueError, os.spawnl, os.P_NOWAIT, args[0])
3095 self.assertRaises(ValueError, os.spawnl, os.P_NOWAIT, args[0], '')
3100 self.assertRaises(ValueError, os.spawnle, os.P_NOWAIT, args[0], {})
3101 self.assertRaises(ValueError, os.spawnle, os.P_NOWAIT, args[0], '', {})
3106 self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, args[0], ())
3107 self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, args[0], [])
3108 self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, args[0], ('',))
3109 self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, args[0], [''])
3114 self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, args[0], (), {})
3115 self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, args[0], [], {})
3116 self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, args[0], ('',), {})
3117 self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, args[0], [''], {})
3123 newenv = os.environ.copy()
3126 exitcode = spawn(os.P_WAIT, args[0], args, newenv)
3133 newenv = os.environ.copy()
3136 exitcode = spawn(os.P_WAIT, args[0], args, newenv)
3143 newenv = os.environ.copy()
3146 exitcode = spawn(os.P_WAIT, args[0], args, newenv)
3156 fp.write('import sys, os\n'
3157 'if os.getenv("FRUIT") != "orange=lemon":\n'
3160 newenv = os.environ.copy()
3162 exitcode = spawn(os.P_WAIT, args[0], args, newenv)
3167 self._test_invalid_env(os.spawnve)
3171 self._test_invalid_env(os.spawnvpe)
3177 @unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin")
3180 user_name = os.getlogin()
3184 @unittest.skipUnless(hasattr(os, 'getpriority') and hasattr(os, 'setpriority'),
3185 "needs os.getpriority and os.setpriority")
3187 """Tests for os.getpriority() and os.setpriority()."""
3191 base = os.getpriority(os.PRIO_PROCESS, os.getpid())
3192 os.setpriority(os.PRIO_PROCESS, os.getpid(), base + 1)
3194 new_prio = os.getpriority(os.PRIO_PROCESS, os.getpid())
3202 os.setpriority(os.PRIO_PROCESS, os.getpid(), base)
3294 @unittest.skipUnless(hasattr(os, 'sendfile'), "test needs os.sendfile()")
3341 return os.sendfile(*args, **kwargs)
3401 sent = os.sendfile(self.sockno, self.fileno, offset, 4096)
3416 os.sendfile(self.sockno, self.fileno, -1, 4096)
3421 os.sendfile(out_fd=self.sockno, in_fd=self.fileno,
3424 os.sendfile(out_fd=self.sockno, in_fd=self.fileno,
3434 sent = os.sendfile(self.sockno, self.fileno, 0, 4096,
3464 os.sendfile(self.sockno, f.fileno(), 0, 5,
3476 os.sendfile(self.sockno, self.fileno, 0, 0,
3485 os.sendfile(self.sockno, self.fileno, 0, 0,
3490 @unittest.skipUnless(hasattr(os, 'SF_NODISKIO'),
3491 'test needs os.SF_NODISKIO')
3494 os.sendfile(self.sockno, self.fileno, 0, 4096,
3495 flags=os.SF_NODISKIO)
3502 if not hasattr(os, "setxattr"):
3508 os.setxattr(fp.fileno(), b"user.test", b"")
3540 setxattr(fn, s("user.test"), b"hello", os.XATTR_REPLACE, **kwargs)
3544 setxattr(fn, s("user.test"), b"bye", os.XATTR_CREATE, **kwargs)
3548 setxattr(fn, s("user.test2"), b"bye", os.XATTR_REPLACE, **kwargs)
3551 setxattr(fn, s("user.test2"), b"foo", os.XATTR_CREATE, **kwargs)
3575 self._check_xattrs_str(os.fsencode, *args, **kwargs)
3579 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
3580 os.listxattr)
3583 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
3584 os.listxattr, follow_symlinks=False)
3589 return os.getxattr(fp.fileno(), *args)
3592 os.setxattr(fp.fileno(), *args)
3595 os.removexattr(fp.fileno(), *args)
3598 return os.listxattr(fp.fileno(), *args)
3602 @unittest.skipUnless(hasattr(os, 'get_terminal_size'), "requires os.get_terminal_size")
3611 size = os.get_terminal_size()
3641 actual = os.get_terminal_size(sys.__stdin__.fileno())
3651 @unittest.skipUnless(hasattr(os, 'memfd_create'), 'requires os.memfd_create')
3655 fd = os.memfd_create("Hi", os.MFD_CLOEXEC)
3657 self.addCleanup(os.close, fd)
3658 self.assertFalse(os.get_inheritable(fd))
3663 fd2 = os.memfd_create("Hi")
3664 self.addCleanup(os.close, fd2)
3665 self.assertFalse(os.get_inheritable(fd2))
3668 @unittest.skipUnless(hasattr(os, 'eventfd'), 'requires os.eventfd')
3678 fd = os.eventfd(initval)
3680 self.addCleanup(os.close, fd)
3681 self.assertFalse(os.get_inheritable(fd))
3684 res = os.read(fd, size)
3687 os.write(fd, pack(23))
3688 res = os.read(fd, size)
3691 os.write(fd, pack(40))
3692 os.write(fd, pack(2))
3693 res = os.read(fd, size)
3697 os.eventfd_write(fd, 20)
3698 os.eventfd_write(fd, 3)
3699 res = os.eventfd_read(fd)
3704 flags = os.EFD_CLOEXEC | os.EFD_SEMAPHORE | os.EFD_NONBLOCK
3705 fd = os.eventfd(initval, flags)
3707 self.addCleanup(os.close, fd)
3710 res = os.eventfd_read(fd)
3712 res = os.eventfd_read(fd)
3716 os.eventfd_read(fd)
3718 os.read(fd, 8)
3721 os.eventfd_write(fd, 1)
3722 res = os.eventfd_read(fd)
3726 os.eventfd_read(fd)
3729 flags = os.EFD_CLOEXEC | os.EFD_NONBLOCK
3730 fd = os.eventfd(0, flags)
3732 self.addCleanup(os.close, fd)
3739 os.eventfd_write(fd, 23)
3742 self.assertEqual(os.eventfd_read(fd), 23)
3745 os.eventfd_write(fd, (2**64) - 2)
3748 os.eventfd_read(fd)
3767 encoded = os.fsencode(os_helper.TESTFN)
3776 (self.filenames, os.chdir,),
3777 (self.filenames, os.chmod, 0o777),
3778 (self.filenames, os.lstat,),
3779 (self.filenames, os.open, os.O_RDONLY),
3780 (self.filenames, os.rmdir,),
3781 (self.filenames, os.stat,),
3782 (self.filenames, os.unlink,),
3786 (self.bytes_filenames, os.rename, b"dst"),
3787 (self.bytes_filenames, os.replace, b"dst"),
3788 (self.unicode_filenames, os.rename, "dst"),
3789 (self.unicode_filenames, os.replace, "dst"),
3790 (self.unicode_filenames, os.listdir, ),
3794 (self.filenames, os.listdir,),
3795 (self.filenames, os.rename, "dst"),
3796 (self.filenames, os.replace, "dst"),
3798 if hasattr(os, "chown"):
3799 funcs.append((self.filenames, os.chown, 0, 0))
3800 if hasattr(os, "lchown"):
3801 funcs.append((self.filenames, os.lchown, 0, 0))
3802 if hasattr(os, "truncate"):
3803 funcs.append((self.filenames, os.truncate, 0))
3804 if hasattr(os, "chflags"):
3805 funcs.append((self.filenames, os.chflags, 0))
3806 if hasattr(os, "lchflags"):
3807 funcs.append((self.filenames, os.lchflags, 0))
3808 if hasattr(os, "chroot"):
3809 funcs.append((self.filenames, os.chroot,))
3810 if hasattr(os, "link"):
3812 funcs.append((self.bytes_filenames, os.link, b"dst"))
3813 funcs.append((self.unicode_filenames, os.link, "dst"))
3815 funcs.append((self.filenames, os.link, "dst"))
3816 if hasattr(os, "listxattr"):
3818 (self.filenames, os.listxattr,),
3819 (self.filenames, os.getxattr, "user.test"),
3820 (self.filenames, os.setxattr, "user.test", b'user'),
3821 (self.filenames, os.removexattr, "user.test"),
3823 if hasattr(os, "lchmod"):
3824 funcs.append((self.filenames, os.lchmod, 0o777))
3825 if hasattr(os, "readlink"):
3826 funcs.append((self.filenames, os.readlink,))
3846 cpus = os.cpu_count()
3856 fd = os.open(__file__, os.O_RDONLY)
3857 self.addCleanup(os.close, fd)
3858 self.assertEqual(os.get_inheritable(fd), False)
3860 os.set_inheritable(fd, True)
3861 self.assertEqual(os.get_inheritable(fd), True)
3865 fd = os.open(__file__, os.O_RDONLY)
3866 self.addCleanup(os.close, fd)
3867 self.assertEqual(os.get_inheritable(fd), False)
3874 self.assertEqual(os.get_inheritable(fd), True)
3878 fd = os.open(__file__, os.O_RDONLY)
3879 self.addCleanup(os.close, fd)
3883 os.set_inheritable(fd, True)
3887 @unittest.skipUnless(hasattr(os, 'O_PATH'), "need os.O_PATH")
3889 fd = os.open(__file__, os.O_PATH)
3890 self.addCleanup(os.close, fd)
3891 self.assertEqual(os.get_inheritable(fd), False)
3893 os.set_inheritable(fd, True)
3894 self.assertEqual(os.get_inheritable(fd), True)
3896 os.set_inheritable(fd, False)
3897 self.assertEqual(os.get_inheritable(fd), False)
3903 os.get_inheritable(fd)
3907 os.set_inheritable(fd, True)
3911 os.set_inheritable(fd, False)
3915 fd = os.open(__file__, os.O_RDONLY)
3916 self.addCleanup(os.close, fd)
3917 self.assertEqual(os.get_inheritable(fd), False)
3919 @unittest.skipUnless(hasattr(os, 'pipe'), "need os.pipe()")
3921 rfd, wfd = os.pipe()
3922 self.addCleanup(os.close, rfd)
3923 self.addCleanup(os.close, wfd)
3924 self.assertEqual(os.get_inheritable(rfd), False)
3925 self.assertEqual(os.get_inheritable(wfd), False)
3928 fd1 = os.open(__file__, os.O_RDONLY)
3929 self.addCleanup(os.close, fd1)
3931 fd2 = os.dup(fd1)
3932 self.addCleanup(os.close, fd2)
3933 self.assertEqual(os.get_inheritable(fd2), False)
3936 fd = os.dup(1)
3937 self.addCleanup(os.close, fd)
3942 # os.dup() was creating inheritable fds for character files.
3943 fd1 = os.open('NUL', os.O_RDONLY)
3944 self.addCleanup(os.close, fd1)
3945 fd2 = os.dup(fd1)
3946 self.addCleanup(os.close, fd2)
3947 self.assertFalse(os.get_inheritable(fd2))
3949 @unittest.skipUnless(hasattr(os, 'dup2'), "need os.dup2()")
3951 fd = os.open(__file__, os.O_RDONLY)
3952 self.addCleanup(os.close, fd)
3955 fd2 = os.open(__file__, os.O_RDONLY)
3956 self.addCleanup(os.close, fd2)
3957 self.assertEqual(os.dup2(fd, fd2), fd2)
3958 self.assertTrue(os.get_inheritable(fd2))
3961 fd3 = os.open(__file__, os.O_RDONLY)
3962 self.addCleanup(os.close, fd3)
3963 self.assertEqual(os.dup2(fd, fd3, inheritable=False), fd3)
3964 self.assertFalse(os.get_inheritable(fd3))
3966 @unittest.skipUnless(hasattr(os, 'openpty'), "need os.openpty()")
3968 master_fd, slave_fd = os.openpty()
3969 self.addCleanup(os.close, master_fd)
3970 self.addCleanup(os.close, slave_fd)
3971 self.assertEqual(os.get_inheritable(master_fd), False)
3972 self.assertEqual(os.get_inheritable(slave_fd), False)
3981 ('access', False, (os.F_OK,), None),
3984 ('open', False, (0,), getattr(os, 'close', None)),
3989 if os.name == 'nt':
3992 bytes_filename = os.fsencode(os_helper.TESTFN)
3994 fd = os.open(FakePath(str_filename), os.O_WRONLY|os.O_CREAT)
3996 self.addCleanup(os.close, fd)
4004 fn = getattr(os, name)
4028 'os.PathLike'):
4034 os.stat(FakePath(2))
4036 os.stat(FakePath(2.34))
4038 os.stat(FakePath(object()))
4041 @unittest.skipUnless(hasattr(os, 'get_blocking'),
4042 'needs os.get_blocking() and os.set_blocking()')
4045 fd = os.open(__file__, os.O_RDONLY)
4046 self.addCleanup(os.close, fd)
4047 self.assertEqual(os.get_blocking(fd), True)
4049 os.set_blocking(fd, False)
4050 self.assertEqual(os.get_blocking(fd), False)
4052 os.set_blocking(fd, True)
4053 self.assertEqual(os.get_blocking(fd), True)
4059 self.assertIn('open', os.__all__)
4060 self.assertIn('walk', os.__all__)
4065 self.path = os.path.realpath(os_helper.TESTFN)
4067 os.mkdir(self.path)
4070 self.assertRaises(TypeError, os.DirEntry)
4073 filename = create_file(os.path.join(self.path, "file.txt"), b'python')
4074 entry = [entry for entry in os.scandir(self.path)].pop()
4075 self.assertIsInstance(entry, os.DirEntry)
4085 self.path = os.path.realpath(os_helper.TESTFN)
4086 self.bytes_path = os.fsencode(self.path)
4088 os.mkdir(self.path)
4092 filename = os.path.join(path, name)
4098 for entry in os.scandir(self.path))
4116 scandir_iter = os.scandir(self.path)
4122 scandir_iter = os.scandir(self.path)
4128 self.assertIsInstance(entry, os.DirEntry)
4130 self.assertEqual(entry.path, os.path.join(self.path, name))
4132 os.stat(entry.path, follow_symlinks=False).st_ino)
4134 entry_stat = os.stat(entry.path)
4140 os.path.islink(entry.path))
4142 entry_lstat = os.stat(entry.path, follow_symlinks=False)
4150 os.name == 'nt' and not is_symlink)
4153 os.name == 'nt')
4156 link = hasattr(os, 'link')
4159 dirname = os.path.join(self.path, "dir")
4160 os.mkdir(dirname)
4164 os.link(filename, os.path.join(self.path, "link_file.txt"))
4166 self.skipTest('os.link(): %s' % e)
4168 os.symlink(dirname, os.path.join(self.path, "symlink_dir"),
4170 os.symlink(filename, os.path.join(self.path, "symlink_file.txt"))
4198 entries = list(os.scandir(path))
4207 return self.get_entry(os.path.basename(filename))
4211 old_dir = os.getcwd()
4213 os.chdir(self.path)
4217 entries = dict((entry.name, entry) for entry in os.scandir())
4219 [os.path.basename(filename)])
4221 os.chdir(old_dir)
4229 self.assertEqual(os.fspath(entry), os.path.join(self.path, 'file.txt'))
4232 bytes_filename = os.fsencode('bytesfile.txt')
4234 fspath = os.fspath(bytes_entry)
4237 os.path.join(os.fsencode(self.path),bytes_filename))
4240 path = os.path.join(self.path, 'dir')
4242 os.mkdir(path)
4244 os.rmdir(path)
4247 if os.name == 'nt':
4251 if os.name == 'nt':
4263 os.unlink(entry.path)
4267 if os.name == 'nt':
4270 if os.name == 'nt':
4285 os.symlink(filename,
4286 os.path.join(self.path, "symlink.txt"))
4289 os.unlink(filename)
4304 path_bytes = os.fsencode(self.path)
4305 entries = list(os.scandir(path_bytes))
4311 os.fsencode(os.path.join(self.path, 'file.txt')))
4317 path_bytes = cls(os.fsencode(self.path))
4319 entries = list(os.scandir(path_bytes))
4325 os.fsencode(os.path.join(self.path, 'file.txt')))
4329 @unittest.skipUnless(os.listdir in os.supports_fd,
4332 self.assertIn(os.scandir, os.supports_fd)
4336 os.symlink('file.txt', os.path.join(self.path, 'link'))
4340 with os.scandir(fd) as it:
4344 self.assertEqual(names, os.listdir(fd))
4347 self.assertEqual(os.fspath(entry), entry.name)
4349 if os.stat in os.supports_dir_fd:
4350 st = os.stat(entry.name, dir_fd=fd)
4352 st = os.stat(entry.name, dir_fd=fd, follow_symlinks=False)
4356 self.assertRaises(FileNotFoundError, os.scandir, '')
4360 iterator = os.scandir(self.path)
4371 self.assertRaises(TypeError, os.scandir, obj)
4376 iterator = os.scandir(self.path)
4387 with os.scandir(self.path) as iterator:
4395 with os.scandir(self.path) as iterator:
4403 with os.scandir(self.path) as iterator:
4412 iterator = os.scandir(self.path)
4418 iterator = os.scandir(self.path)
4428 fspath = staticmethod(os.fspath)
4443 self.assertEqual(b"path/like/object", os.fsencode(pathlike))
4444 self.assertEqual("path/like/object", os.fsdecode(pathlike))
4448 self.assertTrue(issubclass(FakePath, os.PathLike))
4449 self.assertTrue(isinstance(FakePath('x'), os.PathLike))
4453 for o in int, type, os, vapor():
4473 class A(os.PathLike):
4476 self.assertTrue(issubclass(FakePath, os.PathLike))
4479 self.assertIsInstance(os.PathLike[bytes], types.GenericAlias)
4484 times = os.times()
4485 self.assertIsInstance(times, os.times_result)
4492 if os.name == 'nt':
4501 # bpo-42540: ensure os.fork() with non-default memory allocator does
4504 import os
4506 pid = os.fork()
4516 if hasattr(os, "_fspath"):
4519 """Explicitly test the pure Python implementation of os.fspath()."""
4521 fspath = staticmethod(os._fspath)