Skip to content

[3.9] bpo-46426: Improve tests for the dir_fd argument (GH-30668) #30757

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Lib/test/support/__init__.py
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Loading