0

I have a function that searches for .json files in directory recursively. It uses pathlib.

def search(where: Path) -> List[Path]: ...

I want to unit test it, so I need to a way create fake Path object with children, so that fake_path.iterdir() and fake_path.resolve() would work.

Ideally, I want this:

topdir = FakePath()
subdir1 = FakePath()
subdir1.add_children(Path('file1'), Path('file2'))
topdir.add_children(subdir1)

for dir in topdir.iterdir():
    for file in dir.iterdir():
        print(file.name)

>> file1
>> file2

and have it behave like normal Path object after that.

Is there a library that does that? Or can pathlib do what I want, and I'm just blind?

(I know I can just create temp files, but I'd prefer to not have any IO in unit tests.)

Alexey
  • 3
  • 1
  • 3
  • I'd say: don't. `pathlib` is already well tested and proven. I don't see what `search()` function adds, especially seeing that its interface is identical to the underlying pathlib call (you *are* using `glob()`, right?) – smassey Apr 07 '18 at 07:35
  • In this particular case, I think you're right. But with more complex logic, like if want to move files to directories based on part of a name of a file, I'd want to test that. (Shame on me, I used `chain(*(p.iterdir() for p in mydir.iterdir()))` with `filter` instead of `glob` .) – Alexey Apr 07 '18 at 07:46
  • Take a look at https://stackoverflow.com/questions/19672138/how-do-i-mock-the-filesystem-in-python-unit-tests – sudormrfbin Apr 07 '18 at 08:57
  • @Gokul Thanks! Guess I should just get better at googling (: Looks like `pyfakefs` from second answer is exactly what I need. – Alexey Apr 07 '18 at 09:04
  • Use `glob.glob("**/*.json", recursive=True)`, since it's from stdlib, there's no need to test it :) – Dima Tisnek Oct 02 '19 at 03:16

0 Answers0