【发布时间】:2015-03-03 06:17:00
【问题描述】:
我有一个具有以下属性的课程clusters:
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 = ClustererKmeans.clusters(sut) 行更改为以下内容:
r = sut.clusters
但我又遇到了一个意外错误。
AssertionError: False is not true : r shall be a <class 'numpy.ndarray'> (is now a <class 'unittest.mock.Mock'>)
有没有一种简单的方法可以使用 unittest 框架在 Python 中测试属性的实现?
【问题讨论】:
-
你不应该做
r = sut.clusters吗?self参数默认发送。我看到另一个问题sut.clustering不是初始化类变量的正确方法。您应该在初始化类时将其作为参数发送 -
我确实尝试过
r = sut.clusters,但在上面的代码中,它返回一个 Mock 对象,而不是一个 numpy 数组。
标签: python properties unit-testing