Say I have a method that gets passed some paths, reads the files at each of these paths, then returns a dictionary from file name to file content, like so:
from contextlib import ExitStack
from pathlib import Path
class ClassToTest:
def method_to_test(self, *paths: Path):
with ExitStack() as stack:
files = [stack.enter_context(path.open(mode='r')) for path in paths]
return {f.name: f.read() for f in files}
Now say I want to test that if I pass in e.g. C:\wherever\file_name.xyz
that the returned dictionary contains the key file_name.xyz
. Since my method under test is opening and reading files, I want to mock out the Path object. I think I can do something like:
from unittest.mock import Mock, mock_open
class Tests:
def test(self):
mock_path = Mock(spec=Path)
mock_path.open = mock_open()
# ???
files = ClassToTest().method_to_test(mock_path)
assert 'file_name.xyz' in files
But I can't figure out how to get f.name
(i.e. mock_path.open().name
) to return file_name.xyz
.