Customizing unittest.mock.mock_open for iteration
The mock_open() object does indeed not implement iteration. If you are not using the file object as a context manager, you could use: m = unittest.mock.MagicMock(name=”open”, spec=open) m.return_value = iter(self.TEST_TEXT) with unittest.mock.patch(‘builtins.open’, m): Now open() returns an iterator, something that can be directly iterated over just like a file object can be, and it’ll also … Read more