phy*_*ion 4 python unit-testing numpy mocking
我在类中有一个方法,我想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__
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()
Run Code Online (Sandbox Code Playgroud)
比较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')
Run Code Online (Sandbox Code Playgroud)
您可以访问Mock()by call_args 属性的被调用参数,并np.testing.assert_array_equal按照/sf/answers/1044494601/和/sf/answers/997480641/中的指示比较两个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])
Run Code Online (Sandbox Code Playgroud)