def encodedata(self): '构造发送的code,time+username形式(yyyymmddhhmmss+username),使用本地时间' nowtime = datetime.datetime.now().strftime("%Y%m%d%H%M%S") code = (nowtime + user['username']).encode('utf-8') print('code=========', code) encodedata = base64.b64encode(code) logger.info(encodedata) return encodedata
def encode_base64(self): '构造发送的code,time+username形式(yyyymmddhhmmss+username),获取登录页面返回的服务器时间' # nowtime = datetime.datetime.now().strftime("%Y%m%d%H%M%S") # code = (nowtime + user['username']).encode('utf-8') code = (Login.nowtime + user['username']).encode('utf-8') print('code=========', code) Login.data = base64.b64encode(code) logger.info(Login.data) return Login.data
def test_a_gettoken(self): '获取access_token-无用户信息' datas={ "Authorization": "1222", "client_id": "webApp", "client_secret": "webApp" } mytoken = {"access_token":""} r = requests.post(url=url+'api-auth/oauth/client/token', headers=datas) logger.info(r.text) print(r.url)
def setUpClass(self): '获取登录页的cookie' r = requests.get(url=url + '/login') print(r.elapsed.total_seconds()) # 接口响应时间 print(r.url) # 必须有这一行,统计接口数量用 Login.mycookie = r.cookies.get_dict() if '获取验证码' in r.text: globals()["sendsms"] = 1 user['smsSend'] = "true" # 获取服务器时间(在登录页面中) Login.nowtime = re.findall('(?!\bsendSms\(\")\d{14}', r.text) Login.nowtime = Login.nowtime[0] logger.info('Login.nowtime=======%s' % (Login.nowtime)) else: globals()["sendsms"] = 2 user['smsSend'] = "false"
def usertokenbyurl(username, password, gateway, client_id, client_secret): ''' 获取用户名密码获取token gateway:系统gateway地址 client_id: client_secret: ''' headers={ "Authorization": "1222", "client_id": client_id, "client_secret": client_secret } mytoken = {"Authorization":""} r = requests.post(url=gateway+'/api-auth/oauth/user/token', data={"username":username, "password":password}, headers=headers) mytoken['Authorization'] = "Bearer " + r.json()['access_token'] logger.info(mytoken) return mytoken
def test_h1_login(self): '登录请求-登录成功' user['username'] = successuser['username'] user['password'] = successuser['password'] user['kaptcha'] = successuser['kaptcha'] if globals()["sendsms"] == 1: user['phonecode'] = Login.phonecode print(user) r = requests.post(url=url + 'login', data=user, headers=header_www, cookies=Login.mycookie) print(r.url) print(r.text) # 将cookie写入文件中 with open(cookiefile, 'w') as f: json.dump(Login.mycookie, f) logger.info(Login.mycookie) self.assertIn('个人资料', r.text)
def test_b0_listproject(self): '获取项目id-标准' r = requests.post(url=url + 'project_list/queryProject', data={ 'page': 1, 'limit': 100, 'status': '', 'name': project['name'] }, headers=header_json, cookies=self.cookie) print(r.text) projectsid = [] for projects in r.json()['data']: projectsid.append(projects['id']) projectsid.sort(reverse=True) cdatas.projectid = projectsid[0] logger.info('标准项目id=%s' % (projectsid[0])) self.assertEqual(200, r.status_code)
def test_f1_listproject(self): '获取项目id-定向' r = requests.post(url=url + 'orientation/projectinfo/list', data={ 'page': 1, 'limit': 100, 'status': '', 'name': nproject['name'] }, headers=header_json, cookies=self.cookie) print(r.text) oprojectsid = [] for nprojects in r.json()['data']: oprojectsid.append(nprojects['id']) oprojectsid.sort(reverse=True) cdatas.oprojectid = oprojectsid[0] logger.info('定向项目id=%s' % oprojectsid[0]) self.assertEqual(200, r.status_code)
def getjkarg(args, n=3): ''' 获取jenkins传入的参数 n:jenkins传入参数的个数 systype:将要执行的系统 TASK_ID:任务ID BUILD_NUMBER:jenkins构建号 ''' try: if len(args) < n: raise Exception('请设置脚本执行参数') else: logger.info(args) # systype = sys.argv[1] # 执行项目:xr-星睿,zt-证投,all-所有,默认执行所有 result_devops.TASK_ID = sys.argv[2] # 获取任务ID result_devops.BUILD_NUMBER = sys.argv[3] # 获取jenkins构建号 return True except Exception as e: logger.error(e) return False
def test_c_addproject(self): '新增项目-非标准' nproject['trustee'] = Project.teeid r = requests.post(url=url + 'projectinfo/addProject', params=nproject, headers=header_json, cookies=self.cookie) logger.info(self.cookie) logger.info(r.text) # 如果名称已存在,删除后新增 if r.json()['message'] == '项目名称已存在': sql = "delete from collection_project_approval where name='%s'" % ( nproject['name']) self.db.delete_data(sql) print('delete same name productinfo') r = requests.post(url=url + 'projectinfo/addProject', params=nproject, headers=header_json, cookies=self.cookie) self.assertEqual("新增成功", r.json()['message'])
def send_email(report_file, result): msg = MIMEMultipart() # 混合MIME格式 if result != 'Sucess': msg.attach(MIMEText(result, 'plain', 'utf-8')) try: msg.attach( MIMEText( open(report_file, encoding='utf-8').read(), 'html', 'utf-8')) # 添加html格式邮件正文(会丢失css格式) att1 = MIMEText(open(report_file, 'rb').read(), 'base64', 'utf-8') # 二进制格式打开 att1["Content-Type"] = 'application/octet-stream' att1["Content-Disposition"] = 'attachment; filename=%s' % ( email_conf.attchname) # filename为邮件中附件显示的名字 msg.attach(att1) except: print('找不到附件--%s' % report_file) send_name = email_conf.fromname + "<%s>" % (email_conf.sender) msg['From'] = _format_addr(send_name) # 发件人名称展示 # msg['To'] = Header(email_conf.receivers) # 收件人名称展示 msg['To'] = email_conf.receivers # 收件人名称展示 msg['Subject'] = Header(email_conf.subject, 'utf-8') # 中文邮件主题,指定utf-8编 logfile = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'report', project_conf.project + '.log') att2 = MIMEText(open(logfile, 'rb').read(), 'base64', 'utf-8') att2["Content-Type"] = 'application/octet-stream' att2["Content-Disposition"] = 'attachment; filename=%s' % ( project_conf.project + '.log') msg.attach(att2) try: smtp = smtplib.SMTP_SSL(email_conf.server) # smtp服务器地址 使用SSL模式 smtp.login(email_conf.user, email_conf.passwd) # 用户名和授权码(注意不是登录密码) smtp.sendmail(email_conf.sender, email_conf.receivers.split(","), msg.as_string()) #smtp.sendmail("*****@*****.**", "*****@*****.**", msg.as_string()) # 发送给另一个邮箱 logger.info("邮件发送完成!") except Exception as e: logger.error(str(e)) finally: smtp.quit()
def test_a_getusertoken(self): '获取access_token-根据用户名密码获取' headers={ "Authorization": "1222", "client_id": "webApp", "client_secret": "webApp" } # datas = { # "username": "******", # "password": "******" # } mytoken = {"access_token":""} r = requests.post(url=url+'api-auth/oauth/user/token', data=userinfo, headers=headers) logger.info(r.text) print(r.url) mytoken['access_token'] = 'Bearer ' + r.json()['access_token'] logger.info('access_token:%s'%mytoken) # 将access_token写入文件中 with open(tokenfile, 'w') as f: json.dump(mytoken,f ) logger.info(mytoken)
def devopscase_add(caseinfo): '将接口自动化测试案例插入devops中' token = usertokenbyurl(devops.username,devops.mypasswd,devops.gateway,devops.client_id,devops.client_secret) headers = token r = requests.post(url=devops.gateway+'/api-devops/testCase/importAutoTestcaseData', json=caseinfo, headers=headers) logger.info(r.text)
def run_toga(): report_html(os.path.join(report_path, report_name + ".html")) report_xml(report_path) def report_bf(reppath, fname): '使用BeautifulReport库生成格式更美观的html报告' run = bf(all_case()) #实例化BeautifulReport模块 run.report(filename=fname, report_dir=reppath, description=email_conf.subject) if __name__ == '__main__': getjkarg(sys.argv, 3) logger.info('本次执行地址:%s' % (get_host_ip())) now = time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime(time.time())) mvreport(report_path, his_report_path) # 创建新的报告文件 # report_abspsth = os.path.join(report_path,"result_"+now+".html") report_name = "report_" + now + '.html' logger.info('report_name:%s' % report_name) # 执行所有的case try: if testnet() == 0: logger.info('网络正常,开始执行测试任务') report_html(os.path.join(report_path, report_name)) # report_xml(report_path) # report_bf(report_path, report_name) flag = 'Sucess'
def _generate_report_test(self, rows, cid, tid, n, t, o, e): # e.g. 'pt1.1', 'ft1.1', etc has_output = bool(o or e) tid = (n == 0 and 'p' or 'f') + 't%s.%s' % (cid+1,tid+1) name = t.id().split('.')[-1] doc = t.shortDescription() or "" desc = doc and ('%s: %s' % (name, doc)) or name tmpl = has_output and self.REPORT_TEST_WITH_OUTPUT_TMPL or self.REPORT_TEST_NO_OUTPUT_TMPL testcase_REC_CRT_TMS = str(self.startTime)[:19] # 测试案例结果入库时间 test_casename_e = name # 测试案例英文名称 test_casename_c = doc # 测试案例中文名称 if result_devops.isinsertcase == 1: # 测试用例入库判断 # 接口自动化测试案例数据构建 try: self.apicaseinfo['projectKey'] = result_devops.projectKey self.apicaseinfo['No'] = 0 self.apicaseinfo['Function'] = self.test_classname_d # 一级子功能-使用模块描述 self.apicaseinfo['SubFunctionData'] = [] # --测试步骤和预期-- TestingProcedureData_1 = { "TestingProcedure": "", "ExpectedResultsData": "" } TestingProcedureData_1['TestingProcedure'] = test_casename_c # 测试步骤-取测试案例中文名称 # self.TestingProcedureData.append(TestingProcedureData_1) TestCaseData_1 = { "autoTestcase": "API-TTTT-0001", "TestCase": "测试用例1", "label": "API", "marker": "", "premise": "", "TestingProcedureData": [] } # TestCaseData_1['autoTestcase'] = test_casename_e TestCaseData_1['autoTestcase'] = 'API_'+result_devops.projectKey+'_'+test_casename_e # 使用项目key+案例名称方式,避免重复 TestCaseData_1['TestCase'] = test_casename_c TestCaseData_1['TestingProcedureData'].append(TestingProcedureData_1) SubFunctionData_1 = { 'SubFunction':'', 'TestCaseData':[] } SubFunctionData_1['SubFunction'] = self.test_classname # 二级子功能-使用模块类名 SubFunctionData_1['TestCaseData'].append(TestCaseData_1) self.apicaseinfo['SubFunctionData'].append(SubFunctionData_1) # 数据为list结构 # self.apicaseinfo = [self.apicaseinfo] logger.info(self.apicaseinfo) devopscase_add([self.apicaseinfo]) # 通过调用接口,将测试用例插入到devops库中 except Exception as e: logger.info(e) else: pass # print(self.testcaseinfo) if result_devops.isinsert == 1: # 测试案例执行结果插入devops数据库中 self.devopsdb = mysqlconnectcommon(result_devops.host, result_devops.port, result_devops.user, result_devops.password, result_devops.dbname) # 测试结果数据构建 self.testcaseinfo['TASK_ID'] = result_devops.TASK_ID self.testcaseinfo['BUILD_NUMBER'] = result_devops.BUILD_NUMBER self.testcaseinfo['AUTO_TESTCASE_ID'] = 'API_'+result_devops.projectKey+'_'+test_casename_e # 自动化用例ID,取自动化用例的英文名称 self.testcaseinfo['ZH_NAME'] = str(test_casename_c) self.testcaseinfo['CASE_NAME'] = test_casename_e self.testcaseinfo['TIMES'] = '' # 执行次数,暂时设为常量1 self.testcaseinfo['PERFORM_TIME'] = testcaseruntime[test_casename_e] # 测试案例执行耗时 self.testcaseinfo['EXECUTE_ST'] = testcaseispass[test_casename_e] # 案例执行结果 self.testcaseinfo['REC_CRT_TMS'] = testcase_REC_CRT_TMS # 测试案例结果入库时间 self.testcaseinfo['REC_UPD_TMS'] = testcase_REC_CRT_TMS # 测试案例结果更新时间 self.testcaseinfo['REC_CREATER'] = result_devops.creater # 测试案例结果创建人 self.testcaseinfo['REC_MODIFIER'] = result_devops.creater # 测试案例结果更新人 logger.info('开始将测试结果写入devops库') # 获取最终入库的对象-tuple类型 # print([n for n in self.testcaseinfo.values()]) caseresultinfo = tuple([n for n in self.testcaseinfo.values()]) logger.info(caseresultinfo) sql = "insert into %s (`TASK_ID`, `BUILD_NUMBER`, `AUTO_TESTCASE_ID`, `ZH_NAME`, `CASE_NAME`, `TIMES`, `CALLED`, `PERFORM_TIME`, `EXECUTE_ST`, `PASSED`, `FAILED`, `VERIFY_P`, `VERIFY_F`, `AUTOCASE`, `DATA_ST`, `REC_CREATER`, `REC_CRT_TMS`, `REC_MODIFIER`, `REC_UPD_TMS`) VALUES (%s,'%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')"%((result_devops.table,)+ caseresultinfo) logger.info(sql) lastrowid = self.devopsdb.getlastid(sql) logger.info('Devops测试结果写入完成') self.devopsdb.closedb() else: pass # o and e should be byte string because they are collected from stdout and stderr? if isinstance(o,str): # TODO: some problem with 'string_escape': it escape \n and mess up formating # uo = unicode(o.encode('string_escape')) # uo = o.decode('latin-1') uo = e else: uo = o if isinstance(e,str): # TODO: some problem with 'string_escape': it escape \n and mess up formating # ue = unicode(e.encode('string_escape')) # ue = e.decode('latin-1') ue = e else: ue = e script = self.REPORT_TEST_OUTPUT_TMPL % dict( id = tid, output = saxutils.escape(str(uo)+ue), ) row = tmpl % dict( tid = tid, Class = (n == 0 and 'hiddenRow' or 'none'), style = n == 2 and 'errorCase' or (n == 1 and 'failCase' or 'none'), desc = desc, script = script, status = self.STATUS[n], ) rows.append(row) if not has_output: return
def getReportAttributes(self, result): """ Return report attributes as a list of (name, value). Override this to add custom attributes. """ startTime = str(self.startTime)[:19] duration = str(self.stopTime - self.startTime) status = [] if result.success_count: status.append('Pass %s' % result.success_count) if result.failure_count: status.append('Failure %s' % result.failure_count) if result.error_count: status.append('Error %s' % result.error_count ) if status: status = ' '.join(status) else: status = 'none' total2 = result.success_count+result.failure_count+result.error_count +result.skip_count logger.info(total2) # 将执行结果插入数据库 if result_db.isinsert == 1: ipaddress = get_host_ip() logger.info(ipaddress) sql = "INSERT INTO %s (project, sucesss, error, fail, skip, total, starttime, duration, ipaddress) VALUES ('%s', %s, %s, %s, %s, %s, '%s', '%s', '%s')"%(result_db.table,result_db.project,result.success_count,result.error_count,result.failure_count,result.skip_count,total2,startTime,duration, ipaddress) self.testdb = mysqlconnectcommon(result_db.host, result_db.port, result_db.user, result_db.password, result_db.dbname) global dblastid logger.info(sql) logger.info('测试结果开始插入数据库。。。') dblastid = self.testdb.getlastid(sql) logger.info('测试结果入库完成') logger.info(dblastid) else: pass return [ ('Start Time', startTime), ('Duration', duration), ('Status', status), ]