相关疑难解决方法(0)

比较(断言相等)两个在unittest中包含numpy数组的复杂数据结构

我使用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的答案 ;
  • 在比较中总是将它用作LHS.

我在这方面的问题是:

  1. 它会起作用吗(我的意思是,这对我来说听起来不错,但也许一些棘手的边缘案例无法正确处理)?正如我所期望的那样,我的自定义对象总是在递归等式检查中最终成为LHS吗?
  2. 再次,有更好的方法(鉴于我至少得到一个真实numpy数组的结构).

编辑2:我试了一下,(看似)工作实现在这个答案中显示 …

python unit-testing numpy

20
推荐指数
3
解决办法
2万
查看次数

模拟:assert_called_once_with一个numpy数组作为参数

我在类中有一个方法,我想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)

python unit-testing numpy mocking

4
推荐指数
1
解决办法
1879
查看次数

标签 统计

numpy ×2

python ×2

unit-testing ×2

mocking ×1