記錄python接口自動化測試--利用unittest生成測試報告(第四目)


前面介紹了是用unittest管理測試用例,這次看看如何生成html格式的測試報告

 生成html格式的測試報告需要用到 HTMLTestRunner,在網上下載了一個HTMLTestRunner.py,然后放到python安裝路徑下的lib目錄中。

(我用的python3,是下載的蟲師寫的那個,下載地址-->鏈接:https://pan.baidu.com/s/101y-X--o6iSd9WTDv5K4XQ 密碼:24xh)

1.執行單個.py文件中的測試用例

# -*-coding:UTF:8-*-

import unittest
from interface.demo import RunMain   # 從之前封裝的文件中,引入RunMain類
import HTMLTestRunner     # 導入HTMLTestRunner模塊
import json


class TestMethod(unittest.TestCase):    # 定義一個類,繼承自unittest.TestCase

    def setUp(self):
        self.run = RunMain()   # 在初始化方法中實例化一個對象,這樣就不需要在每個用例中再進行實例化了

    def test01(self):
        """獲取辦件申請人信息"""   #在用例名下添加接口描述,可以增加測試報告可讀性
        url = 'http://localhost:7001/XXX'
        data = {
            'controlSeq': '2018118325'
        }
        r = self.run.run_main(url, 'POST', data)   # 調用RunMain類中run_main方法
        print(r)
        re = json.loads(r)
        self.assertEqual(re['status'], '200', '測試失敗')
        # globals()['userid'] = 22   #定義全局變量

    def test02(self):
        """查詢辦件進度結果信息接口"""
        # print(userid)   #使用case1中的全局變量,執行時需要全部執行,不能只執行后面的,不然會報錯
        url = 'http://localhost:7001/XXX'
        data = {
            "controlSeq": "2018118325"
        }
        r = self.run.run_main(url, 'GET', data)
        print(r)
        re = json.loads(r)
        self.assertEqual(re["status"], '200', '測試失敗')

    # @unittest.skip('test03')  # 跳過用例test03
    def test03(self):
        """保存辦件快遞信息接口(審批3.0)"""
        url = 'http://localhost:7001/XXX'
        data = {
            'controlSeq': '2018118361',
            'seq': '2939',
            'type': '1'
        }
        r = self.run.run_main(url, 'POST', data)
        print(r)
        # print(type(r)) # 查看返回對象r的類型
        re = json.loads(r)
        # print(type(re))
        self.assertEqual(re['status'], '200', '測試失敗')


if __name__ == "__main__":
    # unittest.main()
    # print('__name__==__main__')
    filename = 'E:/CommonService/interface/report/testresult.html'    #測試報告的存放路徑及文件名
    fp = open(filename, 'wb')    # 創測試報告html文件,此時還是個空文件

    suite = unittest.TestSuite()   # 調用unittest的TestSuite(),理解為管理case的一個容器(測試套件)
    suite.addTest(TestMethod('test01'))  # 向測試套件中添加用例,"TestMethod"是上面定義的類名,"test01"是用例名
    suite.addTest(TestMethod('test02'))
    suite.addTest(TestMethod('test03'))
    # runner = unittest.TextTestRunner()   # 執行套件中的用例
    runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='接口測試報告', description='測試結果如下: ')
    #  stream = fp  引用文件流
    #  title  測試報告標題
    #  description  報告說明與描述
    runner.run(suite)   # 執行測試
    fp.close()   # 關閉文件流,將HTML內容寫進測試報告文件

 

2.使用discover()方法批量加載多個.py文件中的測試用例

工程目錄如下:

case是測試用例所在目錄,里面包括2個二級目錄,存放的都是測試用例;

report存放測試報告的目錄;

最外層的run_all_case.py,用它來執行所有用例

(1)直接加載discover中的用例

run_all_case.py

import
time from HTMLTestRunner import HTMLTestRunner import unittest case_dir = 'E:/CommonService/interface/case' # 定義用例所在路徑 """定義discover方法""" discover = unittest.defaultTestLoader.discover(case_dir, pattern='test_*.py', top_level_dir=None) """ 1.case_dir即測試用例所在目錄 2.pattern='test_*.py' :表示用例文件名的匹配原則,“*”表示任意多個字符,這里表示匹配所有以test_開頭的文件 3.top_level_dir=None:測試模塊的頂層目錄。如果沒頂層目錄(也就是說測試用例不是放在多級目錄 中),默認為 None """ if __name__ == "__main__": """直接加載discover""" now = time.strftime("%Y-%m-%d %H_%M_%S") filename = 'E:/CommonService/interface/report/' + now + '_result.html' fp = open(filename, 'wb') runner = HTMLTestRunner(stream=fp, title='UnifiedReporting Test Report', description='Implementation Example with: ') runner.run(discover) fp.close()

(2)通過把discover中的用例加載到測試套件中執行

run_all_case.py

import
time from HTMLTestRunner import HTMLTestRunner import unittest case_dir = 'E:/CommonService/interface/case' # 定義用例所在路徑 """定義discover方法""" discover = unittest.defaultTestLoader.discover(case_dir, pattern='test_*.py', top_level_dir=None) """ 1.case_dir即測試用例所在目錄 2.pattern='test_*.py' :表示用例文件名的匹配原則,“*”表示任意多個字符 3.top_level_dir=None:測試模塊的頂層目錄。如果沒頂層目錄(也就是說測試用例不是放在多級目錄 中),默認為 None """ if __name__ == '__main__': """通過把discover中的用例加載到測試套件中執行""" suite = unittest.TestSuite() # 定義一個測試套件
# discover 方法篩選出來的用例,循環添加到測試套件中 for test_suite in discover: for test_case in test_suite: suite.addTests(test_case) print(suite) #打印一下可以看到suite中添加了哪些測試用例 now = time.strftime("%Y-%m-%d %H_%M_%S") filename = 'E:/CommonService/interface/report/' + now + '_result.html' fp = open(filename, 'wb') runner = HTMLTestRunner(stream=fp, title='UnifiedReporting Test Report', description='Implementation Example with: ') runner.run(suite)

(3)把discover加載測試用例的過程封裝到一個函數中

run_all_case.py

import
time from HTMLTestRunner import HTMLTestRunner import unittest def allCase(): """定義一個函數,封裝discover加載測試用例的方法""" case_dir = 'E:/CommonService/interface/case' # 定義用例所在路徑 suite = unittest.TestSuite() # 定義一個測試套件 discover = unittest.defaultTestLoader.discover(case_dir, pattern='test_*.py', top_level_dir=None) # discover 方法篩選出來的用例,循環添加到測試套件中 for test_suite in discover: for test_case in test_suite: suite.addTests(test_case) return suite if __name__ == '__main__': allsuite = allCase() # runner = unittest.TextTestRunner() now = time.strftime("%Y-%m-%d %H_%M_%S") filename = 'E:/CommonService/interface/report/' + now + '_result.html' fp = open(filename, 'wb') runner = HTMLTestRunner(stream=fp, title='UnifiedReporting Test Report', description='Implementation Example with: ') runner.run(allsuite)

 測試報告如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM