寫python就不無聊了
沒事的時候,或者叫忙裏偷閒,寫寫python,提升一下代碼能力;
前段時間寫了對比文件的python工具代碼,需要手工來對比數據;
略顯雞肋,這是我們開發同學工作未做足,接口文檔不標識變更;
json文件的對比
思路:因爲生成的json文件都在某個目錄下,所以先對比md5,再判斷內容,生成對應的html報告
excel文件的對比
- 第一版的實現很不友好,需要人工對比,篩選出用例做出標記
思路:將json格式數據的文件解析生成excel用例,然後再逐條對比excel的數據,並寫入text文本
思路:不需要將excel的行的所有列進行對比,只抽取其中的某幾列,如:接口url及參數params
思路:繼續抽取其中的編號列,然後統一寫入一個新的excel文件中,比寫入文本更加直觀
思路:我不想把有變更的用例重寫文件,而是直接在原文件中做標記(添加背景色),可能會用到數據驅動或者unittest單元測試框架
附上代碼及註釋
import xlrd
import xlwt
import time
import config
from common.HandleLogging import log
class DiffExcelFile():
'''對比excel文件的工具類'''
def __init__(self,wb_name="Excel_Workbook.xlsx",sheet_name="Sheet1"):
self.workbook = xlwt.Workbook(encoding = 'ascii')
self.wb_name=wb_name
self.sheet_name=sheet_name
self.worksheet = self.workbook.add_sheet(self.sheet_name)
def write_excel(self,row,col,content,style='pattern: pattern solid, fore_colour yellow; font: bold on'):
'''寫入文件對象,傳入行和列及寫入內容,style樣式默認'''
style=xlwt.easyxf(style)
self.worksheet.write(row, col, label = content, style=style)
self.save_excel()
def save_excel(self):
'''保存工作對象'''
self.workbook.save(self.wb_name)
def write_file(filename,content):
'''
寫入文件,將對比不同的測試用例寫入日誌
'''
if not isinstance(content,str):
content=str(content)
with open(filename,'a',encoding='utf-8') as file:
time_now= time.strftime("%Y-%m-%d", time.localtime())
file.write(time_now+':變更的接口及參數==>'+content+'\n')
def read_excel(file_path,sheet_name="Sheet1"):
'''讀取excel表格,返回一個list所有列數據'''
datas=[]
xlsx_file={}
wb=xlrd.open_workbook(file_path)
sheet_name_list=wb.sheet_names()
if sheet_name in sheet_name_list:
sheet_name=wb.sheet_by_name(sheet_name)
for rows in range(0,sheet_name.nrows):
orign_list=sheet_name.row_values(rows)
xlsx_file[rows]=orign_list
else:
log.info("{}子表名不存在{}文件中!".format(sheet_name,file_path))
for row in range(1,len(xlsx_file)):
data=dict(zip(xlsx_file[0],xlsx_file[row]))
datas.append(data)
return datas
xw=DiffExcelFile(wb_name=config.datas_path+"test124.xlsx")
def diff_excel(src_file,des_file,check="caseid,url,params"):
'''對比文件的數據某個字段的值,默認sheet_name=Sheet1'''
fail=0
res1=read_excel(src_file)
res2=read_excel(des_file)
lis1=check.split(",")
index=lis1[0]
check1=lis1[1]
check2=lis1[2]
data=[]
for i in range(len(res2)):
data.append([res2[i][check1],res2[i][check2]])
datas=[]
for r1 in range(len(res1)):
case=[res1[r1][check1],res1[r1][check2]]
if case not in data:
log.info("新增/變更數據:{}".format(case))
fail+=1
case_id=str(res1[r1][index])
content="".join([case_id,str(case)])
datas.append(content)
write_file(config.logs_path+"diff_data.log",content)
for i in range(len(datas)):
xw.write_excel(i+1, 0, datas[i])
if __name__ == '__main__':
res=diff_excel(config.datas_path+"test123.xlsx", config.datas_path+"test321.xlsx")