class IsContent: def __init__(self): self.excel=OperationExcel() self.log=MyLog() def isContent(self,row,str2): flag=None if self.excel.getExpect(row=row) in str2: flag=True self.log.infoLog('%s接口通过预期结果断言成功'%self.excel.getCaseID(row)) else: flag=False self.log.errorLog('%s接口通过预期结果断言失败'%self.excel.getCaseID(row)) return flag
class Method: def __init__(self): self.operationJson=OperationJson() self.excel=OperationExcel() self.log=MyLog() def post(self,row,data=None): try: r=requests.post( url=self.excel.getUrl(row), data=data, headers=getHeadersValue(), timeout=6) self.log.infoLog('接口%s请求成功,请求方式:post,请求参数:%s' %(self.excel.getCaseID(row),data)) return r except Exception as e: self.log.errorLog('接口%s请求错误,原因:%s'%(self.excel.getCaseID(row),e)) raise RuntimeError('接口请求发生未知的错误') def get(self,row,params=None): try: r=requests.get(url=self.excel.getUrl(row), params=params, headers=getHeadersValue(), timeout=6) self.log.infoLog('接口%s请求成功,请求方式:get,请求参数:%s' %(self.excel.getCaseID(row),params)) return r except Exception as e: self.log.errorLog('接口%s请求错误,原因:%s'%(self.excel.getCaseID(row),e)) raise RuntimeError('接口请求发生未知错误') def method(self,row,data=None,params=None): method=self.excel.getMethod(row) if method == 'post': r=requests.post( url=self.excel.getUrl(row), data=data, headers=getHeadersInfo(), timeout=6) self.log.infoLog('接口%s请求成功,请求方式:post,请求参数:%s' %(self.excel.getCaseID(row),data)) return r elif method == 'get': r=requests.get( url=self.excel.getUrl(row), params=params, headers=getHeadersInfo(), timeout=6) self.log.infoLog('接口%s请求成功,请求方式:get,请求参数:%s' %(self.excel.getCaseID(row),params)) return r else: self.log.errorLog('接口请求方式不正确')
class OperationExcel: def __init__(self): self.log=MyLog() def getExcel(self): db=xlrd.open_workbook(data_dir('data','data.xls')) sheet=db.sheet_by_index(0) return sheet def get_rows(self): '''获取excel的行数''' return self.getExcel().nrows def get_row_cel(self,row,col): '''获取单元格的内容''' return self.getExcel().cell_value(row,col) def getCaseID(self,row): '''获取测试ID''' return self.get_row_cel(row,getCaseID()) def getUrl(self,row): '''获取请求地址''' return self.get_row_cel(row,getUrl()) def get_request_data(self,row): '''获取请求参数''' return self.get_row_cel(row, get_request_data()) def getMethod(self,row): '''获取请求方式''' return self.get_row_cel(row,getMethod()) def getExpect(self,row): '''获取期望结果''' return self.get_row_cel(row,getExpect()) def getResult(self,row): '''获取实际的结果''' return self.get_row_cel(row,getResult()) def writeResult(self,row,content): '''测试结果写到文件中''' try: col=getResult() work =xlrd.open_workbook(data_dir('data','data.xls')) #打开表 old_content = copy(work) #利用xlutils.copy下的copy函数复制 ws = old_content.get_sheet(0) #获取表单0 ws.write(row,col,content) ##改变(row,col)的值 old_content.save(data_dir("data","data.xls")) #保存文件 self.log.infoLog('测试结果写入excel成功,写入结果:%s' %content) except Exception as e: self.log.errorLog('测试结果写入excel失败,原因:%s'%e) def run_success_result(self): '''获取执行成功的用例数''' pass_count=[] fail_count=None for i in range(1,self.get_rows()): if self.getResult(i)=='pass': pass_count.append(i) return int(len(pass_count)) def run_fail_result(self): '''获取执行失败的用例数''' return int((self.get_rows()-1)-self.run_success_result()) #总数减去成功数 def run_pass_rate(self): '''测试结果通过率''' rate='' if self.run_fail_result()==0: rate='100%' elif self.run_fail_result()!=0: rate=str(int(self.run_success_result()/int(self.get_rows()-1)*100))+'%' return rate
class Runner: def __init__(self): self.excel=OperationExcel() self.log=MyLog() def getSuite(self): '''获取要执行的测试套件''' suite = unittest.TestLoader().discover( start_dir=os.path.join(os.path.dirname(os.path.dirname(__file__)),'tests'), pattern='test_*.py', top_level_dir=None) return suite def getNowtime(self): '''获取当前时间''' now=time.strftime('%Y-%m-%d %H_%M_%S',time.localtime(time.time())) return now def getRun(self): '''生成测试报告''' filename=os.path.join(os.path.dirname(os.path.dirname(__file__)),'report',self.getNowtime()+'.html') fp=open(filename,'wb') runner=HTMLTestRunner.HTMLTestRunner(stream=fp,verbosity=2,title='自动化测试报告',description='接口自动化测试') return runner def send_mail(self,smtp_server,sender,psw,receiver,port,content): ''' 发送邮件内容 :param sender:发送邮件的人 :param receiver:接受邮件的人 :param content:邮件内容 ''' #找到生成最新报告的文件 file_path=os.path.join(os.path.dirname(os.path.dirname(__file__)),'report') lists=os.listdir(file_path) report_path=os.path.join(file_path,lists[-1]) #定义邮件内容 msg = MIMEMultipart() body = MIMEText(content, _subtype='plain', _charset='utf-8') self.log.infoLog('添加邮件内容:%s'%content) msg['Subject'] = "接口自动化测试报告" msg["from"] = sender self.log.infoLog('发件人邮箱:%s'%sender) msg["to"] = psw msg.attach(body) #添加附件 att = MIMEText(open(report_path, "rb").read(), "base64", "utf-8") self.log.infoLog('读取附件') att["Content-Type"] = "application/octet-stream" att["Content-Disposition"] = 'attachment; filename= "report.html"' msg.attach(att) self.log.infoLog('添加邮件附件') try: smtp = smtplib.SMTP_SSL(smtp_server, port) self.log.infoLog('连接邮箱smtp服务') except: smtp = smtplib.SMTP() smtp.connect(smtp_server, port) self.log.infoLog('连接邮箱smtp服务') self.log.infoLog('smtp服务连接成功') #用户名密码 smtp.login(sender, psw) smtp.sendmail(sender, receiver, msg.as_string()) self.log.infoLog('收件人邮箱:%s'%receiver) smtp.quit() def main_run(self): '''执行测试用例''' self.getRun().run(self.getSuite()) self.log.infoLog('-------------------------测试用例执行完毕-----------------------') self.log.infoLog('已生成html报告。。。') #统计测试用例成功率 content='测试用例执行情况:通过数:{0} 失败数:{1} 通过率:{2} \n附件为-->接口自动化测试报告<--'.format( self.excel.run_success_result(), self.excel.run_fail_result(), self.excel.run_pass_rate()) self.log.infoLog('统计测试用例执行成功率完成。。。') #邮箱配置 from config import readconfig smtp_server=readconfig.smtp_server sender=readconfig.sender psw=readconfig.psw receiver=readconfig.receiver port=readconfig.port self.log.infoLog('----------------开始发送邮件----------------------') self.send_mail(smtp_server,sender,psw,receiver,port,content) print('Please wait while the statistics test results are sent in the mail') self.log.infoLog('----------------邮件发送成功----------------------')