更多内容请访问:与华为官方共建的Harmonyos技术社区https://harmonyos.51cto.com1.运行环境工具列表Appium-Desktopv1.8.2AndroidSDKPythonAppium-Python-客户端PytestPycharm工具安装:Appium-Desktopv1.8.2下载地址:Appium-Desktopv1.8.2,鸿蒙系统,Appium最佳兼容版本为v1.8.2。其他版本获取文本时值为“0.0”。安装过程:AndroidSDK1。下载地址:AndroidSDK2。在默认路径下安装AndroidStudio:C:\ProgramFiles\Android\AndroidStudio3。在AndroidStudio的SDK管理器中下载AndroidSDK4。配置环境变量:新建JAVA_HOME,值为C:\ProgramFiles\Android\AndroidStudio\jre新建ANDROID_HOME,值为C:\Users\Administrator\AppData\Local\Android\Sdk编辑路径,创建新建%JAVA_HOME%\bin、%JAVA_HOME%\jre\bin、%ANDROID_HOME%\tools、%ANDROID_HOME%\tools\bin、%ANDROID_HOME%\platform-toolsPython下载地址:Python在默认位置安装Python环境变量配置打开CMD,输入python–version测试python命令,输入pip–V测试pip命令如果测试失败,需要配置python环境变量Appium-Python-Client安装命令:pipinstallAppium-Python-ClientPytest安装命令:pipinstallpytestPycharm1。下载地址:PycharmPycharm是一款比较流行的Python编辑器(IDE工具),选择Community版下载2.在默认位置安装Pycharm3.选择python编译器2.元素定位元素定位常用工具:uiautomatorviewer.bat,weditor.exe,Appium-Desktop以uiautomatorviewer为例看常见的搜索控制方式1.通过id定位,resrouce-idelement=conf.driver.find_element_by_id("Id_myButton").click()2.通过ClassName定位:classnameelement=conf.driver.find_elements_by_class_name("android.widget.Button").click()3.通过Accessiblityld定位:content-descelement=driver.find_element_by_accessibility_id("content-desc-text").click()4.通过AndroidUiAutomatorui_str='newUiScrollable(UiSelector().className("{}")).scrollIntoView(newUiSelector().textContains("{}"))'.format(list_id,text_contains)element=conf.driver.find_element_by_android_uiautomator(ui_str)。点击()5。通过坐标定位,XYTouchAction(conf.driver).tap(x=int(x*phonewidth),y=int(y*phoneheight)).release().perform()6.positiontheultimatebyxpath定位的方式有很多种,常见的有以下几种:如果元素文本是唯一的,可以通过文本text来定位://*[@text='text文本属性']element=conf.driver.find_element_by_xpath("//*[@text='Clickme!']").click()如果元素id唯一,也可以使用id属性定位//*[@resource-id='idattribute']element=conf.driver.find_element_by_xpath("//*[@resource-id='org.ohosannotations.sample:id/Id_myButton']").click()通过content-desc属性定位//*[@content-德sc='desc的文字']element=conf.driver.find_element_by_xpath("//*[@content-desc='desc的文字']").click()包含模糊定位//[contains(@content-desc,'desc'stext')]element=conf.driver.find_element_by_xpath("//*[contains(@content-desc,'desc'stext')]").click()组合定位如果一个元素有2个属性,通过xpath也可以同时匹配2个属性,text,resource-id,class,index,content-desc这几个属性可以任意组合,通过id和class属性定位搜索框id_class='//android.widget.EditText[@resource-id="org.ohosannotations.sample:id/Id_myTextField"]'element=conf.driver.find_element_by_xpath(id_class).click()通过文本和索引属性定位按钮启动列表能力!desc_class='//*[@text="Startlistability!"and@index="3"]'element=conf.driver.find_element_by_xpath(desc_class).click()通过class和text属性定位输入框class_text='//android.widget.EditText[@text="输入框默认value"]'element=conf.driver.find_element_by_xpath(class_text).send_keys("zdhtest")通过class和desc定位搜索框id_desc='//*[contains(@resource-id,"Id_myTextField")and@content-desc="desc'stext"]'element=conf.driver.find_element_by_xpath(id_desc).click()鸿蒙和Android定位方式基本相同3.在自动化用户操作事件中模拟用户事件,鸿蒙的基本方法和安卓一样,这里介绍一些常见的操作事件:1.点击(确认点击),输入和清空操作点击:支持点击跳转的定位元素,执行driver.find_element_by_id(通过.click()'org.ohosannotations.sample:id/Id_myTextField').click()输入:在输入框中有需要输入的定位元素,执行driver.find_element_by_id('org.ohosannotations.sample:id/id_myTextField')through.send_keys().send_keys('zdhtest')清空:清空输入框的内容,通过.clear执行driver.find_element_by_id('org.ohosannotations.sample:id/Id_myTextField').clear()()2.元素等待自动化过程中,元素的出现受网络环境、设备性能等多种因素影响,元素加载时间可能不一致,久而久之会导致元素定位失败报错,但实际上元素加载正常,但它出现较晚。因此设置元素等待可以让定位元素的等待时间更加灵活,从而增强脚本的健壮性,提高执行效率强制等待:设置固定的等待时间,使用sleep()方法实现fromtimeimportsleep#强制等待for5secondssleep(5)隐式等待:隐式等待是为所有元素设置的等待时间driver.implicitly_wait(20)显式等待:显式等待是为一个元素设置的等待时间。方法WebDriverWait格式参数如下:fromselenium.webdriver.support.uiimportWebDriverWaitWebDriverWait(driver,timeout,poll_frequency=0.5,ignored_exceptions=None)driver:WebDriver#timeout:最长超时时间,默认以秒为单位#poll_frequency:间隔时间ofsleeptime,默认0.5秒#ignored_exceptions:超时后的异常信息,默认抛出NoSuchElementException。WebDriverWait()一般与until()或until_not()方法结合使用fromselenium.webdriver.support.uiimportWebDriverWaitWebDriverWait(conf.driver,10).until(EC.visibility_of_element_located((By.ID,self.locator)))3.ToastContentAcquisitionToast是一个简单的消息提示框。当视图显示给用户时,它在应用程序中显示为浮动。与Dialog不同的是,它永远不会获得焦点,也无法被点击。而且Toast的显示时间是有限的,一般3秒左右就会消失。在鸿蒙应用中,目前无法捕获到Toast,解决方法是使用截图对比#Android获取Toast的方式toast_message="Thisisatoasttext"message='//*[@text=\'{}\']'.format(toast_message)#显示待检测元素toast_element=WebDriverWait(driver,5).until(EC.visibility_of_element_located((message,self.locator)))print(toast_element.text)#鸿蒙中Toast处理方法self.get_image(imagepath)flag=self.image_assert(assertimagepath,imagepath,imagesucess)4.截图操作save_screenshot():方法直接将当前截图保存到当前脚本所在的文件位置driver.save_screenshot('aa.png')get_screenshot_as_file(self,filename):保存截图保存到指定文件路径driver.get_screenshot_as_file('./images/aa.png')5.滑动操作#获取机器屏幕尺寸x,ydefgetSize():x=dr.get_window_size()['width']y=dr.get_window_size()['height']return(x,y)#向上滑动屏幕defswipeUp(t):l=getSize()x1=int(l[0]*0.5)#x坐标y1=int(l[1]*0.75)#起始y坐标y2=int(l[1]*0.25)#结束y坐标dr.swipe(x1,y1,x1,y2,t)#向下滑动屏幕defswipeDown(t):l=getSize()x1=int(l[0]*0.5)#x坐标y1=int(l[1]*0.25)#起始y坐标y2=int(l[1]*0.75)#终点的y坐标dr.swipe(x1,y1,x1,y2,t)#向左滑动屏幕defswipLeft(t):l=getSize()x1=int(l[0]*0.75)y1=int(l[1]*0.5)x2=int(l[0]*0.05)dr.swipe(x1,y1,x2,y1,t)#向右滑动屏幕defswipRight(t):l=getSize()x1=int(l[0]*0.05)y1=int(l[1]*0.5)x2=int(l[0]*0.75)dr.swipe(x1,y1,x2,y1,t)#调用向左滑动swipLeft(1000)#向右滑动swipRight(1000)#向上滑动swipeUp(1000)#SwipeDown(1000)6.长按,长按,点击(只需点击),移动,暂停,释放、执行等操作强制等待:设置一个固定的等待时间,使用sleep()方法实现按下:press()开始按下一个元素或坐标点(x,y),按下上的某个位置手机屏幕用你的手指。press也可以接收屏幕的坐标(x,y)。press(self,el=None,x=None,y=None)TouchAction(driver).press(x=0,y=308)长按:longPress()开始按下一个元素或坐标点(x,y).与press()方法相比,longPress()方法多了一个输入参数。既然是长按,那肯定是有时间再按的。持续时间以毫秒为单位。1000表示按下一秒钟。它的用法与press()方法相同。long_press(self,el=None,x=None,y=None,duration=1000)Tap:tap()对元素或控件执行点击操作。用法参考press()。不能点击跳转,直接点击(例如:点击查看,点击喜欢,点击播放等)移动:move_to()将指针从上一个点移动到指定的元素或点。(滑动验证条)move_to(self,el=None,x=None,y=None)Pause:Wait()暂停脚本执行,以毫秒为单位wait(self,ms=0)Release:方法release()结束Action取消屏幕上的指针。release(self)执行:由perform()执行的动作发送到服务器的命令动作。执行(自我)7。获取屏幕尺寸和元素名称获取屏幕尺寸:屏幕总尺寸:resolutionphonesize=self.get_phone_size()屏幕宽度:X值phonewidth=phonesize["width"]屏幕高度:Y值phoneheight=phonesize["height"]获取元素的名称:driver.find_element_by_xpath(xpath).textdriver.find_element_by_id(“org.ohosannotations.sample:id/Id_myTextField”).text4.简单示例下面是两个简单的案例1。下例1以ohosannotations组件为例,案例包含的事件包括:点击、长按、输入、文本断言和图片对比断言deftest_ohosannotations(self,getlocator):annotations_locators=getlocator["ohosannotations"]withallure.step("点击Clickme_按钮点击事件"):self.ta_tap(annotations_locators["Clickme_button"])withallure.step("在输入框中输入内容"):self.text_input(annotations_locators["myTextField_control"],"这是acontentcontent!")self.ta_tap(annotations_locators["Clickme_button"])time.sleep(2)assert"Thisisacontentwithcontent!"==self.get_element_text(annotations_locators["myText_control"]),"文本显示不正确"withallure.step("长按Startextraability,longclick!Controls"):logger.info("长按Startextraability,longclick!Control")self.ta_longpress(annotations_locators["Startextraability,longclick_button"],1000)time.sleep(2)withallure.step("断言弹出框是图片与预期图片一致?”):self.get_image(imagepath)flag=self.image_assert(assertimagepath,imagepath,imagesucess)ifflagisTrue:withopen(imagesucess,"rb")asf:context=f.read()allure.attach(context,"匹配成功的图片",attachment_type=allure.attachment_type.PNG)else:withopen(imagepath,"rb")asf:context=f.read()allure.attach(context,"匹配失败的图片",attachment_type=allure.attachment_type.PNG)logger.info("匹配结果:%s"%flag)assertflagisTrue运行结果:2.示例2以Sensey组件为例演示多点触控的使用,验证两者Sensey组件检测功能的手指@allure.story('Sensey')@allure.title("sensey_006双指检测")@allure.tag("L1")@allure.severity("normal")#blocker:阻塞缺陷critical:严重缺陷normal:一般缺陷minor:次要缺陷trivial:次要缺陷@allure.description("双指检测")@pytest.mark.flaky(reruns=1,重播_delay=5)#reruns:重试次数reruns_delay:重试间隔deftest_sensey_006(self,getlocator):logger.info("sensey_006双指检测")self.ta_tap(["TOUCHDETECTOR","XPATH","//*[@text=\"TOUCHDETECTOR\"]"])self.ta_tap(["TouchDetection","XPATH","//*[@resource-id=\"Id_switch_touch\"]"])a1=TouchAction(conf.driver).tap(x=530,y=1380).release()a2=TouchAction(conf.driver).tap(x=730,y=1380).release()action=MultiAction(conf.driver)action.add(a1,a2)action.perform()time.sleep(0.5)text=self.get_element_text(["Result","XPATH","//*[@resource-id=\"Id_tv_result\"]"])asserttext=="TwoFingerTap","TwoFingerTapisnotcorrect"运行结果:5.使用allure-pytest插件生成测试报告@allure.feature('settingapplication')#featurenameclassTestSettings(BaseCase):@allure.story('声音和振动')#子函数名@allure.title('settings_001设置来电铃声')#用例标题@allure.severity('normal')#缺陷级别@allure.description('检查是否是ok设置来电铃声')#Usecasedescriptiondeftest_settings_001(self):#测试步骤withallure.step('输入声音和振动'):passwithallure.step('设置来电铃声'):passwithallure.step('判断来电铃声设置成功'):通过生成html报告并打开if__name__=='__main__':now=time.strftime('%Y%m%d%H%M%S',time.localtime())print('执行脚本(%s)'%now)xml_path='./reports/report-%s/xml'%nowhtml_path='./reports/report-%s/html'%nowcase_path='./testcases/'#运行测试脚本pytest.main(['-s','-q','--alluredir',xml_path,case_path])#生成html报告cmd='alluregenerate%s-o%s--clean'%(xml_path,html_path)os.system(cmd)#打开测试报告cmd='allureopen%s'%html_pathos.system(cmd)生成的报告如下:展开详情:更多信息请访问:与华为官方共建的鸿蒙技术社区https://harmonyos.51cto.com
