我使用Python的unittest模块,并想检查两个复杂的数据结构是否相等.对象可以是具有各种值的dicts列表:数字,字符串,Python容器(列表/元组/ dicts)和numpy数组.后者是提出问题的原因,因为我不能这样做
self.assertEqual(big_struct1, big_struct2)
Run Code Online (Sandbox Code Playgroud)
因为它会产生一个
ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()
Run Code Online (Sandbox Code Playgroud)
我想我需要为此编写自己的相等测试.它应该适用于任意结构.我目前的想法是递归函数:
arg1到相应节点arg2;ValueError被抓住,会更深入,直到找到numpy.array;看起来有点问题的是跟踪两个结构的"相应"节点,但也许这zip就是我所需要的.
问题是:这种方法有更好(更简单)的替代方案吗?也许numpy为此提供了一些工具?如果没有建议的替代方案,我将实施这个想法(除非我有一个更好的想法)并发布作为答案.
PS我有一种模糊的感觉,我可能已经看到了解决这个问题的问题,但我现在找不到它.
PPS另一种方法是遍历结构并将所有numpy.arrays 转换为列表的函数,但是这更容易实现吗?对我来说似乎一样.
编辑:子类化numpy.ndarray听起来很有希望,但显然我没有将比较的两面硬编码到测试中.但其中一个确实是硬编码的,所以我可以:
numpy.array;isinstance(other, SaneEqualityArray)以isinstance(other, np.ndarray)在jterrace的答案 ;我在这方面的问题是:
numpy数组的结构).编辑2:我试了一下,(看似)工作实现在这个答案中显示 …
我在类中有一个方法,我想unittest使用Python 3.4 使用框架进行测试.我更喜欢使用a Mock作为类的对象来测试,正如Daniel Arbuckle的Learning Python Testing中所解释的那样.
问题
这就是我要做的:
class Test_set_initial_clustering_rand(TestCase):
def setUp(self):
self.sut = Mock()
def test_gw_01(self):
self.sut.seed = 1
ClustererKmeans.set_initial_clustering_rand(self.sut, N_clusters=1, N_persons=6)
e = np.array([0, 0, 0, 0, 0, 0])
self.sut.set_clustering.assert_called_once_with(e)
Run Code Online (Sandbox Code Playgroud)
这将检查函数set_clustering是否使用期望参数调用一次.框架尝试使用比较两个参数actual_arg == expected_arg.如果参数是一个numpy数组,则会出错.
Traceback (most recent call last):
File "/Users/.../UT_ClustererKmeans.py", line 184, in test_gw_01
self.sut.set_clustering.assert_called_once_with(e)
File "/Users/.../anaconda/lib/python3.4/unittest/mock.py", line 782, in assert_called_once_with
return self.assert_called_with(*args, **kwargs)
File "/Users/.../anaconda/lib/python3.4/unittest/mock.py", line 769, in assert_called_with
if expected != actual:
File "/Users/.../anaconda/lib/python3.4/unittest/mock.py", line 2001, in __ne__ …Run Code Online (Sandbox Code Playgroud)