当前位置: 首页 > news >正文

AirTest 基本操作范例和参数解释(一)

背景:基于目前团队中推广UIAutomation,采用了网易的UI自动化平台,平台兼容iOS、Android和WEB,是个跨平台的多库平台,利用poco和python进行脚本编写和开展自动化,但是在日常使用中有些同学对于一些关键字和参数有时记不住或者使用错误,这里特地整理完备供大家日常参考。

一、基本操作

1.前置用例引用

        可以将一些通用的操作写在一个.air脚本中,然后在其他脚本中import它

from airtest.core.api import using
using("replace_install.air") # 需要使用相对路径,不然找不到.air
import replace_install

2.引用自定义的公共类或方法

        在编写自动化的过程中,有一些自定义的方法或类,需要在.air下的.py中引用时候,需要将项目路径添加到环境变量中 

import sys import os # 必填,将项目目录添加到系统环境变量中 sys.path.append(‘项目路径’)

3.元素定位方式

(1)尽量使用text定位元素

poco(text="立即体验") poco(textMatches="^.*滑动来解锁.*$")#正则来模糊定位

(2)如果不能直接定位,建议使用局部布局

        子元素

poco(text='main_node').child(text='list_item')

        后代

poco(text='main_node').offspring(text='name')

        父

poco(text='main_node').parent()

        所有子元素

poco(text='main_node').children()

        兄弟元素

poco(text='main_node').sibling(text='name')

备注:

  • 因为text变化的概率相对较小,所以建议使用text,且脚本易读;
  • resourceid不建议,因为release版会混淆,除非公司对resourceid进行了统一设计和规划,且release版本不混淆。

4.元素操作

(1)点击元素身上的某一点

        通过相对坐标,控制点击的具体位置。左上角(0, 0),右下角(1, 1),横坐标为x,纵坐标为y。

(2)等待元素出现或消失

        实际写用例时,有一些扫描或缓冲场景,需要等待元素出现或消失,才能进行下一步操作。

        当使用wait_for_appearance或wait_for_disappearance时,建议处理PocoTargetTimeout,并截图,以方便在报告中查看出错时的页面情况

try:poco(text='main_node').wait_for_appearance(timeout=10)poco(text='main_node').wait_for_disappearance(timeout=10)
except PocoTargetTimeout:snapshot(msg="元素出现或未出现")

(3)滑动和拖动

        拖动

poco('star').drag_to(poco('shell'))

        滑动

poco('Scroll View').swipe([0, -0.1]) # 滑动指定坐标 
poco('Scroll View').swipe('up') # 向上滑动 
poco('Scroll View').swipe('down') # 向下滑动

        向量滑动

x, y = poco('Scroll View').get_position()
end = [x, y - 0.1]
dir = [0, -0.1]
poco.swipe([x, y], end)  # 从A点滑动到B点
poco.swipe([x, y], direction=dir)  # 从点A向给定方向和长度进行滑动

(4)获取元素信息(重要手段)

"""
attribute name, it can be one of the following or any other customized type implemented by SDK
- visible: whether or not it is visible to user
- text: string value of the UI element
- type: the type name of UI element from remote runtime
- pos: the position of the UI element
- size: the percentage size [width, height] in range of 0~1 according to the screen
- name: the name of UI element
- ...: other sdk implemented attributes
"""poco(text="text_content").attr("checkable")
poco(text="text_content").get_position()
poco(text="text_content").get_text()
....

(5)连续滑动与自定义滑动操作

from airtest.core.api import * dev = device() # 获取当前手机设备

        手指按照顺序依次滑过3个坐标,可以用于九宫格解锁

dev.minitouch.swipe_along([(100, 100), (200, 200), (300, 300)])

        自定义操作:实现两个手指同时点击的操作

from airtest.core.android.minitouch import *multitouch_event = [
DownEvent((100, 100), 0),  # 手指1按下(100, 100)
DownEvent((200, 200), 1),  # 手指2按下(200, 200)
SleepEvent(1),
UpEvent(0), UpEvent(1)]  # 2个手指分别抬起device().minitouch.perform(multitouch_event)

        自定义操作:三只滑动操作

from poco.utils.track import *tracks = [
MotionTrack().start([0.5, 0,5]).move([0.5, 0.6]).hold(1).
MotionTrack().start([0.5, 0,5]).move([0.5, 0.6]).hold(1).
MotionTrack().start([0.5, 0,5]).move([0.5, 0.6]).hold(1)
]poco.apply_motion_tracks(tracks)

        手       势操作:点击ui1保持1秒,拖动到ui2并保持1秒,然后抬起

ui1.start_gesture().hold(1).to(ui2).hold(1).up()

(6)点击元素偏移位置

        点击, focus为偏移值,sleep_interval为点击后的间隔时间

poco(text="立即清理").click(focus=(0.1, 0.1), sleep_interval=5)

(7)隐性等待元素

        隐形等待元素出现,元素出现后,wait()方法结束(隐藏元素常用方法)

poco(text="立即清理").wait(timeout=5)

(8)判断元素是否存在

        判断元素是否存在,存在返回True

poco(text="立即清理").exists()

(9)UI状态清除(请运行完毕之后,务必执行)

        在poco里选择出来的ui都是代理对象,在执行同一个用例里,一个ui控件选出来后能持续多长时间有效这个是要看android那回收ui资源的策略的,每个厂商的差异比较大.

        对于cocos2d-x引擎的poco,由于使用的是快照模式,获取到UI状态后如果UI状态确实发生了改变,需要调用ui.invalidate()进行重新获取。

ui = poco(text="立即清理")
ui.click()
ui.invalidate()
ui.click()

(10)long click

        长按操作,单位:秒

poco(text="立即清理").long_click(duration=2.0)

(11)两指挤压收缩操作

        在给定的范围和持续时间下,在UI上两指挤压收缩操作

poco.pinch(direction='in', percent=0.6, duration=2.0, dead_zone=0.1)

(12)根据UI滑动

        根据UI的给定高度或宽度,滑动距离的百分比:

        从底部上滑5秒

poco.scroll(direction='vertical', percent=1, duration=5)

        从顶部下滑5秒

poco.scroll(direction='vertical', percent=-1, duration=5)

二、异常类

        建议对每一个可能出现异常的地方都进行异常处理,并截图,最后看报告时方便迅速定位问题。

1.InvalidOprationException

        这个异常特指无效的操作,或者不起作用的操作

try:poco.click([1.1, 1.1])  # click outside screen
except InvalidOperationException:snapshot(msg="出现异常")

2.PocoNoSuchNodeException(经常遇到)

        如果从一个不存在的UI空间读取属性或操作,就会出现该异常。

node = poco("not existed node")
try:node.click()
except PocoNoSuchNodeException:snapshot(msg="出现异常")
try:node.attr('text')
except PocoNoSuchNodeException:snapshot(msg="出现异常")

3.PocoTargetTimeout

        这个异常只会在你主动等待UI出现或消失时抛出,和 PocoNoSuchNodeException 不一样,当你的操作速度太快,界面来不及跟着变化的话,你只会遇到 PocoNoSuchNodeException 而不是 PocoTargetTimeout ,其实就是在那个UI还没有出现的时候就想要进行操作。

node = poco("not existed node")
try:node.click()
except PocoNoSuchNodeException:snapshot(msg="出现异常")
try:node.attr('text')
except PocoNoSuchNodeException:snapshot(msg="出现异常")

4.PocoTargetRemovedException

        如果操作速度远远慢于UI变化的速度,很可能会出现这个异常。当且仅当访问或操作一个刚才存在现在不在的UI元素时,才会出现,并且一般不会出现。

try:poco(text="demo").click()
except PocoNoSuchNodeException:snapshot(msg="出现异常")

三、封装API好的函数

1.滚动查找元素(poco_swipe_to)

        滚动查找元素,当找到元素后,滑动元素到页面中间。

        公式:poco_swipe_to(text=None, textMatches=None, poco=None)

# 滚动查找元素
def poco_swipe_to(text=None, textMatches=None, poco=None):find_ele = Falsefind_element = Noneif poco is None:raise Exception("poco is None")if text or textMatches:swipe_time = 0snapshot(msg="开始滚动查找目标元素")if text:find_element = poco(text=text)elif textMatches:find_element = poco(textMatches=textMatches)while True:snapshot(msg="找到目标元素结果: " + str(find_element.exists()))if find_element.exists():# 将元素滚动到屏幕中间position1 = find_element.get_position()x, y = position1if y < 0.5:# 元素在上半页面,向下滑动到中间poco.swipe([0.5, 0.5], [0.5, 0.5+(0.5-y)], duration=2.0)else:poco.swipe([0.5, 0.5], [0.5, 0.5-(y-0.5)], duration=2.0)snapshot(msg="滑动元素到页面中间: " + str(text) + str(textMatches) )find_ele = Truebreakelif swipe_time < 30:poco.swipe([0.5, 0.8], [0.5, 0.4], duration=2.0)# poco.swipe((50, 800), (50, 200), duration=500)swipe_time = swipe_time + 1else:breakreturn find_ele

2.等待任一元素出现(poco.wait_for_any)

try:poco(text="demo").click()
except PocoNoSuchNodeException:snapshot(msg="出现异常了呀")

3.等待所有元素(poco.wait_for_all)

try:poco(text="demo").click()
except PocoNoSuchNodeException:snapshot(msg="出现异常")

4.观察者函数(watcher)

        说明:利用子进程对页面元素进行监控,发元素后,自动操作。

        适用场景:多用于不可预测的弹窗或元素

        公式:watcher(text=None, textMatches=None, timeout=10, poco=None)

​
def loop_watcher(find_element, timeout):start_time = time.time()while True:# find_element.invalidate()if find_element.exists():find_element.click()print("观察者:发现元素!!!")breakelif (time.time() - start_time) < timeout:print("--------------------观察者:等待1秒----------------")time.sleep(1)else:print("观察者:超时未发现!!")breakdef watcher(text=None, textMatches=None, timeout=10, poco=None):print("观察者:启动!!")# 目标元素find_element = Noneif poco is None:raise Exception("poco is None")if text or textMatches:if text:find_element = poco(text=text)elif textMatches:find_element = poco(textMatches=textMatches)# 定义子线程: 循环查找目标元素from multiprocessing import Processp = Process(target=loop_watcher, args=(find_element, timeout,))p.start()​


http://www.mrgr.cn/news/30917.html

相关文章:

  • 浏览网站记录怎么查?(如何查看浏览历史记录)三分钟学会五种方法!
  • 算法.图论-并查集上
  • 使用 Go 语言实现简单聊天系统
  • 【AI视频】Runway Gen-2:图文生视频与运动模式详解
  • 微信小程序. tarojs webView的 onload 事件不触发
  • 解决哈希冲突的方法
  • 1--SpringBoot外卖项目介绍及环境搭建 详解
  • 集采良药:从“天价神药”到低价良药,伊马替尼的真实世界研究!
  • 使用Python进行图像处理的11个基本操作
  • 常用函数式接口的使用
  • SpringBoot开发——整合SpringDoc实现在线接口文档
  • 一文搞懂软著申请细则!
  • 上海市计算机学会竞赛平台2024年7月月赛丙组子集归零
  • 数据库数据恢复—SQL Server附加数据库出现“错误823”怎么恢复数据?
  • 编程的魅力
  • 灵当CRM系统index.php存在SQL注入漏洞
  • 由一个 SwiftData “诡异”运行时崩溃而引发的钩深索隐(六)
  • 计算机知识包括哪些和应用?
  • 如何通过全面技术方案与灵活商务服务引领实时云渲染的未来?
  • 滚雪球学SpringCloud[6.2讲]: Zipkin:分布式追踪系统详解