unittest_DDT資料驅動及BeautifulReport生產HTML測試報告
阿新 • • 發佈:2020-11-16
1、建立一個被測模組
users = [{'user': 'python34', 'password': '123456'}] def register(username, password1, password2): # 判斷是否有引數為空 if not all([username, password1, password2]): return {"code": 0, "msg": "所有引數不能為空"} # 註冊功能 for user in users: # 遍歷出所有賬號,判斷賬號是否存在 if username == user['user']: # 賬號存在 return {"code": 0, "msg": "該賬戶已存在"} else: if password1 != password2: # 兩次密碼不一致 return {"code": 0, "msg": "兩次密碼不一致"} else: # 賬號不存在 密碼不重複,判斷賬號密碼長度是否在 6-18位之間 if 6 <= len(username) >= 6 and 6 <= len(password1) <= 18: # 註冊賬號 users.append({'user': username, 'password': password2}) return {"code": 1, "msg": "註冊成功"} else: # 賬號密碼長度不對,註冊失敗 return {"code": 0, "msg": "賬號和密碼必須在6-18位之間"} if __name__ == "__main__": res = register('python14', '123456', '123456') print(res)
2、建立獲取Excel包
載入工作簿,一個excel檔案 openpyxl模組下的load_workbook 封裝為一個openpyxl.workbook.workbook.Workbook的物件 wb = load_workbook('case.xlsx') wb.active上次關閉的sheet 讀取表 表又被封裝為worksheet物件 wb[表名] ws = wb['Sheet1'] # # 可以獲取總行/列數 print(ws.max_row,ws.max_column) 獲取單元格 根據行row列column取單元格,行列都是從1開始 cell = ws.cell(row=2,column=1) 通過cell物件的value屬性可以獲取值 value只有兩種型別,字串和數值 如果cell裡沒有值,返回None print(cell,cell.value) from openpyxl import load_workbook class open_excel: def __init__(self,filename,sheetname): self.wb = load_workbook(filename) self.ws = self.wb[sheetname] def open_sheet(self): """ 把每行資料用字典封裝起來,合併成一個集合,方便後面呼叫 :return: """ row = self.ws.max_row column = self.ws.max_column title = {} data = [] for i in range(1,column+1): wa = self.ws.cell(row=1,column=i).value title[i]=wa for i in range(1, row + 1): temp = {} for j in range(1,column+1): temp[title[j]] = self.ws.cell(i,j).value data.append(temp) del data[0] for i in data: i['expect'] = eval(i['expect']) return data if __name__ == '__main__': res = open_excel(r'D:\PYthon\untitled_test\Ningmengban\day18\case.xlsx','Sheet1') s = res.open_sheet() print(s)
3、測試用例模組
from unittest import TestCase from ddt import ddt,data from register import registers from register import excel res = excel.open_excel(r'D:\PYthon\untitled_test\Ningmengban\day18\case.xlsx', 'Sheet1') case = res.open_sheet() # ddt 資料驅動 @ddt class test_case(TestCase): @data(*case) def test_log(self,case): res = registers.register( username=case['username'], password1=case['password1'], password2=case['password2'] ) self.assertEqual(res,case['expect']) if __name__ == '__main__': res = excel.open_excel(r'D:\PYthon\untitled_test\Ningmengban\day18\case.xlsx', 'Sheet1') case = res.open_sheet() print(case)
4、main模組
from BeautifulReport import BeautifulReport
import unittest
res = unittest.TestLoader()
ts = res.discover(r'D:\PYthon\untitled_test\Ningmengban\day18\register')
br = BeautifulReport(ts)
br.report('測試報告','玩玩.html',report_dir=r'D:\PYthon\untitled_test\Ningmengban\day18\register')