[TIP] testing calls to mocked open?

Julian Berman julian at grayvines.com
Wed Sep 14 11:06:17 PDT 2011

On Sep 14, 2011, at 1:23 PM, Andrew Hammond wrote:

> I have the following code that I want to test:
>        with open(self.file_name, 'rb') as f:
>            f.seek(self.last_byte_uploaded)
>            chunk = f.read(self.chunk_size)
> Using Mock, I have patched open and the following tests work correctly:
>        k = self.mock_open.call_args_list
>        self.assertEquals(1, len(k))
>        self.assertEquals(('/path/to/fake_file_name.txt', 'rb'), k[0][0])
>        self.assertEquals({}, k[0][1])

In case you're unaware, there's a quick way of writing your assertion using assert_called_once_with. The answer to your question (at least how I generally do it) is to do something like:

mock_file = mock.Mock()

with mock.patch(yourmodule, "open", create=True) as mock_open:
    mock_open.return_value = mock_file
    mock_open.assert_called_once_with(('/path/to/fake_file_name.txt', 'rb'))

You can also make mock_file have the spec of a file object if you want to be careful about that.

(Mock is lovely :)

-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 1539 bytes
Desc: not available
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20110914/1772017d/attachment.bin>

More information about the testing-in-python mailing list