Skip to content

Commit

Permalink
Randomize list order for FakeFilesystem.listdir
Browse files Browse the repository at this point in the history
- makes the output order for os.listdir, `os.scandir` and `pathlib.Path.listdir` random
- see pytest-dev#638
  • Loading branch information
mrbean-bremen committed Sep 23, 2021
1 parent dfda25a commit 169b25e
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
6 changes: 5 additions & 1 deletion CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Expand Down
9 changes: 6 additions & 3 deletions pyfakefs/fake_filesystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
import io
import locale
import os
import random
import sys
import traceback
import uuid
Expand Down Expand Up @@ -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[arg-type]

def __str__(self) -> str:
return str(self.root)
Expand Down

0 comments on commit 169b25e

Please sign in to comment.