如何测试我是否正确调用了 pickle.dump()? [英] How do I test that I'm calling pickle.dump() correctly?
问题描述
我想测试这个方法:
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)
我可以设置测试以确保 pickle.dump
被调用,并且第一个参数是对象:
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])
不过,我不确定如何处理第二个参数.如果我为测试打开一个新文件,它将与执行时调用的文件不同.我至少想确定我打开的是正确的文件.我会模拟 open
并确保在某个时候使用正确的名称调用它吗?
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?
推荐答案
Patch open()
并从中返回可写 StringIO 的实例.从该 StringIO 加载腌制数据并测试其结构和值(测试它是否等效于 self.data).像这样:
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)
这篇关于如何测试我是否正确调用了 pickle.dump()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!