@SProperty(name = "ng-repeat-row") public By getByRepeaterRow(String repeaterRow) { String repeater = repeaterRow.split("###")[0]; int row = Integer.valueOf(repeaterRow.split("###")[1]); return new ByAngularRepeaterRow(NgWebDriver.DEFAULT_ROOT_SELECTOR, repeater, false, row) { @Override public List<WebElement> findElements(SearchContext searchContext) { List<WebElement> elements = new ArrayList<>(); try { elements.add(this.findElement(searchContext)); } catch (Exception ex) { } return elements; } }; }
/** * Returns a 'wait' proxy that determines if this page component is visible * * @return page component if visible; otherwise 'null' */ public static Coordinator<PageComponent> componentIsVisible() { return new Coordinator<PageComponent>() { @Override public PageComponent apply(SearchContext context) { PageComponent component = verifyContext(context); return (component.isDisplayed()) ? component : null; } @Override public String toString() { return "page component to be visible"; } }; }
/** * Returns a 'wait' proxy that determines if this page component is hidden * * @return page component if hidden; otherwise 'null' */ public static Coordinator<PageComponent> componentIsHidden() { return new Coordinator<PageComponent>() { @Override public PageComponent apply(SearchContext context) { PageComponent component = verifyContext(context); return (component.isInvisible()) ? component : null; } @Override public String toString() { return "page component to be absent or hidden"; } }; }
/** * 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>() { @Override public RobustElementWrapper apply(SearchContext context) { try { return acquireReference(wrapper); } catch (StaleElementReferenceException e) { ((WrapsContext) context).refreshContext(((WrapsContext) context).acquiredAt()); return acquireReference(wrapper); } } @Override public String toString() { return "element reference to be refreshed"; } }; }
/** * 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>() { @Override public SearchContext apply(SearchContext ignore) { if (context.parent != null) { context.parent.switchTo(); } try { return context.switchToContext(); } catch (StaleElementReferenceException e) { return context.refreshContext(context.acquiredAt()); } } @Override public String toString() { return "context to be switched"; } }; }
/** * Returns a 'wait' proxy that determines if the expected landing page has appeared. * * @return 'true' if the expected landing page has appeared */ private static Coordinator<Boolean> landingPageAppears() { return new Coordinator<Boolean>() { @Override public Boolean apply(SearchContext context) { verifyLandingPage((Page) context); return Boolean.TRUE; } @Override public String toString() { return "expected landing page to appear"; } }; }
/** * Returns a 'wait' proxy that determines if a new window has opened * * @param initialHandles initial set of window handles * @return new window handle; 'null' if no new window found */ public static Coordinator<String> newWindowIsOpened(final Set<String> initialHandles) { return new Coordinator<String>() { @Override public String apply(SearchContext context) { Set<String> currentHandles = WebDriverUtils.getDriver(context).getWindowHandles(); currentHandles.removeAll(initialHandles); if (currentHandles.isEmpty()) { return null; } else { return currentHandles.iterator().next(); } } @Override public String toString() { return "new window to be opened"; } }; }
/** * Returns a 'wait' proxy that determines if the specified window has closed * * @param windowHandle handle of window that's expected to close * @return 'true' if the specified window has closed; otherwise 'false' */ public static Coordinator<Boolean> windowIsClosed(final String windowHandle) { return new Coordinator<Boolean>() { @Override public Boolean apply(SearchContext context) { Set<String> currentHandles = WebDriverUtils.getDriver(context).getWindowHandles(); return Boolean.valueOf( ! currentHandles.contains(windowHandle)); } @Override public String toString() { return "window with handle '" + windowHandle + "' to be closed"; } }; }
/** * Returns a 'wait' proxy that determines if the first element matched by the specified locator is visible * * @param locator web element locator * @return web element reference; 'null' if the indicated element is absent or hidden */ public static Coordinator<WebElement> visibilityOfElementLocated(final By locator) { return new Coordinator<WebElement>() { @Override public WebElement apply(SearchContext context) { try { return elementIfVisible(context.findElement(locator)); } catch (StaleElementReferenceException e) { return null; } } @Override public String toString() { return "visibility of element located by " + locator; } }; }
/** * Returns a 'wait' proxy that determines if any element matched by the specified locator is visible * * @param locator web element locator * @return web element reference; 'null' if no matching elements are visible */ public static Coordinator<WebElement> visibilityOfAnyElementLocated(final By locator) { return new Coordinator<WebElement>() { @Override public WebElement apply(SearchContext context) { try { List<WebElement> visible = context.findElements(locator); return (WebDriverUtils.filterHidden(visible)) ? null : visible.get(0); } catch (StaleElementReferenceException e) { return null; } } @Override public String toString() { return "visibility of element located by " + locator; } }; }
/** * Returns a 'wait' proxy that determines if an element is either hidden or non-existent. * * @param locator web element locator * @return 'true' if the element is hidden or non-existent; otherwise 'false' */ public static Coordinator<Boolean> invisibilityOfElementLocated(final By locator) { return new Coordinator<Boolean>() { @Override public Boolean apply(SearchContext context) { try { return !(context.findElement(locator).isDisplayed()); } catch (NoSuchElementException | StaleElementReferenceException e) { // NoSuchElementException: The element is not present in DOM. // StaleElementReferenceException: Implies that element no longer exists in the DOM. return true; } } @Override public String toString() { return "element to no longer be visible: " + locator; } }; }
/** * Returns a 'wait' proxy that determines if the specified element reference has gone stale. * * @param element the element to wait for * @return 'false' if the element reference is still valid; otherwise 'true' */ public static Coordinator<Boolean> stalenessOf(final WebElement element) { return new Coordinator<Boolean>() { private final ExpectedCondition<Boolean> condition = conditionInitializer(); // initializer for [condition] field private final ExpectedCondition<Boolean> conditionInitializer() { if (element instanceof WrapsElement) { return ExpectedConditions.stalenessOf(((WrapsElement) element).getWrappedElement()); } else { return ExpectedConditions.stalenessOf(element); } } @Override public Boolean apply(SearchContext ignored) { return condition.apply(null); } @Override public String toString() { return condition.toString(); } }; }
@Test public void testGetDriver() { WebDriver driver = getDriver(); ExamplePage page = getPage(); WebElement element = page.findElement(By.tagName("html")); assertTrue(WebDriverUtils.getDriver((SearchContext) driver) == driver); assertTrue(WebDriverUtils.getDriver(page) == driver); assertTrue(WebDriverUtils.getDriver(element) == driver); try { WebDriverUtils.getDriver(mock(SearchContext.class)); fail("No exception was thrown"); } catch (UnsupportedOperationException e) { assertEquals(e.getMessage(), "Unable to extract the driver from the specified context"); } }
@Test public void testBrowserName() { WebDriver driver = getDriver(); ExamplePage page = getPage(); WebElement element = page.findElement(By.tagName("html")); SeleniumConfig config = SeleniumConfig.getConfig(); String browserName = config.getBrowserCaps().getBrowserName(); assertEquals(WebDriverUtils.getBrowserName((SearchContext) driver), browserName); assertEquals(WebDriverUtils.getBrowserName(page), browserName); assertEquals(WebDriverUtils.getBrowserName(element), 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"); } }
@SProperty(name = "ng-repeat-cell") public By getByRepeaterCell(String repeaterVal) { String repeater = repeaterVal.split("###")[0]; int row = Integer.valueOf(repeaterVal.split("###")[1]); String column = repeaterVal.split("###")[2]; return new ByAngularRepeaterCell(NgWebDriver.DEFAULT_ROOT_SELECTOR, repeater, false, row, column) { @Override public List<WebElement> findElements(SearchContext searchContext) { List<WebElement> elements = new ArrayList<>(); try { elements.add(this.findElement(searchContext)); } catch (Exception ex) { } return elements; } }; }
@SProperty(name = "ng-exactRepeat-row") public By getByExactRepeaterRow(String repeaterRow) { String repeater = repeaterRow.split("###")[0]; int row = Integer.valueOf(repeaterRow.split("###")[1]); return new ByAngularRepeaterRow(NgWebDriver.DEFAULT_ROOT_SELECTOR, repeater, true, row) { @Override public List<WebElement> findElements(SearchContext searchContext) { List<WebElement> elements = new ArrayList<>(); try { elements.add(this.findElement(searchContext)); } catch (Exception ex) { } return elements; } }; }
@SProperty(name = "ng-exactRepeat-cell") public By getByExactRepeaterCell(String repeaterVal) { String repeater = repeaterVal.split("###")[0]; int row = Integer.valueOf(repeaterVal.split("###")[1]); String column = repeaterVal.split("###")[2]; return new ByAngularRepeaterCell(NgWebDriver.DEFAULT_ROOT_SELECTOR, repeater, true, row, column) { @Override public List<WebElement> findElements(SearchContext searchContext) { List<WebElement> elements = new ArrayList<>(); try { elements.add(this.findElement(searchContext)); } catch (Exception ex) { } return elements; } }; }
/** * Produces a proxy that will provide value for the list of PageObjects. Handler of this proxy is an * instance of PageObjectListInvocationHandler. */ @Override public Optional<Object> provideValue(Object pageObject, Field field, PageObjectContext context) { FramePath framePath = frameMap.get(pageObject); By selector = PageObjectProviderHelper.getSelectorFromGenericPageObject(field); SearchContext searchContext = getSearchContext(context, field); NestedSelectorScopedElementLocator locator = new NestedSelectorScopedElementLocator(searchContext, context.getElementLocatorFactory(), selector, field.isAnnotationPresent(Global.class)); PageObjectListInvocationHandler handler = new PageObjectListInvocationHandler(PageObjectProviderHelper.getGenericType(field), locator, injector, shouldCacheResults(field), framePath); ClassLoader classLoader = PageObjectProviderHelper.getGenericType(field).getClassLoader(); Object proxyInstance = Proxy.newProxyInstance(classLoader, new Class[]{List.class}, handler); return Optional.of(proxyInstance); }
@Override public WebElement findElement( SearchContext context ) { long startTime = System.currentTimeMillis(); WebElement returnValue = null; try { returnValue = by.findElement( context ); } finally { addResult( toString(), (int) (System.currentTimeMillis() - startTime), returnValue != null ); } return returnValue; }
@Override public List<WebElement> findElements( SearchContext context ) { List<WebElement> elems = new ArrayList<>(); for ( By by : bys ) { List<WebElement> elementList = by.findElements( context ); resultList.addAll( ( (ReportableBy) by ).getResults() ); if ( elementList != null && !elementList.isEmpty()) { elems.addAll( by.findElements( context ) ); return elems; } } return elems; }
@Override public List<WebElement> findElements( SearchContext context ) { if ( imageName != null ) { Rectangle r = webDriver.getCloud().getCloudActionProvider().findImage( webDriver, imageName, propertyMap ); if ( r != null ) { List<WebElement> elementList = new ArrayList<WebElement>( 1 ); elementList.add( new VisualWebElement( webDriver, r ) ); return elementList; } } return null; }
@Override public List<WebElement> findElements( SearchContext context ) { if ( text != null ) { Rectangle r = webDriver.getCloud().getCloudActionProvider().findText( webDriver, text, propertyMap ); if ( r != null ) { List<WebElement> elementList = new ArrayList<WebElement>( 1 ); elementList.add( new VisualWebElement( webDriver, r ) ); return elementList; } } return null; }
/** * This method extract an instance of {@link org.openqa.selenium.WebDriver} from the given * {@link org.openqa.selenium.SearchContext}. * @param searchContext is an instance of {@link org.openqa.selenium.SearchContext} * It may be the instance of {@link org.openqa.selenium.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 org.openqa.selenium.internal.WrapsDriver} or * {@link org.openqa.selenium.internal.WrapsElement} * @return the instance of {@link org.openqa.selenium.WebDriver}. * Note: if the given {@link org.openqa.selenium.SearchContext} is not * {@link org.openqa.selenium.WebDriver} and it doesn't implement * {@link org.openqa.selenium.internal.WrapsDriver} or * {@link org.openqa.selenium.internal.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; }
@Override public List<WebElement> findElements(SearchContext context) { if (locators.length == 0) { return new ArrayList<WebElement>(); } List<WebElement> elems = new ArrayList<WebElement>(); for (String locator : locators) { By by = LocatorUtil.getBy(locator); elems.addAll(by.findElements(context)); if (!elems.isEmpty()) { break; } } return elems; }
@Override public List<WebElement> findElements(SearchContext searchContext) { logger.finer("finding label " + label + " in " + searchContext); String safeLabel; if (label.contains("'")) { // replace each ' with ', "'", ' so we can use it in a concat expression // makes concat('O', "'", 'Neil') from O'Neil safeLabel = "concat('" + label.replace("'", "', \"'\", '") + "')"; } else { safeLabel = "'" + label + "'"; } // start from . for instances where we are searching within a scoped element // tr elements having a _afrrk (rowkey) attribute are considered tree nodes String xpath = ".//tr[@_afrrk and .//span[text()=" + safeLabel + "]]"; logger.finer("using xpath " + xpath); return ((FindsByXPath) searchContext).findElementsByXPath(xpath); }
private SearchContext getSearchContext(Object element) { if (element == null || !isClass(element.getClass(), BaseElement.class)) return getDefaultContext(); BaseElement bElement = (BaseElement) element; if (bElement.useCache && isClass(bElement.getClass(), Element.class)) { Element el = (Element) bElement; if (el.avatar.hasWebElement()) return el.avatar.webElement; } Object p = bElement.getParent(); By locator = bElement.getLocator(); By frame = bElement.avatar.frameLocator; SearchContext searchContext = frame != null ? getFrameContext(frame) : p == null || containsRoot(locator) ? getDefaultContext() : getSearchContext(p); return locator != null ? searchContext.findElement(correctLocator(locator)) : searchContext; }
private SearchContext getSearchContext(Object element) { Object p; BaseElement bElement; Element el; if (element == null || !isClass(element.getClass(), BaseElement.class) || ((p = (bElement = (BaseElement) element).getParent()) == null && bElement.avatar.frameLocator == null)) return getDriver().switchTo().defaultContent(); if (isClass(bElement.getClass(), Element.class) && (el = (Element) bElement).avatar.hasWebElement()) return el.getWebElement(); By locator = bElement.getLocator(); SearchContext searchContext = containsRoot(locator) ? getDriver().switchTo().defaultContent() : getSearchContext(p); locator = containsRoot(locator) ? trimRoot(locator) : locator; By frame = bElement.avatar.frameLocator; if (frame != null) getDriver().switchTo().frame((WebElement)getDriver().findElement(frame)); return locator != null ? searchContext.findElement(correctXPaths(locator)) : searchContext; }
@Override protected void selectAction(String name) { expandAction(); String[] nodes = name.split(" > "); SearchContext context = getDriver(); if (treeLocators.size() < nodes.length) return; for(int i=0; i < nodes.length; i++) { String value = nodes[i]; List<WebElement> els = context.findElements(correctXPaths(treeLocators.get(i))); if (els.size() == 0) throw exception("No elements found for locator: " + treeLocators.get(i) + "in TreeDropdown " + this); context = first(els, el -> el.getText().equals(value)); if (context == null) throw exception("Can't find: " + value + "in TreeDropdown " + this); if (i < nodes.length - 1) { int next = i + 1; boolean nextValue = LinqUtils.any(context.findElements(correctXPaths(treeLocators.get(next))), el -> el.getText().equals(nodes[next])); if (nextValue) continue; } ((WebElement) context).click(); } }
@Inject public AugmentedAndroidFunctions(@Assisted SearchContext searchContext, @Named(PropertiesModule.WAIT_IN_SECONDS) String waitTimeInSeconds, @Named(PropertiesModule.PRESS_TIME_IN_MILLISECONDS) String pressTimeInMilliSeconds, @Named(PropertiesModule.SWIPE_QUANTITY) String swipeQuantity, @Named(PropertiesModule.TAP_FINGERS) String tapFingers, AugmentedAndroidElementFactory augmentedAndroidElementFactory, AugmentedAndroidDriverProvider augmentedAndroidDriverProvider) { this.searchContext = Preconditions.checkNotNull(searchContext); this.augmentedAndroidDriveProvider = Preconditions.checkNotNull(augmentedAndroidDriverProvider); this.pressTimeInMilliSeconds = Integer.valueOf(Preconditions.checkNotNull(pressTimeInMilliSeconds)); this.swipeQuantity = Integer.valueOf(Preconditions.checkNotNull(swipeQuantity)); this.tapFingers = Integer.valueOf(Preconditions.checkNotNull(tapFingers)); this.waitTimeInSeconds= Integer.valueOf(Preconditions.checkNotNull(waitTimeInSeconds)); this.augmentedAndroidElementFactory = Preconditions.checkNotNull(augmentedAndroidElementFactory); }
@Inject public AugmentedIOSFunctions(@Assisted SearchContext searchContext, @Named(PropertiesModule.WAIT_IN_SECONDS) String waitTimeInSeconds, @Named(PropertiesModule.PRESS_TIME_IN_MILLISECONDS) String pressTimeInMilliSeconds, @Named(PropertiesModule.SWIPE_QUANTITY) String swipeQuantity, @Named(PropertiesModule.TAP_FINGERS) String tapFingers, AugmentedIOSElementFactory augmentedIOSElementFactory, AugmentedIOSDriverProvider augmentedIOSDriverProvider) { this.searchContext = Preconditions.checkNotNull(searchContext); this.augmentedIOSDriverProvider = Preconditions.checkNotNull(augmentedIOSDriverProvider); this.pressTimeInMilliSeconds = Integer.valueOf(Preconditions.checkNotNull(pressTimeInMilliSeconds)); this.swipeQuantity = Integer.valueOf(Preconditions.checkNotNull(swipeQuantity)); this.tapFingers = Integer.valueOf(Preconditions.checkNotNull(tapFingers)); this.waitTimeInSeconds= Integer.valueOf(Preconditions.checkNotNull(waitTimeInSeconds)); this.augmentedIOSElementFactory = Preconditions.checkNotNull(augmentedIOSElementFactory); }
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, "css selector", cssLocator }; m.invoke(element, parameters); } catch (Exception e) { logger.error("Something bad happened when fixing locator", e); } } }
@Deprecated /** * @deprecated - use FindingExpectations#presenceOf * @param finder * @return */ public static ExpectedCondition<WebElement> presenceOfA(final MFinder<WebElement,SearchContext> finder){ return new ExpectedCondition<WebElement>(){ @Override public String toString() { return new StringDescription().appendDescriptionOf(finder).toString(); } @Override public WebElement apply(WebDriver driver) { ExpectationCheckResult<WebElement, CollectionOf<WebElement>> result = checkerFor((SearchContext) driver).resultOfChecking(expectationOfSome(finder)); if(result.meetsExpectation()) return result.foundQuantity().iterator().next(); else return null; } }; }
public static ExpectedCondition<Boolean> invisibilityOf(final MFinder<WebElement, SearchContext> finder){ return new ExpectedCondition<Boolean>(){ @Override public Boolean apply(WebDriver driver) { Collection<WebElement> foundElements = checkerFor((SearchContext) driver).thatWhichIsFoundBy(expectationOfSome(finder)); if(foundElements.isEmpty()) return true; else { for(WebElement element:foundElements){ try{ if(element.isDisplayed()) return false; }catch(StaleElementReferenceException e){} // if stale this implies element is not displayed so we can skip over it } return true; } } @Override public String toString() { return newDescription().appendDescriptionOf(finder).appendText(" to be invisible or not present").toString(); } }; }
/** * Perform action/supplier in context. * @param context context to perfom action in. * @param action action to perform. * @param <R> type of action result. * @return action result. */ public <R> R doInContext(SearchContext context, Supplier<R> action) { R result; if (context == null) { result = action.get(); } else { // store current context (without triggering exception if it was stale) SearchContext currentSearchContext = currentContext; boolean contextIsStale = currentContextIsStale; setCurrentContext(context); try { result = action.get(); } finally { // make original current context active again currentContext = currentSearchContext; currentContextIsStale = contextIsStale; } } return result; }
@SuppressWarnings("unchecked") @Override public List<WebElement> findElements(SearchContext context) { Object o; try { String jQueryLoader = readFile(getClass().getResourceAsStream(JQUERY_LOAD_SCRIPT)); ((JavascriptExecutor) context).executeAsyncScript(jQueryLoader); log.debug("JQuery library injected from file {}!!!", getClass().getClassLoader().getResource(JQUERY_LOAD_SCRIPT).getPath()); } catch (IOException e) { log.error("Error trying to inject jquery: " + e); } if (siblingSelector != null || !siblingSelector.isEmpty()) { o = ((JavascriptExecutor) context) .executeScript("return $('" + ownSelector + "').siblings('" + siblingSelector + "');"); } else { o = ((JavascriptExecutor) context) .executeScript("return $('" + ownSelector + "').siblings();"); } return (List<WebElement>) o; }
@SuppressWarnings("unchecked") @Override public List<WebElement> findElements(SearchContext context) { Object o; try { String jQueryLoader = readFile(getClass().getResourceAsStream(JQUERY_LOAD_SCRIPT)); ((JavascriptExecutor) context).executeAsyncScript(jQueryLoader); log.debug("JQuery library injected from file {}!!!", getClass().getClassLoader().getResource(JQUERY_LOAD_SCRIPT).getPath()); } catch (IOException e) { log.error("Error trying to inject jquery: " + e); } if (parentSelector != null || !parentSelector.isEmpty()) { o = ((JavascriptExecutor) context) .executeScript("return $('" + ownSelector + "').parent('" + parentSelector + "');"); } else { o = ((JavascriptExecutor) context) .executeScript("return $('" + ownSelector + "').parent();"); } return (List<WebElement>) o; }
@Override public List<WebElement> findElements(SearchContext searchContext) { List<WebElement> result; JavascriptExecutor executor = JavascriptHelper.getJavascriptExecutor(searchContext); Object results = JavascriptHelper.executeScript(executor, script, scriptParameters); if (results instanceof List) { result = (List<WebElement>) results; } else { if (results == null) { result = Collections.emptyList(); } else { throw new RuntimeException("Script returned something else than a list: " + results); } } return result; }
@Override public WebElement findElement(SearchContext driver) { String attrName = getAttrName(); String attrVal = getValue(); By by = getBy(); List<WebElement> elementList = driver.findElements(by); for(WebElement ele : elementList) { if(driver instanceof WebDriver) { new Actions((WebDriver) driver).moveToElement(ele); } if(attrVal.equals(ele.getAttribute(attrName))) { return ele; } } return null; }
@SuppressWarnings("unchecked") public E findElement(SearchContext driver) { By by = getBy(); if(driver instanceof WebDriver) { elementWait((WebDriver) driver, getTimeout(), by); } return (E) driver.findElement(by); }
@SuppressWarnings("unchecked") public List<E> findElements(SearchContext driver) { By by = getBy(); if(driver instanceof WebDriver) { elementWait((WebDriver) driver, getTimeout(), by); } return (List<E>) driver.findElements(by); }