Unittest实现Python属性
我有一个具有以下属性的类Unittest实现Python属性,python,properties,unit-testing,Python,Properties,Unit Testing,我有一个具有以下属性的类集群: import numpy as np class ClustererKmeans(object): def __init__(self): self.clustering = np.array([0, 0, 1, 1, 3, 3, 3, 4, 5, 5]) @property def clusters(self): assert self.clustering is not None, 'A clust
集群:
import numpy as np
class ClustererKmeans(object):
def __init__(self):
self.clustering = np.array([0, 0, 1, 1, 3, 3, 3, 4, 5, 5])
@property
def clusters(self):
assert self.clustering is not None, 'A clustering shall be set before obtaining clusters'
return np.unique(self.clustering)
现在我想为这个简单属性编写一个单元测试。我从以下几点开始:
from unittest import TestCase, main
from unittest.mock import Mock
class Test_clusters(TestCase):
def test_gw_01(self):
sut = Mock()
sut.clustering = np.array([0, 0, 1, 1, 3, 3, 3, 4, 5, 5])
r = ClustererKmeans.clusters(sut)
e = np.array([0, 1, 3, 4, 5])
# The following line checks to see if the two numpy arrays r and e are equal,
# and gives a detailed error message if they are not.
TestUtils.equal_np_matrix(self, r, e, 'clusters')
if __name__ == "__main__":
main()
但是,这不会运行
TypeError: 'property' object is not callable
接下来,我将行r=clusterkmeans.clusters(sut)
更改为以下内容:
r = sut.clusters
但是,我又犯了一个意想不到的错误
AssertionError: False is not true : r shall be a <class 'numpy.ndarray'> (is now a <class 'unittest.mock.Mock'>)
AssertionError:False不是true:r应该是a(现在是a)
有没有一种简单的方法可以使用unittest框架在Python中测试属性的实现?直接替换原始代码中的ClustererKmeans.clusters(sut)
byClustererKmeans.clusters.\uu get(sut)
即使我是一个嘲笑的热情的IMHO,这个案例也不是一个应用它的好例子。模拟对于从类和资源中删除依赖项很有用。在您的例子中,clusterkmeans
有一个空的构造函数,并且没有任何依赖关系需要打破。您可以通过以下方式完成:
class Test_clusters(TestCase):
def test_gw_01(self):
sut = ClustererKmeans()
sut.clustering = np.array([0, 0, 1, 1, 3, 3, 3, 4, 5, 5])
np.testing.assert_array_equal(np.array([0, 1, 2, 3, 4, 5]),sut.clusters)
如果要使用mock,可以使用unittest.mock.patch.object
修补clusterkmeans()
对象:
def test_gw_01(self):
sut = ClustererKmeans()
with patch.object(sut,"clustering",new=np.array([0, 0, 1, 1, 3, 3, 3, 4, 5, 5])):
e = np.array([0, 1, 3, 4, 5])
np.testing.assert_array_equal(np.array([0, 1, 2, 3, 4, 5]),sut.clusters)
…但是,当python为您提供了一种简单而直接的方法时,为什么要使用补丁呢
使用mock框架的另一种方法应该是trustnumpy.unique
,并检查属性是否
正确的工作:
@patch("numpy.unique")
def test_gw_01(self, mock_unique):
sut = ClustererKmeans()
sut.clustering = Mock()
v = sut.clusters
#Check is called ....
mock_unique.assert_called_with(sut.clustering)
#.... and return
self.assertIs(v, mock_unique.return_value)
#Moreover we can test the exception
sut.clustering = None
self.assertRaises(Exception, lambda s:s.clusters, sut)
我为一些错误道歉,但我不测试代码。您通知我,我将尽快修复所有问题。您是否应该不执行r=sut.clusters
?默认情况下发送self
参数。我看到另一个问题sut。集群不是初始化类变量的正确方法。您应该在初始化classI did tryr=sut.clusters
时将其作为参数发送,但在上面的代码中,它返回一个模拟对象,而不是numpy数组。我修复了读取后对np.array
的测试以及行r=clusterkmeans.clusters(\uu get\uu(sut))
给我一个错误:名称错误:未定义名称“\uuu get\uuu”。构造函数在这里是空的,因为我在问题中遗漏了所有不相关的细节。实际上,代码更为复杂。行r=clusterkmeans.clusters.\uuuu get\uuuu(sut)
按预期工作。谢谢你指出这一点!