Skip to content

Commit

Permalink
Make randomizing of listdir results optional
Browse files Browse the repository at this point in the history
- the default is to not randomize
- can be changed by setting fs.shuffle_listdir_results to True
- see #647
  • Loading branch information
mrbean-bremen committed Nov 8, 2021
1 parent c0aebec commit b9df036
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
7 changes: 7 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
8 changes: 5 additions & 3 deletions pyfakefs/fake_filesystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -3227,16 +3228,17 @@ 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.
"""
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:
Expand Down

0 comments on commit b9df036

Please sign in to comment.