我正在为一系列函数实现单元测试,这些函数都共享多个不变量.例如,调用具有两个矩阵的函数产生已知形状的矩阵.
我想编写单元测试来测试该属性的整个函数系列,而不必为每个函数编写单独的测试用例(特别是因为稍后可能会添加更多函数).
一种方法是迭代这些函数的列表:
import unittest
import numpy
from somewhere import the_functions
from somewhere.else import TheClass
class Test_the_functions(unittest.TestCase):
def setUp(self):
self.matrix1 = numpy.ones((5,10))
self.matrix2 = numpy.identity(5)
def testOutputShape(unittest.TestCase):
"""Output of functions be of a certain shape"""
for function in all_functions:
output = function(self.matrix1, self.matrix2)
fail_message = "%s produces output of the wrong shape" % str(function)
self.assertEqual(self.matrix1.shape, output.shape, fail_message)
if __name__ == "__main__":
unittest.main()
Run Code Online (Sandbox Code Playgroud)
我从Dive Into Python中得到了这个想法.在那里,它不是正在测试的函数列表,而是已知输入 - 输出对的列表.这种方法的问题在于,如果列表中的任何元素未通过测试,则后面的元素不会被测试.
我查看了子类化unittest.TestCase并以某种方式提供了作为参数测试的特定函数,但据我所知,这阻止我们使用unittest.main(),因为没有办法将参数传递给测试用例.
我还看了动态地将"testSomething"函数附加到测试用例,使用带有lamdba的setattr,但是测试用例没有识别它们.
我怎样才能重写这个,所以扩展测试列表仍然是微不足道的,同时仍然确保每个测试都运行?
在为框架创建测试时,我开始注意以下模式:
class SomeTestCase(unittest.TestCase):
def test_feat_true(self):
_test_feat(self, True)
def test_feat_false(self):
_test_feat(self, False)
def _test_feat(self, arg):
pass # test logic goes here
Run Code Online (Sandbox Code Playgroud)
所以我想以编程test_feat_*方式使用元类为这些类型的测试类创建方法.换句话说,对于每个带签名的私有方法_test_{featname}(self, arg),我想要两个具有签名的顶级可发现方法test_{featname}_true(self)并test_{featname}_false(self)创建.
我想出了类似的东西:
#!/usr/bin/env python
import unittest
class TestMaker(type):
def __new__(cls, name, bases, attrs):
callables = dict([
(meth_name, meth) for (meth_name, meth) in attrs.items() if
meth_name.startswith('_test')
])
for meth_name, meth in callables.items():
assert callable(meth)
_, _, testname = meth_name.partition('_test')
# inject methods: test{testname}_{[false,true]}(self)
for suffix, arg in (('false', False), ('true', True)):
testable_name …Run Code Online (Sandbox Code Playgroud)