文档地址http://docs.python.org/library/unittest.html
第一个例子直接引用文档中的例子,其他的简略的写了写结论性的东西,具体的参考python_testing_cookbook一书。
一、简单的例子
import random import unittest class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.seq = range(10) def test_shuffle(self): # make sure the shuffled sequence does not lose any elements random.shuffle(self.seq) self.seq.sort() self.assertEqual(self.seq, range(10)) # should raise an exception for an immutable sequence self.assertRaises(TypeError, random.shuffle, (1,2,3)) def test_choice(self): element = random.choice(self.seq) self.assertTrue(element in self.seq) def test_sample(self): with self.assertRaises(ValueError): random.sample(self.seq, 20) for element in random.sample(self.seq, 5): self.assertTrue(element in self.seq) if __name__ == '__main__': unittest.main()
实现一个继承unittest.TestCase的类,使用unittest.main()来测试该类中所有以test开头的测试用例。
简单的assert方法有如下:
self.assertEquals(100, value)
self.assertTrue(value == 0)
self.assertFalse(value > 0
self.assertRaises(TypeError, value.convert_to_decimal)
在写测试用例的时候尽量使用assertEquals而不是assertTrue、assertFalse,当assertEquals失败的时候,会打印出比较的两方值更直观
self.fail([msg])会无条件的导致测试失败,不推荐使用。
下面的例子的写法是要避免发生:
import unittest class BadTest(unittest.TestCase): def test_no_roman_numeral(self): value = RomanNumeralConverter(None) try: value.convert_to_decimal() self.fail("Expected a TypeError") except TypeError, e: pass
这个时候推推荐使用assertRaises
二、使用setUp和tearDown
每次运行test方法时,先用setUp初始化程序,然后运行test方法,最后使用tearDown清理程序
def setUp(self):
print "Creating a new RomanNumeralConverter..."
self.cvt = RomanNumeralConverter()
def tearDown(self):
print "Destroying the RomanNumeralConverter..."
self.cvt = None
如果不同的方法需要不同的setUp和tearDown方法,那么只好写过个测试用例了。
三、使用比unittest.main()更详细的运行测试用例的方法
if __name__ == "__main__":
suite = unittest.TestLoader().loadTestsFromTestCase( \
RomanNumeralConverterTest)
unittest.TextTestRunner(verbosity=2).run(suite)
python使用unittest.TestLoader().loadTestsFromTestCase方法获取RomanNumeralConverterTest的所有test方法
然后通过TextTestRunner来运行
四、运行部分测试方法
if __name__ == "__main__": import sys suite = unittest.TestSuite() if len(sys.argv) == 1: suite = unittest.TestLoader().loadTestsFromTestCase(\ RomanNumeralConverterTest) else: for test_name in sys.argv[1:]: suite.addTest(\ RomanNumeralConverterTest(test_name)) unittest.TextTestRunner(verbosity=2).run(suite)五、一次运行多个测试用例
if __name__ == "__main__": import unittest from recipe5 import * suite1 = unittest.TestLoader().loadTestsFromTestCase( \ RomanNumeralConverterTest) suite2 = unittest.TestLoader().loadTestsFromTestCase( \ RomanNumeralComboTest) suite = unittest.TestSuite([suite1, suite2]) unittest.TextTestRunner(verbosity=2).run(suite)六、在test model 中 使用test suites
def high_and_low(): suite = unittest.TestSuite() suite.addTest(\ RomanNumeralConverterTest("test_parsing_millenia")) suite.addTest(\ RomanNumeralConverterTest("test_parsing_one")) return suite def combos(): return unittest.TestSuite(map(RomanNumeralConverterTest,\ ["test_combo1", "test_combo2", "test_combo3"])) def all(): return unittest.TestLoader().loadTestsFromTestCase(\ RomanNumeralConverterTest) if __name__ == "__main__": for suite_func in [high_and_low, combos, all]: print "Running test suite '%s'" % suite_func.func_name suite = suite_func() unittest.TextTestRunner(verbosity=2).run(suite)
七、将已有的测试代码迁移到unittest
不使用unittest
from recipe7 import * class RomanNumeralTester(object): def __init__(self): self.cvt = RomanNumeralConverter() def simple_test(self): print "+++ Converting M to 1000" assert self.cvt.convert_to_decimal("M") == 1000 def combo_test1(self): print "+++ Converting MMX to 2010" assert self.cvt.convert_to_decimal("MMXX") == 2010 def combo_test2(self): print "+++ Converting MMMMDCLXVIII to 4668" val = self.cvt.convert_to_decimal("MMMMDCLXVII") self.check(val, 4668) def other_test(self): print "+++ Converting MMMM to 4000" val = self.cvt.convert_to_decimal("MMMM") self.check(val, 4000) def check(self, actual, expected): if (actual != expected): raise AssertionError("%s doesn't equal %s" % \ (actual, expected)) def test_the_system(self): self.simple_test() self.combo_test1() self.combo_test2() self.other_test() if __name__ == "__main__": tester = RomanNumeralTester() tester.test_the_system()迁移到unittest
from recipe7 import * from recipe7_legacy import * import unittest if __name__ == "__main__": tester = RomanNumeralTester() suite = unittest.TestSuite() for test in [tester.simple_test, tester.combo_test1, \ tester.combo_test2, tester.other_test]: testcase = unittest.FunctionTestCase(test) suite.addTest(testcase) unittest.TextTestRunner(verbosity=2).run(suite)
八、简单化
一个测试函数里面写一个assert***,便于查看bug
九、测试边缘
比如测试一个到4000为止的整数,需要测试
1,4000, 0 4001, -1, None, 1.2
错误的输入也是必要的
通过迭代测试边缘
def test_bad_inputs(self): r = self.cvt.convert_to_roman d = self.cvt.convert_to_decimal edges = [("equals", r, "", None),\ ("equals", r, "I", 1.2),\ ("raises", d, TypeError, None),\ ("raises", d, TypeError, 1.2)\ ] [self.checkout_edge(edge) for edge in edges] def checkout_edge(self, edge): if edge[0] == "equals": f, output, input = edge[1], edge[2], ed print("Converting %s to %s..." % (input self.assertEquals(output, f(input)) elif edge[0] == "raises": f, exception, args = edge[1], edge[2], print("Converting %s, expecting %s" % \ (args, exception)) self.assertRaises(exception, f, *args)