1. 程式人生 > >介面自動化框架之一:excel管理資料

介面自動化框架之一:excel管理資料

1.背景描述:
屬於東莞某某證券的介面自動化專案,客戶方強烈希望實現excel資料驅動用例,excel方式管理資料。
           要求1:所有介面資訊都放在excel中,外部通過填寫功能號,便可將該功能號對應的所有正反用例資訊給讀取出來;
           要求2:正反例的入引數據和出引數據在excel中填寫。
           要求3:excel中資料如果是SQL,就就需要查詢SQL並將查詢資料作為excel資料返回;
           要求4:讀取excel返回的最終入引數據是一個拼接成形如A1=A2;B1=B2..的字串;
           要求5:要便於出參校驗,引數是是以字典的形式返回,便於通過輸入欄位名來校驗指定的出差欄位;


2.excel要求模板如下(根據客戶需求,自己再填加一些顏色區分):
3.呼叫方式: a測試平臺呼叫方式: 程式碼呼叫方式: a = dg_GetSheetData(u'C:\\Users\\Administrator\\Desktop\\1.xlsx', u"Sheet1", "332634") 4.返回結果資料結構: 格式: [[功能號,入參字串1,出參1],[功能號,入參字串2,出參2],[功能號,入參字串2,出參3],----] 實際例子: ["332634", "op=;op_branch_no=測試專案;op_entrust_way=0;op_station=;op1222=1233456788;op_branch_no=測試專案;op_entrust_way1=0;op_entrust_way2=;op1222afasd=", {"trade_plat": "4"}] 5.介面呼叫:
省略............ 省略............ 6.讀取excel的python程式碼: 程式碼如下: ###### 讀取excel中資料,如果資料是sql語句,就將查詢改SQL語句,並將值作為excel資料返回---- # coding=utf-8 import os from datetime import datetime, date import json import string import xlrd import win32com.client import MySQLdb # import cx_Oracle import sys reload(sys) sys.setdefaultencoding("UTF-8") ##################################################################################### def dg_GetSheetData(file_path, sheet_name, funcnum): # 連線資料庫 error_sign = True """ try: os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.ZHS16GBK' #conn = cx_Oracle.connect("使用者名稱 / 密碼@ Oracle伺服器IP / Oracle的SERVICE_NAME") db= cx_Oracle.connect('hs_user/
[email protected]
:1521/testdb') cursor = db.cursor() except Exception as e: print u'請檢查資料庫連線,錯誤原因:',cellvalue,str(e).decode('GBK') """ try: db = MySQLdb.connect("127.0.0.1", "root", "kdbase11", "kt", charset='utf8') cursor = db.cursor() except: error_sign = False print u"----Error>>>>資料庫連線失敗,請檢查資料庫連線資訊以及資料庫環境<<<<Error----" print u"----警告>>>所有SQL語句當普通字串處理<<<<警告----" #開始excel操作 wb = xlrd.open_workbook(file_path) # 獲取workbook中所有的表格sheetname sheets = wb.sheet_names() if sheet_name in sheets: # 按照指定sheet_name去查詢 sheet = wb.sheet_by_name(sheet_name) # 統計第一行中欄位多少,以便後面使用 listrows = [] sign1 = 0 nrows = sheet.nrows # print nrows for r in range(0, nrows - 1): listrow = [] sigenlistrow = [] cell_col0_val = str(data_type(sheet, r, 0)).decode('UTF-8') nestcell_col0_val = str(data_type(sheet, r + 1, 0)).decode('UTF-8') if cell_col0_val == str(funcnum) and nestcell_col0_val == '': sign1 = 1 for c in range(3, sheet.ncols): cellvaluelast = str(data_type(sheet, r, c)).decode('UTF-8') cellvalue = str(data_type(sheet, r + 1, c)).decode('UTF-8') listrow.append(cellvalue) sigenlistrow.append(cellvaluelast) # listrows.append(listrow) # print listrow inparameter = listrow[0:sigenlistrow.index(u'預期值')] # 去入參欄位 outparameter = listrow[sigenlistrow.index(u'預期值') + 1:] while len(outparameter) and outparameter[-1] == '': # 去列表右側空格 del outparameter[-1] # print outparameter # print inparameter elif cell_col0_val == '' and sign1 == 1 and nestcell_col0_val == '': a = 1 str1 = '' num = 0 for c in range(3, sheet.ncols): if a == 1: cellvalue0 = str(data_type(sheet, r + 1, c)).decode('UTF-8') cellvalue1 = cellvalue0.strip().replace("\n", " ").replace(",",",") cellvalue = cellvalue1.replace(" ", " ") if error_sign == True and cellvalue.split(' ')[0].lower() == 'select' and 'from' in cellvalue: listvalue = cellvalue.split(" ") for v in range(len(listvalue)): if 'from' == listvalue[v].replace(' ', ''): str1 = ''.join(listvalue[0:v]) break else: pass if str1: num = str1.count(',') + 1 try: cursor.execute(cellvalue) result = cursor.fetchone() except: print u"----Error>>>>請檢查SQL語句:", cellvalue, u"的正確性!<<<<Error----" result = None if result and num == len(result): for m in range(len(result)): listrow.append(str(result[m])) # listrow.append(str(result[m]).decode("GBK")) a = len(result) elif not result: # 這裡包括兩種情況為空,一是資料庫查詢結果為None,二是因為執行SQL語句失敗而返回為None a = num # 如果結果為空就給值賦值為空 for m in range(num): listrow.append('') else: print u"----Error>>>>請檢查SQL語句:", cellvalue, u"的正確性!<<<<Error----" print u"----警告>>>>SQL語句:", cellvalue, u"將當作普通字串處理!<<<<警告----" listrow.append(cellvalue) else: listrow.append(cellvalue1) else: a = a - 1 pass if listrow.count('') != len(listrow): # 判斷是否為空行,如果不為空行就統計資料 # listrows.append(listrow) # 將入參拼接成形如A1=A2;B1=B2..的字串 inparameters = '' for k in range(0, len(inparameter)): inparameters = inparameters + inparameter[k] + '=' + listrow[k] + ';' # 將出參拼接成形如{A1:A2;B1:B2,.....}的字典 outparameters = {} for k in range(0, len(outparameter)): outparameters[outparameter[k]] = listrow[k + len(inparameter) + 1] # print outparameters listrows.append([funcnum, inparameters[:-1], outparameters]) # print inparameters[:-1] elif cell_col0_val == '' and sign1 == 1 and (nestcell_col0_val != '' or r == nrows): break if error_sign == True: cursor.close() db.close() return listrows else: print 'you input not in sheets' ##################################################################################### ####型別轉化##### def data_type(table, row, col): name = table.cell_value(row, col) type = table.cell_type(row, col) if type == 0: # 空0 name = "" elif type == 1: # 字串1 name = name elif type == 2 and name % 1 == 0: # 數字2 name = int(name) elif type == 3: # 日期3 date_value = xlrd.xldate_as_tuple(name, 0) name = datetime(*date_value).strftime('%Y/%m/%d %H:%M:%S') elif type == 4: # 布林4 name = True if name == 1 else False elif type == 5: # error 5 name = u"Excel資料關聯有問題,請檢查Excel資料" return name ##################################################################################### # 刪除指定行資料 def DelSheetRow(self, url, sheetname, start, end): start = int(start) end = int(end) Exlapp = win32com.client.Dispatch('Excel.Application') Exlfile = Exlapp.Workbooks.Open(url) ExlShet = Exlfile.Worksheets(sheetname) for i in xrange(end, start - 1, -1): ExlShet.Rows(i).Delete() Exlfile.Close(SaveChanges=1) # 完成 關閉儲存檔案 del Exlapp if __name__ == '__main__': a = dg_GetSheetData(u'C:\\Users\\Administrator\\Desktop\\1.xlsx', u"Sheet1", "332634") for i in a: print json.dumps(i, encoding="utf-8", ensure_ascii=False)