[TIP] testing calls to mocked open?
Andrew Hammond
andrew.george.hammond at gmail.com
Wed Sep 14 12:48:01 PDT 2011
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
More information about the testing-in-python
mailing list