python+unittest+requests+HTMLRunner編寫接口自動化測試集

問題描述:
搭建接口測試框架,執行用例請求多個不一樣請求方式的接口html

 

實現步驟:python

① 建立配置文件config.ini,寫入部分公用參數,如接口的基本url、測試報告文件路徑、測試數據文件路徑等配置項web

1 [DATABASE] 2 data_address = ./data/data.xlsx 3 report_address = ./report/
4 driver = ./drivers/chromedriver.exe 5 
6 [HTTP] 7 base_url = https://***.***.cn//

② 從配置文件中讀取並返回文件中內容,或寫入配置文件的方法,文件命名 readConfig.pychrome

 1 import os  2 import configparser  3 
 4 # 獲取當前py文件地址
 5 proDir = os.path.split(os.path.realpath(__file__))[0]  6 # 組合config文件地址
 7 configPath = os.path.join(proDir,"config.ini")  8 
 9 class ReadConfig: 10     def __init__(self): 11         # 獲取當前路徑下的配置文件
12         self.cf = configparser.ConfigParser() 13  self.cf.read(configPath) 14 
15     def get_config(self,field,key): 16         # 獲取配置文件中的key值
17         result = self.cf.get(field,key) 18         return result 19 
20     def set_config(self,field,key,value): 21         # 向配置文件中寫入配置信息
22         fb = open(configPath,'w') 23  self.cf.set(field,key,value) 24         self.cf.write(fb)

③ 從配置文件中獲取到接口的基本url後,根據不一樣的接口請求方式讀取請求體或其餘參數信息,參數信息從excel中讀取,所以文件readExcel.py用於讀取並返回excel文件中內容,或寫入Excel的方法json

 1 import xlrd  2 import xlutils.copy  3 from Base.readConfig import ReadConfig  4 import time  5 
 6 class ReadExcel:  7 
 8     def __init__(self,section,field,sheet):  9         # 打開工做表,並定位到sheet
10         data_address = ReadConfig().get_config(section,field) 11         workbook = xlrd.open_workbook(data_address) 12         self.table = workbook.sheets()[sheet] 13 
14 
15     def get_rows(self): 16         # 獲取excel行數
17         rows = self.table.nrows 18         return rows 19 
20     def get_cell(self,row,col): 21         # 獲取單元格數據
22         cell_data = self.table.cell(row,col).value 23         return cell_data 24 
25     def get_col(self,col): 26         # 獲取整列數據
27         col_data = self.table.col_value(col) 28         return col_data 29 
30 class WriteExcel: 31     def __init__(self,section,field,sheet): 32         # 打開工做表
33         self.address = ReadConfig().get_config(section,field) 34         self.workbook = xlrd.open_workbook(self.address) 35         self.wf = xlutils.copy.copy(self.workbook) 36         self.ws = self.wf.get_sheet(sheet) 37 
38     def set_cell(self,row,col,value): 39         #設置單元格數據
40  self.ws.write(row,col,value) 41 
42     def save_excel(self,filename,format): 43         #獲取當前時間
44         self.time = time.strftime("%Y%m%d%H%M%S", time.localtime()) 45         #生成文件的文件名及格式
46         self.report = filename + '_' +self.time + format 47         #保存文件
48         self.wf.save(self.report)

④ 將獲取接口的url、請求頭、參數等方法封裝成類並寫入base.py中,用於測試框架中測試集的直接調取api

 1 from Base.readConfig import ReadConfig  2 from Base.readExcel import ReadExcel  3 
 4 # 實例化
 5 readexcel = ReadExcel('DATABASE','data_address',0)  6 
 7 class BasePage(object):  8     def __init__(self, selenium_driver):  9         self.driver = selenium_driver 10 
11     def get_api(self, row, col): 12         # 獲取url
13         self.base_url = ReadConfig().get_config('HTTP', 'base_url') 14 
15         # 獲取excel中的接口地址,與url進行拼接
16         self.url = self.base_url + readexcel.get_cell(row, col) 17         print(self.url) 18         return self.url 19 
20     def get_cell(self, row, col): 21         # 獲取excel單元格數據,獲取接口請求的參數
22         self.cell = readexcel.get_cell(row, col) 23         return self.cell

⑤ 從base.py文件獲取到請求地址後,須要組合不一樣類型的請求方式,如get請求直接將參數與地址進行拼接,或post請求以json數據格式等爲請求體請求接口,而後再獲取接口對象,獲得接口返回的數據,此過程涉及的方法封裝到request_way.py(注:該實例get請求返回數據格式爲jsonp,所以須要jsonp格式數據轉換爲json格式的方法)數組

 1 from Base.readExcel import ReadExcel  2 from base import BasePage  3 import requests  4 import urllib.parse  5 import json  6 import re  7 
 8 # 實例化
 9 readexcel = ReadExcel('DATABASE','data_address',0) 10 
11 # jsonp格式數據轉換爲json格式
12 def jsonp_to_json(_jsonp): 13      # 解析jsonp數據格式爲json
14     try: 15         return json.loads(re.match(".*?({.*}).*", _jsonp, re.S).group(1)) 16     except: 17         raise ValueError('Invalid Input') 18 
19 class RequestPage(BasePage): 20     # post方式請求,json格式爲請求體
21     def post_requests(self, url, i): 22         # 定義請求數據,獲取excel中參數信息賦值給data,以json格式拼接好數據
23         data_1_json = json.dumps(BasePage(self.driver).get_cell(i, 4)) 24         data_2_json = json.dumps(BasePage(self.driver).get_cell(i + 1, 4)) 25         data = "{" + data_1_json + ":" + data_2_json + "}"
26         print(data) 27         # 打開請求,獲取對象
28         response = requests.post(url, data) 29         # 打印狀態碼
30         print(response) 31         return response 32 
33     # get方式請求
34     def get_request(self, url, j): 35         # 定義請求數據,獲取excel中參數信息賦值給values
36         #values = {}
37         values = BasePage(self.driver).get_cell(j, 4) 38         # 若是參數不止一個則對請求數據進行編碼拼接'&'
39         #data = urllib.parse.urlencode(values)
40         # 將數據與url進行拼接
41         req = url + '?' + values 42         print(req) 43         # 打開請求,獲取對象
44         response = urllib.request.urlopen(req) 45         # 打印Http狀態碼
46         print(response.status) 47         # 讀取服務器返回的數據,對HTTPResponse類型數據進行讀取操做,bytes格式數據編譯成中文編碼
48         the_page = response.read().decode("unicode_escape") 49         # 將返回的bytes格式數據先轉換成str,再將返回的jsonp格式數據轉換成json格式
50         the_page = jsonp_to_json(str(the_page)) 51         return the_page

⑥ 獲得接口實際返回結果後,須要與預期結果作比對,判斷用例執行結果,因此封裝校驗類到check.py文件。校驗方式其一是校驗json數組內每一個數值是否一致,其二是直接簡單校驗數組中的status值和message是否返回正確服務器

 1 from base import BasePage  2 from Base.readExcel import WriteExcel  3 
 4 # 實例化
 5 writeexcel = WriteExcel('DATABASE','data_address',0)  6 
 7 class CheckPage(BasePage):  8     # 校驗json數組內每一個值是否一致
 9     def check_value(self, i, actualresult, expectresult): 10         # 遍歷字典的值value,並將value賦值給實際接口數據的值
11         for value in actualresult.values(): 12             actualresult_value = value 13         # 遍歷字典的值value,並將value賦值給excel中預期數據的值
14         for value in expectresult.values(): 15             expectresult_value = value 16         # 若是實際接口返回的每一個鍵值與excel中預期返回的數據的每一個鍵值同樣,則接口測試用例執行經過,若是不是則打印預期結果和實際結果,可比較差別
17         if actualresult_value == expectresult_value: 18             writeexcel.set_cell(i, 8, 'SUCCESS') 19             print("接口用例執行結果經過") 20         else: 21             writeexcel.set_cell(i, 8, 'FAILURE') 22             writeexcel.set_cell(i, 7, str(actualresult)) 23             print('', i + 1, '行用例執行失敗:預期結果是', expectresult, '實際結果是', actualresult) 24 
25         # 保存測試報告
26         writeexcel.save_excel('testreport', '.xls') 27 
28 
29     # 校驗json數組中的status值和message是否返回成功
30     def easy_check_value(self, i, actualresult,expectresult): 31         # 判斷實際接口值是否狀態碼和消息返回成功
32         if actualresult['status'] == 1 and actualresult['message'] == '完成': 33             writeexcel.set_cell(i, 8, 'SUCCESS') 34             print('', i+1, '行用例執行結果正確,用例經過') 35         else: 36             writeexcel.set_cell(i, 8, 'FAILURE') 37             writeexcel.set_cell(i, 7, str(actualresult)) 38             print('', i + 1, '行用例執行失敗:預期結果是', expectresult, '實際結果是', actualresult) 39 
40         # 保存測試報告
41         writeexcel.save_excel('testreport', '.xls')

⑦ 最後編寫測試集 testcase.py,其中用例包含有執行post和get方式的請求,增長用例可直接在該文件繼續添加編寫框架

 1 import unittest  2 from selenium import webdriver  3 from Base.readConfig import ReadConfig  4 from base import BasePage  5 from requests_way import RequestPage  6 from check import CheckPage  7 from packages.HTMLTestRunner import HTMLTestRunner  8 
 9 driver = webdriver.Chrome(ReadConfig().get_config('DATABASE', 'driver')) 10 
11 class SmokeTest(unittest.TestCase): 12     #初始化
13     def setUp(self): 14         self.driver = driver 15 
16     def test_case_10(self): 17         """以json格式數據爲請求體的post方式接口請求"""
18         # 獲取url
19         self.url = BasePage(self.driver).get_api(1,1) 20 
21         # 將接口實際返回數據轉換爲json可序列化,使用json.dumps()時須要對象相應的類型是json可序列化的
22         i = 3
23         actualresult = RequestPage(self.driver).post_requests(self.url, i).json() 24 
25         # 獲取excel中的預期結果
26         expectresult = eval(BasePage(self.driver).get_cell(i, 6)) 27 
28         # 校驗實際接口返回結果和用例預期結果是否一致(校驗json數組內每一個值是否一致)
29  CheckPage(self.driver).check_value(i, actualresult, expectresult) 30 
31     def test_case_11(self): 32         """get方式接口請求"""
33         # 獲取url
34         self.url = BasePage(self.driver).get_api(8, 1) 35 
36         # 獲取接口實際返回值與excel中的預期結果
37         j = 8
38         actualresult = RequestPage(self.driver).get_request(self.url, j) 39         expectresult = eval(BasePage(self.driver).get_cell(j, 6)) 40 
41         # 校驗實際接口返回結果和用例預期結果是否一致(校驗json數組中的status值和message是否返回成功)
42  CheckPage(self.driver).easy_check_value(j, actualresult, expectresult) 43 
44     # 釋放資源
45     def test_case_12(self): 46  self.driver.quit() 47 
48 
49 if __name__ == '__main__': 50     #構造測試集合
51     suite = unittest.TestSuite() 52     suite.addTest(SmokeTest('test_case_10')) 53     suite.addTest(SmokeTest('test_case_11')) 54     suite.addTest(SmokeTest('test_case_12')) 55 
56     #建立html文件
57     filename = ReadConfig().get_config('DATABASE', 'report_address') + 'testreport.html'
58     fp = open(filename, 'wb') 59 
60     #執行測試並生成html測試報告
61     runner = HTMLTestRunner(stream=fp, description='接口用例執行狀況:', title='接口自動化測試報告') 62  runner.run(suite) 63 
64     #關閉文件
65     fp.close()

⑧ 其中涉及HTMLTestRunner.py原生HTML測試報告庫,是用於生成測試報告testreport.html,模塊下載後直接集成到該項目post

模塊下載地址:http://tungwaiyip.info/software/HTMLTestRunner.html

⑨ 以python文件模式執行腳本才能生成測試報告

參考:http://www.javashuo.com/article/p-drurdrth-by.html

以上,總體框架以下圖

 

執行方式正確獲得如下兩種類型測試報告,excel表和html測試報告

相關文章
相關標籤/搜索