This commit is contained in:
jerrylizilong 2018-08-24 14:09:57 +08:00
parent a81c035f06
commit e92e937d96
17 changed files with 465 additions and 39 deletions

76
app/core/atx_core.py Normal file
View File

@ -0,0 +1,76 @@
from app.core import log, buildCase, atx_steps
from app.db import test_batch_manage
import requests
class atx_core():
# run a signle case.
# the main method
def run_case(self, steps, caseNo, deviceList=[]):
search_result = test_batch_manage.test_batch_manage().search_test_batch_detail1(caseNo, ['ip'])
if len(search_result):
log.log().logger.info(search_result)
log.log().logger.info(deviceList)
if search_result['ip']:
deviceList = [search_result['ip']]
log.log().logger.info(deviceList)
step_name = ''
steps = steps.split(',')
steps = buildCase.buildCase().readPublic(steps)
step0 = steps[0].split('|')
if len(step0) != 2:
log.log().logger.error('android init is not defined!')
return 2, 'init', []
elif step0[0] != 'Android':
log.log().logger.error('android init is not defined!')
return 2, 'init', []
else:
package = step0[1]
isConnected, device0, u = atx_steps.atx_driver().connectDevice(package, deviceList)
log.log().logger.info(' is %s connected? %s' % (device0, isConnected))
if isConnected:
log.log().logger.info('start runnning test on %s' % device0)
screenFileList = []
result = 1
for step in steps:
log.log().logger.info('current step is: %s' % step)
if len(step) == 0:
pass
else:
step = step.split('|')
# log().logger.info(step)
if len(step) >= 1:
step_name = step[0]
log.log().logger.info(step_name)
if len(step) > 1:
detail = step[1].split('@@')
log.log().logger.info(detail)
else:
detail = []
trytime = 3
while trytime:
log.log().logger.info('try time: %s' % (4 - trytime))
try:
u, result, screenFileList = atx_steps.atx_driver().run_step(u, step_name, detail,
caseNo, screenFileList)
except requests.exceptions.ConnectionError as e:
log.log().logger.error(e)
result = 2
if result == 2:
log.log().logger.error('failed at %s : %s, try again!' % (step_name, detail))
trytime += -1
else:
trytime = 0
log.log().logger.info('finish step %s : %s.' % (step_name, detail))
if trytime == 0 and result == 2:
log.log().logger.error('failed at %s : %s after trying 3 times!' % (step_name, detail))
break
else:
pass
return result, step_name, screenFileList
else:
log.log().logger.info('package is not found in any device!')
return 2, 'package not found', []

242
app/core/atx_steps.py Normal file
View File

@ -0,0 +1,242 @@
import requests
import time
import uiautomator2 as ut2
from app.core import log, util, buildCase, hubs
class atx_driver():
# connect to an availble android device. if deviceList is not given, it will try to connect to availbe device in database.
def connectDevice(self, package, deviceList=[]):
if len(deviceList) == 0:
deviceList = hubs.hubs().getDevices()
isConnected = 0
device0 = ''
for device in deviceList:
isConnected, u = self.init(device)
if isConnected:
if self.start_app(u, package) != 0:
device0 = device
return isConnected, device0, u
else:
isConnected = 0
device0 = ''
log.log().logger.error('package not found!')
return 0, '', ''
# init and try to unlock the device.
def init(self, device=''):
log.log().logger.info('trying to connect device : %s' % device)
try:
u = ut2.connect(device)
log.log().logger.info(u.device_info)
isConnected = 1
except requests.exceptions.ConnectionError as e:
log.log().logger.error(e)
isConnected = 0
u = ''
return isConnected, u
# 通过 adb 查询当前包是否已安装。 需要USB 链接,暂时不是使用。
def is_app_exist0(self, package):
import subprocess
cmd = 'dumpsys package %s | grep version' % package
cmds = [cmd, "exit", ]
pipe = subprocess.Popen("adb shell", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
code = pipe.communicate(("\n".join(cmds) + "\n").encode())
log.log().logger.info(code)
return 'versionCode' in str(code)
# 通过 adb 查询当前包是否已安装。 不需要USB 链接,目前使用
def is_app_exist(self, u, package):
cmd = 'dumpsys package %s | grep version' % package
result = u.adb_shell(cmd)
log.log().logger.info(result)
return 'versionCode' in str(result)
# start the testing app. for example , com.ghw.sdk2
def start_app(self, u, package):
# try to unlock device.
try:
log.log().logger.info('trying to unlock...')
u.unlock()
except requests.exceptions.ReadTimeout as e:
log.log().logger.error(e)
try:
log.log().logger.info('trying to unlock again...')
u.app_start('xdf.android_unlock')
except requests.exceptions.ReadTimeout as e:
log.log().logger.error(e)
time.sleep(2)
log.log().logger.info('trying to swipe up...')
u.swipe_points([(0.509, 0.601), (0.503, 0.149)], 0.2)
time.sleep(2)
log.log().logger.info('trying to start app...')
u.app_clear(package)
u.app_start(package, stop=True, unlock=True)
time.sleep(2)
if self.is_app_exist(u, package):
log.log().logger.info('package found, start testing!')
time.sleep(2)
u1, result1 = self.click(u, 'name', '允许')
time.sleep(1)
if result1 == 2:
u1, result1 = self.click(u, 'name', '始终允许')
time.sleep(1)
if result1 == 2:
u1, result1 = self.click(u, 'name', 'ALLOW')
time.sleep(1)
return u
else:
log.log().logger.error('package is not found in this device , try to connect another !')
return 0
# save a screenshot to corresponding folder.
def take_screenshot(self, u, type, caseNo, screenFileList):
fileName, fileName1 = util.util().screenshot(type, caseNo)
image = u.screenshot()
image.save(fileName)
screenFileList.append(fileName1)
return screenFileList
# type text into the target element.
# method : id, name the method used to locate the target element.
# resource_id : target element's attribute, with which to locate target.
def type_text(self, u, method, resource_id, text):
if method == 'id':
if u(resourceId=resource_id).exists:
u(resourceId=resource_id).send_keys(text)
time.sleep(1)
result = 1
u.adb_shell('input', 'keyevent', 'BACK')
time.sleep(1)
else:
log.log().logger.error(u"出错了,没有找到元素! by %s , %s" % (method, resource_id))
result = 2
elif method == 'name':
if u(text=resource_id).exists:
u(text=resource_id).send_keys(text)
time.sleep(1)
result = 1
u.adb_shell('input', 'keyevent', 'BACK')
time.sleep(1)
else:
log.log().logger.error(u"出错了,没有找到元素! by %s , %s" % (method, resource_id))
result = 2
elif method == 'class':
if u(className=resource_id).exists:
u(className=resource_id).send_keys(text)
time.sleep(1)
result = 1
u.adb_shell('input', 'keyevent', 'BACK')
time.sleep(1)
else:
log.log().logger.error(u"出错了,没有找到元素! by %s , %s" % (method, resource_id))
result = 2
else:
log.log().logger.error(u"元素方法未定义! %s" % method)
result = 2
return u, result
def click(self, u, by, text):
result = 2
if by == 'name':
u, result = self.click_text(u, text)
elif by == 'id':
u, result = self.click_id(u, text)
elif by == 'description':
u, result = self.click_description(u, text)
elif by == 'class':
u, result = self.click_class(u, text)
return u, result
# click an element locating by it's text name.
def click_text(self, u, text):
if u(text=text).exists:
u(text=text).click()
time.sleep(1)
result = 1
else:
log.log().logger.error(u"出错了,没有找到元素! by %s , %s" % ('text', text))
result = 2
return u, result
# click an element locating by it's resourceId.
def click_id(self, u, id):
if u(resourceId=id).exists:
u(resourceId=id).click()
time.sleep(1)
result = 1
else:
log.log().logger.error(u"出错了,没有找到元素! by %s , %s" % ('id', id))
result = 2
return u, result
# click an element locating by it's description.
def click_description(self, u, id):
if u(description=id).exists:
u(description=id).click()
time.sleep(1)
result = 1
else:
log.log().logger.error(u"出错了,没有找到元素! by %s , %s" % ('description', id))
result = 2
return u, result
# click an element locating by it's className.
def click_class(self, u, id):
if u(className=id).exists:
u(className=id).click()
time.sleep(1)
result = 1
else:
log.log().logger.error(u"出错了,没有找到元素! by %s , %s" % ('className', id))
result = 2
return u, result
# Send event to data collection. used to test sending data in SDK demo.
def sendData(self, u, name):
u, result = self.click_text(u, name)
time.sleep(2)
if result == 1:
if u(text='发送').exists:
u, result = self.click_text(u, '发送')
else:
u, result = self.click_text(u, 'SEND')
u.adb_shell('input', 'keyevent', 'BACK')
time.sleep(1)
return u, result
# run step.
# if a new step type is defined, it should be added to the step_name list.
def run_step(self, u, step_name, detail, caseNo, screenFileList):
result = 1
if step_name == 'Android':
time.sleep(1)
elif step_name == '点击':
u, result = self.click(u, detail[0], detail[1])
elif step_name == '尝试点击':
self.click(u, detail[0], detail[1])
elif step_name == '等待':
time.sleep(int(detail[0]))
elif step_name == '发送':
u, result = self.sendData(u, detail[0])
elif step_name == '填写':
u, result = self.type_text(u, detail[0], detail[1], detail[2])
elif step_name == '返回':
u.adb_shell('input', 'keyevent', 'BACK')
time.sleep(1)
elif step_name == '截图':
screenFileList = self.take_screenshot(u, 'normal', caseNo, screenFileList)
else:
result = 2
log.log().logger.error('method is not defined : %s' % step_name)
if result == 0:
log.log().logger.error('package is not fould!')
elif result == 2:
screenFileList = self.take_screenshot(u, 'fail', caseNo, screenFileList)
return u, result, screenFileList

View File

@ -60,7 +60,7 @@ class extend():
else:
fileName, fileName1 = util.util().screenshot('normal', id)
try:
print(fileName)
# print(fileName)
driver.save_screenshot(fileName)
screenFileList.append(fileName1)
result = 1

View File

@ -1,4 +1,4 @@
from app import useDB
from app import useDB, config
from app.core import log,util
import json
class hubs():
@ -111,3 +111,31 @@ class hubs():
results.append(result)
return results
def getDevices(self):
url = config.ATXHost + '/list'
response, content = util.util().send(url)
content = json.loads(content)
deviceList = []
for device in content:
if device['present']:
deviceList.append(device['ip'] + ':7912')
else:
# log.log().logger.info(device['ip'] + ' is not ready!')
pass
return deviceList
# 获取设备列表信息
def getDevicesList(self):
url = config.ATXHost + '/list'
response, content = util.util().send(url)
content = json.loads(content)
deviceLists = []
for device in content:
deviceList = {}
if device['present']:
deviceList["ip"] = device['ip'] + ':7912'
deviceList["model"] = device['model']
deviceLists.append(deviceList)
else:
log.log().logger.info(device['ip'] + ' is not ready!')
return deviceLists

View File

@ -4,19 +4,6 @@ from app import useDB
class keywords(object):
def getPara1(self, keyword):
print(self.keywords)
keywords = self.keywords
result = 0
log.log().logger.info(keyword)
for list in keywords:
if list['index']==keyword:
result =1
return list['paraCount'], list['template']
break
if result ==0:
return '',''
def getPara(self, keyword):
result = 0
log.log().logger.info(keyword)

View File

@ -10,6 +10,7 @@ class log :
import logging
formatter = logging.Formatter('%(asctime)-15s - [%(filename)s: %(lineno)s] -%(levelname)s: %(message)s');
logzero.formatter(formatter)
logzero.loglevel(logging.INFO)
self.logger = logzero.logger

View File

@ -8,7 +8,7 @@ import requests
from selenium.common.exceptions import *
from selenium.webdriver.support.select import Select
from app import useDB, config
from app.core import buildCase, log, hubs, coredriver, util, extend
from app.core import buildCase, log, hubs, coredriver, util, extend, atx_core
from app.db import test_task_manage,test_batch_manage
isUseATX = config.isUseATX
@ -31,8 +31,10 @@ class process():
if len(newstep[0][1]) == 1 :
if newstep[0][1][0]!='1':
package = newstep[0][1][0]
if runType != 'Chrome' :
log.log().logger.info('runtype is wrong : %s' %runType)
if runType == 'Android' and isUseATX:
# 使用 atx 执行 Android 用例
result, stepN, screenFileList = atx_core.atx_core().run_case(case, id, deviceList=deviceList)
log.log().logger.info('%s, %s, %s' % (result, stepN, screenFileList))
else:
# 使用 selenium 执行 web 用例
if browserType !=''and devicename =='':
@ -152,11 +154,72 @@ class process():
pool.close()
pool.join()
def runmain(self,test_suite_id,threadNum, runType ):
def runmain(self, test_suite_id, threadNum, runType):
if runType == 'Android' and isUseATX:
Hubs = hubs.hubs().getDevices()
log.log().logger.info('Run type is ATX and usable devices are %s' % Hubs)
else:
Hubs = hubs.hubs().showHubs(runType)
if len(Hubs) ==0:
if len(Hubs) == 0:
log.log().logger.error('cannot run for no available hubs!')
elif runType == 'Android' and isUseATX:
self.atxMain()
else:
self.multipleRun(util.util().getTeseCases(test_suite_id),threadNum)
self.multipleRun(util.util().getTeseCases(test_suite_id), threadNum)
test_task_manage.test_task_manage().update_test_suite_check()
def atxMain(self):
q = queue.Queue()
Hubs = hubs.hubs().getDevices()
alllist = util.util().getTeseCasesATX(all=True)
if len(Hubs) and len(alllist):
count = 0
threads = []
for i in range(len(Hubs)):
j = Hubs[i]
threads.append(MyThread(q, i, j))
for mt in threads:
mt.start()
log.log().logger.info("start time: %s" % time.ctime())
elif len(alllist):
log.log().logger.info('no device is avaible!')
else:
log.log().logger.info('no test case is needed!')
class MyThread(threading.Thread):
def __init__(self, q, t, j):
super(MyThread, self).__init__()
self.q = q
self.t = t
self.j = j
def run(self):
list0 = util.util().getTeseCasesATX(self.j, isRunning=True)
if len(list0):
log.log().logger.info('case still running !')
else:
list = util.util().getTeseCasesATX(self.j)
if len(list):
log.log().logger.info('start test by single devices :%s ' % list[0][0])
self.q.put(u"打点我是第%d个线程ip: %s, 测试用例:%s" % (self.t, self.j, list[0][0]))
log.log().logger.info(u"打点我是第%d个线程ip: %s, 测试用例:%s" % (self.t, self.j, list[0][0]))
process().main(list[0])
time.sleep(2)
else:
list2 = util.util().getTeseCasesATX(all=True)
log.log().logger.info('current list lenth is: %s' % len(list2))
if len(list2):
try:
case = list2[self.t]
except:
case = list2[0]
log.log().logger.info('current ip is : %s' % str(self.j))
log.log().logger.info('start test by multiple devices :%s ' % case[0])
self.q.put(u"我是第%d个线程ip: %s, 测试用例:%s" % (self.t, self.j, case[0]))
log.log().logger.info(u"打点我是第%d个线程ip: %s, 测试用例:%s" % (self.t, self.j, case[0]))
process().main(case, deviceList=[str(self.j)])
time.sleep(3)
else:
log.log().logger.info('no case !')

View File

@ -8,14 +8,14 @@ def tcplink(sock, addr):
while True:
try:
data = sock.recv(1024)
print(data.decode('utf-8'))
# print(data.decode('utf-8'))
except ConnectionResetError:
hubs.hubs().updateHub(ip,'all','0','0')
break
time.sleep(1)
ip = addr[0]
port = data.decode('utf-8')
print(data.decode('utf-8'))
# print(data.decode('utf-8'))
if not data :
break
elif data.decode('utf-8') == 'exit':

View File

@ -49,7 +49,7 @@ class util():
content = {}
headers = {'Content-type': 'application/json;charset=utf8'}
try:
print('url is :', url)
# print('url is :', url)
response, content = http.request(url, 'GET')
content = content.decode('utf-8')
except httplib2.ServerNotFoundError as e:

View File

@ -119,7 +119,7 @@ class test_batch_manage(object):
useDB.useDB().insert(sql)
# steps = useDB.useDB().insert('select steps from test_case where id = (select test_case_id from test_batch where id = %s);' %id)
sql = 'update test_batch set status=0, steps =(select steps from test_case where id = %s) where id = %s ;' %(test_case_id,id)
print(sql)
# print(sql)
useDB.useDB().insert(sql)
@ -311,12 +311,12 @@ class test_batch_manage(object):
for id in result:
sql = 'SELECT COUNT(1) FROM test_batch WHERE test_suite_id = %s AND STATUS in (0,4);' %id
result1 = useDB.useDB().search(sql)
print(result1[0][0])
# print(result1[0][0])
if len(result1) and (result1[0][0]==0):
if check_result !='':
check_result += ','
check_result +=(str(id[0]))
print(check_result)
# print(check_result)
return check_result

View File

@ -10,9 +10,9 @@ class test_keyword_manage:
valueList[0]) + ' order by id desc limit 1;'
else:
sql = 'select id, keyword, paraCount, template, example,description from test_keyword where status = 1 and keyword like "%' + str(valueList[0]) + '%" order by id desc limit '+ str(rows)+';'
print(sql)
# print(sql)
cases = useDB.useDB().search(sql)
print(cases)
# print(cases)
log.log().logger.info('cases : %s'%cases)
for i in range(len(cases)):
result = {}
@ -23,18 +23,18 @@ class test_keyword_manage:
result['example'] = cases[i][4]
result['description'] = cases[i][5]
results.append(result)
print(results)
# print(results)
return results
def new_test_keyword(self,name, paraCount, description, template,example):
sql = "insert into test_keyword (keyword, paraCount, description, template,example) values ('%s','%s','%s','%s','%s');" %(name, paraCount, description, template,example)
print(sql)
# print(sql)
useDB.useDB().insert(sql)
return True
def copy_test_keyword(self,id):
result = self.show_test_keywords(['id'],[id],[],1)
print(result)
# print(result)
if len(result):
result=result[0]
result = self.new_test_keyword(result["keyword"]+'_copy',result["paraCount"],result["description"],result["template"],result['example'])
@ -49,6 +49,6 @@ class test_keyword_manage:
update_value += ", %s = '%s'" %(fieldlist[i],str(valueList[i]).replace("'",'"'))
sql = string.Template('update test_keyword set $field where id = $id;')
sql = sql.substitute(field = update_value, id = id)
print(sql)
# print(sql)
useDB.useDB().insert(sql)
return 1

View File

@ -27,7 +27,7 @@ class test_user_manage:
result['id'] = users[i][0]
result['username'] = users[i][1]
results.append(result)
print(results)
# print(results)
return results
def new_user(self, username,password):
@ -36,7 +36,7 @@ class test_user_manage:
return 0
else:
sql = 'insert into auth_user (username,password) values ("%s","%s");' %(username,password)
print(sql)
# print(sql)
useDB.useDB().insert(sql)
return 1

View File

@ -26,7 +26,8 @@
<label for="name" class="col-sm-2 control-label">执行类型</label>
<div class="col-sm-10">
<select class="form-control required" name="run_type" id="run_type" onchange="selectOnchang(this);">
<option value="2">2-Chrome</option>
<option value="2">Chrome</option>
<option value="0">Android</option>
</select>
</div>
</div>

View File

@ -32,6 +32,10 @@
<div class="col-sm-6" style="text-align:left;">
<button type="button" style="margin-left:70px" id="btn_query" class="btn btn-primary" onclick="searchHubs()">查询</button>
<button type="button" style="margin-left:70px" id="btn_check_hubs" class="btn btn-primary" onclick="check_hubs()">检测</button>
<button id="rerun_locust" style="margin-left:70px" type="button" class="btn btn-primary"
onclick="window.location.href=('/view_hub')">
查看Android设备列表
</button>
</div>
</div>
</form>

View File

@ -0,0 +1,24 @@
{% extends "base.html" %}
{% block title %}WingSDK 测试平台 - 单元测试记录{% endblock %}
{% block head %}
<meta name="viewport" content="width=device-width"/>
<script src="../static/jquery-1.12.4.js"></script>
<!--<script src="../static/scripts/hubs.js"></script>-->
<script src="../static/bootstrap-3.3.7-dist/dist/js/bootstrap.js"></script>
<link href="../static/bootstrap-3.3.7-dist/dist/css/bootstrap.css" rel="stylesheet"/>
<script src="../static/bootstrap-table-develop/dist/bootstrap-table.js"></script>
<link href="../static/bootstrap-table-develop/dist/bootstrap-table.css" rel="stylesheet"/>
{% endblock %}
{% block content %}
<div class="panel-body" style="padding-bottom:0px;">
<h1 style="text-align:center">ATX 手机设备管理</h1>
<div class="main-container" id="main" style="height:100%">
<iframe src="{{host}}" width="100%" height="600"></iframe>
</div>
</div>
{% endblock %}

View File

@ -295,7 +295,7 @@ def save_new_test_suite():
code = 500
result = jsonify({'code': code, 'msg': message,'ext':ext})
log.log().logger.info(result)
log.log().logger.info('code is : %s'%result['code'])
# log.log().logger.info('code is : %s'%result['code'])
return result
@mod.route('/add_test_suite', methods=['POST', 'GET'])

View File

@ -1,5 +1,5 @@
from flask import Blueprint,render_template, jsonify, request,session
from app import log
from app import log, config
from app.core import hubs
from app.view import viewutil,user
from app.db import test_unittest_manage
@ -166,7 +166,7 @@ def search_hubs():
@mod.route('/view_hub')
@user.authorize
def view_hub():
return render_template("util/view_hub.html")
return render_template("util/view_hub.html", host=config.ATXHost)