org.openqa.selenium.SearchContext Java Examples
The following examples show how to use
org.openqa.selenium.SearchContext.
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: Shadow.java From shadow-automation-selenium with Apache License 2.0 | 6 votes |
private void fixLocator(SearchContext context, String cssLocator, WebElement element) { if (element instanceof RemoteWebElement) { try { @SuppressWarnings("rawtypes") Class[] parameterTypes = new Class[] { SearchContext.class, String.class, String.class }; Method m = element.getClass().getDeclaredMethod( "setFoundBy", parameterTypes); m.setAccessible(true); Object[] parameters = new Object[] { context, "cssSelector", cssLocator }; m.invoke(element, parameters); } catch (Exception fail) { //fail("Something bad happened when fixing locator"); } } }
Example #2
Source File: CheckboxNameSearch.java From vividus with Apache License 2.0 | 6 votes |
private List<WebElement> searchCheckboxLabels(SearchContext searchContext, SearchParameters parameters) { String checkBoxName = parameters.getValue(); SearchParameters nonDisplayedParameters = new SearchParameters(parameters.getValue(), Visibility.ALL, parameters.isWaitForElement()); List<WebElement> checkboxLabels = findElements(searchContext, getXPathLocator(String.format(CHECKBOX_LABEL_FORMAT, checkBoxName)), parameters); List<WebElement> matchedCheckboxLabels = searchCheckboxByLabels(searchContext, nonDisplayedParameters, checkboxLabels); if (matchedCheckboxLabels.isEmpty()) { checkboxLabels = findElements(searchContext, getXPathLocator(CHECKBOX_LABEL_DEEP), parameters).stream() .filter(e -> getWebElementActions().getElementText(e).contains(checkBoxName)) .collect(Collectors.toList()); return searchCheckboxByLabels(searchContext, nonDisplayedParameters, checkboxLabels); } return matchedCheckboxLabels; }
Example #3
Source File: CheckboxNameSearch.java From vividus with Apache License 2.0 | 6 votes |
private List<WebElement> searchCheckboxByLabels(SearchContext searchContext, SearchParameters parameters, List<WebElement> labelElements) { for (WebElement label : labelElements) { List<WebElement> checkboxes; String checkBoxId = label.getAttribute("for"); if (checkBoxId != null) { checkboxes = findElements(searchContext, getXPathLocator("input[@type='checkbox' and @id=%s]", checkBoxId), parameters); } else { checkboxes = label.findElements(getXPathLocator(PRECEDING_SIBLING_CHECKBOX_LOCATOR)); if (checkboxes.isEmpty()) { continue; } } return checkboxes.stream().map(e -> new Checkbox(e, label)).collect(Collectors.toList()); } return List.of(); }
Example #4
Source File: WebDriverUtilsTest.java From Selenium-Foundation with Apache License 2.0 | 6 votes |
@Test public void testBrowserName() { WebDriver driver = getDriver(); ExamplePage page = getPage(); WebElement element = page.findElement(By.tagName("html")); SeleniumConfig config = SeleniumConfig.getConfig(); String browserName = config.getCurrentCapabilities().getBrowserName(); assertThat(WebDriverUtils.getBrowserName((SearchContext) driver), equalToIgnoringCase(browserName)); assertThat(WebDriverUtils.getBrowserName(page), equalToIgnoringCase(browserName)); assertThat(WebDriverUtils.getBrowserName(element), equalToIgnoringCase(browserName)); try { WebDriverUtils.getBrowserName(mock(WebDriver.class)); fail("No exception was thrown"); } catch (UnsupportedOperationException e) { assertEquals(e.getMessage(), "The specified context is unable to describe its capabilities"); } }
Example #5
Source File: MobileBy.java From java-client with Apache License 2.0 | 6 votes |
/** * {@inheritDoc} * * @throws WebDriverException when current session doesn't support the given selector or when * value of the selector is not consistent. * @throws IllegalArgumentException when it is impossible to find something on the given * {@link SearchContext} instance */ @SuppressWarnings("unchecked") @Override public List<WebElement> findElements(SearchContext context) throws WebDriverException, IllegalArgumentException { Class<?> contextClass = context.getClass(); if (FindsByAndroidViewTag.class.isAssignableFrom(contextClass)) { return FindsByAndroidViewTag.class.cast(context) .findElementsByAndroidViewTag(getLocatorString()); } if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) { return super.findElements(context); } throw formIllegalArgumentException(contextClass, FindsByAndroidViewTag.class, FindsByFluentSelector.class); }
Example #6
Source File: AbstractExpectedConditions.java From vividus with Apache License 2.0 | 6 votes |
/** * An expectation for checking that is at least one element present * within the search context * @param searchCriteria used to find elements * @return the list of WebElements once they are located */ @Override @SuppressWarnings("checkstyle:nonullforcollectionreturn") public IExpectedSearchContextCondition<List<WebElement>> presenceOfAllElementsLocatedBy(final T searchCriteria) { return new IExpectedSearchContextCondition<>() { @Override public List<WebElement> apply(SearchContext searchContext) { List<WebElement> elements = findElements(searchContext, searchCriteria); return !elements.isEmpty() ? elements : null; } @Override public String toString() { return "presence of any elements " + toStringParameters(searchCriteria); } }; }
Example #7
Source File: WebDriverUnpackUtility.java From java-client with Apache License 2.0 | 6 votes |
/** * This method extract an instance of {@link WebDriver} from the given {@link SearchContext}. * @param searchContext is an instance of {@link SearchContext}. It may be the instance of * {@link WebDriver} or {@link org.openqa.selenium.WebElement} or some other * user's extension/implementation. * Note: if you want to use your own implementation then it should implement * {@link WrapsDriver} or {@link WrapsElement} * @return the instance of {@link WebDriver}. * Note: if the given {@link SearchContext} is not * {@link WebDriver} and it doesn't implement * {@link WrapsDriver} or {@link WrapsElement} then this method returns null. * */ public static WebDriver unpackWebDriverFromSearchContext(SearchContext searchContext) { if (searchContext instanceof WebDriver) { return (WebDriver) searchContext; } if (searchContext instanceof WrapsDriver) { return unpackWebDriverFromSearchContext( ((WrapsDriver) searchContext).getWrappedDriver()); } // Search context it is not only Webdriver. Webelement is search context too. // RemoteWebElement and MobileElement implement WrapsDriver if (searchContext instanceof WrapsElement) { return unpackWebDriverFromSearchContext( ((WrapsElement) searchContext).getWrappedElement()); } return null; }
Example #8
Source File: ByChained.java From java-client with Apache License 2.0 | 6 votes |
@Override public WebElement findElement(SearchContext context) { AppiumFunction<SearchContext, WebElement> searchingFunction = null; for (By by: bys) { searchingFunction = Optional.ofNullable(searchingFunction != null ? searchingFunction.andThen(getSearchingFunction(by)) : null).orElse(getSearchingFunction(by)); } FluentWait<SearchContext> waiting = new FluentWait<>(context); try { checkNotNull(searchingFunction); return waiting.until(searchingFunction); } catch (TimeoutException e) { throw new NoSuchElementException("Cannot locate an element using " + toString()); } }
Example #9
Source File: MobileBy.java From java-client with Apache License 2.0 | 6 votes |
/** * {@inheritDoc} * * @throws WebDriverException when current session doesn't support the given selector or when * value of the selector is not consistent. * @throws IllegalArgumentException when it is impossible to find something on the given * {@link SearchContext} instance */ @Override public WebElement findElement(SearchContext context) throws WebDriverException, IllegalArgumentException { Class<?> contextClass = context.getClass(); if (FindsByAccessibilityId.class.isAssignableFrom(contextClass)) { return FindsByAccessibilityId.class.cast(context) .findElementByAccessibilityId(getLocatorString()); } if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) { return super.findElement(context); } throw formIllegalArgumentException(contextClass, FindsByAccessibilityId.class, FindsByFluentSelector.class); }
Example #10
Source File: MobileBy.java From java-client with Apache License 2.0 | 6 votes |
/** * {@inheritDoc} * * @throws WebDriverException when current session doesn't support the given selector or when * value of the selector is not consistent. * @throws IllegalArgumentException when it is impossible to find something on the given * {@link SearchContext} instance */ @SuppressWarnings("unchecked") @Override public List<WebElement> findElements(SearchContext context) throws WebDriverException, IllegalArgumentException { Class<?> contextClass = context.getClass(); if (FindsByAndroidUIAutomator.class.isAssignableFrom(contextClass)) { return FindsByAndroidUIAutomator.class.cast(context) .findElementsByAndroidUIAutomator(getLocatorString()); } if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) { return super.findElements(context); } throw formIllegalArgumentException(contextClass, FindsByAndroidUIAutomator.class, FindsByFluentSelector.class); }
Example #11
Source File: NestedStepsTests.java From vividus with Apache License 2.0 | 6 votes |
@Test void shouldNotExecuteStepsIfInitialElementsNumberIsNotValid() { SearchContext searchContext = mockWebUiContext(); SearchAttributes searchAttributes = mock(SearchAttributes.class); when(searchActions.findElements(searchContext, searchAttributes)).thenReturn(List.of(mock(WebElement.class))); nestedSteps.performAllStepsWhileElementsExist(ComparisonRule.EQUAL_TO, 2, searchAttributes, 5, subSteps); verifyNoInteractions(subSteps); verify(searchActions, times(1)).findElements(searchContext, searchAttributes); verify(softAssert).assertThat(eq(ELEMENTS_NUMBER), eq(1), argThat(m -> ComparisonRule.EQUAL_TO.getComparisonRule(2).toString().equals(m.toString()))); verify(softAssert, never()).recordFailedAssertion(anyString()); verify(webUiContext, never()).getSearchContextSetter(); }
Example #12
Source File: MobileBy.java From java-client with Apache License 2.0 | 6 votes |
/** * {@inheritDoc} * * @throws WebDriverException when current session doesn't support the given selector or when * value of the selector is not consistent. * @throws IllegalArgumentException when it is impossible to find something on the given * {@link SearchContext} instance */ @SuppressWarnings("unchecked") @Override public List<WebElement> findElements(SearchContext context) { Class<?> contextClass = context.getClass(); if (FindsByWindowsAutomation.class.isAssignableFrom(contextClass)) { return FindsByWindowsAutomation.class.cast(context) .findElementsByWindowsUIAutomation(getLocatorString()); } if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) { return super.findElements(context); } throw formIllegalArgumentException(contextClass, FindsByWindowsAutomation.class, FindsByFluentSelector.class); }
Example #13
Source File: SeleniumTest.java From gatf with Apache License 2.0 | 5 votes |
@SuppressWarnings("serial") private static List<WebElement> getElements(WebDriver d, SearchContext sc, String finder) { String by = finder.substring(0, finder.indexOf("@")).trim(); if(by.charAt(0)==by.charAt(by.length()-1)) { if(by.charAt(0)=='"' || by.charAt(0)=='\'') { by = by.substring(1, by.length()-1); } } String classifier = finder.substring(finder.indexOf("@")+1).trim(); if(classifier.charAt(0)==classifier.charAt(classifier.length()-1)) { if(classifier.charAt(0)=='"' || classifier.charAt(0)=='\'') { classifier = classifier.substring(1, classifier.length()-1); } } List< WebElement> el = null; if(by.equalsIgnoreCase("id")) { el = By.id(classifier).findElements(sc); } else if(by.equalsIgnoreCase("name")) { el = By.name(classifier).findElements(sc); } else if(by.equalsIgnoreCase("class") || by.equalsIgnoreCase("className")) { el = By.className(classifier).findElements(sc); } else if(by.equalsIgnoreCase("tag") || by.equalsIgnoreCase("tagname")) { el = By.tagName(classifier).findElements(sc); } else if(by.equalsIgnoreCase("xpath")) { el = By.xpath(classifier).findElements(sc); } else if(by.equalsIgnoreCase("cssselector") || by.equalsIgnoreCase("css")) { el = By.cssSelector(classifier).findElements(sc); } else if(by.equalsIgnoreCase("text")) { el = By.xpath("//*[contains(text(), '" + classifier+"']").findElements(sc); } else if(by.equalsIgnoreCase("linkText")) { el = By.linkText(classifier).findElements(sc); } else if(by.equalsIgnoreCase("partialLinkText")) { el = By.partialLinkText(classifier).findElements(sc); } else if(by.equalsIgnoreCase("active")) { el = new ArrayList<WebElement>(){{add(((TargetLocator)d).activeElement());}}; } return el; }
Example #14
Source File: ComponentContainer.java From Selenium-Foundation with Apache License 2.0 | 5 votes |
/** * Returns a 'wait' proxy that switches focus to the specified context * * @param context search context on which to focus * @return target search context */ static Coordinator<SearchContext> contextIsSwitched(final ComponentContainer context) { return new Coordinator<SearchContext>() { /** * {@inheritDoc} */ @Override public SearchContext apply(final SearchContext ignore) { if (context.parent != null) { context.parent.switchTo(); } try { return context.switchToContext(); } catch (StaleElementReferenceException e) { //NOSONAR return context.refreshContext(context.acquiredAt()); } } /** * {@inheritDoc} */ @Override public String toString() { return "context to be switched"; } }; }
Example #15
Source File: CheckboxNameSearch.java From vividus with Apache License 2.0 | 5 votes |
@Override public List<WebElement> search(SearchContext searchContext, SearchParameters parameters) { List<WebElement> checkboxLabels = searchCheckboxLabels(searchContext, parameters); return checkboxLabels.isEmpty() ? findElements(searchContext, getXPathLocator(CHECKBOX_LOCATOR), parameters) .stream() .filter(c -> parameters.getValue().equals(getWebElementActions().getElementText(c))) .map(Checkbox::new) .collect(Collectors.toList()) : checkboxLabels; }
Example #16
Source File: ByChained.java From java-client with Apache License 2.0 | 5 votes |
private static AppiumFunction<SearchContext, WebElement> getSearchingFunction(By by) { return input -> { try { return input.findElement(by); } catch (NoSuchElementException e) { return null; } }; }
Example #17
Source File: WebElementHighlighterTests.java From vividus with Apache License 2.0 | 5 votes |
@Test void testTakeScreenshotWithHighlightsNoContext() { when(webUiContext.getAssertingWebElements()).thenReturn(List.of(webElement)); SearchContext searchContext = mock(SearchContext.class); when(webUiContext.getSearchContext()).thenReturn(searchContext); Object expected = new Object(); Object actual = webElementHighlighter.takeScreenshotWithHighlights(() -> expected); assertEquals(expected, actual); verify(javascriptActions).executeScript(ENABLE_HIGHLIGHT_SCRIPT, webElement); verify(javascriptActions).executeScript(DISABLE_HIGHLIGHT_SCRIPT, webElement); }
Example #18
Source File: ByExtended.java From stevia with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Find element by sizzle css. * @param context * * @param cssLocator * the cssLocator * @return the web element */ public WebElement findElementBySizzleCss(SearchContext context, String cssLocator) { List<WebElement> elements = findElementsBySizzleCss(context, cssLocator); if (elements != null && elements.size() > 0 ) { return elements.get(0); } // if we get here, we cannot find the element via Sizzle. throw new NoSuchElementException("selector '"+cssLocator+"' cannot be found in DOM"); }
Example #19
Source File: ByAny.java From qaf with MIT License | 5 votes |
@Override public WebElement findElement(SearchContext context) { List<WebElement> elements = findElements(context); if (elements.isEmpty()) { throw new NoSuchElementException("Cannot locate an element using " + toString()); } return elements.get(0); }
Example #20
Source File: AbstractVisualSteps.java From vividus with Apache License 2.0 | 5 votes |
protected <T extends VisualCheck> VisualCheckResult execute(Function<T, VisualCheckResult> checkResultProvider, Supplier<T> visualCheckFactory, String templateName) { SearchContext searchContext = webUiContext.getSearchContext(); Validate.validState(searchContext != null, "Search context is null, please check is browser session started"); T visualCheck = visualCheckFactory.get(); visualCheck.setSearchContext(searchContext); VisualCheckResult result = checkResultProvider.apply(visualCheck); if (null != result) { attachmentPublisher.publishAttachment(templateName, Map.of("result", result), "Visual comparison"); } return result; }
Example #21
Source File: AshotScreenshotProviderTests.java From vividus with Apache License 2.0 | 5 votes |
@Test void shouldTakeScreenshot() { SearchContext searchContext = mock(SearchContext.class); VisualCheck visualCheck = mockSearchContext(searchContext); Screenshot screenshot = mock(Screenshot.class); when(searchActions.findElements(A_LOCATOR)).thenReturn(List.of()); when(screenshotTaker.takeAshotScreenshot(searchContext, Optional.empty())).thenReturn(screenshot); screenshotProvider.setIgnoreStrategies(Map.of(IgnoreStrategy.AREA, Set.of(A_LOCATOR))); assertSame(screenshot, screenshotProvider.take(visualCheck)); verifyNoInteractions(screenshotDebugger); }
Example #22
Source File: RobustElementWrapper.java From Selenium-Foundation with Apache License 2.0 | 5 votes |
/** * Returns a 'wait' proxy that refreshes the wrapped reference of the specified robust element. * * @param wrapper robust element wrapper * @return wrapped element reference (refreshed) */ private static Coordinator<RobustElementWrapper> referenceIsRefreshed(final RobustElementWrapper wrapper) { return new Coordinator<RobustElementWrapper>() { /** * {@inheritDoc} */ @Override public RobustElementWrapper apply(final SearchContext context) { try { return acquireReference(wrapper); } catch (StaleElementReferenceException e) { //NOSONAR ((WrapsContext) context).refreshContext(((WrapsContext) context).acquiredAt()); return acquireReference(wrapper); } } /** * {@inheritDoc} */ @Override public String toString() { return "element reference to be refreshed"; } }; }
Example #23
Source File: ElementFactory.java From qaf with MIT License | 5 votes |
@SuppressWarnings("unchecked") private Object initList(Field field, String loc, SearchContext context, Object clsObject) throws Exception { loc = ConfigurationManager.getBundle().getString(loc, loc); Class<? extends QAFExtendedWebElement> cls = (Class<? extends QAFExtendedWebElement>) getListType(field); InvocationHandler iHandler = QAFWebComponent.class.isAssignableFrom(cls) ? new ComponentListHandler(context, loc, cls, clsObject) : new ComponentListHandler(context, loc, getElemenetClass(), clsObject); return Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { List.class }, iHandler); }
Example #24
Source File: ASTJavaContextConverterTest.java From bromium with MIT License | 5 votes |
private void baseIndexCorrectlyConstructs(int index) { String tableCssSelector = ".entity-triggers-container"; String rowsCssSelector = ".trigger-list-entry"; String indexAlias = "triggerNo"; CssSelectorImpl tableLocator = new CssSelectorImpl(){}; tableLocator.setSelector(hardcoded(tableCssSelector)); CssSelectorImpl rowsLocator = new CssSelectorImpl(){}; rowsLocator.setSelector(hardcoded(rowsCssSelector)); RowIndexImpl rowSelector = new RowIndexImpl(){}; rowSelector.setIndex(exposed(indexAlias)); TableActionContextImpl actionContext = new TableActionContextImpl(){}; actionContext.setTableLocator(tableLocator); actionContext.setRowsLocator(rowsLocator); actionContext.setRowSelector(rowSelector); ParameterValues parameterValues = new ParameterValues(); parameterValues.put(indexAlias, String.valueOf(index)); WebElement rowOne = mock(WebElement.class); WebElement rowTwo = mock(WebElement.class); List<WebElement> rows = Arrays.asList(rowOne, rowTwo); WebElement table = mock(WebElement.class); WebDriver webDriver = mock(WebDriver.class); when(webDriver.findElements(By.cssSelector(tableCssSelector))).thenReturn(Collections.singletonList(table)); when(table.findElements(By.cssSelector(rowsCssSelector))).thenReturn(Arrays.asList(rowOne, rowTwo)); ASTJavaContextConverter converter = new ASTJavaContextConverter(); Function<ParameterValues, SearchContextFunction> convert = converter.convert(actionContext); SearchContext searchContext = convert.apply(parameterValues).apply(webDriver); Assert.assertNotNull(searchContext); Assert.assertEquals(rows.get(index), searchContext); }
Example #25
Source File: ExpectedSearchContextConditionsTests.java From vividus with Apache License 2.0 | 5 votes |
@Test void testElementToBeClickableVisibleEnabled() { WebElement webElement = mock(WebElement.class); SearchContext searchContext = mock(SearchContext.class); when(searchContext.findElement(XPATH_LOCATOR)).thenReturn(webElement); when(webElement.isDisplayed()).thenReturn(TRUE); when(webElement.isEnabled()).thenReturn(TRUE); assertEquals(webElement, expectedConditions.elementToBeClickable(XPATH_LOCATOR).apply(searchContext)); }
Example #26
Source File: ExpectedSearchContextConditionsTests.java From vividus with Apache License 2.0 | 5 votes |
@Test void testInvisibilityOfElementLocatedSuccessIsDisplayed() { WebElement webElement = mock(WebElement.class); SearchContext searchContext = mock(SearchContext.class); when(searchContext.findElement(XPATH_LOCATOR)).thenReturn(webElement); when(webElement.isDisplayed()).thenReturn(true); assertFalse(expectedConditions.invisibilityOfElement(XPATH_LOCATOR).apply(searchContext) .booleanValue()); }
Example #27
Source File: ZoneSearchStrategy.java From phoenix.webui.framework with Apache License 2.0 | 5 votes |
/** * 失败重试 * @param absLocator * @param webEle * @return */ private WebElement retry(AbstractLocator<WebElement> absLocator, SearchContext webEle) { WebElement result = null; if(webEle != null) { result = absLocator.findElement(webEle); } else { result = absLocator.findElement(webEle); } if(result != null || ++failedCount > maxFailed) { return result; } else { logger.warn("Can not found element by locator {}, " + "will retry locate again {} millis later, failed times {}.", absLocator, timeout, failedCount); ThreadUtil.silentSleep(timeout); return retry(absLocator, webEle); } }
Example #28
Source File: VisualStepsTests.java From vividus with Apache License 2.0 | 5 votes |
@Test void shouldPublishAttachment() { SearchContext searchContext = mock(SearchContext.class); VisualCheck visualCheck = mock(VisualCheck.class); VisualCheckResult visualCheckResult = mock(VisualCheckResult.class); when(webUiContext.getSearchContext()).thenReturn(searchContext); Function<VisualCheck, VisualCheckResult> checkResultProvider = check -> visualCheckResult; Supplier<VisualCheck> visualCheckFactory = () -> visualCheck; assertSame(visualCheckResult, visualSteps.execute(checkResultProvider, visualCheckFactory, TEMPLATE)); verify(attachmentPublisher).publishAttachment(TEMPLATE, Map.of("result", visualCheckResult), "Visual comparison"); verify(visualCheck).setSearchContext(searchContext); }
Example #29
Source File: BaseValidations.java From vividus with Apache License 2.0 | 5 votes |
@Override public WebElement assertIfAtLeastOneElementExists(String businessDescription, SearchContext searchContext, SearchAttributes searchAttributes) { List<WebElement> elements = assertIfElementsExist(businessDescription, searchContext, searchAttributes); return elements.isEmpty() ? null : elements.get(0); }
Example #30
Source File: AdjustingCoordsProvider.java From vividus with Apache License 2.0 | 5 votes |
private Coords adjustToSearchContext(WebDriver driver, Coords coords) { SearchContext searchContext = webUiContext.getSearchContext(); if (searchContext instanceof WebElement) { Coords searchContextCoords = super.ofElement(driver, (WebElement) searchContext); Coords intersected = coords.intersection(searchContextCoords); intersected.x = intersected.x - searchContextCoords.x; intersected.y = intersected.y - searchContextCoords.y; return intersected; } return coords; }