Lines Matching refs:os

1 # As a test suite for the os module, this is woefully inadequate, but this
14 import os
72 if hasattr(os, 'geteuid'):
73 root_in_posix = (os.geteuid() == 0)
85 HAVE_WHEEL_GROUP = sys.platform.startswith('freebsd') and os.getgid() == 0
89 return unittest.skipUnless(hasattr(os, name), 'requires os.%s' % name)
108 cwd = os.getcwd()
114 # longer path if longer paths support is enabled. Internally, the os
137 cwd = os.getcwd()
140 need = min_len - (len(cwd) + len(os.path.sep))
146 path = os.path.join(path, dirname)
148 os.mkdir(path)
151 os.chdir(path)
169 cwd = os.getcwdb()
171 self.assertEqual(os.fsdecode(cwd), os.getcwd())
177 if os.path.lexists(os_helper.TESTFN):
178 os.unlink(os_helper.TESTFN)
182 f = os.open(os_helper.TESTFN, os.O_CREAT|os.O_RDWR)
183 os.close(f)
184 self.assertTrue(os.access(os_helper.TESTFN, os.W_OK))
193 first = os.open(os_helper.TESTFN, os.O_CREAT|os.O_RDWR)
197 second = os.dup(first)
201 os.close(first)
206 first, second = second, os.dup(second)
208 os.close(second)
210 os.closerange(first, first + 2)
211 self.assertRaises(OSError, os.write, first, b"a")
217 self.assertRaises(TypeError, os.rename, path, 0)
226 os.lseek(fd, 0, 0)
227 s = os.read(fd, 4)
241 # Issue #21932: Make sure that os.read() does not raise an
244 data = os.read(fp.fileno(), size)
251 # os.write() accepts bytes- and buffer-like objects but not strings
252 fd = os.open(os_helper.TESTFN, os.O_CREAT | os.O_WRONLY)
253 self.assertRaises(TypeError, os.write, fd, "beans")
254 os.write(fd, b"bacon\n")
255 os.write(fd, bytearray(b"eggs\n"))
256 os.write(fd, memoryview(b"spam\n"))
257 os.close(fd)
282 fd = os.open(os_helper.TESTFN, os.O_RDONLY)
283 f = os.fdopen(fd, *args, encoding="utf-8")
287 fd = os.open(os_helper.TESTFN, os.O_CREAT|os.O_RDWR)
288 os.close(fd)
302 os.replace(os_helper.TESTFN, TESTFN2)
303 self.assertRaises(FileNotFoundError, os.stat, os_helper.TESTFN)
308 f = os.open(path=__file__, flags=os.O_RDONLY, mode=0o777,
310 os.close(f)
313 symlink = support.get_attribute(os, "symlink")
320 @unittest.skipUnless(hasattr(os, 'copy_file_range'), 'test needs os.copy_file_range()')
323 os.copy_file_range(0, 1, -10)
325 @unittest.skipUnless(hasattr(os, 'copy_file_range'), 'test needs os.copy_file_range()')
343 i = os.copy_file_range(in_fd, out_fd, 5)
359 @unittest.skipUnless(hasattr(os, 'copy_file_range'), 'test needs os.copy_file_range()')
380 i = os.copy_file_range(in_fd, out_fd, bytes_to_copy,
404 @unittest.skipUnless(hasattr(os, 'splice'), 'test needs os.splice()')
407 os.splice(0, 1, -10)
409 @unittest.skipUnless(hasattr(os, 'splice'), 'test needs os.splice()')
422 read_fd, write_fd = os.pipe()
423 self.addCleanup(lambda: os.close(read_fd))
424 self.addCleanup(lambda: os.close(write_fd))
427 i = os.splice(in_fd, write_fd, 5)
440 self.assertEqual(os.read(read_fd, 100), data[:i])
442 @unittest.skipUnless(hasattr(os, 'splice'), 'test needs os.splice()')
457 read_fd, write_fd = os.pipe()
458 self.addCleanup(lambda: os.close(read_fd))
459 self.addCleanup(lambda: os.close(write_fd))
462 i = os.splice(in_fd, write_fd, bytes_to_copy, offset_src=in_skip)
475 read = os.read(read_fd, 100)
480 @unittest.skipUnless(hasattr(os, 'splice'), 'test needs os.splice()')
491 read_fd, write_fd = os.pipe()
492 self.addCleanup(lambda: os.close(read_fd))
493 self.addCleanup(lambda: os.close(write_fd))
494 os.write(write_fd, data)
502 i = os.splice(read_fd, out_fd, bytes_to_copy, offset_dst=out_seek)
524 # Test attributes on return values from os.*stat* family.
532 result = os.stat(fname)
585 result2 = os.stat_result((10,))
592 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
607 result = os.stat(self.fname)
616 @unittest.skipUnless(hasattr(os, 'statvfs'), 'test needs os.statvfs()')
618 result = os.statvfs(self.fname)
649 result2 = os.statvfs_result((10,))
656 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
660 @unittest.skipUnless(hasattr(os, 'statvfs'),
661 "need os.statvfs()")
663 result = os.statvfs(self.fname)
677 os.stat(r"c:\pagefile.sys")
684 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
687 r, w = os.pipe()
689 os.stat(r) # should not raise error
691 os.close(r)
692 os.close(w)
694 os.stat(r)
706 result = os.stat(self.fname)
714 os.mkdir(dirname)
715 self.addCleanup(os.rmdir, dirname)
717 result = os.stat(dirname)
727 # os.environ['TEMP'] should be located on a volume that
729 fname = os.path.join(os.environ['TEMP'], self.fname)
741 result = os.stat(fname)
746 # bpo-38030: os.stat fails for block devices
748 fname = "//./" + os.path.splitdrive(os.getcwd())[0]
749 result = os.stat(fname)
756 self.fname = os.path.join(self.dirname, "f1")
759 os.mkdir(self.dirname)
765 st = os.stat(filename)
778 # The resolution of the C internal function used by os.utime()
790 st = os.stat(filename)
804 os.utime(filename, ns=ns)
811 # issue, os.utime() rounds towards minus infinity.
822 os.utime(filename, (atime, mtime))
831 os.utime(filename, times=(atime, mtime))
834 @unittest.skipUnless(os.utime in os.supports_follow_symlinks,
841 os.utime(filename, ns=ns, follow_symlinks=False)
844 @unittest.skipUnless(os.utime in os.supports_fd,
851 os.utime(fp.fileno(), ns=ns)
854 @unittest.skipUnless(os.utime in os.supports_dir_fd,
858 dirname, name = os.path.split(filename)
861 os.utime(name, dir_fd=dirfd, ns=ns)
866 # test calling os.utime() on a directory
867 os.utime(filename, ns=ns)
874 # Call os.utime() to set the timestamp to the current system clock
886 st = os.stat(self.fname)
895 os.utime(self.fname)
901 os.utime(self.fname, None)
906 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
924 os.utime(self.fname, (large, large))
925 self.assertEqual(os.stat(self.fname).st_mtime, large)
930 os.utime(self.fname, (5, 5), ns=(5, 5))
932 os.utime(self.fname, [5, 5])
934 os.utime(self.fname, (5,))
936 os.utime(self.fname, (5, 5, 5))
938 os.utime(self.fname, ns=[5, 5])
940 os.utime(self.fname, ns=(5,))
942 os.utime(self.fname, ns=(5, 5, 5))
944 if os.utime not in os.supports_follow_symlinks:
946 os.utime(self.fname, (5, 5), follow_symlinks=False)
947 if os.utime not in os.supports_fd:
950 os.utime(fp.fileno(), (5, 5))
951 if os.utime not in os.supports_dir_fd:
953 os.utime(self.fname, (5, 5), dir_fd=0)
965 os.utime(self.fname, ns=(get_bad_int(42), 1))
967 os.utime(self.fname, ns=(get_bad_int(()), 1))
969 os.utime(self.fname, ns=(get_bad_int((1, 2, 3)), 1))
975 """check that os.environ object conform to mapping protocol"""
979 self.__save = dict(os.environ)
980 if os.supports_bytes_environ:
981 self.__saveb = dict(os.environb)
983 os.environ[key] = value
986 os.environ.clear()
987 os.environ.update(self.__save)
988 if os.supports_bytes_environ:
989 os.environb.clear()
990 os.environb.update(self.__saveb)
996 os.environ.clear()
997 return os.environ
1000 @unittest.skipUnless(unix_shell and os.path.exists(unix_shell),
1002 @unittest.skipUnless(hasattr(os, 'popen'), "needs os.popen()")
1005 os.environ.clear()
1006 os.environ.update(HELLO="World")
1007 with os.popen("%s -c 'echo $HELLO'" % unix_shell) as popen:
1011 @unittest.skipUnless(unix_shell and os.path.exists(unix_shell),
1013 @unittest.skipUnless(hasattr(os, 'popen'), "needs os.popen()")
1016 with os.popen("%s -c 'echo \"line1\nline2\nline3\"'"
1027 for key, val in os.environ.items():
1033 self.assertEqual(os.environ.get(key), value)
1037 """Check that the repr() of os.environ looks like environ({...})."""
1038 env = os.environ
1046 defpath_list = os.defpath.split(os.pathsep)
1048 test_env = {'PATH': os.pathsep.join(test_path)}
1050 saved_environ = os.environ
1052 os.environ = dict(test_env)
1053 # Test that defaulting to os.environ works.
1054 self.assertSequenceEqual(test_path, os.get_exec_path())
1055 self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
1057 os.environ = saved_environ
1060 self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
1062 self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
1064 self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
1066 if os.supports_bytes_environ:
1076 self.assertRaises(ValueError, os.get_exec_path, mixed_env)
1079 self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}),
1081 self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}),
1083 self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}),
1086 @unittest.skipUnless(os.supports_bytes_environ,
1087 "os.environb required for this test.")
1089 # os.environ -> os.environb
1098 os.environ['unicode'] = value
1099 self.assertEqual(os.environ['unicode'], value)
1100 self.assertEqual(os.environb[b'unicode'], value_bytes)
1102 # os.environb -> os.environ
1104 os.environb[b'bytes'] = value
1105 self.assertEqual(os.environb[b'bytes'], value)
1107 self.assertEqual(os.environ['bytes'], value_str)
1113 code = f'import os; print(repr(os.environ.get({name!r})))'
1118 os.putenv(name, value)
1123 os.unsetenv(name)
1134 self.assertRaises((OSError, ValueError), os.putenv, name, "value")
1135 self.assertRaises((OSError, ValueError), os.unsetenv, name)
1141 self.assertRaises(ValueError, os.putenv, longstr, "1")
1142 self.assertRaises(ValueError, os.putenv, "X", longstr)
1143 self.assertRaises(ValueError, os.unsetenv, longstr)
1147 self.assertNotIn(missing, os.environ)
1150 os.environ[missing]
1155 del os.environ[missing]
1163 next(iterator) # start iteration over os.environ.items
1165 # add a new key in os.environ mapping
1166 os.environ[new_key] = "test_environ_iteration"
1170 self.assertEqual(os.environ[new_key], "test_environ_iteration")
1172 del os.environ[new_key]
1175 self._test_environ_iteration(os.environ)
1178 self._test_environ_iteration(os.environ.items())
1181 self._test_environ_iteration(os.environ.values())
1184 if not (unix_shell and os.path.exists(unix_shell)):
1189 with os.popen(f"{unix_shell} -c 'echo ${var}'") as popen:
1197 os.environ[overridden_key] = original_value
1200 expected = dict(os.environ)
1203 actual = os.environ | new_vars_dict
1208 self.assertIs(NotImplemented, os.environ.__or__(new_vars_items))
1215 os.environ[overridden_key] = 'original_value'
1218 expected = dict(os.environ)
1221 os.environ |= new_vars_dict
1222 self.assertEqual(expected, os.environ)
1223 self.assertEqual('3', os.environ[overridden_key])
1229 os_environ_copy = os.environ.copy()
1232 os.environ |= dict_with_bad_key
1236 os.environ |= dict_with_bad_val
1239 self.assertEqual(os_environ_copy, os.environ)
1243 os.environ[overridden_key] = 'original_value'
1246 expected = dict(os.environ)
1249 os.environ |= new_vars_items
1250 self.assertEqual(expected, os.environ)
1251 self.assertEqual('3', os.environ[overridden_key])
1259 os.environ[overridden_key] = original_value
1263 expected.update(os.environ)
1265 actual = new_vars_dict | os.environ
1270 self.assertIs(NotImplemented, os.environ.__ror__(new_vars_items))
1277 """Tests for os.walk()."""
1279 # Wrapper to hide minor differences between os.walk and os.fwalk
1284 return os.walk(top, **kwargs)
1287 join = os.path.join
1324 os.makedirs(self.sub11_path)
1325 os.makedirs(sub2_path)
1326 os.makedirs(sub21_path)
1327 os.makedirs(t2_path)
1334 os.symlink(os.path.abspath(t2_path), self.link_path)
1335 os.symlink('broken', broken_link_path, True)
1336 os.symlink(join('tmp3', 'broken'), broken_link2_path, True)
1337 os.symlink(join('SUB21', 'tmp5'), broken_link3_path, True)
1346 os.chmod(sub21_path, 0)
1348 os.listdir(sub21_path)
1350 self.addCleanup(os.chmod, sub21_path, stat.S_IRWXU)
1352 os.chmod(sub21_path, stat.S_IRWXU)
1353 os.unlink(tmp5_path)
1354 os.rmdir(sub21_path)
1438 path1 = os.path.join(root, dir1)
1439 path1new = os.path.join(root, dir1 + '.new')
1440 os.rename(path1, path1new)
1448 self.assertIn(os.path.join(root, dir2), roots)
1450 os.rename(path1new, path1)
1454 base = os.path.join(os_helper.TESTFN, 'deep')
1455 p = os.path.join(base, *(['d']*depth))
1456 os.makedirs(p)
1463 p = os.path.dirname(p)
1471 p = os.path.join(p, 'd')
1474 @unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
1476 """Tests for os.fwalk()."""
1483 return os.fwalk(*args, **kwargs)
1496 for root, dirs, files in os.walk(**walk_kwargs):
1509 fd = os.open(".", os.O_RDONLY)
1515 os.close(fd)
1523 os.fstat(rootfd)
1525 os.stat(rootfd)
1527 self.assertEqual(set(os.listdir(rootfd)), set(dirs) | set(files))
1536 minfd = os.dup(1)
1537 os.close(minfd)
1541 newfd = os.dup(1)
1542 self.addCleanup(os.close, newfd)
1550 """Tests for os.walk() with bytes."""
1554 for broot, bdirs, bfiles in os.walk(os.fsencode(top), **kwargs):
1555 root = os.fsdecode(broot)
1556 dirs = list(map(os.fsdecode, bdirs))
1557 files = list(map(os.fsdecode, bfiles))
1559 bdirs[:] = list(map(os.fsencode, dirs))
1560 bfiles[:] = list(map(os.fsencode, files))
1562 @unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
1564 """Tests for os.walk() with bytes."""
1566 for broot, bdirs, bfiles, topfd in os.fwalk(os.fsencode(top), *args, **kwargs):
1567 root = os.fsdecode(broot)
1568 dirs = list(map(os.fsdecode, bdirs))
1569 files = list(map(os.fsdecode, bfiles))
1571 bdirs[:] = list(map(os.fsencode, dirs))
1572 bfiles[:] = list(map(os.fsencode, files))
1577 os.mkdir(os_helper.TESTFN)
1581 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
1582 os.makedirs(path) # Should work
1583 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
1584 os.makedirs(path)
1587 self.assertRaises(OSError, os.makedirs, os.curdir)
1588 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
1589 os.makedirs(path)
1590 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
1592 os.makedirs(path)
1601 parent = os.path.join(base, 'dir1')
1602 path = os.path.join(parent, 'dir2')
1603 os.makedirs(path, 0o555)
1604 self.assertTrue(os.path.exists(path))
1605 self.assertTrue(os.path.isdir(path))
1606 if os.name != 'nt':
1607 self.assertEqual(os.stat(path).st_mode & 0o777, 0o555)
1608 self.assertEqual(os.stat(parent).st_mode & 0o777, 0o775)
1615 path = os.path.join(os_helper.TESTFN, 'dir1')
1617 old_mask = os.umask(0o022)
1618 os.makedirs(path, mode)
1619 self.assertRaises(OSError, os.makedirs, path, mode)
1620 self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
1621 os.makedirs(path, 0o776, exist_ok=True)
1622 os.makedirs(path, mode=mode, exist_ok=True)
1623 os.umask(old_mask)
1626 os.makedirs(os.path.abspath('/'), exist_ok=True)
1633 path = os.path.join(os_helper.TESTFN, 'dir1')
1636 old_mask = os.umask(0o022)
1639 os.lstat(os_helper.TESTFN).st_mode)
1641 os.chmod(os_helper.TESTFN, existing_testfn_mode | S_ISGID)
1644 if (os.lstat(os_helper.TESTFN).st_mode & S_ISGID != S_ISGID):
1646 # The os should apply S_ISGID from the parent dir for us, but
1648 os.makedirs(path, mode | S_ISGID)
1651 os.makedirs(path, mode, exist_ok=True)
1653 os.chmod(path, stat.S_IMODE(os.lstat(path).st_mode) & ~S_ISGID)
1655 os.makedirs(path, mode | S_ISGID, exist_ok=True)
1657 os.umask(old_mask)
1661 path = os.path.join(os_helper.TESTFN, 'dir1')
1664 self.assertRaises(OSError, os.makedirs, path)
1665 self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
1666 self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
1667 os.remove(path)
1669 @unittest.skipUnless(os.name == 'nt', "requires Windows")
1672 path = os.path.abspath(os.path.join(os_helper.TESTFN, 'dir'))
1673 os.mkdir(path, mode=0o700)
1675 os.rmdir(path)
1682 path = os.path.join(os_helper.TESTFN, 'dir1', 'dir2', 'dir3',
1687 while not os.path.exists(path) and path != os_helper.TESTFN:
1688 path = os.path.dirname(path)
1690 os.removedirs(path)
1698 os.mkdir(os_helper.TESTFN)
1701 stat = os.stat(os_helper.TESTFN)
1705 self.assertRaises(TypeError, os.chown, os_helper.TESTFN, value, gid)
1706 self.assertRaises(TypeError, os.chown, os_helper.TESTFN, uid, value)
1707 self.assertIsNone(os.chown(os_helper.TESTFN, uid, gid))
1708 self.assertIsNone(os.chown(os_helper.TESTFN, -1, -1))
1710 @unittest.skipUnless(hasattr(os, 'getgroups'), 'need os.getgroups')
1712 groups = os.getgroups()
1717 uid = os.stat(os_helper.TESTFN).st_uid
1719 os.chown(os_helper.TESTFN, uid, gid_1)
1720 gid = os.stat(os_helper.TESTFN).st_gid
1723 os.chown(os_helper.TESTFN, uid, gid_2)
1724 gid = os.stat(os_helper.TESTFN).st_gid
1731 gid = os.stat(os_helper.TESTFN).st_gid
1732 os.chown(os_helper.TESTFN, uid_1, gid)
1733 uid = os.stat(os_helper.TESTFN).st_uid
1735 os.chown(os_helper.TESTFN, uid_2, gid)
1736 uid = os.stat(os_helper.TESTFN).st_uid
1743 gid = os.stat(os_helper.TESTFN).st_gid
1745 os.chown(os_helper.TESTFN, uid_1, gid)
1746 os.chown(os_helper.TESTFN, uid_2, gid)
1750 os.rmdir(os_helper.TESTFN)
1755 os.makedirs(os_helper.TESTFN)
1761 dira = os.path.join(os_helper.TESTFN, 'dira')
1762 os.mkdir(dira)
1763 dirb = os.path.join(dira, 'dirb')
1764 os.mkdir(dirb)
1765 os.removedirs(dirb)
1766 self.assertFalse(os.path.exists(dirb))
1767 self.assertFalse(os.path.exists(dira))
1768 self.assertFalse(os.path.exists(os_helper.TESTFN))
1771 dira = os.path.join(os_helper.TESTFN, 'dira')
1772 os.mkdir(dira)
1773 dirb = os.path.join(dira, 'dirb')
1774 os.mkdir(dirb)
1775 create_file(os.path.join(dira, 'file.txt'))
1776 os.removedirs(dirb)
1777 self.assertFalse(os.path.exists(dirb))
1778 self.assertTrue(os.path.exists(dira))
1779 self.assertTrue(os.path.exists(os_helper.TESTFN))
1782 dira = os.path.join(os_helper.TESTFN, 'dira')
1783 os.mkdir(dira)
1784 dirb = os.path.join(dira, 'dirb')
1785 os.mkdir(dirb)
1786 create_file(os.path.join(dirb, 'file.txt'))
1788 os.removedirs(dirb)
1789 self.assertTrue(os.path.exists(dirb))
1790 self.assertTrue(os.path.exists(dira))
1791 self.assertTrue(os.path.exists(os_helper.TESTFN))
1797 with open(os.devnull, 'wb', 0) as f:
1800 with open(os.devnull, 'rb') as f:
1806 self.assertEqual(len(os.urandom(0)), 0)
1807 self.assertEqual(len(os.urandom(1)), 1)
1808 self.assertEqual(len(os.urandom(10)), 10)
1809 self.assertEqual(len(os.urandom(100)), 100)
1810 self.assertEqual(len(os.urandom(1000)), 1000)
1813 data1 = os.urandom(16)
1815 data2 = os.urandom(16)
1820 'import os, sys',
1821 'data = os.urandom(%s)' % count,
1835 @unittest.skipUnless(hasattr(os, 'getrandom'), 'need os.getrandom()')
1840 os.getrandom(1)
1850 data = os.getrandom(16)
1855 empty = os.getrandom(0)
1859 self.assertTrue(hasattr(os, 'GRND_RANDOM'))
1861 # Don't test os.getrandom(1, os.GRND_RANDOM) to not consume the rare
1867 os.getrandom(1, os.GRND_NONBLOCK)
1873 data1 = os.getrandom(16)
1874 data2 = os.getrandom(16)
1878 # os.urandom() doesn't use a file descriptor when it is implemented with the
1886 "os.random() does not use a file descriptor")
1899 import os
1905 os.urandom(16)
1917 import os
1920 os.urandom(4)
1922 os.closerange(3, 256)
1923 sys.stdout.buffer.write(os.urandom(4))
1934 import os
1937 os.urandom(4)
1941 os.close(fd)
1947 os.closerange(3, 256)
1954 os.dup2(new_fd, fd)
1955 sys.stdout.buffer.write(os.urandom(4))
1956 sys.stdout.buffer.write(os.urandom(4))
1986 orig_execv = os.execv
1987 orig_execve = os.execve
1988 orig_defpath = os.defpath
1989 os.execv = mock_execv
1990 os.execve = mock_execve
1992 os.defpath = defpath
1995 os.execv = orig_execv
1996 os.execve = orig_execve
1997 os.defpath = orig_defpath
1999 @unittest.skipUnless(hasattr(os, 'execv'),
2000 "need os.execv()")
2005 self.assertRaises(OSError, os.execvpe, 'no such app-',
2009 self.assertRaises(ValueError, os.execv, 'notepad', ())
2010 self.assertRaises(ValueError, os.execv, 'notepad', [])
2011 self.assertRaises(ValueError, os.execv, 'notepad', ('',))
2012 self.assertRaises(ValueError, os.execv, 'notepad', [''])
2015 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
2016 self.assertRaises(ValueError, os.execvpe, 'notepad', [], {})
2017 self.assertRaises(ValueError, os.execvpe, 'notepad', [''], {})
2019 @unittest.skipUnless(hasattr(os, '_execvpe'),
2020 "No internal os._execvpe function to test.")
2022 program_path = os.sep + 'absolutepath'
2025 fullpath = os.path.join(os.fsencode(program_path), program)
2031 fullpath = os.path.join(program_path, program)
2032 if os.name != "nt":
2033 native_fullpath = os.fsencode(fullpath)
2038 # test os._execvpe() with an absolute path
2041 os._execvpe, fullpath, arguments)
2045 # test os._execvpe() with a relative path:
2046 # os.get_exec_path() returns defpath
2049 os._execvpe, program, arguments, env=env)
2054 # test os._execvpe() with a relative path:
2055 # os.get_exec_path() reads the 'PATH' variable
2063 os._execvpe, program, arguments, env=env_path)
2070 if os.name != "nt":
2077 newenv = os.environ.copy()
2080 os.execve(args[0], args, newenv)
2083 newenv = os.environ.copy()
2086 os.execve(args[0], args, newenv)
2089 newenv = os.environ.copy()
2092 os.execve(args[0], args, newenv)
2098 os.execve('', ['arg'], {})
2109 os.stat(os_helper.TESTFN)
2114 self.fail("file %s must not exist; os.stat failed with %s"
2120 self.assertRaises(OSError, os.rename, os_helper.TESTFN, os_helper.TESTFN+".bak")
2123 self.assertRaises(OSError, os.remove, os_helper.TESTFN)
2126 self.assertRaises(OSError, os.chdir, os_helper.TESTFN)
2132 self.assertRaises(OSError, os.mkdir, os_helper.TESTFN)
2135 self.assertRaises(OSError, os.utime, os_helper.TESTFN, None)
2138 self.assertRaises(OSError, os.chmod, os_helper.TESTFN, 0)
2149 if hasattr(os, f):
2150 self.check(getattr(os, f))
2165 self.check(os.fdopen, encoding="utf-8")
2167 @unittest.skipUnless(hasattr(os, 'isatty'), 'test needs os.isatty()')
2169 self.assertEqual(os.isatty(os_helper.make_bad_fd()), False)
2171 @unittest.skipUnless(hasattr(os, 'closerange'), 'test needs os.closerange()')
2177 try: os.fstat(fd+i)
2185 self.assertEqual(os.closerange(fd, fd + i-1), None)
2187 @unittest.skipUnless(hasattr(os, 'dup2'), 'test needs os.dup2()')
2189 self.check(os.dup2, 20)
2191 @unittest.skipUnless(hasattr(os, 'dup2'), 'test needs os.dup2()')
2197 valid_fd = os.open(__file__, os.O_RDONLY)
2198 self.addCleanup(os.close, valid_fd)
2208 os.dup2(fd, fd2)
2211 @unittest.skipUnless(hasattr(os, 'fchmod'), 'test needs os.fchmod()')
2213 self.check(os.fchmod, 0)
2215 @unittest.skipUnless(hasattr(os, 'fchown'), 'test needs os.fchown()')
2217 self.check(os.fchown, -1, -1)
2219 @unittest.skipUnless(hasattr(os, 'fpathconf'), 'test needs os.fpathconf()')
2225 self.check(os.pathconf, "PC_NAME_MAX")
2226 self.check(os.fpathconf, "PC_NAME_MAX")
2228 @unittest.skipUnless(hasattr(os, 'ftruncate'), 'test needs os.ftruncate()')
2230 self.check(os.truncate, 0)
2231 self.check(os.ftruncate, 0)
2233 @unittest.skipUnless(hasattr(os, 'lseek'), 'test needs os.lseek()')
2235 self.check(os.lseek, 0, 0)
2237 @unittest.skipUnless(hasattr(os, 'read'), 'test needs os.read()')
2239 self.check(os.read, 1)
2241 @unittest.skipUnless(hasattr(os, 'readv'), 'test needs os.readv()')
2244 self.check(os.readv, [buf])
2246 @unittest.skipUnless(hasattr(os, 'tcsetpgrp'), 'test needs os.tcsetpgrp()')
2248 self.check(os.tcsetpgrp, 0)
2250 @unittest.skipUnless(hasattr(os, 'write'), 'test needs os.write()')
2252 self.check(os.write, b" ")
2254 @unittest.skipUnless(hasattr(os, 'writev'), 'test needs os.writev()')
2256 self.check(os.writev, [b'abc'])
2260 self.check(os.get_inheritable)
2261 self.check(os.set_inheritable, True)
2263 @unittest.skipUnless(hasattr(os, 'get_blocking'),
2264 'needs os.get_blocking() and os.set_blocking()')
2266 self.check(os.get_blocking)
2267 self.check(os.set_blocking, True)
2270 @unittest.skipUnless(hasattr(os, 'link'), 'requires os.link')
2274 self.file2 = os.path.join(os_helper.TESTFN + "2")
2278 if os.path.exists(file):
2279 os.unlink(file)
2285 os.link(file1, file2)
2287 self.skipTest('os.link(): %s' % e)
2289 self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
2300 os.fsencode("\xf1")
2314 @unittest.skipUnless(hasattr(os, 'setuid'), 'test needs os.setuid()')
2316 if os.getuid() != 0:
2317 self.assertRaises(OSError, os.setuid, 0)
2318 self.assertRaises(TypeError, os.setuid, 'not an int')
2319 self.assertRaises(OverflowError, os.setuid, self.UID_OVERFLOW)
2321 @unittest.skipUnless(hasattr(os, 'setgid'), 'test needs os.setgid()')
2323 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
2324 self.assertRaises(OSError, os.setgid, 0)
2325 self.assertRaises(TypeError, os.setgid, 'not an int')
2326 self.assertRaises(OverflowError, os.setgid, self.GID_OVERFLOW)
2328 @unittest.skipUnless(hasattr(os, 'seteuid'), 'test needs os.seteuid()')
2330 if os.getuid() != 0:
2331 self.assertRaises(OSError, os.seteuid, 0)
2332 self.assertRaises(TypeError, os.setegid, 'not an int')
2333 self.assertRaises(OverflowError, os.seteuid, self.UID_OVERFLOW)
2335 @unittest.skipUnless(hasattr(os, 'setegid'), 'test needs os.setegid()')
2337 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
2338 self.assertRaises(OSError, os.setegid, 0)
2339 self.assertRaises(TypeError, os.setegid, 'not an int')
2340 self.assertRaises(OverflowError, os.setegid, self.GID_OVERFLOW)
2342 @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
2344 if os.getuid() != 0:
2345 self.assertRaises(OSError, os.setreuid, 0, 0)
2346 self.assertRaises(TypeError, os.setreuid, 'not an int', 0)
2347 self.assertRaises(TypeError, os.setreuid, 0, 'not an int')
2348 self.assertRaises(OverflowError, os.setreuid, self.UID_OVERFLOW, 0)
2349 self.assertRaises(OverflowError, os.setreuid, 0, self.UID_OVERFLOW)
2351 @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
2358 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
2360 @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
2363 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
2364 self.assertRaises(OSError, os.setregid, 0, 0)
2365 self.assertRaises(TypeError, os.setregid, 'not an int', 0)
2366 self.assertRaises(TypeError, os.setregid, 0, 'not an int')
2367 self.assertRaises(OverflowError, os.setregid, self.GID_OVERFLOW, 0)
2368 self.assertRaises(OverflowError, os.setregid, 0, self.GID_OVERFLOW)
2370 @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
2377 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
2388 self.bdir = os.fsencode(self.dir)
2393 fn = os.fsencode(fn)
2406 os.mkdir(self.dir)
2409 os_helper.create_empty_file(os.path.join(self.bdir, fn))
2410 fn = os.fsdecode(fn)
2423 found = set(os.listdir(self.dir))
2426 current_directory = os.getcwd()
2428 os.chdir(os.sep)
2429 self.assertEqual(set(os.listdir()), set(os.listdir(os.sep)))
2431 os.chdir(current_directory)
2435 f = open(os.path.join(self.dir, fn), 'rb')
2438 @unittest.skipUnless(hasattr(os, 'statvfs'),
2439 "need os.statvfs()")
2444 fullname = os.path.join(self.dir, fn)
2445 os.statvfs(fullname)
2449 os.stat(os.path.join(self.dir, fn))
2456 # becomes ready, send *sig* via os.kill to the subprocess and check
2504 os.kill(proc.pid, sig)
2512 # os.kill on Windows can take an int which gets set as the exit code
2522 os.path.join(os.path.dirname(__file__),
2534 os.kill(proc.pid, signal.SIGINT)
2536 os.kill(proc.pid, event)
2542 os.kill(proc.pid, signal.SIGINT)
2578 dir_path = os.path.join(os_helper.TESTFN, dir_name)
2580 file_path = os.path.join(os_helper.TESTFN, file_name)
2581 os.makedirs(dir_path)
2594 sorted(os.listdir(os_helper.TESTFN)),
2599 sorted(os.listdir(os.fsencode(os_helper.TESTFN))),
2600 [os.fsencode(path) for path in self.created_paths])
2606 path = '\\\\?\\' + os.path.abspath(os_helper.TESTFN)
2608 sorted(os.listdir(path)),
2612 path = b'\\\\?\\' + os.fsencode(os.path.abspath(os_helper.TESTFN))
2614 sorted(os.listdir(path)),
2615 [os.fsencode(path) for path in self.created_paths])
2618 @unittest.skipUnless(hasattr(os, 'readlink'), 'needs os.readlink()')
2621 filelink_target = os.path.abspath(__file__)
2622 filelinkb = os.fsencode(filelink)
2623 filelinkb_target = os.fsencode(filelink_target)
2626 left = os.path.normcase(left)
2627 right = os.path.normcase(right)
2640 self.assertTrue(os.path.exists(self.filelink_target))
2641 self.assertTrue(os.path.exists(self.filelinkb_target))
2642 self.assertFalse(os.path.exists(self.filelink))
2643 self.assertFalse(os.path.exists(self.filelinkb))
2647 self.assertRaises(OSError, os.readlink, self.filelink_target)
2648 self.assertRaises(OSError, os.readlink, filelink_target)
2651 self.assertRaises(FileNotFoundError, os.readlink, 'missing-link')
2652 self.assertRaises(FileNotFoundError, os.readlink,
2657 os.symlink(self.filelink_target, self.filelink)
2660 self.assertPathEqual(os.readlink(filelink), self.filelink_target)
2664 os.symlink(self.filelinkb_target, self.filelinkb)
2666 path = os.readlink(FakePath(self.filelinkb))
2672 os.symlink(self.filelinkb_target, self.filelinkb)
2674 path = os.readlink(self.filelinkb)
2683 filelink_target = os.path.abspath(__file__)
2685 dirlink_target = os.path.dirname(filelink_target)
2689 assert os.path.exists(self.dirlink_target)
2690 assert os.path.exists(self.filelink_target)
2691 assert not os.path.exists(self.dirlink)
2692 assert not os.path.exists(self.filelink)
2693 assert not os.path.exists(self.missing_link)
2696 if os.path.exists(self.filelink):
2697 os.remove(self.filelink)
2698 if os.path.exists(self.dirlink):
2699 os.rmdir(self.dirlink)
2700 if os.path.lexists(self.missing_link):
2701 os.remove(self.missing_link)
2704 os.symlink(self.dirlink_target, self.dirlink)
2705 self.assertTrue(os.path.exists(self.dirlink))
2706 self.assertTrue(os.path.isdir(self.dirlink))
2707 self.assertTrue(os.path.islink(self.dirlink))
2711 os.symlink(self.filelink_target, self.filelink)
2712 self.assertTrue(os.path.exists(self.filelink))
2713 self.assertTrue(os.path.isfile(self.filelink))
2714 self.assertTrue(os.path.islink(self.filelink))
2720 if os.path.lexists(linkname):
2721 os.remove(linkname)
2723 assert not os.path.exists(target)
2725 os.symlink(target, linkname, target_is_dir)
2729 # For compatibility with Unix, os.remove will check the
2732 os.remove(self.missing_link)
2736 self.assertFalse(os.path.isdir(self.missing_link))
2740 os.rmdir(self.missing_link)
2743 self.assertEqual(os.stat(link), os.stat(target))
2744 self.assertNotEqual(os.lstat(link), os.stat(link))
2746 bytes_link = os.fsencode(link)
2747 self.assertEqual(os.stat(bytes_link), os.stat(target))
2748 self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link))
2751 level1 = os.path.abspath(os_helper.TESTFN)
2752 level2 = os.path.join(level1, "level2")
2753 level3 = os.path.join(level2, "level3")
2756 os.mkdir(level1)
2757 os.mkdir(level2)
2758 os.mkdir(level3)
2760 file1 = os.path.abspath(os.path.join(level1, "file1"))
2763 orig_dir = os.getcwd()
2765 os.chdir(level2)
2766 link = os.path.join(level2, "link")
2767 os.symlink(os.path.relpath(file1), "link")
2768 self.assertIn("link", os.listdir(os.getcwd()))
2770 # Check os.stat calls from the same dir as the link
2771 self.assertEqual(os.stat(file1), os.stat("link"))
2773 # Check os.stat calls from a dir below the link
2774 os.chdir(level1)
2775 self.assertEqual(os.stat(file1),
2776 os.stat(os.path.relpath(link)))
2778 # Check os.stat calls from a dir above the link
2779 os.chdir(level3)
2780 self.assertEqual(os.stat(file1),
2781 os.stat(os.path.relpath(link)))
2783 os.chdir(orig_dir)
2785 @unittest.skipUnless(os.path.lexists(r'C:\Users\All Users')
2786 and os.path.exists(r'C:\ProgramData'),
2789 # os.symlink() calls CreateSymbolicLink, which creates
2797 target = os.readlink(r'C:\Users\All Users')
2798 self.assertTrue(os.path.samefile(target, r'C:\ProgramData'))
2805 path = os.path.join(*[segment] * 10)
2816 os.symlink(src, dest)
2821 os.remove(dest)
2826 os.symlink(os.fsencode(src), os.fsencode(dest))
2831 os.remove(dest)
2836 root = os.path.expandvars(r'%LOCALAPPDATA%\Microsoft\WindowsApps')
2837 if not os.path.isdir(root):
2840 aliases = [os.path.join(root, a)
2841 for a in fnmatch.filter(os.listdir(root), '*.exe')]
2847 st = os.lstat(alias)
2848 self.assertEqual(st, os.stat(alias))
2859 junction_target = os.path.dirname(os.path.abspath(__file__))
2862 assert os.path.exists(self.junction_target)
2863 assert not os.path.lexists(self.junction)
2866 if os.path.lexists(self.junction):
2867 os.unlink(self.junction)
2871 self.assertTrue(os.path.lexists(self.junction))
2872 self.assertTrue(os.path.exists(self.junction))
2873 self.assertTrue(os.path.isdir(self.junction))
2874 self.assertNotEqual(os.stat(self.junction), os.lstat(self.junction))
2875 self.assertEqual(os.stat(self.junction), os.stat(self.junction_target))
2878 self.assertFalse(os.path.islink(self.junction))
2879 self.assertEqual(os.path.normcase("\\\\?\\" + self.junction_target),
2880 os.path.normcase(os.readlink(self.junction)))
2884 self.assertTrue(os.path.exists(self.junction))
2885 self.assertTrue(os.path.lexists(self.junction))
2887 os.unlink(self.junction)
2888 self.assertFalse(os.path.exists(self.junction))
2929 os.stat(name)
2942 # bpo-46785: the implementation of os.stat() falls back to reading
2952 import os
2966 os.remove(filename)
2974 os.stat(filename)
2993 os.makedirs('base/some_dir')
3010 src = os.path.join('base', 'some_link')
3011 os.symlink('some_dir', src)
3012 assert os.path.isdir(src)
3017 self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
3018 self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
3024 bytesfn = os.fsencode(fn)
3027 self.assertEqual(os.fsdecode(bytesfn), fn)
3035 self.assertIsNone(os.device_encoding(123456))
3037 @unittest.skipUnless(os.isatty(0) and not win32_is_iot() and (sys.platform.startswith('win') or
3044 encoding = os.device_encoding(0)
3051 @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid")
3054 'import os; print(os.getppid())'],
3058 self.assertEqual(int(stdout), os.getpid())
3062 # On Windows, os.spawnv() simply joins arguments with spaces:
3067 pid = os.spawnv(os.P_NOWAIT, sys.executable, args)
3072 # don't use support.wait_process() to test directly os.waitpid()
3073 # and os.waitstatus_to_exitcode()
3074 pid2, status = os.waitpid(pid, 0)
3075 self.assertEqual(os.waitstatus_to_exitcode(status), exitcode)
3087 os.waitstatus_to_exitcode(0.0)
3091 # bpo-40138: test os.waitpid() and os.waitstatus_to_exitcode()
3101 self.assertEqual(os.waitstatus_to_exitcode(exitcode << 8),
3106 os.waitstatus_to_exitcode((max_exitcode + 1) << 8)
3108 os.waitstatus_to_exitcode(-1)
3117 os.kill(pid, signum)
3126 # On Windows, os.spawn* simply joins arguments with spaces:
3128 if os.name != 'nt':
3141 self.env = dict(os.environ)
3145 # read the variable from os.environ to check that it exists
3146 code = ('import sys, os; magic = os.environ[%r]; sys.exit(%s)'
3155 program = os.fsencode(program)
3156 args = [os.fsencode(a) for a in args]
3157 self.env = {os.fsencode(k): os.fsencode(v)
3165 exitcode = os.spawnl(os.P_WAIT, program, *args)
3171 exitcode = os.spawnle(os.P_WAIT, program, *args, self.env)
3177 exitcode = os.spawnlp(os.P_WAIT, program, *args)
3183 exitcode = os.spawnlpe(os.P_WAIT, program, *args, self.env)
3189 exitcode = os.spawnv(os.P_WAIT, program, args)
3193 exitcode = os.spawnv(os.P_WAIT, FakePath(program), args)
3199 exitcode = os.spawnve(os.P_WAIT, program, args, self.env)
3205 exitcode = os.spawnvp(os.P_WAIT, program, args)
3211 exitcode = os.spawnvpe(os.P_WAIT, program, args, self.env)
3217 pid = os.spawnv(os.P_NOWAIT, program, args)
3224 exitcode = os.spawnve(os.P_WAIT, program, args, self.env)
3230 self.assertRaises(ValueError, os.spawnl, os.P_NOWAIT, program)
3231 self.assertRaises(ValueError, os.spawnl, os.P_NOWAIT, program, '')
3236 self.assertRaises(ValueError, os.spawnle, os.P_NOWAIT, program, {})
3237 self.assertRaises(ValueError, os.spawnle, os.P_NOWAIT, program, '', {})
3242 self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, program, ())
3243 self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, program, [])
3244 self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, program, ('',))
3245 self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, program, [''])
3250 self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, program, (), {})
3251 self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, program, [], {})
3252 self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, program, ('',), {})
3253 self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, program, [''], {})
3260 newenv = os.environ.copy()
3263 exitcode = spawn(os.P_WAIT, program, args, newenv)
3270 newenv = os.environ.copy()
3273 exitcode = spawn(os.P_WAIT, program, args, newenv)
3280 newenv = os.environ.copy()
3283 exitcode = spawn(os.P_WAIT, program, args, newenv)
3293 fp.write('import sys, os\n'
3294 'if os.getenv("FRUIT") != "orange=lemon":\n'
3298 newenv = os.environ.copy()
3300 exitcode = spawn(os.P_WAIT, program, args, newenv)
3305 self._test_invalid_env(os.spawnve)
3309 self._test_invalid_env(os.spawnvpe)
3315 @unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin")
3318 user_name = os.getlogin()
3322 @unittest.skipUnless(hasattr(os, 'getpriority') and hasattr(os, 'setpriority'),
3323 "needs os.getpriority and os.setpriority")
3325 """Tests for os.getpriority() and os.setpriority()."""
3329 base = os.getpriority(os.PRIO_PROCESS, os.getpid())
3330 os.setpriority(os.PRIO_PROCESS, os.getpid(), base + 1)
3332 new_prio = os.getpriority(os.PRIO_PROCESS, os.getpid())
3340 os.setpriority(os.PRIO_PROCESS, os.getpid(), base)
3346 @unittest.skipUnless(hasattr(os, 'sendfile'), "test needs os.sendfile()")
3396 return await asyncio.to_thread(os.sendfile, *args, **kwargs)
3552 @unittest.skipUnless(hasattr(os, 'SF_NODISKIO'),
3553 'test needs os.SF_NODISKIO')
3557 flags=os.SF_NODISKIO)
3564 if not hasattr(os, "setxattr"):
3570 os.setxattr(fp.fileno(), b"user.test", b"")
3602 setxattr(fn, s("user.test"), b"hello", os.XATTR_REPLACE, **kwargs)
3606 setxattr(fn, s("user.test"), b"bye", os.XATTR_CREATE, **kwargs)
3610 setxattr(fn, s("user.test2"), b"bye", os.XATTR_REPLACE, **kwargs)
3613 setxattr(fn, s("user.test2"), b"foo", os.XATTR_CREATE, **kwargs)
3637 self._check_xattrs_str(os.fsencode, *args, **kwargs)
3641 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
3642 os.listxattr)
3645 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
3646 os.listxattr, follow_symlinks=False)
3651 return os.getxattr(fp.fileno(), *args)
3654 os.setxattr(fp.fileno(), *args)
3657 os.removexattr(fp.fileno(), *args)
3660 return os.listxattr(fp.fileno(), *args)
3664 @unittest.skipUnless(hasattr(os, 'get_terminal_size'), "requires os.get_terminal_size")
3673 size = os.get_terminal_size()
3703 actual = os.get_terminal_size(sys.__stdin__.fileno())
3713 @unittest.skipUnless(hasattr(os, 'memfd_create'), 'requires os.memfd_create')
3717 fd = os.memfd_create("Hi", os.MFD_CLOEXEC)
3719 self.addCleanup(os.close, fd)
3720 self.assertFalse(os.get_inheritable(fd))
3725 fd2 = os.memfd_create("Hi")
3726 self.addCleanup(os.close, fd2)
3727 self.assertFalse(os.get_inheritable(fd2))
3730 @unittest.skipUnless(hasattr(os, 'eventfd'), 'requires os.eventfd')
3740 fd = os.eventfd(initval)
3742 self.addCleanup(os.close, fd)
3743 self.assertFalse(os.get_inheritable(fd))
3746 res = os.read(fd, size)
3749 os.write(fd, pack(23))
3750 res = os.read(fd, size)
3753 os.write(fd, pack(40))
3754 os.write(fd, pack(2))
3755 res = os.read(fd, size)
3759 os.eventfd_write(fd, 20)
3760 os.eventfd_write(fd, 3)
3761 res = os.eventfd_read(fd)
3766 flags = os.EFD_CLOEXEC | os.EFD_SEMAPHORE | os.EFD_NONBLOCK
3767 fd = os.eventfd(initval, flags)
3769 self.addCleanup(os.close, fd)
3772 res = os.eventfd_read(fd)
3774 res = os.eventfd_read(fd)
3778 os.eventfd_read(fd)
3780 os.read(fd, 8)
3783 os.eventfd_write(fd, 1)
3784 res = os.eventfd_read(fd)
3788 os.eventfd_read(fd)
3791 flags = os.EFD_CLOEXEC | os.EFD_NONBLOCK
3792 fd = os.eventfd(0, flags)
3794 self.addCleanup(os.close, fd)
3801 os.eventfd_write(fd, 23)
3804 self.assertEqual(os.eventfd_read(fd), 23)
3807 os.eventfd_write(fd, (2**64) - 2)
3810 os.eventfd_read(fd)
3829 encoded = os.fsencode(os_helper.TESTFN)
3838 (self.filenames, os.chdir,),
3839 (self.filenames, os.lstat,),
3840 (self.filenames, os.open, os.O_RDONLY),
3841 (self.filenames, os.rmdir,),
3842 (self.filenames, os.stat,),
3843 (self.filenames, os.unlink,),
3847 (self.bytes_filenames, os.rename, b"dst"),
3848 (self.bytes_filenames, os.replace, b"dst"),
3849 (self.unicode_filenames, os.rename, "dst"),
3850 (self.unicode_filenames, os.replace, "dst"),
3851 (self.unicode_filenames, os.listdir, ),
3855 (self.filenames, os.listdir,),
3856 (self.filenames, os.rename, "dst"),
3857 (self.filenames, os.replace, "dst"),
3860 funcs.append((self.filenames, os.chmod, 0o777))
3861 if hasattr(os, "chown"):
3862 funcs.append((self.filenames, os.chown, 0, 0))
3863 if hasattr(os, "lchown"):
3864 funcs.append((self.filenames, os.lchown, 0, 0))
3865 if hasattr(os, "truncate"):
3866 funcs.append((self.filenames, os.truncate, 0))
3867 if hasattr(os, "chflags"):
3868 funcs.append((self.filenames, os.chflags, 0))
3869 if hasattr(os, "lchflags"):
3870 funcs.append((self.filenames, os.lchflags, 0))
3871 if hasattr(os, "chroot"):
3872 funcs.append((self.filenames, os.chroot,))
3873 if hasattr(os, "link"):
3875 funcs.append((self.bytes_filenames, os.link, b"dst"))
3876 funcs.append((self.unicode_filenames, os.link, "dst"))
3878 funcs.append((self.filenames, os.link, "dst"))
3879 if hasattr(os, "listxattr"):
3881 (self.filenames, os.listxattr,),
3882 (self.filenames, os.getxattr, "user.test"),
3883 (self.filenames, os.setxattr, "user.test", b'user'),
3884 (self.filenames, os.removexattr, "user.test"),
3886 if hasattr(os, "lchmod"):
3887 funcs.append((self.filenames, os.lchmod, 0o777))
3888 if hasattr(os, "readlink"):
3889 funcs.append((self.filenames, os.readlink,))
3909 cpus = os.cpu_count()
3921 fd = os.open(__file__, os.O_RDONLY)
3922 self.addCleanup(os.close, fd)
3923 self.assertEqual(os.get_inheritable(fd), False)
3925 os.set_inheritable(fd, True)
3926 self.assertEqual(os.get_inheritable(fd), True)
3930 fd = os.open(__file__, os.O_RDONLY)
3931 self.addCleanup(os.close, fd)
3932 self.assertEqual(os.get_inheritable(fd), False)
3939 self.assertEqual(os.get_inheritable(fd), True)
3943 fd = os.open(__file__, os.O_RDONLY)
3944 self.addCleanup(os.close, fd)
3948 os.set_inheritable(fd, True)
3952 @unittest.skipUnless(hasattr(os, 'O_PATH'), "need os.O_PATH")
3954 fd = os.open(__file__, os.O_PATH)
3955 self.addCleanup(os.close, fd)
3956 self.assertEqual(os.get_inheritable(fd), False)
3958 os.set_inheritable(fd, True)
3959 self.assertEqual(os.get_inheritable(fd), True)
3961 os.set_inheritable(fd, False)
3962 self.assertEqual(os.get_inheritable(fd), False)
3968 os.get_inheritable(fd)
3972 os.set_inheritable(fd, True)
3976 os.set_inheritable(fd, False)
3980 fd = os.open(__file__, os.O_RDONLY)
3981 self.addCleanup(os.close, fd)
3982 self.assertEqual(os.get_inheritable(fd), False)
3984 @unittest.skipUnless(hasattr(os, 'pipe'), "need os.pipe()")
3986 rfd, wfd = os.pipe()
3987 self.addCleanup(os.close, rfd)
3988 self.addCleanup(os.close, wfd)
3989 self.assertEqual(os.get_inheritable(rfd), False)
3990 self.assertEqual(os.get_inheritable(wfd), False)
3993 fd1 = os.open(__file__, os.O_RDONLY)
3994 self.addCleanup(os.close, fd1)
3996 fd2 = os.dup(fd1)
3997 self.addCleanup(os.close, fd2)
3998 self.assertEqual(os.get_inheritable(fd2), False)
4001 fd = os.dup(1)
4002 self.addCleanup(os.close, fd)
4007 # os.dup() was creating inheritable fds for character files.
4008 fd1 = os.open('NUL', os.O_RDONLY)
4009 self.addCleanup(os.close, fd1)
4010 fd2 = os.dup(fd1)
4011 self.addCleanup(os.close, fd2)
4012 self.assertFalse(os.get_inheritable(fd2))
4014 @unittest.skipUnless(hasattr(os, 'dup2'), "need os.dup2()")
4016 fd = os.open(__file__, os.O_RDONLY)
4017 self.addCleanup(os.close, fd)
4020 fd2 = os.open(__file__, os.O_RDONLY)
4021 self.addCleanup(os.close, fd2)
4022 self.assertEqual(os.dup2(fd, fd2), fd2)
4023 self.assertTrue(os.get_inheritable(fd2))
4026 fd3 = os.open(__file__, os.O_RDONLY)
4027 self.addCleanup(os.close, fd3)
4028 self.assertEqual(os.dup2(fd, fd3, inheritable=False), fd3)
4029 self.assertFalse(os.get_inheritable(fd3))
4031 @unittest.skipUnless(hasattr(os, 'openpty'), "need os.openpty()")
4033 master_fd, slave_fd = os.openpty()
4034 self.addCleanup(os.close, master_fd)
4035 self.addCleanup(os.close, slave_fd)
4036 self.assertEqual(os.get_inheritable(master_fd), False)
4037 self.assertEqual(os.get_inheritable(slave_fd), False)
4046 ('access', False, (os.F_OK,), None),
4049 ('open', False, (os.O_RDONLY,), getattr(os, 'close', None)),
4054 if os.name == 'nt':
4057 bytes_filename = os.fsencode(os_helper.TESTFN)
4059 fd = os.open(FakePath(str_filename), os.O_WRONLY|os.O_CREAT)
4061 self.addCleanup(os.close, fd)
4069 fn = getattr(os, name)
4093 'os.PathLike'):
4099 os.stat(FakePath(2))
4101 os.stat(FakePath(2.34))
4103 os.stat(FakePath(object()))
4106 @unittest.skipUnless(hasattr(os, 'get_blocking'),
4107 'needs os.get_blocking() and os.set_blocking()')
4111 fd = os.open(__file__, os.O_RDONLY)
4112 self.addCleanup(os.close, fd)
4113 self.assertEqual(os.get_blocking(fd), True)
4115 os.set_blocking(fd, False)
4116 self.assertEqual(os.get_blocking(fd), False)
4118 os.set_blocking(fd, True)
4119 self.assertEqual(os.get_blocking(fd), True)
4125 self.assertIn('open', os.__all__)
4126 self.assertIn('walk', os.__all__)
4131 self.path = os.path.realpath(os_helper.TESTFN)
4133 os.mkdir(self.path)
4136 self.assertRaises(TypeError, os.DirEntry)
4139 filename = create_file(os.path.join(self.path, "file.txt"), b'python')
4140 entry = [entry for entry in os.scandir(self.path)].pop()
4141 self.assertIsInstance(entry, os.DirEntry)
4151 self.path = os.path.realpath(os_helper.TESTFN)
4152 self.bytes_path = os.fsencode(self.path)
4154 os.mkdir(self.path)
4158 filename = os.path.join(path, name)
4164 for entry in os.scandir(self.path))
4182 scandir_iter = os.scandir(self.path)
4188 scandir_iter = os.scandir(self.path)
4194 self.assertIsInstance(entry, os.DirEntry)
4196 self.assertEqual(entry.path, os.path.join(self.path, name))
4198 os.stat(entry.path, follow_symlinks=False).st_ino)
4200 entry_stat = os.stat(entry.path)
4206 os.path.islink(entry.path))
4208 entry_lstat = os.stat(entry.path, follow_symlinks=False)
4216 os.name == 'nt' and not is_symlink)
4219 os.name == 'nt')
4222 link = hasattr(os, 'link')
4225 dirname = os.path.join(self.path, "dir")
4226 os.mkdir(dirname)
4230 os.link(filename, os.path.join(self.path, "link_file.txt"))
4232 self.skipTest('os.link(): %s' % e)
4234 os.symlink(dirname, os.path.join(self.path, "symlink_dir"),
4236 os.symlink(filename, os.path.join(self.path, "symlink_file.txt"))
4264 entries = list(os.scandir(path))
4273 return self.get_entry(os.path.basename(filename))
4277 old_dir = os.getcwd()
4279 os.chdir(self.path)
4283 entries = dict((entry.name, entry) for entry in os.scandir())
4285 [os.path.basename(filename)])
4287 os.chdir(old_dir)
4295 self.assertEqual(os.fspath(entry), os.path.join(self.path, 'file.txt'))
4298 bytes_filename = os.fsencode('bytesfile.txt')
4300 fspath = os.fspath(bytes_entry)
4303 os.path.join(os.fsencode(self.path),bytes_filename))
4306 path = os.path.join(self.path, 'dir')
4308 os.mkdir(path)
4310 os.rmdir(path)
4313 if os.name == 'nt':
4317 if os.name == 'nt':
4329 os.unlink(entry.path)
4333 if os.name == 'nt':
4336 if os.name == 'nt':
4351 os.symlink(filename,
4352 os.path.join(self.path, "symlink.txt"))
4355 os.unlink(filename)
4370 path_bytes = os.fsencode(self.path)
4371 entries = list(os.scandir(path_bytes))
4377 os.fsencode(os.path.join(self.path, 'file.txt')))
4383 path_bytes = cls(os.fsencode(self.path))
4385 entries = list(os.scandir(path_bytes))
4391 os.fsencode(os.path.join(self.path, 'file.txt')))
4395 @unittest.skipUnless(os.listdir in os.supports_fd,
4398 self.assertIn(os.scandir, os.supports_fd)
4402 os.symlink('file.txt', os.path.join(self.path, 'link'))
4406 with os.scandir(fd) as it:
4410 self.assertEqual(names, os.listdir(fd))
4413 self.assertEqual(os.fspath(entry), entry.name)
4415 if os.stat in os.supports_dir_fd:
4416 st = os.stat(entry.name, dir_fd=fd)
4418 st = os.stat(entry.name, dir_fd=fd, follow_symlinks=False)
4423 self.assertRaises(FileNotFoundError, os.scandir, '')
4427 iterator = os.scandir(self.path)
4438 self.assertRaises(TypeError, os.scandir, obj)
4443 iterator = os.scandir(self.path)
4454 with os.scandir(self.path) as iterator:
4462 with os.scandir(self.path) as iterator:
4470 with os.scandir(self.path) as iterator:
4479 iterator = os.scandir(self.path)
4485 iterator = os.scandir(self.path)
4495 fspath = staticmethod(os.fspath)
4510 self.assertEqual(b"path/like/object", os.fsencode(pathlike))
4511 self.assertEqual("path/like/object", os.fsdecode(pathlike))
4515 self.assertTrue(issubclass(FakePath, os.PathLike))
4516 self.assertTrue(isinstance(FakePath('x'), os.PathLike))
4520 for o in int, type, os, vapor():
4540 class A(os.PathLike):
4543 self.assertTrue(issubclass(FakePath, os.PathLike))
4546 self.assertIsInstance(os.PathLike[bytes], types.GenericAlias)
4551 times = os.times()
4552 self.assertIsInstance(times, os.times_result)
4559 if os.name == 'nt':
4568 # bpo-42540: ensure os.fork() with non-default memory allocator does
4571 import os
4573 pid = os.fork()
4583 if hasattr(os, "_fspath"):
4586 """Explicitly test the pure Python implementation of os.fspath()."""
4588 fspath = staticmethod(os._fspath)