user2201041
user2201041

Reputation:

How do I test that I'm calling pickle.dump() correctly?

I want to test this method:

class Data(object):

    def save(self, filename=''):
        if filename:
            self.filename = filename
        if not self.filename:
            raise ValueError('Please provide a path to save to')
        with open(self.filename, 'w') as f:
            pickle.dump(self, f)

I can set up the test to make sure pickle.dump gets called, and that the first argument is the object:

@patch('pickle.dump')
def test_pickle_called(self, dump):
    self.data.save('foo.pkl')
    self.assertTrue(dump.called)
    self.assertEquals(self.data, dump.call_args[0][0])

I'm not sure what to do for the second argument, though. If I open a new file for the test, it's not going to be the same as what gets called for the execution. I'd at least like to be sure I'm opening the right file. Would I just mock open and make sure that gets called with the right name at some point?

Upvotes: 3

Views: 2643

Answers (1)

phd
phd

Reputation: 94696

Patch open() and return an instance of writeable StringIO from it. Load pickled data from that StringIO and test its structure and values (test that it's equivalent to self.data). Something like this:

import builtins # or __builtin__ for Python 2
builtins.open = open = Mock()
open.return_value = sio = StringIO()
self.data.save('foo.pkl')
new_data = pickle.load(sio.getvalue())
self.assertEqual(self.data, new_data)

Upvotes: 5

Related Questions