Commit 13859465 authored by liguangyu06's avatar liguangyu06
Browse files

提交电商项目用例

parent 13b3da0e
Pipeline #6911 failed with stages
in 3 seconds
#需求单列表接口地址
"url1": "/order/back/listDemand"
json_headers: {
"Content-Type": "application/json",
"Cmdc_access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjIsInVzZXJOYW1lIjoiYWRtaW4yIiwidGltZSI6MTY5Mzk4ODY5NDg0M30.f71cshaaFyY2w2i53P87etu5-x2Y3gqMVKraUGYndp0"
}
"payload": {"times":[null],"listOrderStatus":[],"productName":null,"demandCode":null,"demandParentCode":null,"customerName":null,"manufacturer":null,"materialCode":null,"sellerCompanyName":null,"produceRegisterNum":null,"productLineName":null,"auditByName":null,"orderSource":null,"changeTypeList":null,"isRebateEdit":null,"jdeType":null,"pageSize":8,"pageStart":1,"orderChangeType":null,"snSgin":null,"changeSign":null,"customerCode":null,"distributionType":null,"busCustomerCode":null,"loginName":null,"cancelSign":0,"shipmentType":null,"startTime":null}
#预期结果
checkDict1: {"code":"401","message":"Unauthorized","success":false}
# 后台运营管理系统登录信息
"username": "admin2"
"password": "Aa123456"
json_headers1: {
"Content-Type": "application/json",
"Cmdc_access_token": "%s"
}
"payload1": {"times":[null],"listOrderStatus":[],"productName":null,"demandCode":null,"demandParentCode":null,"customerName":null,"manufacturer":null,"materialCode":null,"sellerCompanyName":null,"produceRegisterNum":null,"productLineName":null,"auditByName":null,"orderSource":null,"changeTypeList":null,"isRebateEdit":null,"jdeType":null,"pageSize":8,"pageStart":1,"orderChangeType":null,"snSgin":null,"changeSign":null,"customerCode":null,"distributionType":null,"busCustomerCode":null,"loginName":null,"cancelSign":0,"shipmentType":null,"startTime":null}
#预期结果
checkDict2: {"success":true,"code":"200","message":"OK"}
#需求单草稿订单删除接口地址
"url": "/order/back/deleteDraft"
json_headers2: {
"Cmdc_access_token": "%s"
}
#测试场景一:删除已保存订单状态的需求单
"payload2": {"demandId": "6585"}
#预期结果
"checkDict3": {'success': True, 'code': '200', 'message': 'OK', 'data': None, 'freshToken': None}
#测试场景二:重复删除已保存订单状态的需求单或删除其他状态下需求单
"payload3": {"demandId": "11095"}
#预期结果
"checkDict4": {'success': True, 'code': '200', 'message': 'OK', 'data': None, 'freshToken': None}
# 多彩商城登录信息
"username": "Test001"
"password": "Aa123456"
#需求单列表接口地址
"url1": "/order/public/ownListDemand"
#测试场景:获取用户多彩商城对应的需求单列表信息
json_headers1: {
"Cmdc_access_token": "%s",
"Sourcetype": "mall"
}
"payload1": {"sellerCompanyCodes":[],"materialCode":"","productCode":"","productInfoValue":"","manufacturerList":null,"orderNum":"","paymentType":null,"preferenceType":null,"changeSign":null,"mainOrderStatus":null,"shipmentType":null,"pageStart":1,"pageSize":10}
#预期结果
checkDict1: {"success":true,"code":"200","message":"OK"}
#需求单列表取消接口地址
"url2": "/order/public/customerApplyCancel"
#测试场景:在用户多彩商城中的需求单列表进行需求单取消操作
json_headers2: {
"Cmdc_access_token": "%s",
"Sourcetype": "mall"
}
"payload2": {"demandCode":"16936462668632521","remark":"123"}
#预期结果
checkDict2: {"success":true,"code":"200","message":"OK","data":1,"freshToken":null}
#需求单列表删除接口地址
"url3": "/order/mall/deleteDraft"
#测试场景:在用户多彩商城中的需求单列表进行需求单删除操作
json_headers3: {
"Cmdc_access_token": "%s",
"Sourcetype": "mall"
}
"payload3": {"demandParentId":"6297"}
#预期结果
checkDict3: {"success":true,"code":"200","message":"OK","data":null,"freshToken":null}
# 多彩商城登录信息
"username": "Test001"
"password": "Aa123456"
#常购清单列表新增商品接口地址
"url1": "/product/mall/addFrequentPurchase"
#测试场景:新增商品至用户的常购清单列表
json_headers1: {
"Cmdc_access_token": "%s",
"Sourcetype": "mall"
}
# 添加的商品不需要装机日期
"payload1": {"currentCompanyId":2,"productId":"9","quantity":1,"agreementPriceId":0,"price":68.88}
#预期结果
checkDict1: {"success":true,"code":"200","message":"OK","data":"ok"}
#测试场景:新增不存在的商品至用户的常购清单列表
json_headers4: {
"Cmdc_access_token": "%s",
"Sourcetype": "mall"
}
"payload4": {"currentCompanyId":2,"productId":"954647456754764","quantity":1,"agreementPriceId":0,"price":68.88}
#预期结果
checkDict4: {"success":false,"code":"1078","message":"该商品不存在,加入购物车失败","data":null,"freshToken":null}
#获取用户常购清单列表接口地址
"url2": "/product/mall/queryTotalFrequentPurchaseList"
#测试场景:获取用户常购清单列表
json_headers2: {
"Cmdc_access_token": "%s",
"Sourcetype": "mall"
}
"payload2": {"productName":"","materialCode":"","manufacturer":"","licenseCode":"","timeSortStatus":0,"pageSize":100,"pageStart":1}
#预期结果
checkDict2: {"success":true,"code":"200","message":"OK"}
#常购清单商品删除接口地址
"url3": "/product/mall/removeFrequentPurchase"
#测试场景:从用户常购清单列表删除已添加的商品
json_headers3: {
"Cmdc_access_token": "%s",
"Sourcetype": "mall"
}
"payload3": {"frequentPurchaseIdList":["%s"]}
#预期结果
checkDict3: {"success":true,"code":"200","message":"OK","data":"ok"}
# 多彩商城图形验证码url
"getVerifyCode_url": "/sso/getVerifyCode"
# 多彩商城登录地址
"maii_login_url": "/sso/mallLogin"
# 多彩商城登录信息
"do_username": "Test001"
"do_password": "Aa123456"
# 国药运营后台管理系统登录地址
"do_login_url": "/sso/doLogin"
# 多彩商城登录信息
"username": "admin1"
"password": "Aa123456"
#采购单查询接口
"url": "/order/purchase/list"
# 后台运营管理系统登录信息
"username": "admin2"
"password": "Aa123456"
json_headers1: {
"Content-Type": "application/json",
"Cmdc_access_token": "%s"
}
"payload1": {"billNo":"","billStatusList":[],"creator":"","demandNo":"","startTime":"","endTime":"","times":null,"status":null,"pageNumber":1,"pageSize":8}
#预期结果
checkDict2: {"success":true,"code":"200","message":null}
#采购单查询接口
"url": "/user/querySubCustomerPage"
# 后台运营管理系统登录信息
"username": "admin2"
"password": "Aa123456"
json_headers1: {
"Content-Type": "application/json",
"Cmdc_access_token": "%s"
}
"payload1": {"disableSign":0,"status":3,"telephone":"","userNo":"","userName":"","customerCompanyName":"","pageSize":10,"pageStart":1,"total":0}
#预期结果
checkDict2: {"success":true,"code":"200","message":"OK"}
# 默认数据
"enc_user_id": "u779700044448"
"headers": {
'clientInfo': '{"birthday":"2018-11-18","screenwidth":"375","clientVersion":"2.4.2","screenheight":"667","partner":"meitunmama","clientip":"10.180.81.127","traderName":"iPhone 6S","clientAppVersion":"2.4.2","clientYunyuVersion":"7.9.6","clientSystem":"ios","nettype":"wifi","deviceCode":"1f4b3860acfa303bca0407f5128bc5ea0f529fec"}',
'platform': "1",
'signature': "144c6b3c78fc20ad57da1ebdb879615b",
'token': "%s",
'timestamp': "%s",
}
payload: {}
"post_headers": {
'clientInfo': '{"birthday":"2018-11-18","screenwidth":"375","clientVersion":"2.4.2","screenheight":"667","partner":"meitunmama","clientip":"10.180.81.127","traderName":"iPhone 6S","clientAppVersion":"2.4.2","clientYunyuVersion":"7.9.6","clientSystem":"ios","nettype":"wifi","deviceCode":"1f4b3860acfa303bca0407f5128bc5ea0f529fec"}',
'platform': "1",
'signature': "144c6b3c78fc20ad57da1ebdb879615b",
'token': "%s",
'timestamp': "%s",
'Content-Type': "%s",
}
default_contentType: "application/x-www-form-urlencoded"
login_url: "http://backend-web-backend-web.1.java.babytree-test.com/sso-service/login?loginName=test001&pwd=test001@123"
\ No newline at end of file
# 登录内网测试环境地址
"spd3_login_url": "/hospitaltest2/spd/#/login?redirect=/paltform/info0/paltform/product/calatog/paltform/product/calatog"
"username": "//input[@placeholder='请输入用户名']"
"password": "//input[@placeholder='请输入密码']"
"login_button": "//span[text()='登 录']"
"name1": "xhs"
\ No newline at end of file
172.16.10.203 api.babytree-dev.com
172.16.10.203 api-test11.babytree-test.com
172.16.10.203 api.test11.babytree-fpm.com
172.16.10.203 api.babytree.com
# online
10.54.11.80 idb.baobaoshu.com
10.54.11.80 grafana.baobaoshu.com
10.54.11.80 zabbix.baobaoshu.com
10.54.11.80 cacti.baobaoshu.com
10.54.11.80 ucm.baobaoshu.com
10.54.11.80 rundeck.baobaoshu.com dubbo.baobaoshu.com
10.54.11.80 cmdb.baobaoshu.com
10.54.11.80 apollo.baobaoshu.com muse.baobaoshu.com
10.54.11.80 splunk.baobaoshu.com
172.16.10.203 test100.babytree-dev.com g.babytree-dev.com
122.9.41.244 gerrit.babytree-inc.com
10.54.17.153 localproxy.baobaoshu.com
192.168.24.43 gerrit.mtmm.com
10.17.65.22 case.cmic.com.cn
10.54.50.90 sso.baobaoshu.com
8.131.247.52 docp.plt.babytree-inc.com
user:
live: 6ea032c10ef24b10aa7fcfe5424446afin01
pre: 6ea032c10ef24b10aa7fcfe5424446afin01
health:
live: 6013c13418a245b9866e9cdec92ff9b9in01
pre : 6013c13418a245b9866e9cdec92ff9b9in01
sit: health
alimall:
live: f4d539e7b8204a8890929320f2052d68in01
pre : f4d539e7b8204a8890929320f2052d68in01
sit: alimall
promotion:
live: 9e33dd3e26a54c8caeaf871e873edb38in01
pre: 9e33dd3e26a54c8caeaf871e873edb38in01
sit: promotion
salesorder:
live: 7f9c968b57084c0782aeb620e2a064b1in01
pre : 7f9c968b57084c0782aeb620e2a064b1in01
sit: salesorder
seller:
live: 2888c1775daf4c60897073068b6c219ain01
pre: 2888c1775daf4c60897073068b6c219ain01
sit: seller
cms:
live: 790afd094355416895ca39891c09c0d3in01
pre: 790afd094355416895ca39891c09c0d3in01
sit: cms
community:
live: 790afd094355416895ca39891c09c0d3in01
pre: 790afd094355416895ca39891c09c0d3in01
sit: community
price:
live: 6ea032c10ef24b10aa7fcfe5424446afin01
pre: 6ea032c10ef24b10aa7fcfe5424446afin01
sit: price
medical:
live: 89a813f93c454db0a23c25f95c0d2e2cin01
pre: 89a813f93c454db0a23c25f95c0d2e2cin01
sit: medical
bcoin:
live: f4d539e7b8204a8890929320f2052d68in01
pre: f4d539e7b8204a8890929320f2052d68in01
sit: bcoin
edu:
live: 8e7f2572f92e49f4b0061f75682470eain01
pre: 8e7f2572f92e49f4b0061f75682470eain01
sit: edu
account:
live: 2888c1775daf4c60897073068b6c219ain01
pre: 2888c1775daf4c60897073068b6c219ain01
sit: account
finance:
live: 6013c13418a245b9866e9cdec92ff9b9in01
pre: 6013c13418a245b9866e9cdec92ff9b9in01
sit: finance
socialec:
live: 89a813f93c454db0a23c25f95c0d2e2cin01
pre: 89a813f93c454db0a23c25f95c0d2e2cin01
sit: socialec
item:
live: 2888c1775daf4c60897073068b6c219ain01
pre: 2888c1775daf4c60897073068b6c219ain01
sit: item
new_wms:
live: 89a813f93c454db0a23c25f95c0d2e2cin01
pre: 89a813f93c454db0a23c25f95c0d2e2cin01
sit: new_wms
distribution:
live: 8e7f2572f92e49f4b0061f75682470eain01
pre: 8e7f2572f92e49f4b0061f75682470eain01
sit: distribution
supplier:
live: 790afd094355416895ca39891c09c0d3in01
sit: supplier
local:
live: pc-2zerh8cqy748e33i8
sit : b9e5fbff-08e9-11ed-866f-00163e324a72
"dingding_msg":
- 59d455293168352cecfaa4fb67f2568f3fa54453a2fdb87ce9817c316dc41b57
"select_user_token":
- user
- select token from user.uc_user_token where enc_user_id=%s;
"exp_expert":
- medical
- SELECT id,expert_name,base_service_count,service_count from exp_expert where deleted=%s and status=%s;
"select_memberPrivilegeId":
- user
- SELECT id ,enc_user_id,privilege_type FROM uc_member_privilege WHERE left_times>0 and status=1 AND privilege_type IN (5,12,9,2,10,11) AND start_time <NOW() AND end_time >NOW() AND enc_user_id IN (SELECT enc_user_id FROM uc_user_member WHERE final_end_time >NOW() AND level_type_code=001) order by id desc limit 1
\ No newline at end of file
# 存储业务sql
"select_patient":
- medical
- SELECT relation_id,name,gender,id FROM `patient` where enc_user_id=%s and deleted=0;
# -*- encoding=utf-8 -*-
import os
import sys
import requests
import math
import re
import time
from bs4 import BeautifulSoup
from random import shuffle
import datetime
import pypinyin
import hashlib
def exchange(word):
"""
中文转拼音
:param word:
:return:
"""
s = ''
for i in pypinyin.pinyin(word, style=pypinyin.NORMAL):
s += ''.join(i)
return s
def get_message(case_path, case_name):
# 从注释中获取某个文件的 case tag 信息
tags = []
pyfile = open(case_path + os.sep + case_name + '.py', 'r', encoding='utf-8')
lines = pyfile.readlines()
for line in lines:
if 'case_tag' in line:
line = line.split('case_tag')[-1]
# 对不规范的写法做一些处理,如中文分号, 中文逗号,多空格等。。
line = re.sub(' ', '', line)
line = line.replace(',', ',').replace(':', '').replace(':', '')
line = line.strip().strip('\n')
tags = line.split(',')
pyfile.close()
return tags
def get_all_dir(case_name, case_path):
"""
:return: 获得需要执行的所有air的文件夹,同时创建单个log目录
"""
case_list = []
for dirs in os.listdir(case_path):
isdir = os.path.join(case_path, dirs)
if os.path.isdir(isdir) and isdir.endswith(".air"):
air_name = dirs.replace('.air', '')
if 'all' in case_name or air_name in case_name:
# script = os.path.join(case_path, isdir)
case_list.append(air_name)
return case_list
def get_case_tag_list(case_path, cases):
"""
遍历case目录下的文件,从文件中获取case tag,加入列表中
如果想同时满足两个条件,用#分割
"""
tagList = cases.split('#')
env = os.environ['ENV']
case_list = []
for f in os.listdir(case_path):
script = os.path.join(case_path, f)
air_name = f.replace('.air', '')
case_tags = get_message(script, air_name)
flag = False
for con in tagList:
conList = con.split(',')
if list(set(case_tags) & set(conList)):
flag = True
else:
flag = False
break
if flag and (env in case_tags or env in ('sit', 'sita')):
case_list.append(air_name)
return case_list
def get_dir_exist(path, div_num):
"""
判断报告文件夹是否存在
"""
for i in range(div_num):
test_path = path + os.sep + 'report_' + str(i+1)
if not os.path.isdir(test_path):
return False
return True
def merge_report(div_num, report_path):
"""
合并报告
"""
total_cases = 0
succ_cases = 0
max_time = 0.0
time_str = ''
summary_r = open(report_path + os.sep + 'summary.html', 'r', encoding='utf-8')
lines = summary_r.readlines()[:43]
summary_r.close()
summary_w = open(report_path + os.sep + 'summary.html', 'w', encoding='utf-8')
for i in range(div_num):
file = report_path + os.sep + 'report_' + str(i+1) + os.sep + 'summary.html'
print(file)
htmlfile = open(file, 'r', encoding='utf-8')
htmlhandle = htmlfile.read()
soup = BeautifulSoup(htmlhandle, 'html.parser')
tables = soup.find_all("table")
#print(tables)
#第一个table存的是概要,第二个table存的是具体case。先读第一个表
tab = tables[0]
tr = tab.findAll('tr')[1]
tds = tr.findAll('td')
total_cases += int(tds[0].getText())
succ_cases += int(tds[1].getText())
minite = int(tds[2].getText().split('分')[0])
second = int(tds[2].getText().split('分')[1].split('秒')[0])
number = minite + second/60
#print(number)
if number > max_time:
max_time = number
time_str = tds[2].getText()
#再读第二个表
tab = tables[1]
trs = tab.findAll('tr')
print(len(trs))
for i in range(len(trs)):
if i == 0:
continue
tds = trs[i].findAll('td')
case_name = tds[0].getText()
status = tds[1].getText()
run_time = tds[2].getText()
if status == '成功':
html = '''
<tr width="600">
<td class="details-col-elapsed"><a href='../log/%s/log.html' target='_blank'>%s</a></td>
<td class="success">%s</td>
<td class="details-col-elapsed">%s</td>
</tr>''' % (case_name, case_name, status, run_time)
else:
html = '''
<tr width="600">
<td class="details-col-elapsed"><a href='../log/%s/log.html' target='_blank'>%s</a></td>
<td class="fail">%s</td>
<td class="details-col-elapsed">%s</td>
</tr>''' % (case_name, case_name, status, run_time)
lines.append(html)
#print(html)
pass_rate = round(succ_cases*100/total_cases, 2)
summary = '''
<!--<div><h2>Test Statistics</h2></div>-->
<table width="800">
<caption><ul><li>测试概要</li></ul></caption>
<tr width="600">
<th width="300" class='details-col-msg'>用例总数</th>
<th class='details-col-msg'>成功数</th>
<th class='details-col-msg'>运行用时</th>
<th class='details-col-msg'>成功率</th>
</tr>
<tr width="600">
<td class='details-col-elapsed'>%s</td>
<td class='details-col-elapsed'>%s</td>
<td class='details-col-elapsed'>%s</td>
<td class="details-col-elapsed">%s</td>
</tr>
</table>
</table>
<!--<div><h2>Test detail</h2></div>-->
<table width="800">
<caption><ul><li>测试列表</li></ul></caption>
<tr width="600">
<th width="300" class='details-col-msg'>用例名称</th>
<th class='details-col-msg'>执行结果</th>
<th class='details-col-msg'>执行时间(秒)</th>
</tr>
''' % (total_cases, succ_cases, time_str, str(pass_rate))
summary_w.write(summary)
for line in lines:
summary_w.write(line)
end_html = '''
</table>
<div><h2></h2></div>
</div>
</body>
</html>'''
summary_w.write(end_html)
summary_w.close()
time_str = time_str.replace('分', 'm').replace('秒', 's')
return total_cases, succ_cases, time_str, pass_rate
def get_mess_from_report(report_path):
"""
从报告中获取运行case数
:return:
"""
htmlfile = open(report_path + os.sep + 'summary.html', 'r', encoding='utf-8')
htmlhandle = htmlfile.read()
soup = BeautifulSoup(htmlhandle, 'html.parser')
tables = soup.find_all("table")
# print(tables)
# 第一个table存的是概要,第二个table存的是具体case。先读第一个表
tab = tables[0]
tr = tab.findAll('tr')[1]
tds = tr.findAll('td')
total_cases = int(tds[0].getText())
succ_cases = int(tds[1].getText())
time_str = tds[2].getText()
time_str = time_str.replace('分', 'm').replace('秒', 's')
if int(total_cases) != 0:
pass_rate = round(succ_cases * 100 / total_cases, 2)
else:
pass_rate = 0.00
htmlfile.close()
return total_cases, succ_cases, time_str, pass_rate
def get(url):
try:
return requests.get(url)
except requests.exceptions.ConnectionError:
print('ConnectionError -- please wait 3 seconds')
time.sleep(1)
except requests.exceptions.ChunkedEncodingError:
print('ChunkedEncodingError -- please wait 3 seconds')
time.sleep(1)
except:
print('Unfortunitely -- An Unknow Error Happened, Please wait 3 seconds')
time.sleep(1)
def call_back_atms(runenv, job_name, build_num, total, rate, run_time, pool_name, build_user):
"""
回传数据到atms
:return:
"""
if runenv == 'autotestpreid':
runenv_b = 1
elif runenv == 'autotestsitid':
runenv_b = 2
else:
runenv_b = 0
url = "http://atms.baobaoshu.com/atms/rest/api/getJobResult?jobName=" + job_name + "&runenv=" + str(
runenv_b) + "&buildNumber=" + str(build_num) + "&allSum=" + str(total) + "&passRate=" + str(
rate) + "&execTime=" + run_time + "&poolName=" + pool_name + "&buildUser=" + build_user + "&p0Sum=0&p1Sum=0&p2Sum=0"
print(url)
response = get(url)
print("回调atms返回结果")
print(response.content.decode())
def call_back_cloud(runenv, pool_name, build_num, start, end, job_url, build_user, rate, oldrev, newrev):
"""
回传到云平台
:return:
"""
if rate == 100.0:
status = 'success'
else:
status = 'fail'
url = "http://cloud.baobaoshu.com/cloud/buildautotest?type=" + \
runenv + "&buildid=" + str(build_num) + "&pool=" + pool_name + \
"&codeversion=" + str(newrev) + "&lastcversion=" + str(oldrev) + \
"&starttime=" + str(start) + "&endtime=" + str(end) + "&status=" + status + \
"&url=" + str(job_url) + "&autopassrate=" + str(rate) + "&user=" + str(build_user)
print(url)
response = get(url)
print("回调云平台返回结果")
print(response.content.decode())
def call_back_muse(deployid, cbtoken, build_user, pass_rate, job_url, build_num):
"""
回调muse
:return:
"""
print("call back muse")
result = 'Fail'
if deployid != 'deployid' and cbtoken != 'cbtoken' and build_user == 'SYSTEM':
if pass_rate == 100.0:
result = 'Success'
url = 'http://muse.baobaoshu.com/apiv1/deployment/ci-callback/'
data = {'deployid': deployid, 'job_url': job_url, 'build_number': build_num, 'result': result, 'cbtoken': cbtoken}
r = requests.post(url, data)
print(data)
print(r.content.decode())
else:
print('非远程触发')
pass
def call_back_gitool(deployid, cbtoken, build_user, pass_rate, job_url, build_num,env_t):
"""
回调gitool
:return:
"""
print("call back gitool")
if deployid != 'deployid' and cbtoken == 'cbtoken' and build_user == 'SYSTEM':
timestamp = str(int(time.time()))
data = "gitool_autotest_api_token(- - #)" + timestamp
sign_md5 = hashlib.md5()
sign_md5.update(data.encode(encoding='utf-8'))
data = sign_md5.hexdigest()
verify_str = data + "_" + timestamp
if pass_rate == 100.0:
status = 'pass'
else:
status = 'failed'
if env_t == 'on':
url = 'http://gitool.plt.babytree-inc.com/gitool/update_online_autotest_result?'
elif env_t == 'pre':
url = 'http://gitool.plt.babytree-inc.com/gitool/update_pre_autotest_result?'
elif env_t == 'sit':
url = 'http://gitool.plt.babytree-inc.com/gitool/update_test_autotest_result?'
url = url + "branch_id="+str(deployid)+"&result="+str(status)+"&result_url="+str(job_url)+"&detail_result=&"+"verify_str="+str(verify_str)
print(url)
response = get(url)
print("回调gitool返回结果")
print(response.content.decode())
else:
print('非远程触发')
pass
if __name__ == '__main__':
start = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
print('start')
case_path = os.path.abspath(".") + os.sep + 'air_case'
report_path = os.path.abspath(".") + os.sep + 'report'
# 第一个参数,case执行类型
tag = sys.argv[1]
# 想运行多个tag 用逗号分割。 想运行同时满足两种tag的用&号连接
cases = sys.argv[2]
# 第3个参数,日志数据等级
log_level = sys.argv[3]
# 第4个参数,子任务个数,或者 是 app运行模式
num = sys.argv[4]
# 第5个参数,子任务名或者 设备uid
JobOrDevice = sys.argv[5]
# pool名
pool_name = sys.argv[6]
runenv = sys.argv[7]
job_name = sys.argv[8]
build_num = sys.argv[9]
job_url = sys.argv[10]
build_user = exchange(sys.argv[11])
oldrev = sys.argv[12]
newrev = sys.argv[13]
deployid = sys.argv[14]
cbtoken = sys.argv[15]
if runenv == 'autotestpreid':
env_t = 'pre'
elif runenv == 'autotestonlineid':
env_t = 'on'
elif runenv == 'autotestsitaid':
env_t = 'sita'
else:
env_t = 'sit'
os.environ['ENV'] = env_t
# 如果num是 s,m,d 表示是运行app 用例
if num in ('s', 'm', 'd'):
cmd = 'python runner_app.py ' + JobOrDevice + ' ' + num + ' ' + tag + ' ' + cases + ' ' + log_level
os.system(cmd)
total_cases, succ_cases, run_time, pass_rate = get_mess_from_report(report_path)
else:
num = int(num)
# 如果将任务数设置为1并且子任务名等于job名,就不分任务到子job,直接本机跑
if num != 1 or JobOrDevice != job_name:
case_list = cases.split(',')
if tag == 'tag':
case_list = get_case_tag_list(case_path, cases)
if tag == 'all':
case_list = get_all_dir(case_list, case_path)
shuffle(case_list)
length = len(case_list)
if length >= num:
div_num = num
else:
div_num = length
print(div_num)
for i in range(div_num):
cmd = 'rd /s /q report\\report_' + str(i+1)
os.system(cmd)
one_list = case_list[math.floor(i / div_num * length):math.floor((i + 1) / div_num * length)]
one_list_str = ",".join(one_list)
print(one_list_str)
url = 'http://jenkins.baobaoshu.com/view/Tools/job/' + JobOrDevice + '_' + str(i+1) + '/buildWithParameters?token=123456&tag=choose&cases=' + one_list_str + "&log_level=" + log_level + "&env=" + env_t + "&triger_job_name=" + job_name
print(url)
requests.get(url)
# 等待1分钟
time.sleep(60)
# 判断报告传输是否完成
while True:
is_done = get_dir_exist(report_path, div_num)
if is_done:
total_cases, succ_cases, run_time, pass_rate = merge_report(div_num, report_path)
break
else:
time.sleep(5)
else:
run_url = str(job_url) + str(build_num) + os.sep + "artifact" + os.sep + "report" + os.sep + "summary.html"
cmd = 'python runner.py ' + tag + ' ' + cases + ' ' + log_level + ' ' + env_t + ' ' + run_url
os.system(cmd)
total_cases, succ_cases, run_time, pass_rate = get_mess_from_report(report_path)
end = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
# 回传数据到gitool
call_back_gitool(deployid, cbtoken, build_user, pass_rate, job_url, build_num, env_t)
# 回传数据到muse
call_back_muse(deployid, cbtoken, build_user, pass_rate, job_url, build_num)
# 回传数据到atms
call_back_atms(runenv, job_name, build_num, total_cases, pass_rate, run_time, pool_name, build_user)
# 回传到云平台
call_back_cloud(runenv, pool_name, build_num, start, end, job_url, build_user, pass_rate, oldrev, newrev)
if pass_rate != 100.0:
sys.exit(1)
1691384174643 geckodriver INFO Listening on 127.0.0.1:60395
1691384177063 mozrunner::runner INFO Running command: "D:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe" "--marionette" "-foreground" "-no-remote" "-profile" "C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\rust_mozprofilekzunjD"
console.warn: services.settings: Ignoring preference override of remote settings server
console.warn: services.settings: Allow by setting MOZ_REMOTE_SETTINGS_DEVTOOLS=1 in the environment
1691384177326 Marionette INFO Marionette enabled
Dynamically enable window occlusion 0
console.error: "Warning: unrecognized command line flag" "-foreground"
1691384177391 Marionette INFO Listening on port 60405
1691384177764 RemoteAgent WARN TLS certificate errors will be ignored for this session
[GFX1-]: Failed to create a D3D11 content device: 0x887a0031
[Parent 13764, IPC I/O Parent] WARNING: DuplicateHandle failed for handle 0 in TransferHandles: file /builds/worker/checkouts/gecko/ipc/chromium/src/chrome/common/ipc_channel_win.cc:621
[GPU 15232, IPC I/O Child] WARNING: pipe error: 232: file /builds/worker/checkouts/gecko/ipc/chromium/src/chrome/common/ipc_channel_win.cc:443
1691384189508 Marionette INFO Stopped listening on port 60405
Dynamically enable window occlusion 1
[Parent 13764, IPC I/O Parent] WARNING: DuplicateHandle failed for handle 0 in TransferHandles: file /builds/worker/checkouts/gecko/ipc/chromium/src/chrome/common/ipc_channel_win.cc:621
[GPU 15232, IPC I/O Child] WARNING: pipe error: 232: file /builds/worker/checkouts/gecko/ipc/chromium/src/chrome/common/ipc_channel_win.cc:443
[Parent 13764, IPC I/O Parent] WARNING: DuplicateHandle failed for handle 0 in TransferHandles: file /builds/worker/checkouts/gecko/ipc/chromium/src/chrome/common/ipc_channel_win.cc:621
[GPU 15232, IPC I/O Child] WARNING: pipe error: 232: file /builds/worker/checkouts/gecko/ipc/chromium/src/chrome/common/ipc_channel_win.cc:443
JavaScript error: chrome://remote/content/marionette/cert.sys.mjs, line 51: NS_ERROR_NOT_AVAILABLE: Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsICertOverrideService.setDisableAllSecurityChecksAndLetAttackersInterceptMyData]
[Parent 13764, IPC I/O Parent] WARNING: DuplicateHandle failed for handle 0 in TransferHandles: file /builds/worker/checkouts/gecko/ipc/chromium/src/chrome/common/ipc_channel_win.cc:621
[GPU 15232, IPC I/O Child] WARNING: pipe error: 232: file /builds/worker/checkouts/gecko/ipc/chromium/src/chrome/common/ipc_channel_win.cc:443
[Parent 13764, IPC I/O Parent] WARNING: DuplicateHandle failed for handle 0 in TransferHandles: file /builds/worker/checkouts/gecko/ipc/chromium/src/chrome/common/ipc_channel_win.cc:621
[GPU 15232, IPC I/O Child] WARNING: pipe error: 232: file /builds/worker/checkouts/gecko/ipc/chromium/src/chrome/common/ipc_channel_win.cc:443
[Parent 13764, IPC I/O Parent] WARNING: DuplicateHandle failed for handle 0 in TransferHandles: file /builds/worker/checkouts/gecko/ipc/chromium/src/chrome/common/ipc_channel_win.cc:621
[GPU 15232, IPC I/O Child] WARNING: pipe error: 232: file /builds/worker/checkouts/gecko/ipc/chromium/src/chrome/common/ipc_channel_win.cc:443
File added
/Users/zhangaizhen/devSofeware/SEARCH_Platform_Index/search-platform-index-boot/src/main/java/com/babytree/search/platform/index/controller
\ No newline at end of file
# -*- encoding=utf8 -*-
import os
import sys
import json
import ast
import yaml
curPath = os.path.abspath(os.path.dirname(__file__))
data_path = curPath + os.sep + "data"
class parseCode(object):
def getYamlValue(self, filename):
"""
获取公共sql中的sql
:param filename:
:return:
"""
f = open(filename, 'r', encoding='utf-8')
cont = f.read()
value = yaml.load(cont, Loader=yaml.Loader)
f.close()
return value
def scan_java_doc(self, path, class_name):
flag = True
controllers = []
for controller_file in os.listdir(path):
controllers.append(controller_file)
expect_file = ("".join(class_name[:1].upper() + class_name[1:]).replace("\n", "") + ".java").\
replace("(object)", "").replace(" ", "")
filename = path + os.sep + expect_file
if expect_file in controllers:
# 读取文件在后面追加方法
flag = False
return flag, filename, expect_file
def scan_java_code(self, filename, file_hash):
root_path = ""
entity_path = ""
entity_name = ""
path_flag = False
entity_flag = False
paramsKeys = []
params = {}
f = open(filename, "r", encoding="utf-8")
lines = f.readlines()
if "entity_name" in file_hash:
entity_flag = True
entity_name = file_hash["entity_name"]
for line in lines:
if "@RequestMapping" in line and "value" not in line:
root_path = line.split("\"")[1].split("\"")[0]
elif "@RequestMapping" in line and "value" in line:
path = line.split("\"")[1].split("\"")[0]
all_path = root_path + path
if all_path == file_hash["path"]:
path_flag = True
elif path_flag and "@RequestBody" in line:
boby = line.split("@RequestBody")[1].split(" ")[1].replace(" ", "")
if file_hash["entity_name"] == boby:
file_hash["other_params"] = {}
entity_new_path = entity_path.rsplit("/", 1)[0] + "/" + boby + ".java"
f = open(entity_new_path, "r", encoding="utf-8")
model_lines = f.readlines()
for model_line in model_lines:
if "private" in model_line:
params_key = model_line.split(" ")[2].replace(";", "").replace("\n", "")
params_val = model_line.split(" ")[1]
paramsKeys.append(params_key)
params[params_key] = params_val
for key, val in file_hash["params"].items():
if key not in paramsKeys:
file_hash["other_params"][key] = val
else:
if self.typeof(file_hash["params"][key]) != params[key]:
file_hash["other_params"][key] = val
if len(file_hash["other_params"]) > 0:
new_f = open(entity_new_path, 'r', encoding="utf-8")
lines = new_f.readlines()
new = []
for line in lines:
if "private" in line:
params_key = line.split(" ")[2].replace(";", "").replace("\n", "")
if params_key not in file_hash["other_params"]:
new.append(line)
elif line.replace("\n", "").replace(" ", "") == "}":
pass
else:
for k, v in file_hash["other_params"].items():
if k not in line:
new.append(line)
with open(entity_new_path, "w") as filewrite:
for var in new:
filewrite.write(var)
for k, v in file_hash["other_params"].items():
self.get_set_entity(filewrite, k, v)
filewrite.write("}")
elif entity_flag and "."+entity_name+";" in line:
entity_package = line.replace("import", "").replace(";", "").replace(" ", "")
entity_path = str(file_hash["root_path"]).split(entity_package.split(".")[0])[0] + entity_package.replace(".", "/")
def get_set_entity(self, model_file, key, val):
if isinstance(val, str):
model_file.write("private String " + key + ";\n")
key_d = "".join(key[:1].upper() + key[1:])
model_file.write("public String get" + key_d + "() { return " + key
+ ";}\n")
model_file.write("public void set" + key_d + "(String " + key +
") { this." + key + " = " + key + ";}\n")
elif isinstance(val, list):
model_file.write("private List<Object> " + key + ";\n")
key_d = "".join(key[:1].upper() + key[1:])
model_file.write("public List<Object> get" + key_d + "() { return " + key
+ ";}\n")
model_file.write("public void set" + key_d + "(List<Object> " + key +
") { this." + key + " = " + key + ";}\n")
elif isinstance(val, int):
model_file.write("private int " + key + ";\n")
key_d = "".join(key[:1].upper() + key[1:])
model_file.write("public int get" + key_d + "() { return " + key
+ ";}\n")
model_file.write("public void set" + key_d + "(int " + key +
") { this." + key + " = " + key + ";}\n")
def param_set(self, key, val, result):
if isinstance(val, str):
result = result + "@RequestParam String " + key + ","
elif isinstance(val, list):
result = result + "@RequestParam List<Object> " + key + ","
elif isinstance(val, int):
result = result + "@RequestParam int " + key + ","
return result
def typeof(self, variate):
"""
变量类型
:param variate:
:return:
"""
if isinstance(variate, int):
return "int"
elif isinstance(variate, str):
return "String"
elif isinstance(variate, float):
return "float"
elif isinstance(variate, list):
return "list"
elif isinstance(variate, tuple):
return "tuple"
elif isinstance(variate, dict):
return "dict"
elif isinstance(variate, set):
return "set"
else:
return None
def scan_auto_code(self, path, javaAddress):
file_hash = {}
dirs = os.listdir(path)
for dir in dirs:
if dir == "air_case":
air_paths = os.listdir(path + os.sep + dir)
for air_path in air_paths:
if air_path != '.DS_Store':
path = curPath + os.sep + dir + os.sep + air_path
case_paths = os.listdir(path)
for case_path in case_paths:
filename = path + os.sep + case_path + os.sep + case_path.replace(".air", ".py")
modulename = filename.split("air_case/")[1].split("/")[0]
rootpath = filename.split("air_case/")[0]
yaml_path = rootpath + "data" + os.sep + modulename + os.sep + "data"
if os.path.exists(yaml_path):
yaml_result = self.getYamlValue(yaml_path)
# 读取需要同步的接口代码
f = open(filename, "r", encoding="utf-8")
lines = f.readlines()
class_flag = False
flag_isRun = False
flag_newOrOld = False
for line in lines:
if "case_tag" in line and "change_java_code" in line:
flag_isRun = True
elif "class" in line and flag_isRun:
class_name = line.replace(":", "").replace("class", "").replace(" ", "")
flag_newOrOld, filename, expectFile = self.scan_java_doc(javaAddress, class_name)
class_flag = True
file_hash["className"] = expectFile
file_hash["root_path"] = filename.split("/controller")[0]
file_hash["package"] = "com" + filename.split("/controller")[0].split("/com")[1].replace("/", ".")
elif "def" in line and class_flag and flag_isRun:
method = line.split("(")[0].replace("def", "").replace(" ", "")
file_hash["method"] = method
elif ("payload_" in line and "commonFuc().get_business_data" in line) and class_flag and flag_isRun:
if "RequestParam" in line:
file_hash["param_type"] = "RequestParam"
elif "payload_" in line:
file_hash["param_type"] = "Entity"
file_hash["entity_name"] = line.split("=")[0].replace("payload_", "").replace(" ", "")
param_data = line.split("\"")[1].split("\"")[0]
file_hash["params"] = yaml_result[param_data]
elif "_url" in line and class_flag and flag_isRun:
url_data = line.split("+")[1].split("\"")[1].split("\"")[0]
file_hash["path"] = yaml_result[url_data]
elif "commonFuc().http_" in line and class_flag and flag_isRun:
post_get = line.split("http_")[1].split("(")[0]
file_hash["methodPath"] = "@RequestMapping(value = \"" + file_hash["path"] + "\", method = RequestMethod." + post_get.upper() + ")"
elif "checkDict_" in line and "check_result" not in line and flag_isRun:
file_hash["response"] = line.split("=")[0].replace("checkDict_", "").replace(" ", "")
if flag_isRun:
if flag_newOrOld:
file = open(filename, 'w')
file.write("package " + file_hash["package"] + ".controller;\n\n\n")
file.write("@RestController\n")
file.write("public class " + file_hash["className"].replace(".java", "") + " {" + "\n")
file.write("\n\n")
file.write(file_hash["methodPath"])
file.write("\n@ResponseBody \n")
if "params" in file_hash:
if file_hash["param_type"] == "RequestParam":
param_body = ""
for key, val in file_hash["params"].items():
param_body = self.param_set(key, val, param_body)
file.write("public " + file_hash["response"] + " " + file_hash["method"] + "(" + param_body[:-1] + ") {\n")
else:
entity_name = file_hash["entity_name"]
param_body = "@RequestBody " + entity_name + " " + str.lower(entity_name)
file.write("public " + file_hash["response"] + " " + file_hash["method"] + "("
+ param_body + ") {\n")
model_path = file_hash["root_path"] + "/model"
if not os.path.exists(model_path):
os.mkdir(model_path)
model_filename = model_path + os.sep + entity_name + ".java"
if os.path.exists(model_filename):
os.remove(model_filename)
model_file = open(model_filename, 'a')
model_file.write("package " + file_hash["package"] + ".model;\n\n\n")
model_file.write("public class " + entity_name + "{\n\n")
for key, val in file_hash["params"].items():
self.get_set_entity(model_file, key, val)
model_file.write("}\n")
file.write("\n return null; \n")
file.write(" }\n")
file.write("}\n")
else:
self.scan_java_code(filename, file_hash)
if __name__ == '__main__':
# 第一个参数 本地java代码地址
#pool = sys.argv[1]
f = open(curPath + os.sep + 'javaAddressPath.txt', "r", encoding="utf-8")
lines = f.readlines()
javaAddress = lines[0].replace("\n", "").replace(" ", "")
parseCode().scan_auto_code(curPath, javaAddress)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment