Mocking Numpy Structured Arrays

杀马特。学长 韩版系。学妹 提交于 2019-12-13 06:11:43

问题


I'm trying to figure out how to mock a numpy structured array and am not having much luck. Ideally, I'd like to do something like this:

from mock import MagicMock
mock_obj = MagicMock()
mock_obj['some']['test']['structure'] = 3
assert 3 ==  mock_obj['some']['test']['structure']

I understand how to mock a single dictionary using the side_effect but haven't figured out how to do it for arbitrary, nested __getitem__ or __setitem__ functions.

EDIT:

Here is some context:

def function(self): 
    arr = self.my_structured_array['get']['some']['array']
    #Make decisions based on return value of arr

This way I can literally mock the object self.my_structured_array with some junk values to test other logic. The point is that the dictionary object is actually tied to the h5py library, hence why I want to mock it.


回答1:


I believe that I found the solution. It seems a bit lame, but it's the closet I've been able to get:

from mock import MagicMock
mock_obj = MagicMock()
mock_obj.__getitem__().__getitem__().__getitem__.return_value = 3
assert 3 ==  mock_obj['some']['test']['structure']

The only problem I really see with is that it doesn't work for multiple levels. i.e. mock_obj['some']['test'] returns a mock object and not 3.



来源:https://stackoverflow.com/questions/33511931/mocking-numpy-structured-arrays

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