移动端自动化测试(二)之 Appium常用的API(python)函数介绍

时间:2021-02-06 09:38:15

  上一章节已经介绍了Appium的环境搭建,其实只要掌握了Appium的工作原理,前期的准备工作和安装过程是比较简单的。那么当我们搭建好Appium环境后接下来做些什么呢?通常思路是开始appium的第一个helloworld的例子,但笔者认为现在开始写代码并不能算好,这就犹如在武侠小说里但凡武功达到大臻境界的绝世高手都不会在意一招半式的招式,而内功修炼尤为重要。在网上搜索了一下,并没有一个大而全的api文档集合,所以笔者决定先对Python语言可以使用到的Appium API一一进行介绍。

常用函数

一、获得信息类API

(1)获取当前页面的activity名,比如: (.ui.login.ViewPage)

 def current_activity(self):
"""Retrieves the current activity on the device.
"""
return self.execute(Command.GET_CURRENT_ACTIVITY)['value']

current_activity()

比如我们需要实现这个登录的功能时,主要思路为如果当前界面为登录页面时,就进行登录行为,否则就跳转到登录页面。其伪代码为:

 if driver.current_activity == ".ui.login.ViewPage":
// To login_action
else:
// Trun to loginPage

(2)获取当前页面的树形结构源代码,与uiautomatorviewer截屏所展示出来的结构是相同的

 def page_source(self):
"""
获得当前页面的源码。
:Usage:
driver.page_source
"""
return self.execute(Command.GET_PAGE_SOURCE)['value']

page_source()

例如当我们完成登录流程之后,要判断登录是否成功,则可以判断登录后的页面有没有出现特定的内容(比如:运动圈、发现、运动、商城、我的),其伪代码实现如下:

driver \
.page_source.find(u"运动圈") != -1 and
.page_source.find(u"发现") != -1 and
.page_source.find(u"运动") != -1 and
.page_source.find(u"商城") != -1 and
.page_source.find(u"我的") != -1 and

page_source()的返回数据类型为str。python中,str的find(context)方法,如果str存在context返回值为context在str的index,如果不存在,则返回值为-1。因此只需要判断以上代码块返回的布尔值是True or False,就可以判断是否登录成功。

(3)获取到当前窗口的所有context的名称

 def contexts(self):
"""
Returns the contexts within the current session.
:Usage:
driver.contexts
"""
return self.execute(Command.CONTEXTS)['value']

contexts()

在native和html5混合页面测试时,需要在native层和H5层切换,所以首先需要得到context层级的名称

print driver.contexts

>>> ['NATIVE_APP', 'WEBVIEW_com.codoon.gps']

由此可见,我们知道App的H5层名称为"WEBVIEW_com.codoon.gps"后,使用driver.switch_to.context("WEBVIEW_com.codoon.gps")就可以实现NATIVE和H5层的切换了。

二、获取控件类API

(1)通过元素id查找当前页面的一个目标元素

 def find_element_by_id(self, id_):
""" Finds an element by id.
:Args:
- id\_ - The id of the element to be found.
:Usage:
driver.find_element_by_id('foo')
******************************
Finds element within this element's children by ID.
:Args:
- id_ - ID of child element to locate.
"""
return self.find_element(by=By.ID, value=id_)

find_element_by_id()

通过源码注释可以得到find_element_by_id这一类的api主要有两个使用途径:

driver.find_element_by_id("com.codoon.gps:id/tv_login")  // from webdriver.py

在driver下通过id查找一个元素,此用法通常适用于当前界面的driver有且仅有一个唯一的id元素标示,通过调用find_element_by_id可以准确到找到目标元素;另一种使用途径主要如下:

driver_element = driver.find_element_by_xpath("//android.widget.ListView/android.widget.LinearLayout")

// from webdriverelement.py

driver_element.find_element_by_id("com.codoon.gps:id/activity_active_state")

在driver.find_element_by_xpath返回了driverElement类型,调用find_element_by_id在driverElement下的子元素以id匹配目标元素。

移动端自动化测试(二)之 Appium常用的API(python)函数介绍

上图为uiautomatorviewer对id,name,class的图示说明。特别说明:若id、name、xpath等在当前driver或者driverElement查找的目标元素不是唯一元素,此时调用find_element_by_id(name\xpath)时,会返回查找匹配到的第一个元素。

(2)通过元素id查找当前页面的多个目标元素

 def find_elements_by_id(self, id_):
"""
Finds multiple elements by id. :Args:
- id\_ - The id of the elements to be found. :Usage:
driver.find_elements_by_id('foo')
"""
return self.find_elements(by=By.ID, value=id_)

find_elements_by_id()

在driver下通过id查找多个目标元素,其返回值类型为list。此用法通常适用于当前driver下查询listView、LinearLayout、 RelativeLayout等有相同布局结构的Item;同样除了driver之外,在driverElement下页可以跳用find_elements_by_id来匹配listView、LinearLayout、 RelativeLayout。

driver.find_elements_by_id("com.codoon.gps:id/tv_name")  // from webdriver.py
driver.find_element_by_id("com.codoon.gps:id/webbase_btn_share") \ 
  .find_elements_by_id("com.codoon.gps:id/ll_layout") // from driverelement.py

Tips: 带有find_elements关键字的方法函数的返回类型都是list数据类型,只有driver与driverelement的实例化有find_element(s)等一系列方法,list类型是不能用find_element(s)方法定位数据的。在实际的项目中可能会遇到这样的问题,只有遍历list,取出每一个element实例化对象再进行查找定位元素。

(3) 通过元素name查找当前页面的一个元素

 def find_element_by_name(self, name):
"""
Finds an element by name. :Args:
- name: The name of the element to find. :Usage:
driver.find_element_by_name('foo')
"""
return self.find_element(by=By.NAME, value=name)

find_element_by_name()

使用方式与find_element_by_id相同,只是把匹配条件由id变为name。请参考find_element_by_id的调用方式

driver.find_element_by_name("foo")
driver.find_element_by_id("com.codoon.gps:id/tv_name").find_element_by_name("foo") >>> return the driverElement(obj)

(4) 通过元素name查找当前页面的多个目标元素

 def find_elements_by_name(self, name):
"""
Finds elements by name. :Args:
- name: The name of the elements to find. :Usage:
driver.find_elements_by_name('foo')
"""
return self.find_elements(by=By.NAME, value=name)

find_elements_by_name()

使用方式与find_elements_by_id相同,只是把匹配条件由id变为name。请参考find_elements_by_id的调用方式,注意其返回数据类型是List,并不是driverElement。

driver.find_elements_by_name("foo")
driver.find_element_by_id("com.codoon.gps:id/tv_name").find_elements_by_name("foo") ### return the List<driverElement>
>>> ['driverElement1', 'driverElement2', 'driverElement3', ....]

(5)通过元素xpath查找当前页面的一个目标元素

 def find_element_by_xpath(self, xpath):
"""
Finds an element by xpath. :Args:
- xpath - The xpath locator of the element to find. :Usage:
driver.find_element_by_xpath('//div/td[1]')
"""
return self.find_element(by=By.XPATH, value=xpath)

find_element_by_xpath()

关于find_element_by_xpath的调用方法与通过id、name略有不同,有关Xpath的相关知识点在本章节暂且不表,后续在项目实践中若有需求再另起专题介绍。

driver.find_element_by_xpath("//android.widget.TextView[contains(@text, '开始')]")
driver.find_element_by_xpath("//android.widget.LinearLayout/android.widget.TextView")

在Appium中,xpath所需相关的lib库并没有完全支持,所以使用方法是以上两种(即仅支持在driver下的xpath匹配)。目前的Appium版本无法支持driverelement下的xpath查找,如

driver.find_element_by_xpath("//android.widget.LinearLayout/android.widget.TextView") \ 
.find_element_by_xpath("//android.widget.TextView[contains(@text, '开始')]") // This is the Error!

按上面的写法Appium就会报错,原因是“.find_element_by_xpath("//android.widget.TextView[contains(@text, '开始')]")”不能在Element下查找子元素。

(6) 通过元素xpath查找当前页面的多个目标元素

 def find_elements_by_xpath(self, xpath):
"""
Finds multiple elements by xpath. :Args:
- xpath - The xpath locator of the elements to be found. :Usage:
driver.find_elements_by_xpath("//div[contains(@class, 'foo')]")
"""
return self.find_elements(by=By.XPATH, value=xpath)

find_elements_by_xpath()

参照find_element_by_xpath的调用方式,需注意返回类型为List,用法参考find_elements_by_name()的例子

(7) 通过元素class name查找当前页面的的一个元素

 def find_element_by_class_name(self, name):
"""
Finds an element by class name. :Args:
- name: The class name of the element to find. :Usage:
driver.find_element_by_class_name('foo')
"""
return self.find_element(by=By.CLASS_NAME, value=name)

find_element_by_class_name()

在实际项目中,测试app中class name并不能做为界面的唯一标示定位,所以在实际中几乎没有使用class name在driver查看元素,在driverelement下查找子元素用class name才是正确的使用方式。

(8) 通过元素accessibility_id (content-desc)查找当前页面的一个元素

 def find_element_by_accessibility_id(self, id):
"""Finds an element by accessibility id. :Args:
- id - a string corresponding to a recursive element search using the
Id/Name that the native Accessibility options utilize :Usage:
driver.find_element_by_accessibility_id()
"""
return self.find_element(by=By.ACCESSIBILITY_ID, value=id)

find_element_by_accessibility_id()

在uiautomatorviewer中,content-desc内容即为accessibility_id,在selenium库里可以用find_element_by_name()来匹配content-desc的内容;在Appium库里则用find_element_by_accessibility_id()来匹配content-desc的内容。因为Appium继承了Selenium类,所以如果find_element_by_name无法准确定位时,请试试看find_element_by_accessibility_id。

  常用的获取控件类API就是以上这些。其他的查找和匹配的api还有find_element_by_link_text、find_elements_by_link_text、find_element_by_tag_name、find_elements_by_tag_name、find_element_by_css_selector、find_elements_by_css_selector等,用法都与上述类似。

三、元素操作类API

   我们在实现PC端浏览器Webdriver自动化时,对于网页上的目标的操作主要有:点击(click)、 双击(double_click)、滚动(scroll)、输入(send_keys),而移动端特有的辅助类api:轻击(tap)--支持多点触控,滑动(swipe),放大元素(pinch),缩小元素(zoom)

(1)点击事件

def click(self):
"""Clicks the element."""
self._execute(Command.CLICK_ELEMENT)

click()

 def tap(self, positions, duration=None):
"""Taps on an particular place with up to five fingers, holding for a
certain time :Args:
- positions - an array of tuples representing the x/y coordinates of
the fingers to tap. Length can be up to five.
- duration - (optional) length of time to tap, in ms :Usage:
driver.tap([(100, 20), (100, 60), (100, 100)], 500)
"""
if len(positions) == 1:
action = TouchAction(self)
x = positions[0][0]
y = positions[0][1]
if duration:
action.long_press(x=x, y=y, duration=duration).release()
else:
action.tap(x=x, y=y)
action.perform()
else:
ma = MultiAction(self)
for position in positions:
x = position[0]
y = position[1]
action = TouchAction(self)
if duration:
action.long_press(x=x, y=y, duration=duration).release()
else:
action.press(x=x, y=y).release()
ma.add(action) ma.perform()
return self

tap()

click和tap都能实现单击的效果。其区别在于click是作用于driverelement的实例化对象,而tap是对屏幕上的坐标位置进行点击。前者对元素的位置变化并不敏感,而后者是针对具体的像素坐标点击,受分辨率和元素位置影响较大。

(2)输入事件

 def send_keys(self, *value):
"""Simulates typing into the element. :Args:
- value - A string for typing, or setting form fields. For setting
file inputs, this could be a local file path. Use this to send simple key events or to fill out form fields:: form_textfield = driver.find_element_by_name('username')
form_textfield.send_keys("admin") This can also be used to set file inputs. :: file_input = driver.find_element_by_name('profilePic')
file_input.send_keys("path/to/profilepic.gif")
# Generally it's better to wrap the file path in one of the methods
# in os.path to return the actual path to support cross OS testing.
# file_input.send_keys(os.path.abspath("path/to/profilepic.gif")) """
# transfer file to another machine only if remote driver is used
# the same behaviour as for java binding
if self.parent._is_remote:
local_file = self.parent.file_detector.is_local_file(*value)
if local_file is not None:
value = self._upload(local_file) self._execute(Command.SEND_KEYS_TO_ELEMENT, {'value': keys_to_typing(value)})

send_keys()

 def set_text(self, keys=''):
"""Sends text to the element. Previous text is removed.
Android only. :Args:
- keys - the text to be sent to the element. :Usage:
element.set_text('some text')
"""
data = {
'id': self._id,
'value': [keys]
}
self._execute(Command.REPLACE_KEYS, data)
return self

set_text()

send_keys和set_text也都能满足输入文本内容的操作。其区别在于send_keys会调用设备当前系统输入法键盘,而set_text直接对目标元素设置文本。由此可推,send_keys的输入内容往往和预期内容不一致,而set_text的输入则是直接赋值,并不是键盘事件。

(3)滑动(翻屏)事件

     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 action
action = 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

swipe()

 def flick(self, start_x, start_y, end_x, end_y):
"""Flick from one point to another point. :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 :Usage:
driver.flick(100, 100, 100, 400)
"""
action = TouchAction(self)
action \
.press(x=start_x, y=start_y) \
.move_to(x=end_x, y=end_y) \
.release()
action.perform()
return self

flick()

swipe和flick都是滑动操作,它们都是从[start_x, start_y]划到[end_x, end_y]的过程,唯一不同的是swipe比flick多了一个duration参数,有了这个参数就可以自定义从start到end动作的作用时间,以达到快速滑动或者慢速滑动的效果。

(4)缩放事件

 def pinch(self, element=None, percent=200, steps=50):
"""Pinch on an element a certain amount :Args:
- element - the element to pinch
- percent - (optional) amount to pinch. Defaults to 200%
- steps - (optional) number of steps in the pinch action :Usage:
driver.pinch(element)
"""
if element:
element = element.id opts = {
'element': element,
'percent': percent,
'steps': steps,
}
self.execute_script('mobile: pinchClose', opts)
return self

pinch()

 def zoom(self, element=None, percent=200, steps=50):
"""Zooms in on an element a certain amount :Args:
- element - the element to zoom
- percent - (optional) amount to zoom. Defaults to 200%
- steps - (optional) number of steps in the zoom action :Usage:
driver.zoom(element)
"""
if element:
element = element.id opts = {
'element': element,
'percent': percent,
'steps': steps,
}
self.execute_script('mobile: pinchOpen', opts)
return self

zoom()

默认会对目标元素进行放大一倍或者缩小一半的操作,此api方法适合于在测试运动地图的缩放时的变化。

(5)长按事件

 def long_press(self, el=None, x=None, y=None, duration=1000):
"""Begin a chain with a press down that lasts `duration` milliseconds
"""
self._add_action('longPress', self._get_opts(el, x, y, duration)) return self

long_press()

长按方法是在TouchAction类中,所以在使用时需要先import TouchAction。在删除运动历史记录时,在记录列表长按删除,

action1 = TouchAction(self.driver)
driver_element = driver.find_element_by_xpath("sport_history_item_xpath") action1.long_press(driver_element).wait(i * 1000).perform() // i为长按控件的时间,单位秒

(6)keyevent事件(android only)

  在Android keyevent事件中,不同的值代表了不同的含义和功能,比如手机的返回键:keyevent(4); 手机的HOME键: keyevent(3)等等,具体keyevent与对应值关系请参考http://blog.csdn.net/yun90/article/details/51036544

四、元素事件类API

(1) reset

def reset(self):
"""Resets the current application on the device.
"""
self.execute(Command.RESET
return self

reset()

用法:driver.reset(),重置应用(类似删除应用数据),如首次登录app时出现的引导页,则可以用reset来实现需求。

(2) is_app_installed

 def is_app_installed(self, bundle_id):
"""Checks whether the application specified by `bundle_id` is installed
on the device. :Args:
- bundle_id - the id of the application to query
"""
data = {
'bundleId': bundle_id,
}
return self.execute(Command.IS_APP_INSTALLED, data)['value']

is_app_installed()

检查app是否有安装 返回 True or False。例如:在微信登录时,选择登录方式时会判断是否已安装微信,若未安装则有dialog弹框,已安装则跳转到微信登录页面,

driver.find_element_by_id("weixin_login_button").click()
if driver.is_app_installed("weixin.apk"):
// To do input User, Passwd
else:
// show dialog

(3)install_app

def install_app(self, app_path):
"""Install the application found at `app_path` on the device. :Args:
- app_path - the local or remote path to the application to install
"""
data = {
'appPath': app_path,
}
self.execute(Command.INSTALL_APP, data)
return self

install_app()

接上个例子,若未安装微信出现dialog弹框,检查完dialog后再安装微信app。特别说明:例子中的"weixin.apk"是指app_path + package_name,

driver.find_element_by_id("weixin_login_button").click()
if driver.is_app_installed("weixin.apk"):
// To do input User, Passwd
else:
check_dialog()
driver.install_app("weixin.apk") 

(4) remove_app

 def remove_app(self, app_id):
"""Remove the specified application from the device. :Args:
- app_id - the application id to be removed
"""
data = {
'appId': app_id,
}
self.execute(Command.REMOVE_APP, data)
return self

remove_app()

在测试老版本兼容用例时,用老版本替换新版本时,需要卸载新版本,再安装老版本,所以需要调用到此方法,

driver.remove_app("new_app.apk")  # 卸载
driver.install_app("old_app.apk") # 安装

(5) launch_app

 def launch_app(self):
"""Start on the device the application specified in the desired capabilities.
"""
self.execute(Command.LAUNCH_APP)
return self

launch_app()

打开一个capabilities配置的设备应用。此方法目前并没有使用。待以后用到时再来做更新。

(6) close_app

 def close_app(self):
"""Stop the running application, specified in the desired capabilities, on
the device.
"""
self.execute(Command.CLOSE_APP)
return self

close_app()

关闭app应用程序。此方法常用在代码末尾,在清理和释放对象时使用。结合unittest框架常见tearDown()里使用,

import unittest

class demo(unittest.TestCase):
def setUp(self):
pass def tearDown(self):
driver.close_app()
driver.quit()

(7) start_activity

def start_activity(self, app_package, app_activity, **opts):
"""Opens an arbitrary activity during a test. If the activity belongs to
another application, that application is started and the activity is opened. This is an Android-only method. :Args:
- app_package - The package containing the activity to start.
- app_activity - The activity to start.
- app_wait_package - Begin automation after this package starts (optional).
- app_wait_activity - Begin automation after this activity starts (optional).
- intent_action - Intent to start (optional).
- intent_category - Intent category to start (optional).
- intent_flags - Flags to send to the intent (optional).
- optional_intent_arguments - Optional arguments to the intent (optional).
- stop_app_on_reset - Should the app be stopped on reset (optional)?
"""
data = {
'appPackage': app_package,
'appActivity': app_activity
}
arguments = {
'app_wait_package': 'appWaitPackage',
'app_wait_activity': 'appWaitActivity',
'intent_action': 'intentAction',
'intent_category': 'intentCategory',
'intent_flags': 'intentFlags',
'optional_intent_arguments': 'optionalIntentArguments',
'stop_app_on_reset': 'stopAppOnReset'
}
for key, value in arguments.items():
if key in opts:
data[value] = opts[key]
self.execute(Command.START_ACTIVITY, data)
return self

start_activity()

此方法适用于测试中需使用两个及以上的app程序。例如,在运动相关的测试时,首先需要打开Gps模拟打点工具,开始打点。然后打开咕咚选择运动类型开始运动,那么可以在启动capabilities配置时打开Gps工具,开启配速打点后再打开咕咚app,

driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps={'platformName': 'Android',
'deviceName': 'Android Mechine',
'appPackage': ' Package of GpsTools',
'unicodeKeyboard':True,
'resetKeyboard':True,
'noReset':True,
'appActivity': 'activity of GpsTools'}) # TO DO Gps Mock action driver.start_activity("com.codoon.gps", "ui.login.welcomeActivity")

(8) wait_activity

 def wait_activity(self, activity, timeout, interval=1):
"""Wait for an activity: block until target activity presents
or time out. This is an Android-only method. :Agrs:
- activity - target activity
- timeout - max wait time, in seconds
- interval - sleep interval between retries, in seconds
"""
try:
WebDriverWait(self, timeout, interval).until(
lambda d: d.current_activity == activity)
return True
except TimeoutException:
return False

wait_activity()

此方法适属于appium等待方法的一种。不论是webdriver还是appium,等待方法分为三种类型:显式等待、隐式等待,time.sleep;从wait_activity的源码可以看出,是属于隐式等待。有关等待方式以后可以另开专题详细说明,这里不做赘述。

  此方法主要使用在需要网络加载时的等待,比如在用户登录作为前提条件时,wait_activity接受三个参数: 需要等待加载的activity的名称,timeout超时时间(秒),检测间隔时间(秒),

driver.login_action()
driver.wait_activity("homepage.activity", 30, 1)
driver.find_element_by_id("我的").click()

其含义是,等待加载app的homepage的activity出现,等待最长时间30秒,每隔1秒检测一次当前的activity是否等于homepage的activity。若是,则推出等待,执行点击我的tab的action;若否,则继续等待,30秒后提示超时抛出异常。

四、其他(此类别下主要对上述没有提到的api方法的补充)

(1) 截屏

 def get_screenshot_as_file(self, filename):
"""
Gets the screenshot of the current window. Returns False if there is
any IOError, else returns True. Use full paths in your filename. :Args:
- filename: The full path you wish to save your screenshot to. :Usage:
driver.get_screenshot_as_file('/Screenshots/foo.png')
"""
png = self.get_screenshot_as_png()
try:
with open(filename, 'wb') as f:
f.write(png)
except IOError:
return False
finally:
del png
return True

get_screenshot_as_file()

用法:driver.get_screenshot_as_file('../screenshot/foo.png'),接受参数为保存的图片路径和名称

(2)size 和 location

 def size(self):
"""The size of the element."""
size = {}
if self._w3c:
size = self._execute(Command.GET_ELEMENT_RECT)
else:
size = self._execute(Command.GET_ELEMENT_SIZE)['value']
new_size = {"height": size["height"],
"width": size["width"]}
return new_size

size()

 def location(self):
"""The location of the element in the renderable canvas."""
if self._w3c:
old_loc = self._execute(Command.GET_ELEMENT_RECT)
else:
old_loc = self._execute(Command.GET_ELEMENT_LOCATION)['value']
new_loc = {"x": round(old_loc['x']),
"y": round(old_loc['y'])}
return new_loc

location()

size 和 location是对element位置和尺寸的获取,这两个属性主要运用在有可划动的控件,如完善个人资料页,生日、身高和体重都需要划动。之前我们提到的swipe和flick是针对设备屏幕进行划动,显然在这里不适用。而且没有一个特定的方法,所以需要我们自己针对可划动控件进行划动,

 def swipe_control(self, by, value, heading):
"""
:Usage: 实现界面某些控件元素的上下左右的滑动取值
:param driver: Appium驱动
:param by: 元素的定位方式,如By.ID、By.XPATH等...
:param value: 元素的定位值,根据不同的定位方式表达不同
:param heading: 滑动的方位,包括'UP','DOWN','LEFT','RIGHT'
"""
# "获取控件开始位置的坐标轴"
start = self.driver.find_element(by=by, value=value).location
startX = start.get('x')
startY = start.get('y')
# "获取控件坐标轴差"
q = self.driver.find_element(by=by, value=value).size
x = q.get('width')
y = q.get('height')
# "计算出控件结束坐标"
if startX < 0:
startX = 0
endX = x + startX
endY = y + startY
# "计算中间点坐标"
if endX > 720:
endX = 720
centreX = (endX + startX) / 2
centreY = (endY + startY) / 2 # "定义swipe的方向"
actions = {
'UP': self.driver.swipe(centreX, centreY + 65, centreX, centreY - 65, 450),
'DOWN': self.driver.swipe(centreX, centreY - 65, centreX, centreY + 65, 450),
'LEFT': self.driver.swipe(centreX + 65, centreY, centreX - 65, centreY, 450),
'RIGHT': self.driver.swipe(centreX - 65, centreY, centreX + 65, centreY, 450),
}
# "Take a action"
actions.get(heading)

swipe_control()

(3)获取控件各种属性

def get_attribute(self, name):
"""
:Args:
- name - Name of the attribute/property to retrieve. Example:: # Check if the "active" CSS class is applied to an element.
is_active = "active" in target_element.get_attribute("class")
"""

用法: driver.find_element_by_id().get_attribute(name),name即是左侧的标志(class,package,checkable,checked....),返回值为str类型,即便是true or false,但是其实是"true" or "false"

移动端自动化测试(二)之 Appium常用的API(python)函数介绍

(4)pull_file

 def pull_file(self, path):
"""Retrieves the file at `path`. Returns the file's content encoded as
Base64. :Args:
- path - the path to the file on the device
"""
data = {
'path': path,
}
return self.execute(Command.PULL_FILE, data)['value']

pull_file()

将设备上的文件pull到本地硬盘上,在手机号注册时需要获取手机验证码,此时的实现方式是用另一个apk提取到验证码存在手机内存中,再用pull_file获取到验证码内容,使得appium可以将正确的验证码填入。

  

  本章节Appium常用的一些API函数,日后有需要会慢慢地进行补充。虽然不能面面俱到,但在实际项目中涉及到的都已经差不多提到了。当我们对某个功能进行测试的时候,首先要对其进行操作,这个时候就要考虑到找到相应的对象元素,调用具体的事件类函数,验证结果的时候,我们要检测操作产生的结果是不是与我们预期的一致?那这就要去考虑相应的Assert函数(即断言)了。所以记住这六字箴言:对象-事件-断言,便可以使你可以着手对任何一个App编写对应的自动化测试用例了。