模拟Numpy结构化数组 [英] Mocking Numpy Structured Arrays

查看:103
本文介绍了模拟Numpy结构化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何模拟一个numpy结构化数组,但运气不佳.理想情况下,我想做这样的事情:

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']

我了解如何使用side_effect模拟单个词典,但是还没有弄清楚如何为任意嵌套的__getitem____setitem__函数使用它.

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.

以下是一些上下文:

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

这样,我可以使用一些垃圾值从字面上模拟对象self.my_structured_array,以测试其他逻辑.关键是字典对象实际上是与h5py库绑定的,因此为什么要模拟它.

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.

推荐答案

我相信我找到了解决方案.似乎有些la脚,但这是我已经可以拿到的壁橱:

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']

我真正看到的唯一问题是它不适用于多个级别.即mock_obj['some']['test']返回一个模拟对象而不是3.

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.

这篇关于模拟Numpy结构化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆