title: Mocking open() on pathlib.Path to return a mock file handle with unittest.mock
body: <p>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:</p>
  
  <pre><code>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}
  </code></pre>
  
  <p>Now say I want to test that if I pass in e.g. <code>C:\wherever\file_name.xyz</code> that the returned dictionary contains the key <code>file_name.xyz</code>. Since my method under test is opening and reading files, I want to mock out the Path object. I think I can do <em>something like</em>:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>But I can't figure out how to get <code>f.name</code> (i.e. <code>mock_path.open().name</code>) to return <code>file_name.xyz</code>. </p>