Skip to content

Commit 3f1ea16

Browse files
[3.9] bpo-46426: Improve tests for the dir_fd argument (GH-30668) (GH-30757)
Ensure that directory file descriptors refer to directories different from the current directory, and that src_dir_fd and dst_dir_fd refer to different directories. Add context manager open_dir_fd() in test.support.os_helper. (cherry picked from commit 54610bb) Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent 1398dca commit 3f1ea16

File tree

3 files changed

+207
-217
lines changed

3 files changed

+207
-217
lines changed

Lib/test/support/__init__.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1013,6 +1013,16 @@ def create_empty_file(filename):
10131013
fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
10141014
os.close(fd)
10151015

1016+
@contextlib.contextmanager
1017+
def open_dir_fd(path):
1018+
"""Open a file descriptor to a directory."""
1019+
assert os.path.isdir(path)
1020+
dir_fd = os.open(path, os.O_RDONLY)
1021+
try:
1022+
yield dir_fd
1023+
finally:
1024+
os.close(dir_fd)
1025+
10161026
def sortdict(dict):
10171027
"Like repr(dict), but in sorted order."
10181028
items = sorted(dict.items())

Lib/test/test_os.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -708,12 +708,9 @@ def set_time(filename, ns):
708708
def test_utime_dir_fd(self):
709709
def set_time(filename, ns):
710710
dirname, name = os.path.split(filename)
711-
dirfd = os.open(dirname, os.O_RDONLY)
712-
try:
711+
with support.open_dir_fd(dirname) as dirfd:
713712
# pass dir_fd to test utimensat(timespec) or futimesat(timeval)
714713
os.utime(name, dir_fd=dirfd, ns=ns)
715-
finally:
716-
os.close(dirfd)
717714
self._test_utime(set_time)
718715

719716
def test_utime_directory(self):
@@ -4111,8 +4108,7 @@ def test_fd(self):
41114108
os.symlink('file.txt', os.path.join(self.path, 'link'))
41124109
expected_names.append('link')
41134110

4114-
fd = os.open(self.path, os.O_RDONLY)
4115-
try:
4111+
with support.open_dir_fd(self.path) as fd:
41164112
with os.scandir(fd) as it:
41174113
entries = list(it)
41184114
names = [entry.name for entry in entries]
@@ -4127,8 +4123,6 @@ def test_fd(self):
41274123
self.assertEqual(entry.stat(), st)
41284124
st = os.stat(entry.name, dir_fd=fd, follow_symlinks=False)
41294125
self.assertEqual(entry.stat(follow_symlinks=False), st)
4130-
finally:
4131-
os.close(fd)
41324126

41334127
def test_empty_path(self):
41344128
self.assertRaises(FileNotFoundError, os.scandir, '')

0 commit comments

Comments
 (0)