How to mock os.walk in python with a temporary filesystem?
No. os.walk()
is constructed entirely around os.listdir()
, with assistance of os.path.islink()
and os.path.isdir()
. These are essentially system calls, so you'd have to mock your filesystem at the system level. Unless you want to write a FUSE plugin this is not going to be easy to mock.
All os.walk()
needs to return is a list of tuples, really. Unless you are testing manipulating the dirs
component, it couldn't be more simple:
with mock.patch('os.walk') as mockwalk: mockwalk.return_value = [ ('/foo', ('bar',), ('baz',)), ('/foo/bar', (), ('spam', 'eggs')), ]
This would mock the following directory structure:
/foo ├── baz └── bar ├── spam └── eggs