Skip to content

Commit a1015c6

Browse files
bpo-46426: Improve tests for the dir_fd argument (GH-30668) (GH-30739)
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 68a31db commit a1015c6

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):
@@ -4339,8 +4336,7 @@ def test_fd(self):
43394336
os.symlink('file.txt', os.path.join(self.path, 'link'))
43404337
expected_names.append('link')
43414338

4342-
fd = os.open(self.path, os.O_RDONLY)
4343-
try:
4339+
with os_helper.open_dir_fd(self.path) as fd:
43444340
with os.scandir(fd) as it:
43454341
entries = list(it)
43464342
names = [entry.name for entry in entries]
@@ -4355,8 +4351,6 @@ def test_fd(self):
43554351
self.assertEqual(entry.stat(), st)
43564352
st = os.stat(entry.name, dir_fd=fd, follow_symlinks=False)
43574353
self.assertEqual(entry.stat(follow_symlinks=False), st)
4358-
finally:
4359-
os.close(fd)
43604354

43614355
def test_empty_path(self):
43624356
self.assertRaises(FileNotFoundError, os.scandir, '')

0 commit comments

Comments
 (0)