在我们测试移动端app时,需要模拟用户实现点击、释放、拖动、长按等操作,在appium中同样跟selenium一样为你们提供了 TouchAction 来实现对应操作
一、常用方法:
1、按住:press( )
2、移动至:move_to( )
3、点击:tap( )
4、等待:wait( t单位ms)
5、长按:long_press( )
6、释放:release
7、执行:perform
import time
from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy as By
from appium.webdriver.common.touch_action import TouchAction
desired_caps = {}
desired_caps['platformName'] = 'Android' # 'Android' or ’Ios'
desired_caps['deviceName'] = 'emulator-5554' # 设备名称,可以自定义
desired_caps['appPackage'] = 'com.iodkols.onekeylockscreen'
desired_caps['appActivity'] = '.OneLock'
desired_caps['noReset'] = 'True'
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) # 类似于driver = webdriver.Chrome()
driver.implicitly_wait(10)
time.sleep(5)
def swipe_up(scale=0.5, t=500, n=1):
'''
向上滑动屏幕
:param scale: 滑动距离,即屏幕高度的百分比
:param t: 滑动持续时间,单位毫秒
:param n: 滑动次数
:return: None
'''
l = driver.get_window_size()
print(f"窗口size:{l}")
x = l['width'] * 0.5
y1 = l['height'] * (1 + scale) * 0.5
y2 = l['height'] * (1 - scale) * 0.5
for i in range(n):
driver.swipe(x, y1, x, y2, t)
swipe_up()
TouchAction(driver).press(x=197,y=799).wait(200).move_to(x=522,y=802).wait(200).move_to(x=529,y=1123).release().perform()
注意:TouchAction中传入一个driver的参数,支持链式调用,最后通过perform来执行链中的操作
二、页面滑动swipe方法
appium中也提供了swipe( )来支持我们对app页面进行滑动,swipe中需要传入起始坐标与终止坐标以及滑动执行时间;
driver.swipe(x1,y1,x2,y2,200) # 在当前页面从坐标(x1,y1)滑动到坐标(x2,y2),滑动时间200ms
对app页面的滑动在移动端的测试中元素定位起重要的辅助作用,因此为了稳定性和灵活适用性,我们一般的做法都是对swipe做二次封装,实现向上、向下、向左、向右滑动,同时应该尽量避免根据坐标来滑动,可动态获取屏幕大小,按屏幕长宽比来实现页面的滑动
def swipe_up(scale=0.5, t=500, n=1):
'''
向上滑动屏幕
:param scale: 滑动距离,即屏幕高度的百分比
:param t: 滑动持续时间,单位毫秒
:param n: 滑动次数
:return: None
'''
l = driver.get_window_size()
print(f"窗口size:{l}")
x = l['width'] * 0.5
y1 = l['height'] * (1 + scale) * 0.5
y2 = l['height'] * (1 - scale) * 0.5
for i in range(n):
driver.swipe(x, y1, x, y2, t)
def swipe_down(self, scale=0.5,t=500, n=1):
'''
向下滑动屏幕
:param scale: 滑动距离,即屏幕高度的百分比
:param t: 滑动持续时间,单位毫秒
:param n: 滑动次数
:return: None
'''
l = self.driver.get_window_size()
x = l['width'] * 0.5
y1 = l['height'] * (1-scale)*0.5
y2 = l['height'] * (1+scale)*0.5
for i in range(n):
self.driver.swipe(x, y1, x, y2, t)
def swipe_left(self, scale=0.5, t=500, n=1):
'''
向左滑动屏幕
:param scale: 滑动距离,即屏幕宽度的百分比
:param t: 滑动持续时间,单位毫秒
:param n: 滑动次数
:return: None
'''
l = self.driver.get_window_size()
x1 = l['width'] * (1+scale)*0.5
y = l['height'] * 0.5
x2 = l['width'] * (1-scale)*0.5
for i in range(n):
self.driver.swipe(x1, y, x2, y, t)
def swipe_right(self, scale=0.5, t=500, n=1):
'''
向右滑动屏幕
:param scale: 滑动距离,即屏幕宽度的百分比
:param t: 滑动持续时间,单位毫秒
:param n: 滑动次数
:return: None
'''
l = self.driver.get_window_size()
x1 = l['width'] * (1-scale)*0.5
y = l['height'] * 0.5
x2 = l['width'] * (1+scale)*0.5
for i in range(n):
self.driver.swipe(x1, y, x2, y, t)