1. 程式人生 > >python實現簡單的http接口自動化

python實現簡單的http接口自動化

發送 整體 寫入excel += 常用 xxx sta assign except

今天給大家分享一個簡單的Python腳本,使用python進行http接口的自動化測試,腳本很簡單,邏輯是:讀取excel寫好的測試用例,然後根據excel中的用例內容進行調用,判斷預期結果中的返回值和返回報文中的值是否一致,如果不一致則根據用例標題把bug提交到bug管理系統,這裏使用的bug管理系統是bugfree。最後統計測試結果:總共執行多少條用例、通過多少條用例,失敗多少條用例,郵件標題加上當前時間,將測試結果發送到指定郵箱。

實現步驟:

1、讀取excel,保存測試用例中的內容,這裏需要定義一個讀取excel的函數readExcel();

2、根據excel中的請求url和參數拼接請求報文,調用接口,並保存返回報文,這裏需要定義一個將請求數據轉換為字典的函數param_To_Dic();

3、讀取返回報文,和預期結果對比,不一致的往bugfree數據庫中寫入一條bug,並且把請求報文、返回報文和測試結果寫到測試用例的excel中,這裏需要定義一個比對預期結果和返回結果的函數contrastRes(),一個往bugfree提交bug的函數writeBug(),一個將測試結果寫入excel的函數copy_excel(),還需定義一個接口請求的函數interfaceTest()。

4、統計測試結果,發送測試郵件。需定義一個send_email()的函數。

http接口最常用的兩種請求方式,POST和GET兩種方法,這篇博客分享的就是最簡單常用的url請求。例如:http://192.168.21.129/bugfree/index.php/info/edit?type=bug&action=opened&product_id=1

需要用的到幾個模塊有:requests、xlrd(讀取excel)、xlutils(寫excel)、pymysql(連接數據庫)、yagmail(發送郵件)這五個模塊都是第三方模塊,需要自己單獨安裝。

首先在excel中寫好用例,需要有的字段 項目、用例id、接口名稱、用例描述、請求方式、請求url、請求數據(多個的參數話用&分號隔開)、預期結果、請求報文、返回報文、測試人員、測試結果

測試用例截圖如下:

技術分享圖片

整體代碼如下:

import xlrd,requests,time,pymysql,yagmail
from xlutils import copy

def readExcel(file_path):
    
try: book = xlrd.open_workbook(file_path) except Exception as e: print(路徑不在或者excel不正確,e) else: sheet = book.sheet_by_index(0) rows = sheet.nrows count_check = rows - 1 case_list = [] for i in range(rows): if i != 0: case_list.append(sheet.row_values(i)) interfaceTest(count_check,case_list,file_path) def interfaceTest(count_check,case_list,file_path): result_flags = [] #存測試結果,pass或fail request_urls = [] #存請求報文的list response = [] #存返回報文的list count_pass = 0 count_fail = 0 for case in case_list: try: product = case[0] # 項目,提bug的時候可以根據項目來提 case_id = case[1] # 用例id,提bug的時候用 interface_name = case[2] # 接口名稱,也是提bug的時候用 case_detail = case[3] # 用例描述 method = case[4] # 請求方式 url = case[5] # 請求url param = case[6] # 入參 res_check = case[7] # 預期結果 tester = case[10] # 測試人員 except Exception as e: print(測試用例格式不正確!%s % e) if param == ‘‘: new_url =url request_urls.append(new_url) else: new_url = url + ? + param request_urls.append(new_url) if method.upper() == GET: results = requests.get(url, params=param_To_Dic(param)).json() results_str = requests.get(url, params=param_To_Dic(param)).text response.append(results) res = contrastRes(results, res_check) else: results = requests.post(url, param_To_Dic(param)).json() results_str = requests.post(url, param_To_Dic(param)).text response.append(results) res = contrastRes(results, res_check) if pass in res: result_flags.append(pass) count_pass += 1 else: result_flags.append(fail) count_fail += 1 writeBug(case_id, interface_name, new_url, results_str, res_check) copy_excel(file_path, result_flags, request_urls, response,count_check,count_pass,count_fail) def param_To_Dic(param): data_list = param.split(&) data = {} for i in data_list: k, v = i.split(=) data[k] = v return data def contrastRes(results, res_check): check_code = res_check.split(=)[1] if int(check_code) == results[error_code]: return pass else: # print(錯誤,返回參數和預期結果不一致 + res_check) return fail def copy_excel(file_path, res_flags, request_urls, response,count_check,count_pass,count_fail): book = xlrd.open_workbook(file_path) new_book = copy.copy(book) sheet = new_book.get_sheet(0) i = 1 for request_url, response, flag in zip(request_urls, response, res_flags): sheet.write(i, 8, u%s % request_url) sheet.write(i, 9, u%s % response) sheet.write(i, 11, u%s % flag) i += 1 new_book.save(%s_測試結果.xls % time.strftime(%Y%m%d%H%M%S)) atta = %s_測試結果.xls % time.strftime(%Y%m%d%H%M%S) send_mail(count_check, count_fail, count_pass, atta)
def writeBug(bug_id, interface_name, request, response, res_check):
now = time.strftime("%Y-%m-%d %H:%M:%S") # 取當前時間,作為提bug的時間
bug_title = bug_id + ‘_‘ + interface_name + ‘_結果和預期不符‘ # bug標題用bug編號加上接口名稱然後加上_結果和預期不符,可以自己隨便定義要什麽樣的bug標題
step = ‘[請求報文]<br />‘ + request + ‘<br/>‘ + ‘[預期結果]<br/>‘ + res_check + ‘<br/>‘ + ‘<br/>‘ + ‘[響應報文]<br />‘ + ‘<br/>‘ + response # 復現步驟就是請求報文+預期結果+返回報文
sql = "INSERT INTO `bf_bug_info` (`created_at`, `created_by`, `updated_at`, `updated_by`, `bug_status`, `assign_to`, `title`, `mail_to`, `repeat_step`, `lock_version`, `resolved_at`, `resolved_by`, `closed_at`, `closed_by`, `related_bug`, `related_case`, `related_result`, " \
"`productmodule_id`, `modified_by`, `solution`, `duplicate_id`, `product_id`, " \
"`reopen_count`, `priority`, `severity`) VALUES (‘%s‘, ‘1‘, ‘%s‘, ‘1‘, ‘Active‘, ‘1‘, ‘%s‘, ‘系統管理員‘, ‘%s‘, ‘1‘, NULL , NULL, NULL, NULL, ‘‘, ‘‘, ‘‘, NULL, " \
"‘1‘, NULL, NULL, ‘1‘, ‘0‘, ‘1‘, ‘1‘);" % (now, now, bug_title, step) # 拼sql,這裏面的項目id,創建人,嚴重程度,指派給誰,都在sql裏面寫死,使用的時候可以根據項目和接口來判斷提bug的嚴重程度和提交給誰
coon = pymysql.connect(user=‘root‘, passwd=‘123456‘, db=‘bugfree‘, port=3306, host=‘192.168.21.129‘, charset=‘utf8‘) # 建立連接,使用pymysql模塊的connect方法連接mysql,傳入賬號、密碼、數據庫、端口、ip和字符集
cursor = coon.cursor() # 建立遊標
cursor.execute(sql) # 執行sql
coon.commit() # 提交
cursor.close() # 關閉遊標
coon.close() # 關閉連接

def send_mail(count_check,count_fail,count_pass,atta):
now = time.strftime("%Y-%m-%d %H:%M:%S")
username = ‘[email protected]
passwd = ‘xxxxxxxxxx‘
rece = ‘[email protected]
title = ‘python接口自動化測試報告‘+now
cc = ‘[email protected]
content = ‘大佬 你好:本次測試共運行%s條用例,失敗%s條,成功%s條,測試用例詳細執行結果請查看附件‘ % (count_check, count_fail, count_pass)
mail_host = ‘smtp.qq.com‘
mail = yagmail.SMTP(user = username,password = passwd,host = mail_host,smtp_ssl = True)
mail.send(to = rece,cc = cc,subject = title,contents = content,attachments = atta)
# print(‘發送成功!‘)


查看測試郵件

技術分享圖片

查看bugfree中bug的提交:

技術分享圖片

python實現簡單的http接口自動化