python unittest要產生一個可看的報告,需要藉助一個第三方的包
下載HTMLTestRunner.py 第三方庫 ,參考地址:http://tungwaiyip.info/software/HTMLTestRunner.html
是個牛人自己寫的,真挺不錯的,佩服佩服
下載後,檔案拷貝到python工程的目錄裡,可以引用到就行
使用:
| 代碼如下 |
複製代碼 |
import lib.HTMLTestRunner from testDataDriver import Testdriver import time import sys,os reload(sys) sys.setdefaultencoding('utf-8')
def htr(): runner = lib.HTMLTestRunner runner.run(suite) #自動進行測試 |
如果需要指定報告輸出的名稱和路徑,可以按下列方式:
| 代碼如下 |
複製代碼 |
def htr(): #使用HTMLTestRunner配置參數,輸出報告路徑、報告標題、描述 runner = lib.HTMLTestRunner.HTMLTestRunner(stream=fp,title='API_test_'+str(localtimes),description='Report_description') runner.run(suite) #自動進行測試 |
報告顯示中文亂碼問題的解決方式
輸出的報告中可能包含中文,需要確定一下HTMLTestRunner.py源檔案的編碼方式
首先確認在引用HTMLTestRunner的代碼檔案中設定編碼
| 代碼如下 |
複製代碼 |
import sys reload(sys) sys.setdefaultencoding('utf-8') |
開啟HTMLTestRunner.py源檔案,找到如下行
| 代碼如下 |
複製代碼 |
# o and e should be byte string because they are collected from stdout and stderr? if isinstance(o,str): # TODO: some problem with 'string_escape': it escape n and mess up formating # uo = unicode(o.encode('string_escape')) #uo = o.decode('latin-1') else: uo = o if isinstance(e,str): # TODO: some problem with 'string_escape': it escape n and mess up formating # ue = unicode(e.encode('string_escape')) #ue = e.decode('latin-1') else: ue = e
添加utf-8的解碼
# o and e should be byte string because they are collected from stdout and stderr? if isinstance(o,str): # TODO: some problem with 'string_escape': it escape n and mess up formating # uo = unicode(o.encode('string_escape')) #uo = o.decode('latin-1') uo = o.decode('utf-8') else: uo = o if isinstance(e,str): # TODO: some problem with 'string_escape': it escape n and mess up formating # ue = unicode(e.encode('string_escape')) #ue = e.decode('latin-1') ue = e.decode('utf-8') else: ue = e |
ok,按上述方式,中文亂碼問題解決,it works