1.4 Discover更多测试用例
discover(start_dir,pattern='test*.py',top_level_dir=None)
找到指定目录下所有测试模块,并可递归查到子目录下的测试木块,只有匹配到的文件名才会被加载。如果启动的不是顶层目录,那么顶层目录必然单独指定。
l start_dir:要测试的模块名或测试用例的目录。
l pattent=‘test*.py’:表示用例文件名的匹配原则。此处匹配文件名一test开头的所有.py类型文件,*表示任意多个字符。
l top_level_dir=None :测试模块的顶层目录,如果没有顶层目录,默认为None。
被调用的calculator.py
#0517006:calculator:add test # 计算器类 class count: def __init__(self,a,b): self.a = int(a) self.b = int(b) def add(self): return self.a + self.b def sub(self): return self.a - self.b
测试用例:add
#0517008:suite:add from calculator import count import unittest class testadd(unittest.TestCase): def setUp(self): print('Test add Start') def tearDown(self): print('Test add Over') def test_add1(self): j = count(2,3) self.assertEqual(j.add(),5,msg= '错了1') def test_add2(self): j = count(3,3) self.assertEqual(j.add(),5,msg= '错了2') if __name__ == '__main__': unittest.main()
测试用例:sub
#0517009:suite:sub from calculator import count import unittest class testsub(unittest.TestCase): def setUp(self): print('Test sub Start') def tearDown(self): print('Test sub Over') def test_sub1(self): j = count(2,3) self.assertEqual(j.sub(),-1,msg= '错了1') def test_sub2(self): j = count(3,3) self.assertEqual(j.sub(),5,msg= '错了2') if __name__ == '__main__': unittest.main()
执行用例:runtest
import unittest #定义测试用例的目录为当前目录 test_dir = './' discover = unittest.defaultTestLoader.discover(test_dir, pattern='test*.py') if __name__ == '__main__': runner = unittest.TextTestRunner() runner.run(discover)
执行结果:
>>> RESTART: C:/Users/tians/AppData/Local/Programs/Python/Python36/example-JLL/modules/002-calculator/runtest.py Test add Start Test add Over .Test add Start Test add Over FTest sub Start Test sub Over .Test sub Start Test sub Over F ====================================================================== FAIL: test_add2 (test_add.testadd) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:Users iansAppDataLocalProgramsPythonPython36example-JLLmodules 02-calculator est_add.py", line 19, in test_add2 self.assertEqual(j.add(),5,msg= '错了2') AssertionError: 6 != 5 : 错了2 ====================================================================== FAIL: test_sub2 (test_sub.testsub) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:Users iansAppDataLocalProgramsPythonPython36example-JLLmodules 02-calculator est_sub.py", line 19, in test_sub2 self.assertEqual(j.sub(),5,msg= '错了2') AssertionError: 0 != 5 : 错了2 ---------------------------------------------------------------------- Ran 4 tests in 0.078s FAILED (failures=2) >>>
注:unittest框架默认根据ASCII码的顺序加载测试用例,数字与字母的顺序为:0~9,A~Z,a~z。如果想让某个特定的用例优先执行,要么将该用例的命名靠前,要么使用TestSuite类的addTest()方法按照一定的顺序加载。