androidx.test.uiautomator.By Java Examples
The following examples show how to use
androidx.test.uiautomator.By.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AlertHelpers.java From appium-uiautomator2-server with Apache License 2.0 | 6 votes |
@Nullable private static UiObject2 getRegularAlertButton(AlertAction action, @Nullable String buttonLabel) { final Map<String, UiObject2> alertButtonsMapping = new HashMap<>(); final List<Integer> buttonIndexes = new ArrayList<>(); for (final UiObject2 button : getUiDevice().findObjects(By.res(regularAlertButtonResIdPattern))) { final String resId = button.getResourceName(); alertButtonsMapping.put(resId, button); buttonIndexes.add(Integer.parseInt(resId.substring(regularAlertButtonResIdPrefix.length()))); } if (alertButtonsMapping.isEmpty()) { return null; } Log.d(TAG, String.format("Found %d buttons on the alert", alertButtonsMapping.size())); if (buttonLabel != null) { return filterButtonByLabel(alertButtonsMapping.values(), buttonLabel); } final int minIdx = Collections.min(buttonIndexes); return action == AlertAction.ACCEPT ? alertButtonsMapping.get(buttonResIdByIdx(minIdx)) : alertButtonsMapping.get(buttonResIdByIdx(alertButtonsMapping.size() > 1 ? minIdx + 1 : minIdx)); }
Example #2
Source File: ChangeTextBehaviorTest.java From testing-samples with Apache License 2.0 | 6 votes |
@Before public void startMainActivityFromHomeScreen() { // Initialize UiDevice instance mDevice = UiDevice.getInstance(getInstrumentation()); // Start from the home screen mDevice.pressHome(); // Wait for launcher final String launcherPackage = getLauncherPackageName(); assertThat(launcherPackage, notNullValue()); mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT); // Launch the blueprint app Context context = getApplicationContext(); final Intent intent = context.getPackageManager() .getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); // Clear out any previous instances context.startActivity(intent); // Wait for the app to appear mDevice.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)), LAUNCH_TIMEOUT); }
Example #3
Source File: ElementHelpers.java From appium-uiautomator2-server with Apache License 2.0 | 6 votes |
private static int getTouchPadding(AndroidElement element) throws UiObjectNotFoundException, ReflectiveOperationException { final UiObject2 uiObject2 = element instanceof UiObject2Element ? getUiDevice().findObject(By.clazz(((UiObject2) element.getUiObject()).getClassName())) : getUiDevice().findObject(By.clazz(((UiObject) element.getUiObject()).getClassName())); Field gestureField = uiObject2.getClass().getDeclaredField("mGestures"); gestureField.setAccessible(true); Object gestureObject = gestureField.get(uiObject2); Field viewConfigField = gestureObject.getClass().getDeclaredField("mViewConfig"); viewConfigField.setAccessible(true); Object viewConfigObject = viewConfigField.get(gestureObject); Method getScaledPagingTouchSlopMethod = viewConfigObject.getClass().getDeclaredMethod("getScaledPagingTouchSlop"); getScaledPagingTouchSlopMethod.setAccessible(true); int touchPadding = (int) getScaledPagingTouchSlopMethod.invoke(viewConfigObject); return touchPadding / 2; }
Example #4
Source File: BrowserSignInTest.java From samples-android with Apache License 2.0 | 6 votes |
private void customTabInteraction(boolean enterUserName) throws UiObjectNotFoundException { mDevice.wait(Until.findObject(By.pkg(CHROME_STABLE)), TRANSITION_TIMEOUT); acceptChromePrivacyOption(); UiSelector selector = new UiSelector(); if (enterUserName) { UiObject username = mDevice.findObject(selector.resourceId(ID_USERNAME)); username.setText(USERNAME); } UiObject password = mDevice.findObject(selector.resourceId(ID_PASSWORD)); password.setText(PASSWORD); UiObject signIn = mDevice.findObject(selector.resourceId(ID_SUBMIT)); signIn.click(); mDevice.wait(Until.findObject(By.pkg(SAMPLE_APP)), TRANSITION_TIMEOUT); //wait for token exchange getProgressBar().waitUntilGone(NETWORK_TIMEOUT); }
Example #5
Source File: BrowserSignInTest.java From samples-android with Apache License 2.0 | 6 votes |
@Test public void testA_cancelSignIn() throws UiObjectNotFoundException { getProgressBar().waitUntilGone(NETWORK_TIMEOUT); onView(withId(R.id.clear_data_btn)).check(matches(isDisplayed())); onView(withId(R.id.clear_data_btn)).perform(click()); onView(withId(R.id.browser_sign_in_btn)).check(matches(isDisplayed())); onView(withId(R.id.browser_sign_in_btn)).perform(click()); mDevice.wait(Until.findObject(By.pkg(CHROME_STABLE)), TRANSITION_TIMEOUT); UiSelector selector = new UiSelector(); UiObject closeBrowser = mDevice.findObject(selector.resourceId(ID_CLOSE_BROWSER)); closeBrowser.click(); mDevice.wait(Until.findObject(By.pkg(SAMPLE_APP)), TRANSITION_TIMEOUT); onView(withText(R.string.auth_canceled)).inRoot(new ToastMatcher()).check(matches(isDisplayed())); }
Example #6
Source File: UiObjectMatcher.java From device-automator with MIT License | 5 votes |
/** * Find a view based on the exact text contained within the view. Matching is case-insensitive. * * @param text Exact text in the view. * @param klass Expected class of the view. * @return */ public static UiObjectMatcher withText(String text, Class klass) { Pattern pattern = Pattern.compile("(?i)" + Pattern.quote(text)); UiSelector uiSelector = new UiSelector() .textMatches(pattern.pattern()); BySelector bySelector = By.text(pattern); if (klass != null) { uiSelector = uiSelector.className(klass); bySelector.clazz(klass); } return new UiObjectMatcher(uiSelector, bySelector); }
Example #7
Source File: AlertHelpers.java From appium-uiautomator2-server with Apache License 2.0 | 5 votes |
/** * @return The actual text of the on-screen dialog. An empty * string is going to be returned if the dialog contains no text. * @throws NoAlertOpenException if no dialog is present on the screen */ public static String getText() { final AlertType alertType = getAlertType(); final List<UiObject2> alertRoots = getUiDevice().findObjects(By.res(alertContentResId)); if (alertRoots.isEmpty()) { Log.w(TAG, "Alert content container is missing"); throw new NoAlertOpenException(); } final List<String> result = new ArrayList<>(); final List<UiObject2> alertElements = alertRoots.get(0).findObjects(By.res(alertElementsResIdPattern)); Log.d(TAG, String.format("Detected %d alert elements", alertElements.size())); final String alertButtonsResIdPattern = alertType == AlertType.REGULAR ? regularAlertButtonResIdPattern.toString() : permissionAlertButtonResIdPattern.toString(); for (final UiObject2 element : alertElements) { final String resName = element.getResourceName(); if (resName == null || resName.matches(alertButtonsResIdPattern)) { continue; } final String text = element.getText(); if (StringHelpers.isBlank(text)) { continue; } result.add(text); } return join("\n", result); }
Example #8
Source File: ClassInstancePair.java From appium-uiautomator2-server with Apache License 2.0 | 5 votes |
public BySelector getSelector() { String androidClass = getAndroidClass(); //TODO: remove below comments once code get reviewed //below commented line related to UiAutomator V1(bootstrap) version, as we don't have possibility // in V2 version to use instance, so directly returning By.clazz // new UiSelector().className(androidClass).instance(Integer.parseInt(instance)); return By.clazz(androidClass); }
Example #9
Source File: CustomUiDevice.java From appium-uiautomator2-server with Apache License 2.0 | 5 votes |
@Nullable private static BySelector toSelector(@Nullable AccessibilityNodeInfo nodeInfo) { if (nodeInfo == null) { return null; } final CharSequence className = nodeInfo.getClassName(); return className == null ? null : By.clazz(className.toString()); }
Example #10
Source File: UiObjectMatcher.java From device-automator with MIT License | 5 votes |
/** * Find a view based on the prefixed text in the view. The matching is case-insensitive. * * @param text Prefix to search for. * @param klass Expected class of the view. * @return */ public static UiObjectMatcher withTextStartingWith(String text, Class klass) { UiSelector uiSelector = new UiSelector() .textStartsWith(text); BySelector bySelector = By.textStartsWith(text); if (klass != null) { uiSelector = uiSelector.className(klass); bySelector.clazz(klass); } return new UiObjectMatcher(uiSelector, bySelector); }
Example #11
Source File: UiObjectMatcher.java From device-automator with MIT License | 5 votes |
/** * Find a view based on the text contained within the view. The matching is case-sensitive. * * @param text Text to search for inside a view. * @param klass Expected class of the view. * @return */ public static UiObjectMatcher withTextContaining(String text, Class klass) { UiSelector uiSelector = new UiSelector() .textContains(text); BySelector bySelector = By.textContains(text); if (klass != null) { uiSelector = uiSelector.className(klass); bySelector.clazz(klass); } return new UiObjectMatcher(uiSelector, bySelector); }
Example #12
Source File: ChangeTextBehaviorTest.java From testing-samples with Apache License 2.0 | 5 votes |
@Test public void testChangeText_newActivity() { // Type text and then press the button. mDevice.findObject(By.res(BASIC_SAMPLE_PACKAGE, "editTextUserInput")) .setText(STRING_TO_BE_TYPED); mDevice.findObject(By.res(BASIC_SAMPLE_PACKAGE, "activityChangeTextBtn")) .click(); // Verify the test is displayed in the Ui UiObject2 changedText = mDevice .wait(Until.findObject(By.res(BASIC_SAMPLE_PACKAGE, "show_text_view")), 500 /* wait 500ms */); assertThat(changedText.getText(), is(equalTo(STRING_TO_BE_TYPED))); }
Example #13
Source File: UiObjectMatcher.java From device-automator with MIT License | 5 votes |
/** * Find a view based on the resource id. Resource ids should be the fully qualified id, * ex: com.android.browser:id/url * * @param id The fully qualified id of the view, ex: com.android.browser:id/url * @param klass Expected class of the view. * @return */ public static UiObjectMatcher withResourceId(String id, Class klass) { UiSelector uiSelector = new UiSelector() .resourceId(id); BySelector bySelector = By.res(id); if (klass != null) { uiSelector = uiSelector.className(klass); bySelector.clazz(klass); } return new UiObjectMatcher(uiSelector, bySelector); }
Example #14
Source File: UiObjectMatcher.java From device-automator with MIT License | 5 votes |
/** * Find a view based on it's class. * * @param klass The class of the view to find. * @return */ public static UiObjectMatcher withClass(Class klass) { UiSelector uiSelector = new UiSelector() .className(klass); BySelector bySelector = By.clazz(klass); return new UiObjectMatcher(uiSelector, bySelector); }
Example #15
Source File: DeviceAutomator.java From device-automator with MIT License | 5 votes |
/** * Presses the home button and waits for the launcher with the given timeout. * * @param timeout length of time in milliseconds to wait for the launcher to appear before * timing out. * @return {@link DeviceAutomator} for method chaining. */ public DeviceAutomator onHomeScreen(long timeout) { mDevice.pressHome(); String launcherPackage = mDevice.getLauncherPackageName(); assertThat(launcherPackage, notNullValue()); mDevice.wait(hasObject(By.pkg(launcherPackage).depth(0)), timeout); return this; }
Example #16
Source File: DeviceAutomator.java From device-automator with MIT License | 5 votes |
/** * Launches the intent and waits for it to start with the given timeout. * * @param intent {@link Intent} to launch * @param timeout length of time in milliseconds to wait for the app to appear before timing out. * @return {@link DeviceAutomator} for method chaining. */ public DeviceAutomator launchApp(Intent intent, long timeout) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); getContext().startActivity(intent); mDevice.wait(hasObject(By.pkg(intent.getPackage()).depth(0)), timeout); return this; }
Example #17
Source File: AutomatorAssertion.java From device-automator with MIT License | 5 votes |
/** * Asserts that the foreground app is the package specified. * * @param packageName The package to check for. * @return */ public static AutomatorAssertion foregroundAppIs(final String packageName) { return new AutomatorAssertion() { @Override public void wrappedCheck(UiObject object) throws UiObjectNotFoundException { assertTrue(UiDevice.getInstance(getInstrumentation()).hasObject(By.pkg(packageName))); } }; }
Example #18
Source File: ChangeTextBehaviorTest.java From testing-samples with Apache License 2.0 | 5 votes |
@Test public void testChangeText_sameActivity() { // Type text and then press the button. mDevice.findObject(By.res(BASIC_SAMPLE_PACKAGE, "editTextUserInput")) .setText(STRING_TO_BE_TYPED); mDevice.findObject(By.res(BASIC_SAMPLE_PACKAGE, "changeTextBt")) .click(); // Verify the test is displayed in the Ui UiObject2 changedText = mDevice .wait(Until.findObject(By.res(BASIC_SAMPLE_PACKAGE, "textToBeChanged")), 500 /* wait 500ms */); assertThat(changedText.getText(), is(equalTo(STRING_TO_BE_TYPED))); }
Example #19
Source File: PlaybackControlTest.java From CastVideos-android with Apache License 2.0 | 5 votes |
/** * Scrub progress bar and verify the current duration */ @Test public void testProgressBarControl() throws UiObjectNotFoundException, InterruptedException { mTestUtils.connectToCastDevice(); mTestUtils.playCastContent(VIDEO_WITHOUT_SUBTITLES); mTestUtils.assertPlayerState(MediaStatus.PLAYER_STATE_PLAYING, MAX_TIMEOUT_MS); UiObject2 progressBar = mDevice.findObject(By.res(resources.getResourceName(R.id.cast_seek_bar))); progressBar.scroll(Direction.LEFT, 0.75f, 500); mTestUtils.assertStreamPosition(0.75f); mTestUtils.disconnectFromCastDevice(); }
Example #20
Source File: BrowserSignInTest.java From samples-android with Apache License 2.0 | 5 votes |
private void unlockKeystore() throws UiObjectNotFoundException { onView(withText("Unlock Screen")) .inRoot(isDialog()) .check(matches(isDisplayed())) .perform(click()); mDevice.wait(Until.findObject(By.pkg(SETTINGS_APP)), TRANSITION_TIMEOUT); UiSelector selector = new UiSelector(); UiObject passwordText = mDevice.findObject(selector.focused(true)); passwordText.setText(PINCODE); mDevice.pressEnter(); mDevice.wait(Until.findObject(By.pkg(SAMPLE_APP)), TRANSITION_TIMEOUT); getProgressBar().waitUntilGone(NETWORK_TIMEOUT); }
Example #21
Source File: BrowserSignInTest.java From samples-android with Apache License 2.0 | 5 votes |
@Test public void test3_signInWithSession() { onView(withId(R.id.container)).perform(swipeUp()); onView(withId(R.id.browser_sign_in_btn)).check(matches(isDisplayed())); onView(withId(R.id.browser_sign_in_btn)).perform(click()); mDevice.wait(Until.findObject(By.pkg(CHROME_STABLE)), TRANSITION_TIMEOUT); mDevice.wait(Until.findObject(By.pkg(SAMPLE_APP)), TRANSITION_TIMEOUT); getProgressBar().waitUntilGone(NETWORK_TIMEOUT); onView(withId(R.id.clear_data_btn)).check(matches(isDisplayed())); }
Example #22
Source File: BrowserSignInTest.java From samples-android with Apache License 2.0 | 5 votes |
@Test public void test6_signOutOfOkta() { getProgressBar().waitUntilGone(NETWORK_TIMEOUT); signInIfNotAlready(); onView(withId(R.id.logout_btn)).check(matches(isDisplayed())); onView(withId(R.id.logout_btn)).perform(click()); mDevice.wait(Until.findObject(By.pkg(CHROME_STABLE)), TRANSITION_TIMEOUT); mDevice.wait(Until.findObject(By.pkg(SAMPLE_APP)), TRANSITION_TIMEOUT); onView(withText(R.string.sign_out_success)).inRoot(new ToastMatcher()).check(matches(isDisplayed())); }
Example #23
Source File: EraseAllUserDataTest.java From focus-android with Mozilla Public License 2.0 | 5 votes |
@Test public void systemBarHomeViewTest() throws UiObjectNotFoundException { // Initialize UiDevice instance final int LAUNCH_TIMEOUT = 5000; // Open a webpage TestHelper.inlineAutocompleteEditText.waitForExists(waitingTime); TestHelper.inlineAutocompleteEditText.clearTextField(); TestHelper.inlineAutocompleteEditText.setText(webServer.url(TEST_PATH).toString()); TestHelper.hint.waitForExists(waitingTime); TestHelper.pressEnterKey(); TestHelper.waitForWebContent(); // Switch out of Focus, pull down system bar and select delete browsing history TestHelper.pressHomeKey(); TestHelper.openNotification(); TestHelper.notificationBarDeleteItem.waitForExists(waitingTime); TestHelper.notificationBarDeleteItem.click(); // Wait for launcher final String launcherPackage = TestHelper.mDevice.getLauncherPackageName(); assertThat(launcherPackage, notNullValue()); TestHelper.mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT); // Launch the app mActivityTestRule.launchActivity(new Intent(Intent.ACTION_MAIN)); // Verify that it's on the main view, not showing the previous browsing session TestHelper.inlineAutocompleteEditText.waitForExists(waitingTime); assertTrue(TestHelper.inlineAutocompleteEditText.exists()); }
Example #24
Source File: MultitaskingTest.java From focus-android with Mozilla Public License 2.0 | 5 votes |
private void checkNewTabPopup() { TestHelper.mDevice.wait(Until.findObject( By.res(TestHelper.getAppName(), "snackbar_text")), 5000); TestHelper.mDevice.wait(Until.gone( By.res(TestHelper.getAppName(), "snackbar_text")), 5000); }
Example #25
Source File: AlertHelpers.java From appium-uiautomator2-server with Apache License 2.0 | 5 votes |
private static AlertType getAlertType() { Device.waitForIdle(); if (!getUiDevice().findObjects(By.res(regularAlertTitleResIdPattern)).isEmpty()) { Log.d(TAG, "Regular alert has been detected"); return AlertType.REGULAR; } if (!getUiDevice().findObjects(By.res(permissionAlertTitleResIdPattern)).isEmpty()) { Log.d(TAG, "Permission alert has been detected"); return AlertType.PERMISSION; } throw new NoAlertOpenException(); }
Example #26
Source File: SwitchContextTest.java From focus-android with Mozilla Public License 2.0 | 4 votes |
@Test public void settingsToFocus() throws UiObjectNotFoundException { // Initialize UiDevice instance final int LAUNCH_TIMEOUT = 5000; final String SETTINGS_APP = "com.android.settings"; final UiObject settings = TestHelper.mDevice.findObject(new UiSelector() .packageName(SETTINGS_APP) .enabled(true)); // Open a webpage TestHelper.inlineAutocompleteEditText.waitForExists(waitingTime); TestHelper.inlineAutocompleteEditText.clearTextField(); TestHelper.inlineAutocompleteEditText.setText(webServer.url(TEST_PATH).toString()); TestHelper.hint.waitForExists(waitingTime); TestHelper.pressEnterKey(); // Assert website is loaded TestHelper.waitForWebSiteTitleLoad(); // Switch out of Focus, open settings app TestHelper.pressHomeKey(); // Wait for launcher final String launcherPackage = TestHelper.mDevice.getLauncherPackageName(); assertThat(launcherPackage, notNullValue()); TestHelper.mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT); // Launch the app Context context = InstrumentationRegistry.getInstrumentation() .getTargetContext() .getApplicationContext(); final Intent intent = context.getPackageManager() .getLaunchIntentForPackage(SETTINGS_APP); context.startActivity(intent); // switch to Focus settings.waitForExists(waitingTime); assertTrue(settings.exists()); TestHelper.openNotification(); // If simulator has more recent message, the options need to be expanded TestHelper.expandNotification(); TestHelper.notificationOpenItem.click(); // Verify that it's on the main view, showing the previous browsing session TestHelper.browserURLbar.waitForExists(waitingTime); assertTrue(TestHelper.browserURLbar.exists()); TestHelper.waitForWebSiteTitleLoad(); }
Example #27
Source File: BrowserScreenScreenshots.java From focus-android with Mozilla Public License 2.0 | 4 votes |
private void takeScreenshotOfTabsTrayAndErase() throws Exception { final UiObject mozillaImage = device.findObject(new UiSelector() .resourceId("download") .enabled(true)); UiObject imageMenuTitle = device.findObject(new UiSelector() .resourceId(TestHelper.getAppName() + ":id/topPanel") .enabled(true)); UiObject openNewTabTitle = device.findObject(new UiSelector() .resourceId(TestHelper.getAppName() + ":id/design_menu_item_text") .text(getString(R.string.contextmenu_open_in_new_tab)) .enabled(true)); UiObject multiTabBtn = device.findObject(new UiSelector() .resourceId(TestHelper.getAppName() + ":id/tabs") .enabled(true)); UiObject eraseHistoryBtn = device.findObject(new UiSelector() .text(getString(R.string.tabs_tray_action_erase)) .enabled(true)); assertTrue(mozillaImage.waitForExists(waitingTime)); mozillaImage.dragTo(mozillaImage, 7); assertTrue(imageMenuTitle.waitForExists(waitingTime)); assertTrue(imageMenuTitle.exists()); Screengrab.screenshot("Image_Context_Menu"); //Open a new tab openNewTabTitle.click(); TestHelper.mDevice.wait(Until.findObject( By.res(TestHelper.getAppName(), "snackbar_text")), 5000); Screengrab.screenshot("New_Tab_Popup"); TestHelper.mDevice.wait(Until.gone( By.res(TestHelper.getAppName(), "snackbar_text")), 5000); assertTrue(multiTabBtn.waitForExists(waitingTime)); multiTabBtn.click(); assertTrue(eraseHistoryBtn.waitForExists(waitingTime)); Screengrab.screenshot("Multi_Tab_Menu"); eraseHistoryBtn.click(); device.wait(Until.findObject( By.res(TestHelper.getAppName(), "snackbar_text")), waitingTime); Screengrab.screenshot("YourBrowsingHistoryHasBeenErased"); }
Example #28
Source File: AndroidTestsUtility.java From line-sdk-android with Apache License 2.0 | 4 votes |
public static boolean checkElementExists(int resourceId) { UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); Context context = ApplicationProvider.getApplicationContext(); return uiDevice.wait(Until.hasObject(By.res(toResourceName(context, resourceId))), AndroidTestsConfig.TIMEOUT); }
Example #29
Source File: AndroidTestsUtility.java From line-sdk-android with Apache License 2.0 | 4 votes |
public static boolean checkElementExists(String className) { UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); uiDevice.wait(Until.hasObject(By.clazz(className)), AndroidTestsConfig.TIMEOUT); UiObject2 element = uiDevice.findObject(By.clazz(className)); return element.isEnabled() && element.isClickable() && element.isFocusable(); }
Example #30
Source File: LineAppLoginPage.java From line-sdk-android with Apache License 2.0 | 4 votes |
public void tapAllowButton() { uiDevice.wait(Until.hasObject(By.pkg(AndroidTestsConfig.LINE_PACKAGE_NAME).depth(0)), AndroidTestsConfig.TIMEOUT); assertTrue(checkElementExists(AndroidTestsConfig.ANDROID_WIDGET_BUTTON)); uiDevice.findObjects(By.clazz(AndroidTestsConfig.ANDROID_WIDGET_BUTTON)).get(0).click(); }