Python Mock:assert_调用_once_,以numpy数组作为参数
我有一个类中的方法,我想使用Python 3.4使用Python Mock:assert_调用_once_,以numpy数组作为参数,python,unit-testing,numpy,mocking,Python,Unit Testing,Numpy,Mocking,我有一个类中的方法,我想使用Python 3.4使用unittest框架测试它。我更喜欢使用Mock作为要测试的类的对象,正如Daniel Arbuckle的学习Python测试中所解释的那样 问题 这就是我要做的: class Test_set_initial_clustering_rand(TestCase): def setUp(self): self.sut = Mock() def test_gw_01(self): self.sut
unittest
框架测试它。我更喜欢使用Mock
作为要测试的类的对象,正如Daniel Arbuckle的学习Python测试中所解释的那样
问题
这就是我要做的:
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\u clustering
是否使用预期参数调用一次。框架尝试使用actual\u arg==expected\u 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
访问Mock()的被调用参数,并通过np.testing.assert_array_equal
比较两个numpy数组,如和中所述
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])