def start_server(self): #开启服务 for i in range(0, len(self.kwargs)): cmd = "appium -p %s " % (self.kwargs[i]["port"]) 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) if 'listener started' in appium_line or 'Error: listen' in appium_line: print("----server启动成功---") break
def login(self, **kwargs): f = self.open.exce_case(**kwargs) if f['code'] == 1: LOG.info('无法获取断言') else: beijing = f['data'] return beijing
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 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 register2(self, suc, user, password, yanzhengma): self.deriver.find_elements_by_id(self.regest_for)[2].click() self.deriver.find_element_by_id(self.regest_deng).click() self.deriver.find_element_by_id(self.regest_zhu).click() use = self.deriver.find_element_by_id(self.user) use.clear() use.send_keys(user) passwor = self.deriver.find_element_by_id(self.passw) passwor.clear() passwor.send_keys(password) if suc == 1: self.deriver.find_element_by_id(self.yanzhengmahuo).click() neicun = getnencun(TestappPackage) cpu = caijicpu(TestappPackage) LOG.info('注册占内存:%s,cpu:%s' % (neicun, cpu)) self.text_fail = self.deriver.find_element_by_id( self.regist_fail).text if suc == 0: yanzheng = self.deriver.find_element_by_id(self.yanzhengma) yanzheng.clear() yanzheng.send_keys(yanzhengma) self.deriver.find_element_by_id(self.regest_btn).click() neicun = getnencun(TestappPackage) cpu = caijicpu(TestappPackage) write_recording(cpu=cpu, neicun=neicun) LOG.info('注册占内存:%s,cpu:%s' % (neicun, cpu))
def register1(self, suc, user, password, yanzhengma): self.deriver.find_elements_by_id(self.regest_for)[2].click() self.deriver.find_element_by_id(self.regest_deng).click() self.deriver.find_element_by_id(self.regest_zhu).click() use = self.deriver.find_element_by_id(self.user) use.clear() use.send_keys(user) passwor = self.deriver.find_element_by_id(self.passw) passwor.clear() passwor.send_keys(password) yanzheng = self.deriver.find_element_by_id(self.yanzhengma) yanzheng.clear() yanzheng.send_keys(yanzhengma) path = os.getcwd() pathw = path + '\\testpang\\%s.jpg' % (str(time.time())[:10]) if suc == '1' or suc == 1: self.deriver.find_element_by_id(self.regest_btn).click() neicun = getnencun(TestappPackage) cpu = caijicpu(TestappPackage) write_recording(cpu=cpu, neicun=neicun) LOG.info('注册占内存:%s,cpu:%s' % (neicun, cpu)) self.deriver.get_screenshot_as_file(pathw) time.sleep(2) self.text_fail = self.deriver.find_element_by_id(self.regist_fail) self.rerun_test = self.text_fail.text return self.rerun_test if suc == 0: self.deriver.get_screenshot_as_file(pathw)
def setUp(self): '''初始化测试环境''' self.dis_app = make_dis() self.deriver = webdriver.Remote('http://localhost:4723/wd/hub', self.dis_app) self.res = Regust(self.deriver) LOG.info('register测试用例环境初始化完毕,开始执行测试用例')
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 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://127.0.0.1:' + self.port + '/wd/hub', self.dis_app) LOG.info('reg测试用例开始执行')
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 makecasefile(casename, desc, funtionname): LOG.info("开始生成测试用例文件") pathone = os.path.join(path, "testcase") filepath = pathone + '{}casetest.py'.format(casename) if not os.path.exists(filepath): with open(filepath, 'w', encoding='utf-8') as file: if Test_mobile_type=="Android": file.write(readheader().format(casename, casename)) file.write(readerconet().format(funtionname, desc)) else: file.write(readiosheader().format(casename, casename)) file.write(readeriosconet().format(funtionname, desc))
def test_login(self, data_test): self.user = data_test['username'] self.passw = data_test['password'] self.suc = data_test['suc'] self.assert_v = data_test['assert'] self.assert_return = self.logs.login(suc=self.suc, name=self.user, password=self.passw) LOG.info('登录测试,传入参数:用户名:%s,密码:%s,返回结果:%s' % (self.user, self.passw, self.assert_return)) self.assertEqual(self.assert_v, self.assert_return, msg='fail resons:%s !=%s' % (self.assert_v, self.assert_return))
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['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)
def __init__(self, deriver): self.deriver = deriver LOG.info('获取元素的定位的信息') patth = os.getcwd() self.file = open(patth + '\\data\\data_dingwei.yaml', 'r', encoding='utf-8') self.data = yaml.load(self.file) self.file.close() self.herenzhongxin = self.data['denglu']['weizhilan_id'] self.logi = self.data['denglu']['denglu_id'] self.username = self.data['denglu']['username_id'] self.password = self.data['denglu']['password_id'] self.log_btn = self.data['denglu']['login_btn_id'] self.login_fail = self.data['denglu']['denglu_fail_id'] self.login_sucess = self.data['denglu']['denglu_sucesss_id'] LOG.info('元素定位信息加载成功!!')
def testreg(self, data_test): self.user = data_test['username'] self.password = data_test['password'] self.yanzheng = data_test['yanzhengma'] self.suc = data_test['suc'] self.asserts = data_test['assert'] self.asser_return = self.res.register1(self.suc, self.user, self.password, self.yanzheng) LOG.info( ('测试用例:%s,输入参数:name:%s,pwd:%s,yanzhengma:%s suc:%s,assert:%s' % (data_test['id'], self.user, self.password, self.yanzheng, self.suc, self.asserts))) time.sleep(1) self.assertEqual(self.asser_return, self.asserts, msg='fail resons:%s !=%s' % (self.asser_return, self.asserts))
def report(casepath): test_suit = unittest.TestSuite() discover = unittest.defaultTestLoader.discover(casepath, pattern='*test.py', top_level_dir=None) for test in discover: for test_case in test: test_suit.addTest(test_case) now = time.strftime('%Y-%m-%d-%H-%M', time.localtime(time.time())) path = os.getcwd() report_dir = path + '\\testreport\\%s.html' % now LOG.info('测试报告路径为:%s' % report_dir) re_open = open(report_dir, 'wb') runner = BSTestRunner.BSTestRunner(stream=re_open, title=u'学生端app UI自动化测试', description=u'自动化测试结果') runner.run(test_suit)
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 login(self, suc, name, password): self.deriver.find_elements_by_id(self.herenzhongxin)[2].click() self.deriver.find_element_by_id(self.logi).click() LOG.info('进入登陆界面!!') userna = self.deriver.find_element_by_id(self.username) userna.clear() userna.send_keys(name) passwor = self.deriver.find_element_by_id(self.password) passwor.clear() passwor.send_keys(password) path = os.getcwd() pathw = path + '\\testpang\\%s.jpg' % (str(time.time())[:10]) LOG.info('登陆参数输入完毕') self.deriver.find_element_by_id(self.log_btn).click() neicun = getnencun(TestappPackage) cpu = caijicpu(TestappPackage) write_recording(cpu=cpu, neicun=neicun) LOG.info('登录占内存:%s,cpu:%s' % (neicun, cpu)) self.deriver.get_screenshot_as_file(pathw) time.sleep(5) if suc == '1' or suc == 1: self.login_fai = self.deriver.find_element_by_id( self.login_fail).text return self.login_fai if suc == '0' or suc == 0: self.login_suc = self.deriver.find_element_by_id( self.login_sucess).text return self.login_suc
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
# encoding: utf-8 """ @author: lileilei @software: PyCharm @file: main.py @time: 2017/4/27 13:41 """ '''主运行文件''' from testsuite.repPorT import report import os from untils.log import LOG if __name__=="__main__": LOG.info('UI自动化相关测试开始执行') basepth=os.getcwd() path=basepth+'\\testcase' report(casepath=path) LOG.info('UI自动化相关测试执行完毕!')
def connectmobile() -> list: LOG.info("---开始链接stf平台-----") stf = StfPhoneOpear() all_list_phone = stf.getstflist() if len(all_list_phone) < Test_plan_num: return [] LOG.info("---获取可用设备列表-----") for item in all_list_phone: if item['platform'] == Test_mobile_type and item['use'] is False: test_ophone.append(item) if len(test_ophone) < Test_plan_num: return [] LOG.info("---准备申请设备-----") all_connect_phone = test_ophone[:Test_plan_num] connect_adb_device = [] for i in range(len(all_connect_phone)): #TODO 设备申请后链接需要对链接的设备进行区分, ## 先找到已知设备列表,链接后,找到新增的那台设备,现在有bug LOG.info("---申请设备:%s-----" % all_connect_phone[i]['serial']) stf.oparyonephone(all_connect_phone[i]['serial']) LOG.info("---获取设备:%s 远程地址-----" % all_connect_phone[i]['serial']) connect = stf.getoneconnecturl(all_connect_phone[i]['serial']) all_detail = {} LOG.info("---链接设备:%s -----" % all_connect_phone[i]['serial']) os.popen("/Users/lileilei/Downloads/android-sdk-macosx/platform-tools/adb connect %s" % connect) reslut = os.popen("/Users/lileilei/Downloads/android-sdk-macosx/platform-tools/adb devices").read() index = i + 1 devices = str(reslut).split("\n")[index].split("\t")[0] all_detail['devices'] = devices all_detail['serial'] = all_connect_phone[i]['serial'] all_detail['version'] = all_connect_phone[i]['version'] connect_adb_device.append(all_detail) return connect_adb_device
pool = Pool(len(devices_Pool)) for dev in devices_Pool: pool.map(runnerCaseApp, dev) pool.close() pool.join() 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() makecasefile('reg', 'reg', 'reg') path = os.getcwd() filenm = path + '/testreport/' + 'result.xls' devicess = connectmobile() listport = [] if len(devicess) > 0: for dev in devicess: app = {} app["devices"] = dev port = str(random.randint(4593, 4598)) app["port"] = port l_devices.append(app) listport.append(port) appium_server = AppiumServer(l_devices)
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)
def setUp(self): self.dis_app = make_dis() self.deriver = webdriver.Remote('http://localhost:4723/wd/hub', self.dis_app) LOG.info('reg测试用例开始执行')
def tearDown(self): LOG.info('清空测试环境操作中') self.deriver.quit()
pool.map(runnerCaseApp, devices_Pool) pool.close() pool.join() @logger('组织测试用例') def runnerCaseApp(devices): '''利用unittest的testsuite来组织测试用例''' test_suit = unittest.TestSuite() test_suit.addTest(Parmer.parametrize(testcase_klass=regtest, param=devices)) # 扩展的其他的测试用例均这样添加 unittest.TextTestRunner(verbosity=2).run(test_suit) if __name__ == "__main__": LOG.info("测试开始执行") start_time = datetime.datetime.now() devicess = [] if Test_mobile_type == 'Android': devicess = AndroidDebugBridge().attached_devices() else: #todo 本地获取链接的ios设备 pass makecasefile('reg', 'reg', 'reg') # 没有的时候才会生成,一般都会有这个文件 path = os.getcwd() report_path = os.path.join(path, "testreport") filenm = report_path + 'result.xls' if len(devicess) > 0: for dev in devicess: app = {} app["devices"] = dev