From b9df0367e3edede2213e79a83b1dc348a4bdc757 Mon Sep 17 00:00:00 2001 From: mrbean-bremen Date: Mon, 8 Nov 2021 19:39:45 +0100 Subject: [PATCH] Make randomizing of listdir results optional - the default is to not randomize - can be changed by setting fs.shuffle_listdir_results to True - see #647 --- CHANGES.md | 7 +++++++ pyfakefs/fake_filesystem.py | 8 +++++--- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 841fadff..dbbfcf8f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -3,6 +3,13 @@ The released versions correspond to PyPi releases. ## Version 4.6.0 (as yet unreleased) +### Changes +* `os.listdir`, `os.scandir` and `pathlib.Path.listdir` now return the + directory list in a random order only if explicitly configured in the + file system (use `fs.shuffle_listdir_results = True` with `fs` being the + file system). In a future version, the default may be changed to better + reflect the real filesystem behavior (see [#647](../../issues/647)) + ## [Version 4.5.2](https://pypi.python.org/pypi/pyfakefs/4.5.2) (2021-11-07) This is a bugfix release. diff --git a/pyfakefs/fake_filesystem.py b/pyfakefs/fake_filesystem.py index bdbaa807..a4c58fcd 100644 --- a/pyfakefs/fake_filesystem.py +++ b/pyfakefs/fake_filesystem.py @@ -957,6 +957,7 @@ def __init__(self, path_separator: str = os.path.sep, self.dev_null = FakeNullFile(self) # set from outside if needed self.patch_open_code = PatchMode.OFF + self.shuffle_listdir_results = False @property def is_linux(self) -> bool: @@ -3227,8 +3228,8 @@ def listdir(self, target_directory: AnyStr) -> List[AnyStr]: Returns: A list of file names within the target directory in arbitrary - order. Note that the order is intentionally not the same in - subsequent calls to avoid tests relying on any ordering. + order. If `shuffle_listdir_results` is set, the order is not the + same in subsequent calls to avoid tests relying on any ordering. Raises: OSError: if the target is not a directory. @@ -3236,7 +3237,8 @@ def listdir(self, target_directory: AnyStr) -> List[AnyStr]: target_directory = self.resolve_path(target_directory, allow_fd=True) directory = self.confirmdir(target_directory) directory_contents = list(directory.entries.keys()) - random.shuffle(directory_contents) + if self.shuffle_listdir_results: + random.shuffle(directory_contents) return directory_contents # type: ignore[return-value] def __str__(self) -> str: