appium automate common API

Common Functions

First, access to information like API

(1) the name of the current page acquisition activity, such as: (.ui.login.ViewPage)

  current_activity()

 For example, we need to implement this function login, the main idea is if the current interface is the login page, then log in behavior, or to jump to the login page. Which is a pseudo-code:

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

 

(2) Get current page tree structure of the source code, and screen shots illustrated uiautomatorviewer out structure is the same

  page_source()

For example when we complete the login process to determine whether the login is successful, it may be determined after the login page appears there is no specific content (such as: sports circle, discovery, sports, shopping mall, I), its pseudo-code to achieve the following:

Copy the code
Driver \ 
    .page_source.find (U "the bead")! = -1 and 
    .page_source.find (U "discovery")! = -1 and 
    .page_source.find (U "motion")! = -1 and 
    .page_source .find (u "Mall")! = -1 and 
    .page_source.find (U "my")! = -1 and
Copy the code

page_source () return data type str. the python, the Find str (context) method, if the return value str present context str index in the context, and if not, return value is -1. It is only necessary to determine the return boolean above code block is True or False, you can determine whether the login is successful.

 

(3) the name of the current window to get all the context of

  contexts()

 When mixed native and html5 page test, you need to native H5 layer and layer switching, so you first need to get the name of context hierarchy

print driver.contexts
>>> ['NATIVE_APP', 'WEBVIEW_com.codoon.gps']

Thus, we know the name App H5 layer after as "WEBVIEW_com.codoon.gps", using driver.switch_to.context ( "WEBVIEW_com.codoon.gps") can be achieved NATIVE and switched H5 layer.

 

Second, get control class API

(1) the current page to find a target element by element id

  find_element_by_id()

 Notes find_element_by_id source can be obtained by this type of use api there are two main ways:

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

Look under the driver through the id of an element, this usage is generally applicable to the current interface driver and only one unique id element indicated by calling find_element_by_id be accurate to find the target element; another way to use mainly as follows:

Copy the code

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") 

Copy the code

In driver.find_element_by_xpath returned driverElement type, call find_element_by_id child elements in driverElement to match the target id element.

Pictured uiautomatorviewer of id, name, class of illustration. Special note: If the id, name, xpath and other elements of the current driver in the target or driverElement looking for is not the only element, this time calling find_element_by_id (name \ xpath), will return the first element to find matches.

 

(2) Find more target elements of the current page element by id

  find_elements_by_id()

Finding a plurality of target elements in the id driver, its return value type list. This usage is generally applicable Item query have the same layout configuration listView, LinearLayout, RelativeLayout equal to the current Driver; in addition to the same driver, at page driverElement may hop to match with 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 method with the return type of the function key list data types are only examples of a series of methods find_element (s) and the like driverelement the driver, the type of list is not used find_element (s) Method of positioning data. May be encountered in actual projects such problems, only traverse the list, remove each element to instantiate the object and then to find positioning elements.

 

(3) name of the current page to find an element by element

  find_element_by_name()

Find_element_by_id use the same, but the match condition changes by id name. Please call the way of reference 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) Find more target element by element name of the current page

  find_elements_by_name()

Find_elements_by_id use the same, but the match condition changes by id name. Please refer to the invocation find_elements_by_id, pay attention to the return data type is a List, not 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 to find a target element by element current page

  find_element_by_xpath()

About find_element_by_xpath call method by id, name is slightly different, relevant knowledge about Xpath the time being is not the table in this section, if any subsequent practice in the project needs and then start a new presentation.

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

In Appium in, xpath required relevant lib library is not fully supported, so is the use of two or more (that is only supported in the driver's xpath match). The current version can not support xpath Appium look at driverelement, such as

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

 According to the above wording Appium'll get an error because ".find_element_by_xpath (" // android.widget.TextView [contains (@text, 'start')] ")" can not find the child element in the Element.

 

(6) Find more target elements of the current page by elemental xpath

  find_elements_by_xpath()

 Referring find_element_by_xpath call mode, note that the return type is List, the use of reference find_elements_by_name () Examples

 

(7) Find an element by element of the current page class name

  find_element_by_class_name()

In a real project, test app in class name and not as a unique identifier positioning interface, there is little use in driver class name to view elements in practice, look at driverelement child element with class name is the correct usage.

 

(8) Find an element by element current page accessibility_id (content-desc)

  find_element_by_accessibility_id()

In the uiautomatorviewer, content-desc content shall accessibility_id, selenium in the library can be used find_element_by_name () to match the content of the content-desc; Appium in the library with find_element_by_accessibility_id () to match the content of the content-desc. Selenium because Appium inherited class, so if find_element_by_name not accurate positioning, please try find_element_by_accessibility_id.

   Commonly used to obtain control class API is more than that. Other search and matching api also 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 other usage is similar to the above.

 

Third, the operation element based API

   When we realize the PC browser Webdriver automation, for the operation target on the page are: Click (click), double-click (double_click), scrolling (scroll), input (send_keys), and mobile terminal-specific helper classes api: a tap (tap) - supports multi-touch slide (swipe), amplifying elements (pinch-), reduction element (zoom)

(1) Click event 

  click()
  tap()

click, click and tap can achieve results. The difference is that the click driverelement acting on the object is instantiated, while the tap is a coordinate position on the screen is clicked. The former position is not sensitive to changes in the elements, while the latter is to click on specific pixel coordinates, the position of the element by the resolution and greater impact.

 

(2) the input event

  send_keys()
  set_text()

 send_keys and set_text also able to meet the operational input text content. The difference is that the current system send_keys calls the device keyboard input methods, and set_text text directly on the target element. Thus it can be pushed, the input content send_keys often inconsistent and expectations, and enter set_text is a direct assignment, not keyboard events.

 

(3) slide (scroll) event

  swipe() 
  flick()

swipe and flick operations are sliding, they are designated from [start_x, start_y] to [end_x, end_y] process, the only difference is a swipe more than flick duration parameter, with the parameter from the start can customize to end the operation duration of action to achieve a slow sliding or swiping effect.

 

(4) zoom events

  pinch()
  zoom()

The default target element will be reduced by half or double the zoom operation, this method is suitable for api changes in testing sports map scaling.

 

(5) press event

  long_press()

TouchAction press method in the class, so that when in use need to import TouchAction. When delete sports history, recorded in a long list and press Delete

= TouchAction action1 (self.driver) 
driver_element = driver.find_element_by_xpath ( "sport_history_item_xpath") 

action1.long_press (driver_element) .wait (I * 1000) .perform () // I control is the long press time in seconds

 

(6) keyevent event (android only)

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

 

四、元素事件类API

(1) reset

  reset()

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

 

(2) is_app_installed

  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

  install_app()

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

Copy the code
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") 
Copy the code

 

(4) remove_app

  remove_app()

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

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

 

(5) launch_app

  launch_app()

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

 

(6) close_app

  close_app()

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

Copy the code
import unittest

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

 

(7) start_activity

  start_activity()

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

Copy the code
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")
Copy the code

  

(8) wait_activity

  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) 截屏

  get_screenshot_as_file()

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

 

(2)size 和 location

  size()
  location()

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

  swipe_control()

 

(3) gets control of various properties

  View Code

Usage:. Driver.find_element_by_id () get_attribute (name), name that is the mark on the left (class, package, checkable, checked ....), the return value is str type, even if true or false, but actually " true "or" false "

 

 

(4)pull_file

  pull_file()

Pull the file on the device to the local hard disk, you need to get the phone code when the phone number registered at this time of implementation is extracted with another apk to the verification code in the phone memory, then pull_file to get verification code content, appium such codes can be correctly filled.

  

  This section Appium some common API functions, in the future there will need to be supplemented slowly. Although not exhaustive, but in practice involved in the project it has been almost mentioned. When we test for a feature, we must first manipulate it, this time we should take into account the elements to find the corresponding object, call a specific event class function, verify the results, we want to produce the result of the operation is detected It is not consistent with our expectations? This is going to consider that the appropriate Assert function (ie, assertions) a. So keep that in Liuzizhenyan: Object - Event - assertion, it can allow you to proceed to any App written in the corresponding automated test cases.

Guess you like

Origin www.cnblogs.com/dreamhighqiu/p/10989994.html