Skip to content

Commit b9df036

Browse files
committed
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
1 parent c0aebec commit b9df036

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

CHANGES.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,13 @@ The released versions correspond to PyPi releases.
33

44
## Version 4.6.0 (as yet unreleased)
55

6+
### Changes
7+
* `os.listdir`, `os.scandir` and `pathlib.Path.listdir` now return the
8+
directory list in a random order only if explicitly configured in the
9+
file system (use `fs.shuffle_listdir_results = True` with `fs` being the
10+
file system). In a future version, the default may be changed to better
11+
reflect the real filesystem behavior (see [#647](../../issues/647))
12+
613
## [Version 4.5.2](https://pypi.python.org/pypi/pyfakefs/4.5.2) (2021-11-07)
714
This is a bugfix release.
815

pyfakefs/fake_filesystem.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -957,6 +957,7 @@ def __init__(self, path_separator: str = os.path.sep,
957957
self.dev_null = FakeNullFile(self)
958958
# set from outside if needed
959959
self.patch_open_code = PatchMode.OFF
960+
self.shuffle_listdir_results = False
960961

961962
@property
962963
def is_linux(self) -> bool:
@@ -3227,16 +3228,17 @@ def listdir(self, target_directory: AnyStr) -> List[AnyStr]:
32273228
32283229
Returns:
32293230
A list of file names within the target directory in arbitrary
3230-
order. Note that the order is intentionally not the same in
3231-
subsequent calls to avoid tests relying on any ordering.
3231+
order. If `shuffle_listdir_results` is set, the order is not the
3232+
same in subsequent calls to avoid tests relying on any ordering.
32323233
32333234
Raises:
32343235
OSError: if the target is not a directory.
32353236
"""
32363237
target_directory = self.resolve_path(target_directory, allow_fd=True)
32373238
directory = self.confirmdir(target_directory)
32383239
directory_contents = list(directory.entries.keys())
3239-
random.shuffle(directory_contents)
3240+
if self.shuffle_listdir_results:
3241+
random.shuffle(directory_contents)
32403242
return directory_contents # type: ignore[return-value]
32413243

32423244
def __str__(self) -> str:

0 commit comments

Comments
 (0)