简体   繁体   中英

Mocking Numpy Structured Arrays

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.

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. ie mock_obj['some']['test'] returns a mock object and not 3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM