问题
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