diff --git a/CHANGES.md b/CHANGES.md index 83ce7247..5bb036d7 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -3,8 +3,12 @@ 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 (see [#638](../../issues/638)) + ### Fixes -* fixed handling of alternative path separator in `os.path.split`, +* fixed handling of alternative path separator in `os.path.split`, `os.path.splitdrive` and `glob.glob` (see [#632](../../issues/632)) diff --git a/pyfakefs/fake_filesystem.py b/pyfakefs/fake_filesystem.py index f80de28f..4c07280f 100644 --- a/pyfakefs/fake_filesystem.py +++ b/pyfakefs/fake_filesystem.py @@ -98,6 +98,7 @@ import io import locale import os +import random import sys import traceback import uuid @@ -3213,15 +3214,17 @@ def listdir(self, target_directory: AnyStr) -> List[AnyStr]: Returns: A list of file names within the target directory in arbitrary - order. + order. Note that the order is intentionally 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 = directory.entries - return list(directory_contents.keys()) # type: ignore[arg-type] + directory_contents = list(directory.entries.keys()) + random.shuffle(directory_contents) + return directory_contents # type: ignore[return-value] def __str__(self) -> str: return str(self.root)