簡介:
HTMLTestRunner是Python標准庫unittest單元測試框架的一個擴展,用來生成HTML測試報告。
目前官網中只支持python2的版本,可下載蟲師的版本,支持python3.
安裝方法:
直接將HTMLTestRunner.py文件放到python的lib存放第三方庫里。(目前不支持pip安裝)
例子:

1 # -*-coding:utf-8-*- 2 3 from demo1 import Count 4 import unittest 5 from HTMLTestRunner import HTMLTestRunner 6 import time 7 8 class TestAdd(unittest.TestCase): 9 """做加法?""" 10 def setUp(self): 11 print('Add Start') 12 def tearDown(self): 13 print('Add End') 14 def test_add1(self): 15 "2+3=?" 16 j = Count(2,3) 17 add = j.add() 18 self.assertEqual(add,5) 19 def test_add2(self): 20 j = Count(5,1) 21 add = j.add() 22 self.assertEqual(add,5,'加錯了') 23 24 if __name__ == '__main__': 25 # 把用例集合成一個套件 26 suite = unittest.TestSuite() 27 suite.addTest(TestAdd('test_add1')) 28 suite.addTest(TestAdd('test_add2')) 29 # 使用HTMLTestRunner生成結果報告到'D:/report'文件夾下,名為當前時間+result.html 30 now_time = time.strftime("%Y-%m-%d %H_%M_%S") 31 filename = 'D:\\report\\'+ now_time +'result.html' #假設已新建report文件 32 # 設置HTML的title和概括 33 f = open(filename,'wb') 34 runner = HTMLTestRunner(stream=f, 35 title ='測試報告標題', 36 description='報告概括') 37 runner.run(suite) 38 f.close()
查找最新的測試報告
方法1

1 # -*-coding:utf-8-*- 2 import os 3 4 _dir = r'D:\study\pyproject\Demo1\unit_test' 5 # 獲取所有_dir路徑下的文件名 6 lists = os.listdir(_dir) 7 # 按時間順序排列 8 lists.sort(key=lambda fn: os.path.getmtime(result_dir+'\\'+fn)) 9 print("最新的報告文件為:"+ lists[-1]) 10 #連結路徑和最新報告文件名 11 file = os.path.join(result_dir,lists[-1]) 12 print(file)
方法2
1 def now_report(report_path): 2 ''' 3 參數report_path為報告所在的目錄 4 ''' 5 # 獲取所有report_path路徑下的文件名生成lst列表 6 lst = os.listdir(report_path) 7 # lst列表每個元素套進參數fn,使key獲得每個文件的修改時間,lst.sort再順序排列 8 lst.sort(key=lambda fn: os.path.getmtime(report_path + "\\" + fn)) # getmtime返回文件的最后修改時間 9 file_new = os.path.join(report_path,lst[-1]) 10 print(file_new) 11 return file_new