使用Appium作app自动化测试,绕不开的就是下拉刷新操作,下拉是最常见的,其实还有上滑、左滑、右滑操作。在正式的测试流程里,可以把刷新操作封装成一个模块,需要时直接调用。
Appium中提供了三种滑动的方式:swipe滑动、scroll滑动、drag拖拽事件
swipe()方法是从⼀个坐标位置滑动到另⼀个坐标位置,是两个点之间的滑动。
def swipe(self, start_x, start_y, end_x, end_y, duration=None):"""Swipe from one point to another point, for an optional duration.:Args:- start_x - x-coordinate at which to start- start_y - y-coordinate at which to start- end_x - x-coordinate at which to stop- end_y - y-coordinate at which to stop- duration - (optional) time to take the swipe, in ms.:Usage:driver.swipe(100, 100, 100, 400)"""# `swipe` is something like press-wait-move_to-release, which the server# will translate into the correct actionaction = TouchAction(self)action \.press(x=start_x, y=start_y) \.wait(ms=duration) \.move_to(x=end_x, y=end_y) \.release()action.perform()return self
- start_x - 滑动开始x轴坐标
- start_y - 滑动开始y轴坐标
- end_x - 滑动结束x轴偏移量
- end_y - 滑动结束y轴偏移量
- duration - (可选) 执行此次滑动时间,单位毫秒
其中end_x 和 end_y 为基于start_x 和start_y 的偏移量;最终在执行中的 to_x = start_x +end_x 并非end_x ;duration 参数单位为ms(默认5毫秒),注意 1s = 1000ms。
封装刷新模块
便于随时调用,我们可以自行封装代码,将上滑、下滑、左滑、右滑封装成一个刷新模块。
#coding=utf-8
import timeclass Slide(object):def __init__(self, driver):self.driver = driver#获取机器屏幕大小x,ydef get_size(self):x = self.driver.get_window_size()['width']y = self.driver.get_window_size()['height']return x, y#屏幕向上滑动def swipe_up(self, t): # t是指滑动时间(默认5毫秒,可选参数)"""滑动时X轴不变,Y轴由大到小"""screensize = self.get_size()x1 = int(screensize[0] * 0.5) # x坐标y1 = int(screensize[1] * 0.75) # 起始y坐标y2 = int(screensize[1] * 0.25) # 终点y坐标self.driver.swipe(x1, y1, x1, y2, t)#屏幕向下滑动def swipe_down(self, t):"""滑动时X轴不变,Y轴由小到大"""screensize = self.get_size()x1 = int(screensize[0] * 0.5) # x坐标y1 = int(screensize[1] * 0.25) # 起始y坐标y2 = int(screensize[1] * 0.75) # 终点y坐标self.driver.swipe(x1, y1, x1, y2, t)#屏幕向左滑动def swipe_left(self, n, t): # n是指滑动次数"""滑动时Y轴不变,X轴由大到小"""screensize = self.get_size()x1 = int(screensize[0] * 0.9)y1 = int(screensize[1] * 0.5)x2 = int(screensize[0] * 0.1)for i in range(0, n): # for循环,控制滑动次数time.sleep(3)self.driver.swipe(x1, y1, x2, y1, t)#屏幕向右滑动def swipe_right(self, n, t):"""滑动时Y轴不变,X轴由小到大"""screensize = self.get_size()x1 = int(screensize[0] * 0.1)y1 = int(screensize[1] * 0.5)x2 = int(screensize[0] * 0.9)for i in range(0, n): # for循环,控制滑动次数time.sleep(3)self.driver.swipe(x1, y1, x2, y1, t)
假设刷新模块的文件名为app_slide 那么可以这样调用
from app_slide import Slide#调用时传递appium.webdriver
flush = Slide(driver)#下拉刷新
flush.swipe_down(1000)