def getPhoneInfo(devices): '''获取设备的一些基本信息''' cmd = "adb -s " + devices + " shell cat /system/build.prop " phone_info = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.readlines() release = "ro.build.version.release=" # 版本 model = "ro.product.model=" #型号 brand = "ro.product.brand=" # 品牌 device = "ro.product.device=" # 设备名 result = { "release": release, "model": model, "brand": brand, "device": device } for line in phone_info: for i in line.split(): temp = i.decode() if temp.find(release) >= 0: result["release"] = temp[len(release):] break if temp.find(model) >= 0: result["model"] = temp[len(model):] break if temp.find(brand) >= 0: result["brand"] = temp[len(brand):] break if temp.find(device) >= 0: result["device"] = temp[len(device):] break LOG.info(result) return result
def exce_case(self, **kwargs): data = self.open_file()['data'] case_der = feng(driver=self.deriver) for i in range(len(data) - 1): f = case_der.find_elemens(lujing=data[i]['element_info'], fangfa=data[i]['find_type']) if data[i]['operate_type'] == 'click': f[int(data[i]['index'])].click() elif data[i]['operate_type'] == 'text': f[int(data[i]['index'])].text elif data[i]['operate_type'] == 'send_key': f[int(data[i]['index'])].clear() f[int(data[i]['index'])].set_value(kwargs.get(data[i]['key'])) else: LOG.info('请检查您的测试步骤') i += 1 time.sleep(8) f = case_der.find_elemens(lujing=data[-1]['element_info'], fangfa=data[-1]['find_type']) if data[-1]['operate_type'] == 'text': duanyan = {'code': 0, 'data': f[int(data[-1]['index'])].text} else: duanyan = {'code': 1, 'data': "请检查您的测试步骤最后一步为断言用的"} LOG.info('请检查您的测试步骤最后一步为断言用的') return duanyan
def start_server(self): #开启服务 for i in range(0, len(self.kwargs)): cmd = "appium --session-override -p %s -U %s" % ( self.kwargs[i]["port"], self.kwargs[i]["devices"]) if platform.system() == "Windows": # windows下启动server t1 = RunServer(cmd) p = Process(target=t1.start()) p.start() while True: time.sleep(4) if self.run("http://127.0.0.1:" + self.kwargs[i]["port"] + "/wd/hub/status"): LOG.info("-------win_server_ 成功--------------") break else: appium = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1, close_fds=True) while True: appium_line = appium.stdout.readline().strip().decode() time.sleep(2) print("---------start_server----------") if 'listener started' in appium_line or 'Error: listen' in appium_line: print("----server启动成功---") break
def reg(self, **kwargs): f = self.open.exce_case(**kwargs) if f['code'] == 1: LOG.info('无法获取断言') return else: beijing = f['data'] return beijing
def open_da(path): try: file = open(r'%s' % path, 'r', encoding='utf-8') data = yaml.load(file) return {'code': 0, 'data': data} except Exception as e: LOG.info('yaml文档解析失败!原因:%s' % e) return {'code': 1, 'data': e}
def write_recording(cpu, neicun, devices): try: with open(recording, 'a', encoding='utf-8') as f: m = '%s:cpu:%s,内存:%s' % (devices, cpu, neicun) f.write(m + '\n') f.close() except Exception as e: LOG.info('写入性能数据失败!失败原因:%s' % e)
def makecasefile(casename, desc, funtionname): LOG.info("开始生成测试用例文件") filepath = path + '//testcase//' + casename + 'casetest.py' if not os.path.exists(filepath): with open(filepath, 'w', encoding='utf-8') as file: file.write(readheader().format(casename, casename)) file.write(readerconet().format(funtionname, desc)) else: pass
def save_result(data): if os.path.exists(recording) is True: with open(recording, 'a', encoding='utf-8') as f: f.write(data + '\n') f.close() else: f = open(recording, 'a') f.write(data + '\n') f.close() LOG.info('记录测试结果完毕')
def setUp(self): """ setup """ self.dis_app = make_dis( Testplatform=self.parm['platformName'], TestplatformVersion=self.parm['platformVersion'], Testdevicesname=self.parm['deviceName'], TestappPackage=self.parm['appPackage'], TestappActivity=self.parm['appActivity']) self.deriver = webdriver.Remote( 'http://localhost:' + self.port + '/wd/hub', self.dis_app) LOG.info('reg测试用例开始执行')
def huoqu_test(filepath, index): try: file = xlrd.open_workbook(filepath) me = file.sheets()[index] nrows = me.nrows listdata = [] for i in range(1, nrows): dict_canshu = {} dict_canshu['id'] = me.cell(i, 0).value dict_canshu['model'] = me.cell(i, 0).value dict_canshu['logout'] = (me.cell(i, 2).value) dict_canshu.update(eval(me.cell(i, 3).value)) dict_canshu.update(eval(me.cell(i, 4).value)) listdata.append(dict_canshu) return listdata except Exception as e: LOG.info('获取测试用例参数失败!失败原因:%s' % e) return e
def parse_result(devices): with open(recording, 'r+', encoding='utf-8') as f: reslt = f.readlines() list_result = [] for j in reslt: if devices in j: list_result.append({ 'devices': devices, "result": j.split('&')[1], 'canshu': j.split('&')[2] }) passnum = 0 failnum = 0 for i in list_result: if i['result'] == 'pass': passnum += 1 else: failnum += 1 LOG.info('解析设备测试结果完毕') return passnum, failnum, list_result
def getApkBaseInfo(self): p = subprocess.Popen("aapt dump badging %s" % self.apkPath, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, shell=True) (output, err) = p.communicate() match = re.compile( "package: name='(\S+)' versionCode='(\d+)' versionName='(\S+)'" ).match(output.decode()) if not match: raise Exception("can't get packageinfo") packagename = match.group(1) appKey = match.group(2) appVersion = match.group(3) LOG.info("=====getApkInfo=========") LOG.info('packageName:', packagename) LOG.info('appKey:', appKey) LOG.info('appVersion:', appVersion) return packagename, appKey, appVersion
def tearDown(self): """ tearDown """ LOG.info('测试用例执行完毕,测试环境正在还原!') time.sleep(15) self.deriver.quit()
def __init__(self, parm, methodName='runTest'): super(regtest, self).__init__(methodName) self.port = parm['port'] LOG.info(parm) self.parm = parm
pool.map(runnerCaseApp, devices_Pool) pool.close() pool.join() @logger('组织测试用例') def runnerCaseApp(devices): '''利用unittest的testsuite来组织测试用例''' test_suit = unittest.TestSuite() test_suit.addTest(Parmer.parametrize(regtest, param=devices)) #扩展的其他的测试用例均这样添加 unittest.TextTestRunner(verbosity=2).run(test_suit) if __name__ == "__main__": LOG.info("测试开始执行") start_time = datetime.datetime.now() devicess = AndroidDebugBridge().attached_devices() makecasefile('reg', 'reg', 'reg') #没有的时候才会生成,一般都会有这个文件 path = os.getcwd() filenm = path + '//testreport//' + 'result.xls' if len(devicess) > 0: for dev in devicess: app = {} app["devices"] = dev app["port"] = str(random.randint(4593, 4598)) l_devices.append(app) appium_server = AppiumServer(l_devices) appium_server.start_server() #启动服务 runnerPool(l_devices) try:
def create(filename, testtime, Test_version, devices_list): try: file = Workbook(filename) table = file.add_sheet('测试结果', cell_overwrite_ok=True) style = yangshi1() for i in range(0, 7): table.col(i).width = 380 * 20 style1 = yangshi2() table.write_merge(0, 0, 0, 6, '测试报告', style=style) table.write_merge(2, 3, 0, 6, '测试详情', style=style1) table.write(4, 0, '项目名称', style=style1) table.write(5, 0, '测试版本', style=style1) table.write(6, 0, '提测时间', style=style1) table.write(7, 0, '提测人', style=style1) table.write(4, 2, '测试人', style=style1) table.write(5, 2, '测试时间', style=style1) table.write(6, 2, '审核人', style=style1) table.write(8, 0, '链接号', style=style1) table.write(8, 1, '品牌', style=style1) table.write(8, 2, '设备名', style=style1) table.write(8, 3, '型号', style=style1) table.write(8, 4, '版本', style=style1) table.write(8, 5, '通过', style=style1) table.write(8, 6, '失败', style=style1) table.write(4, 1, Test_Project_name, style=style1) table.write(5, 1, Test_version, style=style1) table.write(6, 1, testtime, style=style1) table.write(7, 1, TiTestuser, style=style1) table.write(4, 3, Test_user, style=style1) table.write(5, 3, datetime.now().strftime("%Y-%m-%d %HH:%MM"), style=style1) table.write(6, 3, "admin", style=style1) all_result = [] for devices in devices_list: fail, pass_a, reslut = parse_result(devices=str(devices)) all_result.append(reslut) de_result = getPhoneInfo(devices=str(devices)) table.write(9, 0, devices, style=style1) table.write(9, 1, de_result['brand'], style=style1) table.write(9, 2, de_result['device'], style=style1) table.write(9, 3, de_result['model'], style=style1) table.write(9, 4, de_result['release'], style=style1) table.write(9, 5, fail, style=style1) table.write(9, 6, pass_a, style=style1) table1 = file.add_sheet('测试详情', cell_overwrite_ok=True) table1.write_merge(0, 0, 0, 8, '测试详情', style=style) for i in range(0, 6): table1.col(i).width = 400 * 20 table1.write(1, 0, '测试用例编号', style=yangshi3()) table1.write(1, 1, '测试模块', style=yangshi3()) table1.write(1, 2, '所需要参数', style=yangshi3()) table1.write(1, 3, '预期', style=yangshi3()) table1.write(1, 4, '结果', style=yangshi3()) table1.write(1, 5, '测试设备', style=yangshi3()) for i in range(len(all_result)): for item in all_result[i]: table1.write(i + 2, 0, str(eval(item['canshu'])['id']), style=yangshi3()) table1.write(i + 2, 1, str(eval(item['canshu'])['model']), style=yangshi3()) table1.write(i + 2, 2, str(eval(item['canshu'])), style=yangshi3()) table1.write(i + 2, 3, str(eval(item['canshu'])['assert']), style=yangshi3()) table1.write(i + 2, 4, str(item['result']), style=yangshi3()) table1.write(i + 2, 5, str(item['devices']), style=yangshi3()) file.save(filename) LOG.info("测试报告保存成功") except Exception as e: LOG.error("测试报告生成失败,原因:%s" % e)