如何模拟 pickle 文件的加载?

How to mock the load of pickle file?

我有一个要测试的生产代码 (code_to_test),它要求我模拟 pickle 文件加载测试以进一步验证。

def code_to_test():
  #need to mock the below line
  with open("path/to/file/model.pickle", "rb") as pickle_file:
     model_dictionary = dill.load(pickle_file)
  #some other stuff to validate based on the mock

我嘲讽如下

from unittest.mock import patch
with patch("path.of.module.code_to_test.dill.load") as _mock:
     _mock.return_value = some_dictionary_fixture

但是测试失败

当我尝试如下模拟时,它出现了

ModuleNotFoundError

更新: 我还尝试修补 builtins.open 并使用 mock_open (像这样 - )。但我不确定如何使用它来模拟我的案例。

你的补丁有点不对劲——你包括了这个功能,但你不应该:

from unittest.mock import patch
with patch("path.of.module.dill.load") as _mock:
     _mock.return_value = some_dictionary_fixture

但是,您甚至不需要它——因为 dill 是作为模块导入的,您可以直接对其进行修补:

import dill
from unittest import mock
with mock.patch.object(dill, 'load', return_value=some_dictionary_fixture):
    ...