[TIP] testing calls to mocked open?

Andrew Hammond andrew.george.hammond at gmail.com
Wed Sep 14 10:23:37 PDT 2011

I have the following code that I want to test:

        with open(self.file_name, 'rb') as f:
            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])

However I can't figure out how to get the next segment to work. I'd
like to prove that the opened file called seek(0) and then read(1024)

# TODO: figure out how to test this
#        l = self.mock_open.return_value.method_calls
#        self.assertEquals(2, len(l))
#        self.assertEquals('seek', l[0][0])
#        self.assertEquals((0), l[0][1])
#        self.assertEquals({}, l[0][2])
#        self.assertEquals('read', l[1][0])
#        self.assertEquals((1024), l[1][1])
#        self.assertEquals({}, l[1][2])


More information about the testing-in-python mailing list