简单案例:unittest+HTMLTestRunner实现生成测试报告
1 HTMLTestRunner for Mac for installing
HTMLTestRunner是标准库拓展脚本,用于实现测试报告生成,和unittest本身的TextTestRunner类似
(1)http://tungwaiyip.info/software/HTMLTestRunner.html 下载后放在新建的HTMLTestRunner文件夹,并创建一个__init__.py 组成模块
(2)进入标准库目录,cd /Library/Python/2.7/site-packages
(3)复制模块到标准库此目录,sudo cp -r /Users/Alex/Desktop/practice/HTMLTestRunner .
(4)查看是否存在,ls -l
2 简单脚本
import HTMLTestRunner 结果运行报错: Traceback (most recent call last): File "/Users/Alex/Desktop/practice/tt_report.py", line 25, in <module> runner = HTMLTestRunner.HTMLTestRunner( AttributeError: 'module' object has no attribute 'HTMLTestRunner'
# coding=utf-8 import unittest import requests from HTMLTestRunner import HTMLTestRunner class GetUserTest(unittest.TestCase): def tearDown(self): print('tear down...') def setUp(self): print('tear...up') def test_get_user(self): self.assertEquals(10, 10) def test_get_user2(self): self.assertIn(10, [10, 9]) if __name__ == '__main__': my_test_suite = unittest.TestSuite() my_test_suite.addTest(GetUserTest('test_get_user')) my_test_suite.addTest(GetUserTest('test_get_user2')) fp = file('my_report_01.html', 'wb') runner = HTMLTestRunner.HTMLTestRunner( stream=fp, title='unite test', description='This demonstrates the report output by HTMLTestRunner.' ) runner.run(my_test_suite) # if __name__ == '__main__': # HTMLTestRunner.main()
3 unittest 的addTests和Discover模式
my_test_suite.addTest(GetUserTest('test_get_user')) my_test_suite.addTest(GetUserTest('test_get_user2')) my_test_suite.addTests([GetUserTest('test_get_user'),GetUserTest('test_get_user2')]) test_dir = './' discover = unittest.defaultTestLoader.discover(test_dir, pattern='test_*.py') fp = file('my_report_02.html', 'wb') runner = HTMLTestRunner.HTMLTestRunner( stream=fp, title='unite test', description='This demonstrates the report output by HTMLTestRunner.' ) runner.run(my_test_suite) # runner.run(discover)
无论是两个addTest还是一个addTests还是discover都能达到效果,但是前两者保证了你可以调整顺序尤其是有流程比如增查改删的时候,后者则没有顺序但是后者在你用例特别多的时候可以自动识别很方便,取决于你自己的业务使用场景。