Skip to content

Commit

Permalink
[3.9] bpo-46426: Improve tests for the dir_fd argument (GH-30668) (GH…
Browse files Browse the repository at this point in the history
…-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 <storchaka@gmail.com>
  • Loading branch information
serhiy-storchaka committed Jan 24, 2022
1 parent 1398dca commit 3f1ea16
Show file tree
Hide file tree
Showing 3 changed files with 207 additions and 217 deletions.
10 changes: 10 additions & 0 deletions Lib/test/support/__init__.py
Expand Up @@ -1013,6 +1013,16 @@ def create_empty_file(filename):
fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
os.close(fd)

@contextlib.contextmanager
def open_dir_fd(path):
"""Open a file descriptor to a directory."""
assert os.path.isdir(path)
dir_fd = os.open(path, os.O_RDONLY)
try:
yield dir_fd
finally:
os.close(dir_fd)

def sortdict(dict):
"Like repr(dict), but in sorted order."
items = sorted(dict.items())
Expand Down
10 changes: 2 additions & 8 deletions Lib/test/test_os.py
Expand Up @@ -708,12 +708,9 @@ def set_time(filename, ns):
def test_utime_dir_fd(self):
def set_time(filename, ns):
dirname, name = os.path.split(filename)
dirfd = os.open(dirname, os.O_RDONLY)
try:
with support.open_dir_fd(dirname) as dirfd:
# pass dir_fd to test utimensat(timespec) or futimesat(timeval)
os.utime(name, dir_fd=dirfd, ns=ns)
finally:
os.close(dirfd)
self._test_utime(set_time)

def test_utime_directory(self):
Expand Down Expand Up @@ -4111,8 +4108,7 @@ def test_fd(self):
os.symlink('file.txt', os.path.join(self.path, 'link'))
expected_names.append('link')

fd = os.open(self.path, os.O_RDONLY)
try:
with support.open_dir_fd(self.path) as fd:
with os.scandir(fd) as it:
entries = list(it)
names = [entry.name for entry in entries]
Expand All @@ -4127,8 +4123,6 @@ def test_fd(self):
self.assertEqual(entry.stat(), st)
st = os.stat(entry.name, dir_fd=fd, follow_symlinks=False)
self.assertEqual(entry.stat(follow_symlinks=False), st)
finally:
os.close(fd)

def test_empty_path(self):
self.assertRaises(FileNotFoundError, os.scandir, '')
Expand Down

0 comments on commit 3f1ea16

Please sign in to comment.