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

Mocking async call in python 3.5

Everyone’s missing what’s probably the simplest and clearest solution: @patch(‘some.path’) def test(self, mock): f = asyncio.Future() f.set_result(‘whatever result you want’) process_smtp_message.return_value = f mock.assert_called_with(1, 2, 3) remember a coroutine can be thought of as just a function which is guaranteed to return a future which can, in turn be awaited.

Python Mocking a function from an imported module

When you are using the patch decorator from the unittest.mock package you are patching it in the namespace that is under test (in this case app.mocking.get_user_name), not the namespace the function is imported from (in this case app.my_module.get_user_name). To do what you describe with @patch try something like the below: from mock import patch from … Read more