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)
851 dirfd = os.open(dirname, os.O_RDONLY)
854 os.utime(name, dir_fd=dirfd, ns=ns)
856 os.close(dirfd)
861 # test calling os.utime() on a directory
862 os.utime(filename, ns=ns)
869 # Call os.utime() to set the timestamp to the current system clock
881 st = os.stat(self.fname)
890 os.utime(self.fname)
896 os.utime(self.fname, None)
901 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
919 os.utime(self.fname, (large, large))
920 self.assertEqual(os.stat(self.fname).st_mtime, large)
925 os.utime(self.fname, (5, 5), ns=(5, 5))
927 os.utime(self.fname, [5, 5])
929 os.utime(self.fname, (5,))
931 os.utime(self.fname, (5, 5, 5))
933 os.utime(self.fname, ns=[5, 5])
935 os.utime(self.fname, ns=(5,))
937 os.utime(self.fname, ns=(5, 5, 5))
939 if os.utime not in os.supports_follow_symlinks:
941 os.utime(self.fname, (5, 5), follow_symlinks=False)
942 if os.utime not in os.supports_fd:
945 os.utime(fp.fileno(), (5, 5))
946 if os.utime not in os.supports_dir_fd:
948 os.utime(self.fname, (5, 5), dir_fd=0)
960 os.utime(self.fname, ns=(get_bad_int(42), 1))
962 os.utime(self.fname, ns=(get_bad_int(()), 1))
964 os.utime(self.fname, ns=(get_bad_int((1, 2, 3)), 1))
970 """check that os.environ object conform to mapping protocol"""
974 self.__save = dict(os.environ)
975 if os.supports_bytes_environ:
976 self.__saveb = dict(os.environb)
978 os.environ[key] = value
981 os.environ.clear()
982 os.environ.update(self.__save)
983 if os.supports_bytes_environ:
984 os.environb.clear()
985 os.environb.update(self.__saveb)
991 os.environ.clear()
992 return os.environ
995 @unittest.skipUnless(unix_shell and os.path.exists(unix_shell),
997 @unittest.skipUnless(hasattr(os, 'popen'), "needs os.popen()")
999 os.environ.clear()
1000 os.environ.update(HELLO="World")
1001 with os.popen("%s -c 'echo $HELLO'" % unix_shell) as popen:
1005 @unittest.skipUnless(unix_shell and os.path.exists(unix_shell),
1007 @unittest.skipUnless(hasattr(os, 'popen'), "needs os.popen()")
1009 with os.popen("%s -c 'echo \"line1\nline2\nline3\"'"
1017 # Verify environ keys and values from the OS are of the
1020 for key, val in os.environ.items():
1026 self.assertEqual(os.environ.get(key), value)
1030 """Check that the repr() of os.environ looks like environ({...})."""
1031 env = os.environ
1037 defpath_list = os.defpath.split(os.pathsep)
1039 test_env = {'PATH': os.pathsep.join(test_path)}
1041 saved_environ = os.environ
1043 os.environ = dict(test_env)
1044 # Test that defaulting to os.environ works.
1045 self.assertSequenceEqual(test_path, os.get_exec_path())
1046 self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
1048 os.environ = saved_environ
1051 self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
1053 self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
1055 self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
1057 if os.supports_bytes_environ:
1067 self.assertRaises(ValueError, os.get_exec_path, mixed_env)
1070 self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}),
1072 self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}),
1074 self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}),
1077 @unittest.skipUnless(os.supports_bytes_environ,
1078 "os.environb required for this test.")
1080 # os.environ -> os.environb
1089 os.environ['unicode'] = value
1090 self.assertEqual(os.environ['unicode'], value)
1091 self.assertEqual(os.environb[b'unicode'], value_bytes)
1093 # os.environb -> os.environ
1095 os.environb[b'bytes'] = value
1096 self.assertEqual(os.environb[b'bytes'], value)
1098 self.assertEqual(os.environ['bytes'], value_str)
1103 code = f'import os; print(repr(os.environ.get({name!r})))'
1108 os.putenv(name, value)
1113 os.unsetenv(name)
1118 # On OS X < 10.6, unsetenv() doesn't return a value (bpo-13415).
1124 self.assertRaises((OSError, ValueError), os.putenv, name, "value")
1125 self.assertRaises((OSError, ValueError), os.unsetenv, name)
1131 self.assertRaises(ValueError, os.putenv, longstr, "1")
1132 self.assertRaises(ValueError, os.putenv, "X", longstr)
1133 self.assertRaises(ValueError, os.unsetenv, longstr)
1137 self.assertNotIn(missing, os.environ)
1140 os.environ[missing]
1145 del os.environ[missing]
1153 next(iterator) # start iteration over os.environ.items
1155 # add a new key in os.environ mapping
1156 os.environ[new_key] = "test_environ_iteration"
1160 self.assertEqual(os.environ[new_key], "test_environ_iteration")
1162 del os.environ[new_key]
1165 self._test_environ_iteration(os.environ)
1168 self._test_environ_iteration(os.environ.items())
1171 self._test_environ_iteration(os.environ.values())
1174 if not (unix_shell and os.path.exists(unix_shell)):
1177 with os.popen(f"{unix_shell} -c 'echo ${var}'") as popen:
1185 os.environ[overridden_key] = original_value
1188 expected = dict(os.environ)
1191 actual = os.environ | new_vars_dict
1196 self.assertIs(NotImplemented, os.environ.__or__(new_vars_items))
1203 os.environ[overridden_key] = 'original_value'
1206 expected = dict(os.environ)
1209 os.environ |= new_vars_dict
1210 self.assertEqual(expected, os.environ)
1211 self.assertEqual('3', os.environ[overridden_key])
1217 os_environ_copy = os.environ.copy()
1220 os.environ |= dict_with_bad_key
1224 os.environ |= dict_with_bad_val
1227 self.assertEqual(os_environ_copy, os.environ)
1231 os.environ[overridden_key] = 'original_value'
1234 expected = dict(os.environ)
1237 os.environ |= new_vars_items
1238 self.assertEqual(expected, os.environ)
1239 self.assertEqual('3', os.environ[overridden_key])
1247 os.environ[overridden_key] = original_value
1251 expected.update(os.environ)
1253 actual = new_vars_dict | os.environ
1258 self.assertIs(NotImplemented, os.environ.__ror__(new_vars_items))
1265 """Tests for os.walk()."""
1267 # Wrapper to hide minor differences between os.walk and os.fwalk
1272 return os.walk(top, **kwargs)
1275 join = os.path.join
1312 os.makedirs(self.sub11_path)
1313 os.makedirs(sub2_path)
1314 os.makedirs(sub21_path)
1315 os.makedirs(t2_path)
1322 os.symlink(os.path.abspath(t2_path), self.link_path)
1323 os.symlink('broken', broken_link_path, True)
1324 os.symlink(join('tmp3', 'broken'), broken_link2_path, True)
1325 os.symlink(join('SUB21', 'tmp5'), broken_link3_path, True)
1332 os.chmod(sub21_path, 0)
1334 os.listdir(sub21_path)
1336 self.addCleanup(os.chmod, sub21_path, stat.S_IRWXU)
1338 os.chmod(sub21_path, stat.S_IRWXU)
1339 os.unlink(tmp5_path)
1340 os.rmdir(sub21_path)
1424 path1 = os.path.join(root, dir1)
1425 path1new = os.path.join(root, dir1 + '.new')
1426 os.rename(path1, path1new)
1434 self.assertIn(os.path.join(root, dir2), roots)
1436 os.rename(path1new, path1)
1440 base = os.path.join(os_helper.TESTFN, 'deep')
1441 p = os.path.join(base, *(['d']*depth))
1442 os.makedirs(p)
1449 p = os.path.dirname(p)
1457 p = os.path.join(p, 'd')
1460 @unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
1462 """Tests for os.fwalk()."""
1469 return os.fwalk(*args, **kwargs)
1482 for root, dirs, files in os.walk(**walk_kwargs):
1495 fd = os.open(".", os.O_RDONLY)
1501 os.close(fd)
1509 os.fstat(rootfd)
1511 os.stat(rootfd)
1513 self.assertEqual(set(os.listdir(rootfd)), set(dirs) | set(files))
1519 minfd = os.dup(1)
1520 os.close(minfd)
1524 newfd = os.dup(1)
1525 self.addCleanup(os.close, newfd)
1533 """Tests for os.walk() with bytes."""
1537 for broot, bdirs, bfiles in os.walk(os.fsencode(top), **kwargs):
1538 root = os.fsdecode(broot)
1539 dirs = list(map(os.fsdecode, bdirs))
1540 files = list(map(os.fsdecode, bfiles))
1542 bdirs[:] = list(map(os.fsencode, dirs))
1543 bfiles[:] = list(map(os.fsencode, files))
1545 @unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
1547 """Tests for os.walk() with bytes."""
1549 for broot, bdirs, bfiles, topfd in os.fwalk(os.fsencode(top), *args, **kwargs):
1550 root = os.fsdecode(broot)
1551 dirs = list(map(os.fsdecode, bdirs))
1552 files = list(map(os.fsdecode, bfiles))
1554 bdirs[:] = list(map(os.fsencode, dirs))
1555 bfiles[:] = list(map(os.fsencode, files))
1560 os.mkdir(os_helper.TESTFN)
1564 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
1565 os.makedirs(path) # Should work
1566 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
1567 os.makedirs(path)
1570 self.assertRaises(OSError, os.makedirs, os.curdir)
1571 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
1572 os.makedirs(path)
1573 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
1575 os.makedirs(path)
1580 parent = os.path.join(base, 'dir1')
1581 path = os.path.join(parent, 'dir2')
1582 os.makedirs(path, 0o555)
1583 self.assertTrue(os.path.exists(path))
1584 self.assertTrue(os.path.isdir(path))
1585 if os.name != 'nt':
1586 self.assertEqual(os.stat(path).st_mode & 0o777, 0o555)
1587 self.assertEqual(os.stat(parent).st_mode & 0o777, 0o775)
1590 path = os.path.join(os_helper.TESTFN, 'dir1')
1592 old_mask = os.umask(0o022)
1593 os.makedirs(path, mode)
1594 self.assertRaises(OSError, os.makedirs, path, mode)
1595 self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
1596 os.makedirs(path, 0o776, exist_ok=True)
1597 os.makedirs(path, mode=mode, exist_ok=True)
1598 os.umask(old_mask)
1601 os.makedirs(os.path.abspath('/'), exist_ok=True)
1604 path = os.path.join(os_helper.TESTFN, 'dir1')
1607 old_mask = os.umask(0o022)
1610 os.lstat(os_helper.TESTFN).st_mode)
1612 os.chmod(os_helper.TESTFN, existing_testfn_mode | S_ISGID)
1615 if (os.lstat(os_helper.TESTFN).st_mode & S_ISGID != S_ISGID):
1617 # The os should apply S_ISGID from the parent dir for us, but
1619 os.makedirs(path, mode | S_ISGID)
1622 os.makedirs(path, mode, exist_ok=True)
1624 os.chmod(path, stat.S_IMODE(os.lstat(path).st_mode) & ~S_ISGID)
1626 os.makedirs(path, mode | S_ISGID, exist_ok=True)
1628 os.umask(old_mask)
1632 path = os.path.join(os_helper.TESTFN, 'dir1')
1635 self.assertRaises(OSError, os.makedirs, path)
1636 self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
1637 self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
1638 os.remove(path)
1641 path = os.path.join(os_helper.TESTFN, 'dir1', 'dir2', 'dir3',
1646 while not os.path.exists(path) and path != os_helper.TESTFN:
1647 path = os.path.dirname(path)
1649 os.removedirs(path)
1652 @unittest.skipUnless(hasattr(os, 'chown'), "Test needs chown")
1657 os.mkdir(os_helper.TESTFN)
1660 stat = os.stat(os_helper.TESTFN)
1664 self.assertRaises(TypeError, os.chown, os_helper.TESTFN, value, gid)
1665 self.assertRaises(TypeError, os.chown, os_helper.TESTFN, uid, value)
1666 self.assertIsNone(os.chown(os_helper.TESTFN, uid, gid))
1667 self.assertIsNone(os.chown(os_helper.TESTFN, -1, -1))
1669 @unittest.skipUnless(hasattr(os, 'getgroups'), 'need os.getgroups')
1671 groups = os.getgroups()
1676 uid = os.stat(os_helper.TESTFN).st_uid
1678 os.chown(os_helper.TESTFN, uid, gid_1)
1679 gid = os.stat(os_helper.TESTFN).st_gid
1682 os.chown(os_helper.TESTFN, uid, gid_2)
1683 gid = os.stat(os_helper.TESTFN).st_gid
1690 gid = os.stat(os_helper.TESTFN).st_gid
1691 os.chown(os_helper.TESTFN, uid_1, gid)
1692 uid = os.stat(os_helper.TESTFN).st_uid
1694 os.chown(os_helper.TESTFN, uid_2, gid)
1695 uid = os.stat(os_helper.TESTFN).st_uid
1702 gid = os.stat(os_helper.TESTFN).st_gid
1704 os.chown(os_helper.TESTFN, uid_1, gid)
1705 os.chown(os_helper.TESTFN, uid_2, gid)
1709 os.rmdir(os_helper.TESTFN)
1714 os.makedirs(os_helper.TESTFN)
1720 dira = os.path.join(os_helper.TESTFN, 'dira')
1721 os.mkdir(dira)
1722 dirb = os.path.join(dira, 'dirb')
1723 os.mkdir(dirb)
1724 os.removedirs(dirb)
1725 self.assertFalse(os.path.exists(dirb))
1726 self.assertFalse(os.path.exists(dira))
1727 self.assertFalse(os.path.exists(os_helper.TESTFN))
1730 dira = os.path.join(os_helper.TESTFN, 'dira')
1731 os.mkdir(dira)
1732 dirb = os.path.join(dira, 'dirb')
1733 os.mkdir(dirb)
1734 create_file(os.path.join(dira, 'file.txt'))
1735 os.removedirs(dirb)
1736 self.assertFalse(os.path.exists(dirb))
1737 self.assertTrue(os.path.exists(dira))
1738 self.assertTrue(os.path.exists(os_helper.TESTFN))
1741 dira = os.path.join(os_helper.TESTFN, 'dira')
1742 os.mkdir(dira)
1743 dirb = os.path.join(dira, 'dirb')
1744 os.mkdir(dirb)
1745 create_file(os.path.join(dirb, 'file.txt'))
1747 os.removedirs(dirb)
1748 self.assertTrue(os.path.exists(dirb))
1749 self.assertTrue(os.path.exists(dira))
1750 self.assertTrue(os.path.exists(os_helper.TESTFN))
1755 with open(os.devnull, 'wb', 0) as f:
1758 with open(os.devnull, 'rb') as f:
1764 self.assertEqual(len(os.urandom(0)), 0)
1765 self.assertEqual(len(os.urandom(1)), 1)
1766 self.assertEqual(len(os.urandom(10)), 10)
1767 self.assertEqual(len(os.urandom(100)), 100)
1768 self.assertEqual(len(os.urandom(1000)), 1000)
1771 data1 = os.urandom(16)
1773 data2 = os.urandom(16)
1778 'import os, sys',
1779 'data = os.urandom(%s)' % count,
1793 @unittest.skipUnless(hasattr(os, 'getrandom'), 'need os.getrandom()')
1798 os.getrandom(1)
1808 data = os.getrandom(16)
1813 empty = os.getrandom(0)
1817 self.assertTrue(hasattr(os, 'GRND_RANDOM'))
1819 # Don't test os.getrandom(1, os.GRND_RANDOM) to not consume the rare
1825 os.getrandom(1, os.GRND_NONBLOCK)
1831 data1 = os.getrandom(16)
1832 data2 = os.getrandom(16)
1836 # os.urandom() doesn't use a file descriptor when it is implemented with the
1844 "os.random() does not use a file descriptor")
1853 # test suite would crash; this actually happened on the OS X Tiger
1857 import os
1863 os.urandom(16)
1875 import os
1878 os.urandom(4)
1880 os.closerange(3, 256)
1881 sys.stdout.buffer.write(os.urandom(4))
1892 import os
1895 os.urandom(4)
1899 os.close(fd)
1905 os.closerange(3, 256)
1912 os.dup2(new_fd, fd)
1913 sys.stdout.buffer.write(os.urandom(4))
1914 sys.stdout.buffer.write(os.urandom(4))
1944 orig_execv = os.execv
1945 orig_execve = os.execve
1946 orig_defpath = os.defpath
1947 os.execv = mock_execv
1948 os.execve = mock_execve
1950 os.defpath = defpath
1953 os.execv = orig_execv
1954 os.execve = orig_execve
1955 os.defpath = orig_defpath
1957 @unittest.skipUnless(hasattr(os, 'execv'),
1958 "need os.execv()")
1963 self.assertRaises(OSError, os.execvpe, 'no such app-',
1967 self.assertRaises(ValueError, os.execv, 'notepad', ())
1968 self.assertRaises(ValueError, os.execv, 'notepad', [])
1969 self.assertRaises(ValueError, os.execv, 'notepad', ('',))
1970 self.assertRaises(ValueError, os.execv, 'notepad', [''])
1973 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
1974 self.assertRaises(ValueError, os.execvpe, 'notepad', [], {})
1975 self.assertRaises(ValueError, os.execvpe, 'notepad', [''], {})
1977 @unittest.skipUnless(hasattr(os, '_execvpe'),
1978 "No internal os._execvpe function to test.")
1980 program_path = os.sep + 'absolutepath'
1983 fullpath = os.path.join(os.fsencode(program_path), program)
1989 fullpath = os.path.join(program_path, program)
1990 if os.name != "nt":
1991 native_fullpath = os.fsencode(fullpath)
1996 # test os._execvpe() with an absolute path
1999 os._execvpe, fullpath, arguments)
2003 # test os._execvpe() with a relative path:
2004 # os.get_exec_path() returns defpath
2007 os._execvpe, program, arguments, env=env)
2012 # test os._execvpe() with a relative path:
2013 # os.get_exec_path() reads the 'PATH' variable
2021 os._execvpe, program, arguments, env=env_path)
2028 if os.name != "nt":
2035 newenv = os.environ.copy()
2038 os.execve(args[0], args, newenv)
2041 newenv = os.environ.copy()
2044 os.execve(args[0], args, newenv)
2047 newenv = os.environ.copy()
2050 os.execve(args[0], args, newenv)
2056 os.execve('', ['arg'], {})
2067 os.stat(os_helper.TESTFN)
2072 self.fail("file %s must not exist; os.stat failed with %s"
2078 self.assertRaises(OSError, os.rename, os_helper.TESTFN, os_helper.TESTFN+".bak")
2081 self.assertRaises(OSError, os.remove, os_helper.TESTFN)
2084 self.assertRaises(OSError, os.chdir, os_helper.TESTFN)
2090 self.assertRaises(OSError, os.mkdir, os_helper.TESTFN)
2093 self.assertRaises(OSError, os.utime, os_helper.TESTFN, None)
2096 self.assertRaises(OSError, os.chmod, os_helper.TESTFN, 0)
2106 if hasattr(os, f):
2107 self.check(getattr(os, f))
2122 self.check(os.fdopen, encoding="utf-8")
2124 @unittest.skipUnless(hasattr(os, 'isatty'), 'test needs os.isatty()')
2126 self.assertEqual(os.isatty(os_helper.make_bad_fd()), False)
2128 @unittest.skipUnless(hasattr(os, 'closerange'), 'test needs os.closerange()')
2134 try: os.fstat(fd+i)
2142 self.assertEqual(os.closerange(fd, fd + i-1), None)
2144 @unittest.skipUnless(hasattr(os, 'dup2'), 'test needs os.dup2()')
2146 self.check(os.dup2, 20)
2148 @unittest.skipUnless(hasattr(os, 'fchmod'), 'test needs os.fchmod()')
2150 self.check(os.fchmod, 0)
2152 @unittest.skipUnless(hasattr(os, 'fchown'), 'test needs os.fchown()')
2154 self.check(os.fchown, -1, -1)
2156 @unittest.skipUnless(hasattr(os, 'fpathconf'), 'test needs os.fpathconf()')
2158 self.check(os.pathconf, "PC_NAME_MAX")
2159 self.check(os.fpathconf, "PC_NAME_MAX")
2161 @unittest.skipUnless(hasattr(os, 'ftruncate'), 'test needs os.ftruncate()')
2163 self.check(os.truncate, 0)
2164 self.check(os.ftruncate, 0)
2166 @unittest.skipUnless(hasattr(os, 'lseek'), 'test needs os.lseek()')
2168 self.check(os.lseek, 0, 0)
2170 @unittest.skipUnless(hasattr(os, 'read'), 'test needs os.read()')
2172 self.check(os.read, 1)
2174 @unittest.skipUnless(hasattr(os, 'readv'), 'test needs os.readv()')
2177 self.check(os.readv, [buf])
2179 @unittest.skipUnless(hasattr(os, 'tcsetpgrp'), 'test needs os.tcsetpgrp()')
2181 self.check(os.tcsetpgrp, 0)
2183 @unittest.skipUnless(hasattr(os, 'write'), 'test needs os.write()')
2185 self.check(os.write, b" ")
2187 @unittest.skipUnless(hasattr(os, 'writev'), 'test needs os.writev()')
2189 self.check(os.writev, [b'abc'])
2192 self.check(os.get_inheritable)
2193 self.check(os.set_inheritable, True)
2195 @unittest.skipUnless(hasattr(os, 'get_blocking'),
2196 'needs os.get_blocking() and os.set_blocking()')
2198 self.check(os.get_blocking)
2199 self.check(os.set_blocking, True)
2205 self.file2 = os.path.join(os_helper.TESTFN + "2")
2209 if os.path.exists(file):
2210 os.unlink(file)
2216 os.link(file1, file2)
2218 self.skipTest('os.link(): %s' % e)
2220 self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
2231 os.fsencode("\xf1")
2245 @unittest.skipUnless(hasattr(os, 'setuid'), 'test needs os.setuid()')
2247 if os.getuid() != 0:
2248 self.assertRaises(OSError, os.setuid, 0)
2249 self.assertRaises(TypeError, os.setuid, 'not an int')
2250 self.assertRaises(OverflowError, os.setuid, self.UID_OVERFLOW)
2252 @unittest.skipUnless(hasattr(os, 'setgid'), 'test needs os.setgid()')
2254 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
2255 self.assertRaises(OSError, os.setgid, 0)
2256 self.assertRaises(TypeError, os.setgid, 'not an int')
2257 self.assertRaises(OverflowError, os.setgid, self.GID_OVERFLOW)
2259 @unittest.skipUnless(hasattr(os, 'seteuid'), 'test needs os.seteuid()')
2261 if os.getuid() != 0:
2262 self.assertRaises(OSError, os.seteuid, 0)
2263 self.assertRaises(TypeError, os.setegid, 'not an int')
2264 self.assertRaises(OverflowError, os.seteuid, self.UID_OVERFLOW)
2266 @unittest.skipUnless(hasattr(os, 'setegid'), 'test needs os.setegid()')
2268 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
2269 self.assertRaises(OSError, os.setegid, 0)
2270 self.assertRaises(TypeError, os.setegid, 'not an int')
2271 self.assertRaises(OverflowError, os.setegid, self.GID_OVERFLOW)
2273 @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
2275 if os.getuid() != 0:
2276 self.assertRaises(OSError, os.setreuid, 0, 0)
2277 self.assertRaises(TypeError, os.setreuid, 'not an int', 0)
2278 self.assertRaises(TypeError, os.setreuid, 0, 'not an int')
2279 self.assertRaises(OverflowError, os.setreuid, self.UID_OVERFLOW, 0)
2280 self.assertRaises(OverflowError, os.setreuid, 0, self.UID_OVERFLOW)
2282 @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
2288 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
2290 @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
2292 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
2293 self.assertRaises(OSError, os.setregid, 0, 0)
2294 self.assertRaises(TypeError, os.setregid, 'not an int', 0)
2295 self.assertRaises(TypeError, os.setregid, 0, 'not an int')
2296 self.assertRaises(OverflowError, os.setregid, self.GID_OVERFLOW, 0)
2297 self.assertRaises(OverflowError, os.setregid, 0, self.GID_OVERFLOW)
2299 @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
2305 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
2316 self.bdir = os.fsencode(self.dir)
2321 fn = os.fsencode(fn)
2334 os.mkdir(self.dir)
2337 os_helper.create_empty_file(os.path.join(self.bdir, fn))
2338 fn = os.fsdecode(fn)
2351 found = set(os.listdir(self.dir))
2354 current_directory = os.getcwd()
2356 os.chdir(os.sep)
2357 self.assertEqual(set(os.listdir()), set(os.listdir(os.sep)))
2359 os.chdir(current_directory)
2363 f = open(os.path.join(self.dir, fn), 'rb')
2366 @unittest.skipUnless(hasattr(os, 'statvfs'),
2367 "need os.statvfs()")
2372 fullname = os.path.join(self.dir, fn)
2373 os.statvfs(fullname)
2377 os.stat(os.path.join(self.dir, fn))
2384 # becomes ready, send *sig* via os.kill to the subprocess and check
2432 os.kill(proc.pid, sig)
2440 # os.kill on Windows can take an int which gets set as the exit code
2449 os.path.join(os.path.dirname(__file__),
2461 os.kill(proc.pid, signal.SIGINT)
2463 os.kill(proc.pid, event)
2469 os.kill(proc.pid, signal.SIGINT)
2503 dir_path = os.path.join(os_helper.TESTFN, dir_name)
2505 file_path = os.path.join(os_helper.TESTFN, file_name)
2506 os.makedirs(dir_path)
2519 sorted(os.listdir(os_helper.TESTFN)),
2524 sorted(os.listdir(os.fsencode(os_helper.TESTFN))),
2525 [os.fsencode(path) for path in self.created_paths])
2531 path = '\\\\?\\' + os.path.abspath(os_helper.TESTFN)
2533 sorted(os.listdir(path)),
2537 path = b'\\\\?\\' + os.fsencode(os.path.abspath(os_helper.TESTFN))
2539 sorted(os.listdir(path)),
2540 [os.fsencode(path) for path in self.created_paths])
2543 @unittest.skipUnless(hasattr(os, 'readlink'), 'needs os.readlink()')
2546 filelink_target = os.path.abspath(__file__)
2547 filelinkb = os.fsencode(filelink)
2548 filelinkb_target = os.fsencode(filelink_target)
2551 left = os.path.normcase(left)
2552 right = os.path.normcase(right)
2565 self.assertTrue(os.path.exists(self.filelink_target))
2566 self.assertTrue(os.path.exists(self.filelinkb_target))
2567 self.assertFalse(os.path.exists(self.filelink))
2568 self.assertFalse(os.path.exists(self.filelinkb))
2572 self.assertRaises(OSError, os.readlink, self.filelink_target)
2573 self.assertRaises(OSError, os.readlink, filelink_target)
2576 self.assertRaises(FileNotFoundError, os.readlink, 'missing-link')
2577 self.assertRaises(FileNotFoundError, os.readlink,
2582 os.symlink(self.filelink_target, self.filelink)
2585 self.assertPathEqual(os.readlink(filelink), self.filelink_target)
2589 os.symlink(self.filelinkb_target, self.filelinkb)
2591 path = os.readlink(FakePath(self.filelinkb))
2597 os.symlink(self.filelinkb_target, self.filelinkb)
2599 path = os.readlink(self.filelinkb)
2608 filelink_target = os.path.abspath(__file__)
2610 dirlink_target = os.path.dirname(filelink_target)
2614 assert os.path.exists(self.dirlink_target)
2615 assert os.path.exists(self.filelink_target)
2616 assert not os.path.exists(self.dirlink)
2617 assert not os.path.exists(self.filelink)
2618 assert not os.path.exists(self.missing_link)
2621 if os.path.exists(self.filelink):
2622 os.remove(self.filelink)
2623 if os.path.exists(self.dirlink):
2624 os.rmdir(self.dirlink)
2625 if os.path.lexists(self.missing_link):
2626 os.remove(self.missing_link)
2629 os.symlink(self.dirlink_target, self.dirlink)
2630 self.assertTrue(os.path.exists(self.dirlink))
2631 self.assertTrue(os.path.isdir(self.dirlink))
2632 self.assertTrue(os.path.islink(self.dirlink))
2636 os.symlink(self.filelink_target, self.filelink)
2637 self.assertTrue(os.path.exists(self.filelink))
2638 self.assertTrue(os.path.isfile(self.filelink))
2639 self.assertTrue(os.path.islink(self.filelink))
2645 if os.path.lexists(linkname):
2646 os.remove(linkname)
2648 assert not os.path.exists(target)
2650 os.symlink(target, linkname, target_is_dir)
2654 # For compatibility with Unix, os.remove will check the
2657 os.remove(self.missing_link)
2661 self.assertFalse(os.path.isdir(self.missing_link))
2665 os.rmdir(self.missing_link)
2668 self.assertEqual(os.stat(link), os.stat(target))
2669 self.assertNotEqual(os.lstat(link), os.stat(link))
2671 bytes_link = os.fsencode(link)
2672 self.assertEqual(os.stat(bytes_link), os.stat(target))
2673 self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link))
2676 level1 = os.path.abspath(os_helper.TESTFN)
2677 level2 = os.path.join(level1, "level2")
2678 level3 = os.path.join(level2, "level3")
2681 os.mkdir(level1)
2682 os.mkdir(level2)
2683 os.mkdir(level3)
2685 file1 = os.path.abspath(os.path.join(level1, "file1"))
2688 orig_dir = os.getcwd()
2690 os.chdir(level2)
2691 link = os.path.join(level2, "link")
2692 os.symlink(os.path.relpath(file1), "link")
2693 self.assertIn("link", os.listdir(os.getcwd()))
2695 # Check os.stat calls from the same dir as the link
2696 self.assertEqual(os.stat(file1), os.stat("link"))
2698 # Check os.stat calls from a dir below the link
2699 os.chdir(level1)
2700 self.assertEqual(os.stat(file1),
2701 os.stat(os.path.relpath(link)))
2703 # Check os.stat calls from a dir above the link
2704 os.chdir(level3)
2705 self.assertEqual(os.stat(file1),
2706 os.stat(os.path.relpath(link)))
2708 os.chdir(orig_dir)
2710 @unittest.skipUnless(os.path.lexists(r'C:\Users\All Users')
2711 and os.path.exists(r'C:\ProgramData'),
2714 # os.symlink() calls CreateSymbolicLink, which creates
2722 target = os.readlink(r'C:\Users\All Users')
2723 self.assertTrue(os.path.samefile(target, r'C:\ProgramData'))
2730 path = os.path.join(*[segment] * 10)
2741 os.symlink(src, dest)
2746 os.remove(dest)
2751 os.symlink(os.fsencode(src), os.fsencode(dest))
2756 os.remove(dest)
2761 root = os.path.expandvars(r'%LOCALAPPDATA%\Microsoft\WindowsApps')
2762 if not os.path.isdir(root):
2765 aliases = [os.path.join(root, a)
2766 for a in fnmatch.filter(os.listdir(root), '*.exe')]
2772 st = os.lstat(alias)
2773 self.assertEqual(st, os.stat(alias))
2784 junction_target = os.path.dirname(os.path.abspath(__file__))
2787 assert os.path.exists(self.junction_target)
2788 assert not os.path.lexists(self.junction)
2791 if os.path.lexists(self.junction):
2792 os.unlink(self.junction)
2796 self.assertTrue(os.path.lexists(self.junction))
2797 self.assertTrue(os.path.exists(self.junction))
2798 self.assertTrue(os.path.isdir(self.junction))
2799 self.assertNotEqual(os.stat(self.junction), os.lstat(self.junction))
2800 self.assertEqual(os.stat(self.junction), os.stat(self.junction_target))
2803 self.assertFalse(os.path.islink(self.junction))
2804 self.assertEqual(os.path.normcase("\\\\?\\" + self.junction_target),
2805 os.path.normcase(os.readlink(self.junction)))
2809 self.assertTrue(os.path.exists(self.junction))
2810 self.assertTrue(os.path.lexists(self.junction))
2812 os.unlink(self.junction)
2813 self.assertFalse(os.path.exists(self.junction))
2854 os.stat(name)
2875 os.makedirs('base/some_dir')
2892 src = os.path.join('base', 'some_link')
2893 os.symlink('some_dir', src)
2894 assert os.path.isdir(src)
2899 self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
2900 self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
2906 bytesfn = os.fsencode(fn)
2909 self.assertEqual(os.fsdecode(bytesfn), fn)
2917 self.assertIsNone(os.device_encoding(123456))
2919 @unittest.skipUnless(os.isatty(0) and not win32_is_iot() and (sys.platform.startswith('win') or
2923 encoding = os.device_encoding(0)
2929 @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid")
2932 'import os; print(os.getppid())'],
2936 self.assertEqual(int(stdout), os.getpid())
2940 # On Windows, os.spawnv() simply joins arguments with spaces:
2945 pid = os.spawnv(os.P_NOWAIT, sys.executable, args)
2950 # don't use support.wait_process() to test directly os.waitpid()
2951 # and os.waitstatus_to_exitcode()
2952 pid2, status = os.waitpid(pid, 0)
2953 self.assertEqual(os.waitstatus_to_exitcode(status), exitcode)
2965 os.waitstatus_to_exitcode(0.0)
2969 # bpo-40138: test os.waitpid() and os.waitstatus_to_exitcode()
2979 self.assertEqual(os.waitstatus_to_exitcode(exitcode << 8),
2984 os.waitstatus_to_exitcode((max_exitcode + 1) << 8)
2986 os.waitstatus_to_exitcode(-1)
2995 os.kill(pid, signum)
3010 self.env = dict(os.environ)
3014 # read the variable from os.environ to check that it exists
3015 code = ('import sys, os; magic = os.environ[%r]; sys.exit(%s)'
3023 args = [os.fsencode(a) for a in args]
3024 self.env = {os.fsencode(k): os.fsencode(v)
3032 exitcode = os.spawnl(os.P_WAIT, args[0], *args)
3038 exitcode = os.spawnle(os.P_WAIT, args[0], *args, self.env)
3044 exitcode = os.spawnlp(os.P_WAIT, args[0], *args)
3050 exitcode = os.spawnlpe(os.P_WAIT, args[0], *args, self.env)
3056 exitcode = os.spawnv(os.P_WAIT, args[0], args)
3060 exitcode = os.spawnv(os.P_WAIT, FakePath(args[0]), args)
3066 exitcode = os.spawnve(os.P_WAIT, args[0], args, self.env)
3072 exitcode = os.spawnvp(os.P_WAIT, args[0], args)
3078 exitcode = os.spawnvpe(os.P_WAIT, args[0], args, self.env)
3084 pid = os.spawnv(os.P_NOWAIT, args[0], args)
3091 exitcode = os.spawnve(os.P_WAIT, args[0], args, self.env)
3097 self.assertRaises(ValueError, os.spawnl, os.P_NOWAIT, args[0])
3098 self.assertRaises(ValueError, os.spawnl, os.P_NOWAIT, args[0], '')
3103 self.assertRaises(ValueError, os.spawnle, os.P_NOWAIT, args[0], {})
3104 self.assertRaises(ValueError, os.spawnle, os.P_NOWAIT, args[0], '', {})
3109 self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, args[0], ())
3110 self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, args[0], [])
3111 self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, args[0], ('',))
3112 self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, args[0], [''])
3117 self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, args[0], (), {})
3118 self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, args[0], [], {})
3119 self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, args[0], ('',), {})
3120 self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, args[0], [''], {})
3126 newenv = os.environ.copy()
3129 exitcode = spawn(os.P_WAIT, args[0], args, newenv)
3136 newenv = os.environ.copy()
3139 exitcode = spawn(os.P_WAIT, args[0], args, newenv)
3146 newenv = os.environ.copy()
3149 exitcode = spawn(os.P_WAIT, args[0], args, newenv)
3159 fp.write('import sys, os\n'
3160 'if os.getenv("FRUIT") != "orange=lemon":\n'
3163 newenv = os.environ.copy()
3165 exitcode = spawn(os.P_WAIT, args[0], args, newenv)
3170 self._test_invalid_env(os.spawnve)
3174 self._test_invalid_env(os.spawnvpe)
3180 @unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin")
3183 user_name = os.getlogin()
3187 @unittest.skipUnless(hasattr(os, 'getpriority') and hasattr(os, 'setpriority'),
3188 "needs os.getpriority and os.setpriority")
3190 """Tests for os.getpriority() and os.setpriority()."""
3194 base = os.getpriority(os.PRIO_PROCESS, os.getpid())
3195 os.setpriority(os.PRIO_PROCESS, os.getpid(), base + 1)
3197 new_prio = os.getpriority(os.PRIO_PROCESS, os.getpid())
3205 os.setpriority(os.PRIO_PROCESS, os.getpid(), base)
3297 @unittest.skipUnless(hasattr(os, 'sendfile'), "test needs os.sendfile()")
3344 return os.sendfile(*args, **kwargs)
3404 sent = os.sendfile(self.sockno, self.fileno, offset, 4096)
3419 os.sendfile(self.sockno, self.fileno, -1, 4096)
3424 os.sendfile(out_fd=self.sockno, in_fd=self.fileno,
3427 os.sendfile(out_fd=self.sockno, in_fd=self.fileno,
3437 sent = os.sendfile(self.sockno, self.fileno, 0, 4096,
3467 os.sendfile(self.sockno, f.fileno(), 0, 5,
3479 os.sendfile(self.sockno, self.fileno, 0, 0,
3488 os.sendfile(self.sockno, self.fileno, 0, 0,
3493 @unittest.skipUnless(hasattr(os, 'SF_NODISKIO'),
3494 'test needs os.SF_NODISKIO')
3497 os.sendfile(self.sockno, self.fileno, 0, 4096,
3498 flags=os.SF_NODISKIO)
3505 if not hasattr(os, "setxattr"):
3511 os.setxattr(fp.fileno(), b"user.test", b"")
3543 setxattr(fn, s("user.test"), b"hello", os.XATTR_REPLACE, **kwargs)
3547 setxattr(fn, s("user.test"), b"bye", os.XATTR_CREATE, **kwargs)
3551 setxattr(fn, s("user.test2"), b"bye", os.XATTR_REPLACE, **kwargs)
3554 setxattr(fn, s("user.test2"), b"foo", os.XATTR_CREATE, **kwargs)
3578 self._check_xattrs_str(os.fsencode, *args, **kwargs)
3582 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
3583 os.listxattr)
3586 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
3587 os.listxattr, follow_symlinks=False)
3592 return os.getxattr(fp.fileno(), *args)
3595 os.setxattr(fp.fileno(), *args)
3598 os.removexattr(fp.fileno(), *args)
3601 return os.listxattr(fp.fileno(), *args)
3605 @unittest.skipUnless(hasattr(os, 'get_terminal_size'), "requires os.get_terminal_size")
3614 size = os.get_terminal_size()
3644 actual = os.get_terminal_size(sys.__stdin__.fileno())
3654 @unittest.skipUnless(hasattr(os, 'memfd_create'), 'requires os.memfd_create')
3658 fd = os.memfd_create("Hi", os.MFD_CLOEXEC)
3660 self.addCleanup(os.close, fd)
3661 self.assertFalse(os.get_inheritable(fd))
3666 fd2 = os.memfd_create("Hi")
3667 self.addCleanup(os.close, fd2)
3668 self.assertFalse(os.get_inheritable(fd2))
3671 @unittest.skipUnless(hasattr(os, 'eventfd'), 'requires os.eventfd')
3681 fd = os.eventfd(initval)
3683 self.addCleanup(os.close, fd)
3684 self.assertFalse(os.get_inheritable(fd))
3687 res = os.read(fd, size)
3690 os.write(fd, pack(23))
3691 res = os.read(fd, size)
3694 os.write(fd, pack(40))
3695 os.write(fd, pack(2))
3696 res = os.read(fd, size)
3700 os.eventfd_write(fd, 20)
3701 os.eventfd_write(fd, 3)
3702 res = os.eventfd_read(fd)
3707 flags = os.EFD_CLOEXEC | os.EFD_SEMAPHORE | os.EFD_NONBLOCK
3708 fd = os.eventfd(initval, flags)
3710 self.addCleanup(os.close, fd)
3713 res = os.eventfd_read(fd)
3715 res = os.eventfd_read(fd)
3719 os.eventfd_read(fd)
3721 os.read(fd, 8)
3724 os.eventfd_write(fd, 1)
3725 res = os.eventfd_read(fd)
3729 os.eventfd_read(fd)
3732 flags = os.EFD_CLOEXEC | os.EFD_NONBLOCK
3733 fd = os.eventfd(0, flags)
3735 self.addCleanup(os.close, fd)
3742 os.eventfd_write(fd, 23)
3745 self.assertEqual(os.eventfd_read(fd), 23)
3748 os.eventfd_write(fd, (2**64) - 2)
3751 os.eventfd_read(fd)
3770 encoded = os.fsencode(os_helper.TESTFN)
3779 (self.filenames, os.chdir,),
3780 (self.filenames, os.chmod, 0o777),
3781 (self.filenames, os.lstat,),
3782 (self.filenames, os.open, os.O_RDONLY),
3783 (self.filenames, os.rmdir,),
3784 (self.filenames, os.stat,),
3785 (self.filenames, os.unlink,),
3789 (self.bytes_filenames, os.rename, b"dst"),
3790 (self.bytes_filenames, os.replace, b"dst"),
3791 (self.unicode_filenames, os.rename, "dst"),
3792 (self.unicode_filenames, os.replace, "dst"),
3793 (self.unicode_filenames, os.listdir, ),
3797 (self.filenames, os.listdir,),
3798 (self.filenames, os.rename, "dst"),
3799 (self.filenames, os.replace, "dst"),
3801 if hasattr(os, "chown"):
3802 funcs.append((self.filenames, os.chown, 0, 0))
3803 if hasattr(os, "lchown"):
3804 funcs.append((self.filenames, os.lchown, 0, 0))
3805 if hasattr(os, "truncate"):
3806 funcs.append((self.filenames, os.truncate, 0))
3807 if hasattr(os, "chflags"):
3808 funcs.append((self.filenames, os.chflags, 0))
3809 if hasattr(os, "lchflags"):
3810 funcs.append((self.filenames, os.lchflags, 0))
3811 if hasattr(os, "chroot"):
3812 funcs.append((self.filenames, os.chroot,))
3813 if hasattr(os, "link"):
3815 funcs.append((self.bytes_filenames, os.link, b"dst"))
3816 funcs.append((self.unicode_filenames, os.link, "dst"))
3818 funcs.append((self.filenames, os.link, "dst"))
3819 if hasattr(os, "listxattr"):
3821 (self.filenames, os.listxattr,),
3822 (self.filenames, os.getxattr, "user.test"),
3823 (self.filenames, os.setxattr, "user.test", b'user'),
3824 (self.filenames, os.removexattr, "user.test"),
3826 if hasattr(os, "lchmod"):
3827 funcs.append((self.filenames, os.lchmod, 0o777))
3828 if hasattr(os, "readlink"):
3829 funcs.append((self.filenames, os.readlink,))
3849 cpus = os.cpu_count()
3859 fd = os.open(__file__, os.O_RDONLY)
3860 self.addCleanup(os.close, fd)
3861 self.assertEqual(os.get_inheritable(fd), False)
3863 os.set_inheritable(fd, True)
3864 self.assertEqual(os.get_inheritable(fd), True)
3868 fd = os.open(__file__, os.O_RDONLY)
3869 self.addCleanup(os.close, fd)
3870 self.assertEqual(os.get_inheritable(fd), False)
3877 self.assertEqual(os.get_inheritable(fd), True)
3881 fd = os.open(__file__, os.O_RDONLY)
3882 self.addCleanup(os.close, fd)
3886 os.set_inheritable(fd, True)
3890 @unittest.skipUnless(hasattr(os, 'O_PATH'), "need os.O_PATH")
3892 fd = os.open(__file__, os.O_PATH)
3893 self.addCleanup(os.close, fd)
3894 self.assertEqual(os.get_inheritable(fd), False)
3896 os.set_inheritable(fd, True)
3897 self.assertEqual(os.get_inheritable(fd), True)
3899 os.set_inheritable(fd, False)
3900 self.assertEqual(os.get_inheritable(fd), False)
3906 os.get_inheritable(fd)
3910 os.set_inheritable(fd, True)
3914 os.set_inheritable(fd, False)
3918 fd = os.open(__file__, os.O_RDONLY)
3919 self.addCleanup(os.close, fd)
3920 self.assertEqual(os.get_inheritable(fd), False)
3922 @unittest.skipUnless(hasattr(os, 'pipe'), "need os.pipe()")
3924 rfd, wfd = os.pipe()
3925 self.addCleanup(os.close, rfd)
3926 self.addCleanup(os.close, wfd)
3927 self.assertEqual(os.get_inheritable(rfd), False)
3928 self.assertEqual(os.get_inheritable(wfd), False)
3931 fd1 = os.open(__file__, os.O_RDONLY)
3932 self.addCleanup(os.close, fd1)
3934 fd2 = os.dup(fd1)
3935 self.addCleanup(os.close, fd2)
3936 self.assertEqual(os.get_inheritable(fd2), False)
3939 fd = os.dup(1)
3940 self.addCleanup(os.close, fd)
3945 # os.dup() was creating inheritable fds for character files.
3946 fd1 = os.open('NUL', os.O_RDONLY)
3947 self.addCleanup(os.close, fd1)
3948 fd2 = os.dup(fd1)
3949 self.addCleanup(os.close, fd2)
3950 self.assertFalse(os.get_inheritable(fd2))
3952 @unittest.skipUnless(hasattr(os, 'dup2'), "need os.dup2()")
3954 fd = os.open(__file__, os.O_RDONLY)
3955 self.addCleanup(os.close, fd)
3958 fd2 = os.open(__file__, os.O_RDONLY)
3959 self.addCleanup(os.close, fd2)
3960 self.assertEqual(os.dup2(fd, fd2), fd2)
3961 self.assertTrue(os.get_inheritable(fd2))
3964 fd3 = os.open(__file__, os.O_RDONLY)
3965 self.addCleanup(os.close, fd3)
3966 self.assertEqual(os.dup2(fd, fd3, inheritable=False), fd3)
3967 self.assertFalse(os.get_inheritable(fd3))
3969 @unittest.skipUnless(hasattr(os, 'openpty'), "need os.openpty()")
3971 master_fd, slave_fd = os.openpty()
3972 self.addCleanup(os.close, master_fd)
3973 self.addCleanup(os.close, slave_fd)
3974 self.assertEqual(os.get_inheritable(master_fd), False)
3975 self.assertEqual(os.get_inheritable(slave_fd), False)
3984 ('access', False, (os.F_OK,), None),
3987 ('open', False, (0,), getattr(os, 'close', None)),
3992 if os.name == 'nt':
3995 bytes_filename = os.fsencode(os_helper.TESTFN)
3997 fd = os.open(FakePath(str_filename), os.O_WRONLY|os.O_CREAT)
3999 self.addCleanup(os.close, fd)
4007 fn = getattr(os, name)
4031 'os.PathLike'):
4037 os.stat(FakePath(2))
4039 os.stat(FakePath(2.34))
4041 os.stat(FakePath(object()))
4044 @unittest.skipUnless(hasattr(os, 'get_blocking'),
4045 'needs os.get_blocking() and os.set_blocking()')
4048 fd = os.open(__file__, os.O_RDONLY)
4049 self.addCleanup(os.close, fd)
4050 self.assertEqual(os.get_blocking(fd), True)
4052 os.set_blocking(fd, False)
4053 self.assertEqual(os.get_blocking(fd), False)
4055 os.set_blocking(fd, True)
4056 self.assertEqual(os.get_blocking(fd), True)
4062 self.assertIn('open', os.__all__)
4063 self.assertIn('walk', os.__all__)
4068 self.path = os.path.realpath(os_helper.TESTFN)
4070 os.mkdir(self.path)
4073 self.assertRaises(TypeError, os.DirEntry)
4076 filename = create_file(os.path.join(self.path, "file.txt"), b'python')
4077 entry = [entry for entry in os.scandir(self.path)].pop()
4078 self.assertIsInstance(entry, os.DirEntry)
4088 self.path = os.path.realpath(os_helper.TESTFN)
4089 self.bytes_path = os.fsencode(self.path)
4091 os.mkdir(self.path)
4095 filename = os.path.join(path, name)
4101 for entry in os.scandir(self.path))
4119 scandir_iter = os.scandir(self.path)
4125 scandir_iter = os.scandir(self.path)
4131 self.assertIsInstance(entry, os.DirEntry)
4133 self.assertEqual(entry.path, os.path.join(self.path, name))
4135 os.stat(entry.path, follow_symlinks=False).st_ino)
4137 entry_stat = os.stat(entry.path)
4143 os.path.islink(entry.path))
4145 entry_lstat = os.stat(entry.path, follow_symlinks=False)
4153 os.name == 'nt' and not is_symlink)
4156 os.name == 'nt')
4159 link = hasattr(os, 'link')
4162 dirname = os.path.join(self.path, "dir")
4163 os.mkdir(dirname)
4167 os.link(filename, os.path.join(self.path, "link_file.txt"))
4169 self.skipTest('os.link(): %s' % e)
4171 os.symlink(dirname, os.path.join(self.path, "symlink_dir"),
4173 os.symlink(filename, os.path.join(self.path, "symlink_file.txt"))
4201 entries = list(os.scandir(path))
4210 return self.get_entry(os.path.basename(filename))
4214 old_dir = os.getcwd()
4216 os.chdir(self.path)
4220 entries = dict((entry.name, entry) for entry in os.scandir())
4222 [os.path.basename(filename)])
4224 os.chdir(old_dir)
4232 self.assertEqual(os.fspath(entry), os.path.join(self.path, 'file.txt'))
4235 bytes_filename = os.fsencode('bytesfile.txt')
4237 fspath = os.fspath(bytes_entry)
4240 os.path.join(os.fsencode(self.path),bytes_filename))
4243 path = os.path.join(self.path, 'dir')
4245 os.mkdir(path)
4247 os.rmdir(path)
4250 if os.name == 'nt':
4254 if os.name == 'nt':
4266 os.unlink(entry.path)
4270 if os.name == 'nt':
4273 if os.name == 'nt':
4288 os.symlink(filename,
4289 os.path.join(self.path, "symlink.txt"))
4292 os.unlink(filename)
4307 path_bytes = os.fsencode(self.path)
4308 entries = list(os.scandir(path_bytes))
4314 os.fsencode(os.path.join(self.path, 'file.txt')))
4320 path_bytes = cls(os.fsencode(self.path))
4322 entries = list(os.scandir(path_bytes))
4328 os.fsencode(os.path.join(self.path, 'file.txt')))
4332 @unittest.skipUnless(os.listdir in os.supports_fd,
4335 self.assertIn(os.scandir, os.supports_fd)
4339 os.symlink('file.txt', os.path.join(self.path, 'link'))
4342 fd = os.open(self.path, os.O_RDONLY)
4344 with os.scandir(fd) as it:
4348 self.assertEqual(names, os.listdir(fd))
4351 self.assertEqual(os.fspath(entry), entry.name)
4353 if os.stat in os.supports_dir_fd:
4354 st = os.stat(entry.name, dir_fd=fd)
4356 st = os.stat(entry.name, dir_fd=fd, follow_symlinks=False)
4359 os.close(fd)
4362 self.assertRaises(FileNotFoundError, os.scandir, '')
4366 iterator = os.scandir(self.path)
4377 self.assertRaises(TypeError, os.scandir, obj)
4382 iterator = os.scandir(self.path)
4393 with os.scandir(self.path) as iterator:
4401 with os.scandir(self.path) as iterator:
4409 with os.scandir(self.path) as iterator:
4418 iterator = os.scandir(self.path)
4424 iterator = os.scandir(self.path)
4434 fspath = staticmethod(os.fspath)
4449 self.assertEqual(b"path/like/object", os.fsencode(pathlike))
4450 self.assertEqual("path/like/object", os.fsdecode(pathlike))
4454 self.assertTrue(issubclass(FakePath, os.PathLike))
4455 self.assertTrue(isinstance(FakePath('x'), os.PathLike))
4459 for o in int, type, os, vapor():
4479 class A(os.PathLike):
4482 self.assertTrue(issubclass(FakePath, os.PathLike))
4485 self.assertIsInstance(os.PathLike[bytes], types.GenericAlias)
4490 times = os.times()
4491 self.assertIsInstance(times, os.times_result)
4498 if os.name == 'nt':
4507 # bpo-42540: ensure os.fork() with non-default memory allocator does
4510 import os
4512 pid = os.fork()
4522 if hasattr(os, "_fspath"):
4525 """Explicitly test the pure Python implementation of os.fspath()."""
4527 fspath = staticmethod(os._fspath)