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

Mock: assert_called_once_with a numpy array as argument

我在 class 中有一个方法,我想使用 unittest 框架测试,使用 Python 3.4。我更喜欢使用 Mock 作为 class 的对象进行测试,如 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)

这将检查函数 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__
    return not self.__eq__(other)
  File "/Users/.../anaconda/lib/python3.4/unittest/mock.py", line 1997, in __eq__
    return (other_args, other_kwargs) == (self_args, self_kwargs)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

比较 numpy 数组是以不同的方式完成的,但比较是在 unittest 框架内进行的。解决此问题的最佳方法是什么?

解决方案 1

我找到了以下解决方案,想在这里分享,希望得到反馈。

class Test_set_initial_clustering_rand(TestCase):

    def setUp(self):
        '''
        This class tests the method set_initial_clustering_rand,
        which makes use of the function set_clustering. For the
        sut is concerned, all that set_clustering has to do is
        to store the value of the input clustering. Therefore,
        this is mocked here.
        '''
        self.sut = Mock()
        self.sut.seed = 1
        def mock_set_clustering(input_clustering):
            self.sut.clustering = input_clustering
        self.sut.set_clustering.side_effect = mock_set_clustering

    def test_gw_01(self):
        ClustererKmeans.set_initial_clustering_rand(self.sut, N_clusters=1, N_persons=6)
        r = self.sut.clustering
        e = np.array([0, 0, 0, 0, 0, 0])
        TestUtils.equal_np_matrix(self, r, e, 'clustering')

您可以通过 call_args property and compare two numpy array by np.testing.assert_array_equal as pointed out in and

访问 Mock() 的调用参数
def test_gw_01(self):
    m = Mock()
    ClustererKmeans.set_initial_clustering_rand(m, N_clusters=1, N_persons=6)
    self.assertTrue(m.set_clustering)
    np.testing.assert_array_equal(np.array([0, 0, 0, 0, 0, 0]),m.set_clustering.call_args[0][0])