Спойлер

воскресенье, 24 февраля 2019 г.

Поиск элементов для нативных и гибридных приложений (Appium)

Есть множество способов найти элементы для нативных и гибридных приложений, такие как UIAutomatorviewer (для Android) и Appium Inspector. Начнем с первого.



Поиск элементов с UIAutomatorviewer


UIAutomatorviewer можно найти в папке Android SDK (C:\%android-sdk%\tools); на Mac можно найти в папке tools:



При открытии, вы увидите такой экран:



Рассмотрим пример со стандартным калькулятором Android:

  1. Откройте эмулятор Android или реальное устройство.
  2. Запустите калькулятор.
  3. В окне UIAutomatorviewer, кликните на иконку скриншота девайса. Если запущено больше одного устройства, UIAutomatorviewer попросит вас выбрать девайс.


Теперь нужно найти элементы приложения, используя разные локаторы.

Поиск по ID


Сигнатура метода такая же, как поиск элемента по ID в web-приложении:

findElement(By.id(String id));

В метод передается ID элемента, с которым мы хотим работать. Ниже пример идентификации клавиши «5» в калькуляторе с использованием UI Automator Viewer:

  1. Открыть UI Automator Viewer и нажать на клавишу «5» в приложении.
  2. В разделе Node Details, вы получите resource-id вида com.android.calculator2:id/digit5:

  3. Мы можем resource-id как ID, чтобы взаимодействовать с клавишей:

    WebElement digit_5=driver.findElement(By.id("com.android.calculator2:id/digit5"));
  4. Чтобы кликнуть на клавишу, используйте команду:

    digit_5.click();

Поиск по name


Сигнатура метода нам уже знакома:

findElement(By.name(String Name));

Нужно передать имя элемента, с которым хотим работать. Ниже пример поиска кнопки DELETE:

  1. Кликнуть на кнопку DELETE в UI Automator Viewer.
  2. В разделе Node Details, вы увидите поле text со значением DELETE:

  3. Чтобы найти и кликнуть кнопку DELETE, используйте следующий код:

    delete.click();
      WebElement delete=driver.findElement(By.name("DELETE"));

Поиск по className


Сигнатура:

findElement(By.className(String ClassName));

Ниже пример поиска окна ввода по className:

  1. Кликнуть на EditBox в UI Automator Viewer.
  2. В разделе Node Detail, найти class со значением android.widget.EditText:

  3. Пример поиска элемента по className:

    WebElement editBox=driver.findElement(By.className("android.widget.EditText"));
  4. Чтобы получить значение элемента EditBox, используйте команду:
    editBox.getText();

Если этот класс используется для нескольких элементов, мы можем обратиться к элементу по индексу в возвращаемой коллекции. Например, мы хотим обратится к клавише «7» по имени класса:

List<WebElement> editBox=driver.findElements(By.className("android.widget.Button"));
  editBox.get(1).click();

Мы использовали метод findElements вместо findElement; так мы получим больше одного элемента по селектору. В нашем примере, у клавиши «7» значение индекса — 1. Поэтому, мы обратились к 1му элементу.

Поиск по AccessibilityId


Разработчики Appium хотели дать нам больше возможностей для локализации элементов, поэтому они создали AccessibilityId. Этот локатор определяет элементы так же, как ID и name. Сигнатура метода:

findElement(By.AccessibilityId(String AccId));

Ниже пример взаимодействия к кнопкой "+":

  1. Откройте UI Automator Viewer и кликните в калькуляторе на "+".
  2. В разделе Node Details, вы найдете content-desc со значением «plus»:

  3. Этот content-desc можно использовать как AccId:

    WebElement plusSign=driver. findElementByAccessibilityId("plus");
              plusSign.click();

Поиск по AndroidUIAutomator


AndroidUIAutomator очень мощный локатор. Он использует библиотеку Android UIAutomator для поиска элементов. 

findElement(By.AndroidUIAutomator(String UIAuto));

Ниже пример взаимодействия с кнопкой "=":

  1. В UI Automator Viewer кликните на "=".
  2. В Node details мы можем выбрать любое поле. Например, resource-id со значением com.android.calculator2:id/equal. Мы можем использовать resource-id как UIAuto для работы с клавишей "=":

    WebElement equal=driver. findElementByAndroidUIAutomator("new UiSelector().resourceId(\"com.android.calculator2:id/equal\")";
  3. Другой пример — выбрать content-desc со значением equals, теперь команда будет выглядеть так:

    WebElement equal=driver. findElementBy.AndroidUIAutomator("new UiSelector().description(\"equals\")");

    Чтобы узнать больше об этом локаторе, посетите эту и эту страницу.

Поиск элементов с Appium Inspector


В предыдущей главе мы уже узнали, что Appium Inspector хорошо работает на Mac. Работая на Mac, мы можем его использовать для поиска элементов. Чтобы запустить Appium Inspector для Android, нам нужно выполнить следующие шаги:

  1. Нужно определить путь до приложения, пакета или имя активити в Appium GUI при работе с эмулятором. Если работаем с девайсом, достаточно имени пакета или активити.

    Как определить имя пакета или активити, если приложение выполняется на девайсе? Можете установить на девайс APK Info из Play Store. Если у вас есть тестируемое приложение на компьютере, то Appium server автоматически подтянет все имена после указания пути к приложени.
  2. В разделе General Settings, должна быть выбрана опция Prelaunch Application.
  3. Если вы работаете с эмулятором, тогда должна быть выбрана опция Launch AVD в разделе Android Settings (предполагается, что эмулятор вы уже создали). Если же вы работаете с девайсом, он должен быть подключен и должен быть разрешен USB debugging.
  4. Нажмите на кнопку запуска.
  5. Нажмите кнопку Inspector. Запустится Appium Inspector.


Мы уже изучили много способов нахождения элементов. Сейчас мы воспользуемся поиском по Xpath

Поиск по Xpath


Сигнатура:

findElement(By.xpath(String XPath));

Ниже пример работы с клавишей «9»:

WebElement digit_9=driver.findElement(By.xpath("//android.widget.LinearLayout[1]/ android.widget.FrameLayout[1]/ android.widget.LinearLayout[1]/ android.support.v4.view.viewPager[1]/ android.widget.LinearLayout[1]/ android.widget.LinearLayout[1]/ android.widget.Button[3]"));



Вы можете работать с переменной digit_9, чтобы взаимодействовать с элементом.
Теперь о том, как работать с Appium Inspector для iOS:

  1. В Appium GUI нужно указать путь до приложения.
  2. Опция Prelaunch Application должна быть включена ( в разделе General Settings).
  3. Если вы работаете с симулятором, должна быть еще и включена опция Force Device в разделе iOS Settings.
  4. Нажмите на кнопку запуска.
  5. Нажмите на кнопку Inspector.

В примере мы будем работать с TestApp, его можно скачать с Appium GitHub.

Поиск по name


Сигнатура метода:

findElement(By.name(String Name));

Ниже пример работы со вторым EditBox в приложении TestApp:

  1. Кликните на второй EditBox в Appium Inspector.
  2. В вкладке Details найдите поле name со значением IntegerB. Мы можем использовать значение для обнаружения второго EditBox:

    WebElement editBox=driver.findElement(By.name("IntegerB"));
  3. Чтобы ввести текст в EditBox, используйте команду:

    editBox.sendKeys("12");


Поиск по IosUIAutomation


UIAutomation — JavaScript библиотека, использующаяся для поиска элементов в Apple's Automation Instruments. Разработчики Appium дали нам похожий способ поиска элементов в Appium, используя IosUIAutomation:

findElements(By.IosUIAutomation(String IosUIAuto));

Для того, чтобы начать использовать IosUIAutomation, нужно:

  1. Нужно передать значение IosUIAuto для элемента, с которым хотим работать. Ниже пример поиска первого EditBox в приложении TestApp:

    WebElement editBox=driver. findElements(By.IosUIAutomation(".elements()[0]")); //Здесь '0' - это индекс элемента
  2. Чтобы ввести текст в первый EditBox, используем команду:

    editBox.sendKeys("10");
  3. Другой пример — поиск элемента по textFields:

    WebElement editBox=driver. findElements(By.IosUIAutomation(".textFields()[0]"));

Чтобы узнать больше о библиотеке UIAutomation, посетите эту страницу.



Вот и все. пришло время автоматизировать наше приложение. В следующей главе, мы будем работать с Appium driver.



UiSelector

public class UiSelector 
extends Object 
java.lang.Object
   ↳android.support.test.uiautomator.UiSelector


Specifies the elements in the layout hierarchy for tests to target, filtered by properties such as text value, content-description, class name, and state information. You can also target an element by its location in a layout hierarchy.

Summary

Public constructors

UiSelector()

Public methods

UiSelectorcheckable(boolean val)
Set the search criteria to match widgets that are checkable.
UiSelectorchecked(boolean val)
Set the search criteria to match widgets that are currently checked (usually for checkboxes).
UiSelectorchildSelector(UiSelector selector)
Adds a child UiSelector criteria to this selector.
UiSelectorclassName(String className)
Set the search criteria to match the class property for a widget (for example, "android.widget.Button").
<T> UiSelectorclassName(Class<T> type)
Set the search criteria to match the class property for a widget (for example, "android.widget.Button").
UiSelectorclassNameMatches(String regex)
Set the search criteria to match the class property for a widget, using a regular expression.
UiSelectorclickable(boolean val)
Set the search criteria to match widgets that are clickable.
UiSelectordescription(String desc)
Set the search criteria to match the content-description property for a widget.
UiSelectordescriptionContains(String desc)
Set the search criteria to match the content-description property for a widget.
UiSelectordescriptionMatches(String regex)
Set the search criteria to match the content-description property for a widget.
UiSelectordescriptionStartsWith(String desc)
Set the search criteria to match the content-description property for a widget.
UiSelectorenabled(boolean val)
Set the search criteria to match widgets that are enabled.
UiSelectorfocusable(boolean val)
Set the search criteria to match widgets that are focusable.
UiSelectorfocused(boolean val)
Set the search criteria to match widgets that have focus.
UiSelectorfromParent(UiSelector selector)
Adds a child UiSelector criteria to this selector which is used to start search from the parent widget.
UiSelectorindex(int index)
Set the search criteria to match the widget by its node index in the layout hierarchy.
UiSelectorinstance(int instance)
Set the search criteria to match the widget by its instance number.
UiSelectorlongClickable(boolean val)
Set the search criteria to match widgets that are long-clickable.
UiSelectorpackageName(String name)
Set the search criteria to match the package name of the application that contains the widget.
UiSelectorpackageNameMatches(String regex)
Set the search criteria to match the package name of the application that contains the widget.
UiSelectorresourceId(String id)
Set the search criteria to match the given resource ID.
UiSelectorresourceIdMatches(String regex)
Set the search criteria to match the resource ID of the widget, using a regular expression.
UiSelectorscrollable(boolean val)
Set the search criteria to match widgets that are scrollable.
UiSelectorselected(boolean val)
Set the search criteria to match widgets that are currently selected.
UiSelectortext(String text)
Set the search criteria to match the visible text displayed in a widget (for example, the text label to launch an app).
UiSelectortextContains(String text)
Set the search criteria to match the visible text in a widget where the visible text must contain the string in your input argument.
UiSelectortextMatches(String regex)
Set the search criteria to match the visible text displayed in a layout element, using a regular expression.
UiSelectortextStartsWith(String text)
Set the search criteria to match visible text in a widget that is prefixed by the text parameter.
StringtoString()

Protected methods

UiSelectorcloneSelector()

Inherited methods

From class java.lang.Object

Public constructors

UiSelector

UiSelector ()

Public methods

checkable

UiSelector checkable (boolean val)
Set the search criteria to match widgets that are checkable. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.
Parameters
valboolean: Value to match
Returns
UiSelectorUiSelector with the specified search criteria

checked

UiSelector checked (boolean val)
Set the search criteria to match widgets that are currently checked (usually for checkboxes). Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.
Parameters
valboolean: Value to match
Returns
UiSelectorUiSelector with the specified search criteria

childSelector

UiSelector childSelector (UiSelector selector)
Adds a child UiSelector criteria to this selector. Use this selector to narrow the search scope to child widgets under a specific parent widget.
Returns
UiSelectorUiSelector with this added search criterion

className

UiSelector className (String className)
Set the search criteria to match the class property for a widget (for example, "android.widget.Button").
Parameters
classNameString: Value to match
Returns
UiSelectorUiSelector with the specified search criteria

className

UiSelector className (Class<T> type)
Set the search criteria to match the class property for a widget (for example, "android.widget.Button").
Parameters
typeClass: type
Returns
UiSelectorUiSelector with the specified search criteria

classNameMatches

UiSelector classNameMatches (String regex)
Set the search criteria to match the class property for a widget, using a regular expression.
Parameters
regexString: a regular expression
Returns
UiSelectorUiSelector with the specified search criteria

clickable

UiSelector clickable (boolean val)
Set the search criteria to match widgets that are clickable. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.
Parameters
valboolean: Value to match
Returns
UiSelectorUiSelector with the specified search criteria

description

UiSelector description (String desc)
Set the search criteria to match the content-description property for a widget. The content-description is typically used by the Android Accessibility framework to provide an audio prompt for the widget when the widget is selected. The content-description for the widget must match exactly with the string in your input argument. Matching is case-sensitive.
Parameters
descString: Value to match
Returns
UiSelectorUiSelector with the specified search criteria

descriptionContains

UiSelector descriptionContains (String desc)
Set the search criteria to match the content-description property for a widget. The content-description is typically used by the Android Accessibility framework to provide an audio prompt for the widget when the widget is selected. The content-description for the widget must contain the string in your input argument. Matching is case-insensitive.
Parameters
descString: Value to match
Returns
UiSelectorUiSelector with the specified search criteria

descriptionMatches

UiSelector descriptionMatches (String regex)
Set the search criteria to match the content-description property for a widget. The content-description is typically used by the Android Accessibility framework to provide an audio prompt for the widget when the widget is selected. The content-description for the widget must match exactly with the string in your input argument.
Parameters
regexString: a regular expression
Returns
UiSelectorUiSelector with the specified search criteria

descriptionStartsWith

UiSelector descriptionStartsWith (String desc)
Set the search criteria to match the content-description property for a widget. The content-description is typically used by the Android Accessibility framework to provide an audio prompt for the widget when the widget is selected. The content-description for the widget must start with the string in your input argument. Matching is case-insensitive.
Parameters
descString: Value to match
Returns
UiSelectorUiSelector with the specified search criteria

enabled

UiSelector enabled (boolean val)
Set the search criteria to match widgets that are enabled. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.
Parameters
valboolean: Value to match
Returns
UiSelectorUiSelector with the specified search criteria

focusable

UiSelector focusable (boolean val)
Set the search criteria to match widgets that are focusable. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.
Parameters
valboolean: Value to match
Returns
UiSelectorUiSelector with the specified search criteria

focused

UiSelector focused (boolean val)
Set the search criteria to match widgets that have focus. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.
Parameters
valboolean: Value to match
Returns
UiSelectorUiSelector with the specified search criteria

fromParent

UiSelector fromParent (UiSelector selector)
Adds a child UiSelector criteria to this selector which is used to start search from the parent widget. Use this selector to narrow the search scope to sibling widgets as well all child widgets under a parent.
Returns
UiSelectorUiSelector with this added search criterion

index

UiSelector index (int index)
Set the search criteria to match the widget by its node index in the layout hierarchy. The index value must be 0 or greater. Using the index can be unreliable and should only be used as a last resort for matching. Instead, consider using the instance(int) method.
Parameters
indexint: Value to match
Returns
UiSelectorUiSelector with the specified search criteria

instance

UiSelector instance (int instance)
Set the search criteria to match the widget by its instance number. The instance value must be 0 or greater, where the first instance is 0. For example, to simulate a user click on the third image that is enabled in a UI screen, you could specify a a search criteria where the instance is 2, the className(String) matches the image widget class, and enabled(boolean)is true. The code would look like this: new UiSelector().className("android.widget.ImageView") .enabled(true).instance(2);
Parameters
instanceint: Value to match
Returns
UiSelectorUiSelector with the specified search criteria

longClickable

UiSelector longClickable (boolean val)
Set the search criteria to match widgets that are long-clickable. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.
Parameters
valboolean: Value to match
Returns
UiSelectorUiSelector with the specified search criteria

packageName

UiSelector packageName (String name)
Set the search criteria to match the package name of the application that contains the widget.
Parameters
nameString: Value to match
Returns
UiSelectorUiSelector with the specified search criteria

packageNameMatches

UiSelector packageNameMatches (String regex)
Set the search criteria to match the package name of the application that contains the widget.
Parameters
regexString: a regular expression
Returns
UiSelectorUiSelector with the specified search criteria

resourceId

UiSelector resourceId (String id)
Set the search criteria to match the given resource ID.
Parameters
idString: Value to match
Returns
UiSelectorUiSelector with the specified search criteria

resourceIdMatches

UiSelector resourceIdMatches (String regex)
Set the search criteria to match the resource ID of the widget, using a regular expression.
Parameters
regexString: a regular expression
Returns
UiSelectorUiSelector with the specified search criteria

scrollable

UiSelector scrollable (boolean val)
Set the search criteria to match widgets that are scrollable. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.
Parameters
valboolean: Value to match
Returns
UiSelectorUiSelector with the specified search criteria

selected

UiSelector selected (boolean val)
Set the search criteria to match widgets that are currently selected. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.
Parameters
valboolean: Value to match
Returns
UiSelectorUiSelector with the specified search criteria

text

UiSelector text (String text)
Set the search criteria to match the visible text displayed in a widget (for example, the text label to launch an app). The text for the element must match exactly with the string in your input argument. Matching is case-sensitive.
Parameters
textString: Value to match
Returns
UiSelectorUiSelector with the specified search criteria

textContains

UiSelector textContains (String text)
Set the search criteria to match the visible text in a widget where the visible text must contain the string in your input argument. The matching is case-sensitive.
Parameters
textString: Value to match
Returns
UiSelectorUiSelector with the specified search criteria

textMatches

UiSelector textMatches (String regex)
Set the search criteria to match the visible text displayed in a layout element, using a regular expression. The text in the widget must match exactly with the string in your input argument.
Parameters
regexString: a regular expression
Returns
UiSelectorUiSelector with the specified search criteria

textStartsWith

UiSelector textStartsWith (String text)
Set the search criteria to match visible text in a widget that is prefixed by the text parameter. The matching is case-insensitive.
Parameters
textString: Value to match
Returns
UiSelectorUiSelector with the specified search criteria

toString

String toString ()
Returns
String

Protected methods


cloneSelector

UiSelector cloneSelector ()
Returns
UiSelector

Комментариев нет:

Отправить комментарий