Python-测试驱动编程
步骤:
- 明确需求
- 编写框架代码
- 编写功能代码
- 改进
工具:
- trace
- unittest
- pychecker/pylint
- profile/timeit
工具说明:
trace:
https://learnku.com/docs/pymotw/trace-follow-program-flow/3467
unittest:
https://www.jianshu.com/p/0b04cb0450ee
pychecker:
http://pychecker.sourceforge.net
pylint:
https://pypi.org/project/pylint/
HTMLTestRunner
http://tungwaiyip.info/software/HTMLTestRunner.html
例子:
unittest例程:
import HTMLTestRunner import unittest class MyTest(unittest.TestCase): #继承unittest.TestCase def setUp(self): # 每个测试用例执行之前做操作 print('setUp') def tearDown(self): # 每个测试用例执行之后做操作 print('tear down') @classmethod def setUpClass(self): # 必须使用@classmethod 装饰器,所有test运行前运行一次 print('setUpClass') @classmethod def tearDownClass(self): # 必须使用 @ classmethod装饰器, 所有test运行完后运行一次 print('tearDownClass') ''' 常用断言 assertEqual(a, b) # a == b assertNotEqual(a, b) # a != b assertTrue(x) # bool(x) is True assertFalse(x) # bool(x) is False assertIsNone(x) # x is None assertIsNotNone(x) # x is not None assertIn(a, b) # a in b assertNotIn(a, b) # a not in b ''' def test_a_run(self): print('test_a_run') self.assertEqual(1, 1) # 测试用例 def test_b_run(self): print('test_b_run') self.assertEqual(2, 2) # 测试用例 if __name__ == '__main__': test_suite = unittest.TestSuite() #创建一个测试集合 #test_suite.addTest(MyTest('test_a_run')) # 测试套件中添加测试用例 test_suite.addTest(unittest.makeSuite(MyTest)) # 使用makeSuite方法添加所有的测试方法 fp = open('test_report.html','wb') # 打开一个保存结果的html文件 runner = HTMLTestRunner.HTMLTestRunner(stream=fp,title='测试报告',description='测试情况') runner.run(test_suite) # 执行测试套件 fp.close() ''' if __name__ == '__main__': #unittest.main()#运行所有的测试用例 '''