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

让人想犯罪 __ 提交于 2021-01-27 16:45:06

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/44607468/how-do-i-test-that-im-calling-pickle-dump-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!