我正在为一系列函数实现单元测试,这些函数都共享一些不变量。例如,用两个矩阵调用函数会生成一个已知形状的矩阵。
我想编写单元测试来测试这个属性的整个函数系列,而不必为每个函数编写单独的测试用例(特别是因为以后可能会添加更多的函数)。
一种方法是遍历这些函数的列表: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()
我是从Dive Into Python那里得到这个主意的。在这里,它不是一个正在测试的函数列表,而是一个已知输入输出对的列表。这种方法的问题是,如果列表中的任何元素未通过测试,则后面的元素将不会得到测试。
我查看了unittest.TestCase的子类化,并以某种方式提供了要作为参数进行测试的特定函数,但据我所知,这阻止了我们使用unittest.main(),因为无法将参数传递给TestCase。
我还研究了动态地将“testSomething”函数附加到testcase,方法是将setattr与lamdba一起使用,但是testcase无法识别它们。
如何重写它,以便在扩展测试列表的同时仍然确保每个测试都在运行?