国产成人精品久久免费动漫-国产成人精品天堂-国产成人精品区在线观看-国产成人精品日本-a级毛片无码免费真人-a级毛片毛片免费观看久潮喷

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Python+unittest+requests+excel實(shí)現(xiàn)接口自動(dòng)化測(cè)試框架

瀏覽:2日期:2022-07-01 13:21:29

環(huán)境:python3 + unittest + requests

Excel管理測(cè)試用例, HTMLTestRunner生成測(cè)試報(bào)告 測(cè)試完成后郵件發(fā)送測(cè)試報(bào)告 jsonpath方式做預(yù)期結(jié)果數(shù)據(jù)處理,后期多樣化處理 后期擴(kuò)展,CI持續(xù)集成

發(fā)送郵件效果:

Python+unittest+requests+excel實(shí)現(xiàn)接口自動(dòng)化測(cè)試框架

項(xiàng)目整體結(jié)構(gòu):

Python+unittest+requests+excel實(shí)現(xiàn)接口自動(dòng)化測(cè)試框架

common模塊代碼

class IsInstance: def get_instance(self, value, check): flag = None if isinstance(value, str): if check == value:flag = True else:flag = False elif isinstance(value, float): if value - float(check) == 0:flag = True else:flag = False elif isinstance(value, int): if value - int(check) == 0:flag = True else:flag = False return flag

# logger.py import loggingimport timeimport os class MyLogging: def __init__(self): timestr = time.strftime(’%Y%m%d%H%M%S’, time.localtime(time.time())) lib_path = os.path.abspath(os.path.join(os.path.dirname(__file__), ’../logs’)) filename = lib_path + ’/’ + timestr + ’.log’ # 日志文件的地址 self.logger = logging.getLogger() # 定義對(duì)應(yīng)的程序模塊名name,默認(rèn)為root self.logger.setLevel(logging.INFO) # 必須設(shè)置,這里如果不顯示設(shè)置,默認(rèn)過(guò)濾掉warning之前的所有級(jí)別的信息 sh = logging.StreamHandler() # 日志輸出到屏幕控制臺(tái) sh.setLevel(logging.INFO) # 設(shè)置日志等級(jí) fh = logging.FileHandler(filename=filename) # 向文件filename輸出日志信息 fh.setLevel(logging.INFO) # 設(shè)置日志等級(jí) # 設(shè)置格式對(duì)象 formatter = logging.Formatter( '%(asctime)s %(filename)s[line:%(lineno)d]%(levelname)s - %(message)s') # 定義日志輸出格式 # 設(shè)置handler的格式對(duì)象 sh.setFormatter(formatter) fh.setFormatter(formatter) # 將handler增加到logger中 self.logger.addHandler(sh) self.logger.addHandler(fh) if __name__ == '__main__': log = MyLogging().logger log.debug('debug') log.info('info') log.warning('warning') log.error('error') log.critical('critical')

# operate_excel.pyimport xlrdfrom xlrd import xldate_as_tupleimport openpyxlimport datetime class ExcelData(): def __init__(self, file_path, sheet_name): self.file_path = file_path self.sheet_name = sheet_name self.workbook = xlrd.open_workbook(self.file_path) # 獲取工作表的內(nèi)容 self.table = self.workbook.sheet_by_name(self.sheet_name) # 獲取第一行內(nèi)容 self.keys = self.table.row_values(0) # 獲取行數(shù) self.rowNum = self.table.nrows # 獲取列數(shù) self.colNum = self.table.ncols def readExcel(self): datas = [] for i in range(1, self.rowNum): sheet_data = [] for j in range(self.colNum):# 獲取單元格類(lèi)型c_type = self.table.cell(i, j).ctype# 獲取單元格數(shù)據(jù)c_cell = self.table.cell_value(i, j)if c_type == 2 and c_cell % 1 == 0: c_cell = int(c_cell)elif c_type == 3: date = datetime.datetime(*xldate_as_tuple(c_cell, 0)) c_cell = date.strftime(’%Y/%d/%m %H:%M:%S’)elif c_type == 4: c_cell = True if c_cell == 1 else False# sheet_data[self.keys[j]] = c_cell # 字典sheet_data.append(c_cell) datas.append(sheet_data) return datas def write(self, rowNum, colNum, result): workbook = openpyxl.load_workbook(self.file_path) table = workbook.get_sheet_by_name(self.sheet_name) table = workbook.active # rows = table.max_row # cols = table.max_column # values = [’E’,’X’,’C’,’E’,’L’] # for value in values: # table.cell(rows + 1, 1).value = value # rows = rows + 1 # 指定單元格中寫(xiě)入數(shù)據(jù) table.cell(rowNum, colNum, result) workbook.save(self.file_path) if __name__ == ’__main__’: file_path = 'D:python_data接口自動(dòng)化測(cè)試.xlsx' sheet_name = '測(cè)試用例' data = ExcelData(file_path, sheet_name) datas = data.readExcel() print(datas) print(type(datas)) for i in datas: print(i) # data.write(2,12,'哈哈')

# send_email.pyfrom email.mime.multipart import MIMEMultipartfrom email.header import Headerfrom email.mime.text import MIMETextfrom config import read_email_configimport smtplib def send_email(subject, mail_body, file_names=list()): # 獲取郵件相關(guān)信息 smtp_server = read_email_config.smtp_server port = read_email_config.port user_name = read_email_config.user_name password = read_email_config.password sender = read_email_config.sender receiver = read_email_config.receiver # 定義郵件內(nèi)容 msg = MIMEMultipart() body = MIMEText(mail_body, _subtype='html', _charset='utf-8') msg['Subject'] = Header(subject, 'utf-8') msg['From'] = user_name msg['To'] = receiver msg.attach(body) # 附件:附件名稱(chēng)用英文 for file_name in file_names: att = MIMEText(open(file_name, 'rb').read(), 'base64', 'utf-8') att['Content-Type'] = 'application/octet-stream' att['Content-Disposition'] = 'attachment;filename=’%s’' % (file_name) msg.attach(att) # 登錄并發(fā)送郵件 try: smtp = smtplib.SMTP() smtp.connect(smtp_server) smtp.login(user_name, password) smtp.sendmail(sender, receiver.split(’,’), msg.as_string()) except Exception as e: print(e) print('郵件發(fā)送失敗!') else: print('郵件發(fā)送成功!') finally: smtp.quit() if __name__ == ’__main__’: subject = '測(cè)試標(biāo)題' mail_body = '測(cè)試本文' receiver = '[email protected],[email protected]' # 接收人郵件地址 用逗號(hào)分隔 file_names = [r’D:PycharmProjectsAutoTestresult2020-02-23 13_38_41report.html’] send_email(subject, mail_body, receiver, file_names)

# send_request.py import requestsimport json class RunMethod: # post請(qǐng)求 def do_post(self, url, data, headers=None): res = None if headers != None: res = requests.post(url=url, json=data, headers=headers) else: res = requests.post(url=url, json=data) return res.json() # get請(qǐng)求 def do_get(self, url, data=None, headers=None): res = None if headers != None: res = requests.get(url=url, data=data, headers=headers) else: res = requests.get(url=url, data=data) return res.json() def run_method(self, method, url, data=None, headers=None): res = None if method == 'POST' or method == 'post': res = self.do_post(url, data, headers) else: res = self.do_get(url, data, headers) return res

config模塊

# coding:utf-8# 郵件配置信息 [mysqlconf]host = 127.0.0.1port = 3306user = rootpassword = rootdb = test

# coding:utf-8# 郵箱配置信息# email_config.ini [email]smtp_server = smtp.qq.comport = 465sender = 780***[email protected] = hrpk******bafuser_name = 780***[email protected] = 780***[email protected],h***[email protected]

# coding:utf-8from pymysql import connect, cursorsfrom pymysql.err import OperationalErrorimport osimport configparser # read_db_config.py # 讀取DB配數(shù)據(jù)# os.path.realpath(__file__):返回當(dāng)前文件的絕對(duì)路徑# os.path.dirname(): 返回()所在目錄cur_path = os.path.dirname(os.path.realpath(__file__))configPath = os.path.join(cur_path, 'db_config.ini') # 路徑拼接:/config/db_config.iniconf = configparser.ConfigParser()conf.read(configPath, encoding='UTF-8') host = conf.get('mysqlconf', 'host')port = conf.get('mysqlconf', 'port ')user = conf.get('mysqlconf', 'user')password = conf.get('mysqlconf', 'password')port = conf.get('mysqlconf', 'port')

# coding:utf-8import osimport configparser# 讀取郵件數(shù)據(jù)# os.path.realpath(__file__):返回當(dāng)前文件的絕對(duì)路徑# os.path.dirname(): 返回()所在目錄 # read_email_config.py cur_path = os.path.dirname(os.path.realpath(__file__)) # 當(dāng)前文件的所在目錄configPath = os.path.join(cur_path, 'email_config.ini') # 路徑拼接:/config/email_config.iniconf = configparser.ConfigParser()conf.read(configPath, encoding=’UTF-8’) # 讀取/config/email_config.ini 的內(nèi)容 # get(section,option) 得到section中option的值,返回為string類(lèi)型smtp_server = conf.get('email', 'smtp_server')sender = conf.get('email', 'sender')user_name = conf.get('email','user_name')password = conf.get('email', 'password')receiver = conf.get('email', 'receiver')port = conf.get('email', 'port')

testcase模塊

# test_case.py from common.operate_excel import *import unittestfrom parameterized import parameterizedfrom common.send_request import RunMethodimport jsonfrom common.logger import MyLoggingimport jsonpathfrom common.is_instance import IsInstancefrom HTMLTestRunner import HTMLTestRunnerimport osimport time lib_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../data'))file_path = lib_path + '/' + '接口自動(dòng)化測(cè)試.xlsx' # excel的地址sheet_name = '測(cè)試用例'log = MyLogging().logger def getExcelData(): list = ExcelData(file_path, sheet_name).readExcel() return list class TestCase(unittest.TestCase): @parameterized.expand(getExcelData()) def test_api(self, rowNumber, caseRowNumber, testCaseName, priority, apiName, url, method, parmsType, data, checkPoint, isRun, result): if isRun == 'Y' or isRun == 'y': log.info('【開(kāi)始執(zhí)行測(cè)試用例:{}】'.format(testCaseName)) headers = {'Content-Type': 'application/json'} data = json.loads(data) # 字典對(duì)象轉(zhuǎn)換為json字符串 c = checkPoint.split(',') log.info('用例設(shè)置檢查點(diǎn):%s' % c) print('用例設(shè)置檢查點(diǎn):%s' % c) log.info('請(qǐng)求url:%s' % url) log.info('請(qǐng)求參數(shù):%s' % data) r = RunMethod() res = r.run_method(method, url, data, headers) log.info('返回結(jié)果:%s' % res) flag = None for i in range(0, len(c)):checkPoint_dict = {}checkPoint_dict[c[i].split(’=’)[0]] = c[i].split(’=’)[1]# jsonpath方式獲取檢查點(diǎn)對(duì)應(yīng)的返回?cái)?shù)據(jù)list = jsonpath.jsonpath(res, c[i].split(’=’)[0])value = list[0]check = checkPoint_dict[c[i].split(’=’)[0]]log.info('檢查點(diǎn)數(shù)據(jù){}:{},返回?cái)?shù)據(jù):{}'.format(i + 1, check, value))print('檢查點(diǎn)數(shù)據(jù){}:{},返回?cái)?shù)據(jù):{}'.format(i + 1, check, value))# 判斷檢查點(diǎn)數(shù)據(jù)是否與返回的數(shù)據(jù)一致flag = IsInstance().get_instance(value, check) if flag:log.info('【測(cè)試結(jié)果:通過(guò)】')ExcelData(file_path, sheet_name).write(rowNumber + 1, 12, 'Pass') else:log.info('【測(cè)試結(jié)果:失敗】')ExcelData(file_path, sheet_name).write(rowNumber + 1, 12, 'Fail') # 斷言 self.assertTrue(flag, msg='檢查點(diǎn)數(shù)據(jù)與實(shí)際返回?cái)?shù)據(jù)不一致') else: unittest.skip('不執(zhí)行') if __name__ == ’__main__’: # unittest.main() # Alt+Shift+f10 執(zhí)行生成報(bào)告 # 報(bào)告樣式1 suite = unittest.TestSuite() suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestCase)) now = time.strftime(’%Y-%m-%d %H_%M_%S’) report_path = r'D:PycharmProjectsAutoTestresultreport.html' with open(report_path, 'wb') as f: runner = HTMLTestRunner(stream=f,, description='測(cè)試用例執(zhí)行情況', verbosity=2) runner.run(suite)

用例執(zhí)行文件

import osimport timeimport unittestfrom HTMLTestRunner import HTMLTestRunnerfrom common.send_email import send_email # run_case.py # 獲取當(dāng)前py文件絕對(duì)路徑cur_path = os.path.dirname(os.path.realpath(__file__)) # 1: 加載測(cè)試用例def all_test(): case_path = os.path.join(cur_path, 'testcase') suite = unittest.TestLoader().discover(start_dir=case_path, pattern='test_*.py', top_level_dir=None) return suite # 2: 執(zhí)行測(cè)試用例def run(): now = time.strftime('%Y_%m_%d_%H_%M_%S') # 測(cè)試報(bào)告路徑 file_name = os.path.join(cur_path, 'report') + '/' + now + '-report.html' f = open(file_name, 'wb') runner = HTMLTestRunner(stream=f,, description='環(huán)境:windows 10 瀏覽器:chrome', tester='wangzhijun') runner.run(all_test()) f.close() # 3: 獲取最新的測(cè)試報(bào)告def get_report(report_path): list = os.listdir(report_path) list.sort(key=lambda x: os.path.getmtime(os.path.join(report_path, x))) print('測(cè)試報(bào)告:', list[-1]) report_file = os.path.join(report_path, list[-1]) return report_file # 4: 發(fā)送郵件def send_mail(subject, report_file, file_names): # 讀取測(cè)試報(bào)告內(nèi)容,作為郵件的正文內(nèi)容 with open(report_file, 'rb') as f: mail_body = f.read() send_email(subject, mail_body, file_names) if __name__ == '__main__': run() report_path = os.path.join(cur_path, 'report') # 測(cè)試報(bào)告路徑 report_file = get_report(report_path) # 測(cè)試報(bào)告文件 subject = 'Esearch接口測(cè)試報(bào)告' # 郵件主題 file_names = [report_file] # 郵件附件 # 發(fā)送郵件 send_mail(subject, report_file, file_names)

data:

Python+unittest+requests+excel實(shí)現(xiàn)接口自動(dòng)化測(cè)試框架

report:

Python+unittest+requests+excel實(shí)現(xiàn)接口自動(dòng)化測(cè)試框架

logs:

Python+unittest+requests+excel實(shí)現(xiàn)接口自動(dòng)化測(cè)試框架

到此這篇關(guān)于Python+unittest+requests+excel實(shí)現(xiàn)接口自動(dòng)化測(cè)試框架的文章就介紹到這了,更多相關(guān)Python 接口自動(dòng)化測(cè)試內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: python
相關(guān)文章:
主站蜘蛛池模板: 国产成人av性色在线影院 | 日本暖暖在线视频 | 视频二区好吊色永久视频 | 一级毛片a免费播放王色 | 精品欧美一区二区在线观看 | 亚洲国产欧美在线不卡中文 | 一级a级国产不卡毛片 | 亚洲一级毛片欧美一级说乱 | 成人在线精品视频 | 偷拍亚洲欧美 | 亚洲片在线观看 | 国产成人综合日韩精品无 | 全部精品孕妇色视频在线 | 免费看黄色三级毛片 | 久久精品中文字幕一区 | 亚洲一区二区在线免费观看 | 免费一级成人免费观看 | 日本免费人成黄页在线观看视频 | 亚洲精品在线播放视频 | 午夜桃色剧场 | 欧美色视频在线观看 | 国产高清一级毛片在线不卡 | 国产一区二区免费播放 | 欧美成人午夜视频免看 | 国产精品国产三级国产an | 天天看夜夜操 | fulidown国产精品合集 | 久久99国产精品久久欧美 | 免费国产一区二区在免费观看 | 特级毛片 | 国产一区二区免费视频 | 午夜国产高清精品一区免费 | 久久99久久精品视频 | 性高湖久久久久久久久 | 日本在线免费播放 | 精品亚洲一区二区三区 | 国产亚洲精品久久久久久无 | 国产成人综合久久精品红 | jiz欧美高清 | 国产理论视频 | 亚洲精品区 |