我正在對一系列函數進行單元測試,這些函數都有許多不變量。例如,用兩個矩陣調用函數會生成已知形狀的矩陣。如何在Python單元測試框架中簡潔地實現多個相似的單元測試?
我想寫單元測試來測試的此屬性功能整個家庭,而不必編寫單獨的測試的情況下爲每個功能(特別是由於多個功能可能稍後被添加)。要做到這一點
一種方法是遍歷這些功能的列表:
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(),因爲就沒有辦法通過論證到測試用例。
我也看了看動態連接「testSomething」功能的測試用例,通過使用SETATTR用lamdba,但測試用例沒認出來。
我怎麼能改寫這個所以它仍然微不足道,擴大測試的名單,同時確保每個測試運行?
相關的問題:http://stackoverflow.com/questions/32899/how-to-generate-dynamic-unit-tests-in-python – jfs 2008-12-07 20:46:14