[TIP] testing calls to mocked open?

Julian Berman julian at grayvines.com
Wed Sep 14 16:35:48 PDT 2011


Yes, apologies I was writing from memory and forgot that you need MagicMock :).

As per http://www.voidspace.org.uk/python/mock/examples.html#mocking-open I think
what you want should be:

   self.mock_open.return_value = mock.MagicMock(spec=file)
   self.mock_open.return_value.__enter__.return_value.seek.assert_called_once_with(0)
   self.mock_open.return_value.__enter__.return_value.read.assert_called_once_with(1024*5)

Julian

On Sep 14, 2011, at 3:48 PM, Andrew Hammond wrote:

> I've tried the approach you mention below but with no luck. My test
> code now reads:
> 
>        self.mock_open.assert_called_once_with('/path/to/fake_file_name.txt',
> 'rb')
> 
> # TODO: figure out how to test this
> #        self.mock_open.return_value.seek.assert_called_once_with(0)
> #        self.mock_open.return_value.read.assert_called_once_with(1024*5)
> 
> The first assertion passes, the two commented out assertions fail.
> 
> A
> 
> On Wed, Sep 14, 2011 at 11:06 AM, Julian Berman <julian at grayvines.com> wrote:
>> 
>> 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'))
>>    mock_file.seek.assert_called_once_with(self.byte_thing)
>>    mock_file.read.assert_called_once_with(whatever)
>> 
>> You can also make mock_file have the spec of a file object if you want to be careful about that.
>> 
>> (Mock is lovely :)
>> 
>> Julian

-------------- 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/26390367/attachment.bin>


More information about the testing-in-python mailing list