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

时间:2015-01-05 14:16:50

标签: python unit-testing numpy mocking

我在类中有一个方法,我想使用Python 3.4使用unittest框架进行测试。我更喜欢使用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)

这将检查函数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')

1 个答案:

答案 0 :(得分:7)

您可以按Mock() property访问call_args的被叫参数,并按照https://stackoverflow.com/a/14921351/4101725和{{中的指示,按np.testing.assert_array_equal比较两个numpy数组3}}

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