Skip to content

Commit 54610bb

Browse files
bpo-46426: Improve tests for the dir_fd argument (GH-30668)
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.
1 parent 40fcd16 commit 54610bb

File tree

3 files changed

+208
-230
lines changed

3 files changed

+208
-230
lines changed

Lib/test/support/os_helper.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -455,6 +455,17 @@ def create_empty_file(filename):
455455
os.close(fd)
456456

457457

458+
@contextlib.contextmanager
459+
def open_dir_fd(path):
460+
"""Open a file descriptor to a directory."""
461+
assert os.path.isdir(path)
462+
dir_fd = os.open(path, os.O_RDONLY)
463+
try:
464+
yield dir_fd
465+
finally:
466+
os.close(dir_fd)
467+
468+
458469
def fs_is_case_insensitive(directory):
459470
"""Detects if the file system for the specified directory
460471
is case-insensitive."""

Lib/test/test_os.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -848,12 +848,9 @@ def set_time(filename, ns):
848848
def test_utime_dir_fd(self):
849849
def set_time(filename, ns):
850850
dirname, name = os.path.split(filename)
851-
dirfd = os.open(dirname, os.O_RDONLY)
852-
try:
851+
with os_helper.open_dir_fd(dirname) as dirfd:
853852
# pass dir_fd to test utimensat(timespec) or futimesat(timeval)
854853
os.utime(name, dir_fd=dirfd, ns=ns)
855-
finally:
856-
os.close(dirfd)
857854
self._test_utime(set_time)
858855

859856
def test_utime_directory(self):
@@ -4341,8 +4338,7 @@ def test_fd(self):
43414338
os.symlink('file.txt', os.path.join(self.path, 'link'))
43424339
expected_names.append('link')
43434340

4344-
fd = os.open(self.path, os.O_RDONLY)
4345-
try:
4341+
with os_helper.open_dir_fd(self.path) as fd:
43464342
with os.scandir(fd) as it:
43474343
entries = list(it)
43484344
names = [entry.name for entry in entries]
@@ -4357,8 +4353,6 @@ def test_fd(self):
43574353
self.assertEqual(entry.stat(), st)
43584354
st = os.stat(entry.name, dir_fd=fd, follow_symlinks=False)
43594355
self.assertEqual(entry.stat(follow_symlinks=False), st)
4360-
finally:
4361-
os.close(fd)
43624356

43634357
def test_empty_path(self):
43644358
self.assertRaises(FileNotFoundError, os.scandir, '')

0 commit comments

Comments
 (0)