public void windowTitleWithPercentage() throws Throwable { driver = new JavaDriver(); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { frame.setTitle("My %Dialog%"); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); WebElement element1 = driver.findElement(By.name("click-me")); String id1 = ((RemoteWebElement) element1).getId(); // driver.switchTo().window("My %25Dialog%25"); TargetLocator switchTo = driver.switchTo(); switchTo.window("My %Dialog%"); WebElement element2 = driver.findElement(By.name("click-me")); String id2 = ((RemoteWebElement) element2).getId(); AssertJUnit.assertEquals(id1, id2); }
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 fail) { //NOOP Would like to log here? } } }
@SuppressWarnings("unchecked") @Override public Object apply(Object result) { if (result instanceof Collection<?>) { Collection<QAFExtendedWebElement> results = (Collection<QAFExtendedWebElement>) result; return Lists.newArrayList(Iterables.transform(results, this)); } result = super.apply(result); if(result instanceof RemoteWebElement){ if(!(result instanceof QAFExtendedWebElement)){ QAFExtendedWebElement ele = newRemoteWebElement(); ele.setId(((RemoteWebElement)result).getId()); return ele; } } return result; }
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); } } }
@Override @Monitor @RetryFailure(retryCount=3) @JSHandle public WebDriverController uploadFile(Object locator, String path) { LocalFileDetector detector = new LocalFileDetector(); File localFile = detector.getLocalFile(path); ((RemoteWebElement)waitController().waitForElementPresence(locator)).setFileDetector(detector); waitController().waitForElementPresence(locator).sendKeys(localFile.getAbsolutePath()); return this; }
public void findElementGetsTheSameElementBetweenCalls() throws Throwable { driver = new JavaDriver(); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { frame.setLocationRelativeTo(null); frame.setVisible(true); } }); WebElement element1 = driver.findElement(By.name("click-me")); String id1 = ((RemoteWebElement) element1).getId(); WebElement element2 = driver.findElement(By.name("click-me")); String id2 = ((RemoteWebElement) element2).getId(); AssertJUnit.assertEquals(id1, id2); }
public void findElementGetsTheSameElementBetweenWindowCalls() throws Throwable { driver = new JavaDriver(); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { frame.setLocationRelativeTo(null); frame.setVisible(true); } }); WebElement element1 = driver.findElement(By.name("click-me")); String id1 = ((RemoteWebElement) element1).getId(); driver.switchTo().window(titleOfWindow); WebElement element2 = driver.findElement(By.name("click-me")); String id2 = ((RemoteWebElement) element2).getId(); AssertJUnit.assertEquals(id1, id2); }
public void getLocationInView() throws Throwable { driver = new JavaDriver(); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { frame.setLocationRelativeTo(null); frame.setVisible(true); } }); WebElement element1 = driver.findElement(By.name("click-me")); try { ((RemoteWebElement) element1).getCoordinates().inViewPort(); throw new MissingException(WebDriverException.class); } catch (WebDriverException e) { } }
protected final <T> T waitForPageLoad(Func<T> func) { RemoteWebElement oldHtml = (RemoteWebElement) driver.findElement(By.tagName("html")); T result = func.call(); WebDriverWait wait = new WebDriverWait(driver, 30); wait.until((WebDriver input) -> { RemoteWebElement newHtml = (RemoteWebElement) driver.findElement(By.tagName("html")); return ! newHtml.getId().equals(oldHtml.getId()); }); return result; }
private Class<?> getTypeForProxy() { Class<? extends SearchContext> driverClass = originalDriver.getClass(); Iterable<Map.Entry<Class<? extends SearchContext>, Class<? extends WebElement>>> rules = elementRuleMap.entrySet(); //it will return MobileElement subclass when here is something for (Map.Entry<Class<? extends SearchContext>, Class<? extends WebElement>> e : rules) { //that extends AppiumDriver or MobileElement if (e.getKey().isAssignableFrom(driverClass)) { return e.getValue(); } } //it is compatible with desktop browser. So at this case it returns RemoteWebElement.class return RemoteWebElement.class; }
@Override public WebElement findElement(By by) { WebElement e = getInstance().findElement(by); if (e instanceof RemoteWebElement) { e = new ClickAndWaitRemoteWebElement(e, this); } return e; }
@Override public List<WebElement> findElements(By by) { List<WebElement> list = getInstance().findElements(by); List<WebElement> newList = new ArrayList<>(list.size()); for (WebElement e : list) { if (e instanceof RemoteWebElement) { e = new ClickAndWaitRemoteWebElement(e, this); } newList.add(e); } return newList; }
/** * When send keys is being executed in a input file=type {@link LocalFileDetector} must be configured for remote drivers. Additionally, * the file path is expanded to be absolute * * @param driver used to run commands * @param element receiving keys * @param value to be set to input file type * @return value expanded to absolute path if for input file type. */ private String cleanValueToSend(WebDriver driver, WebElement element, String value) { if (!StringUtils.equals(element.getAttribute(SeleniumFixture.INPUT_TYPE_ATTRIBUTE), SeleniumFixture.INPUT_TYPE_FILE_VALUE)) { return this.fitnesseMarkup.clean(value); } // set file detector for remote web elements. Local FirefoxDriver uses RemoteWebElement and if (element instanceof RemoteWebElement && !ClassUtils.isAssignable(driver.getClass(), FirefoxDriver.class)) { ((RemoteWebElement) element).setFileDetector(new LocalFileDetector()); } return this.fitnesseMarkup.cleanFile(value).getAbsolutePath(); }
public boolean tapById(String id) { try{ Map<String, ?> params = ImmutableMap.of("element", ((RemoteWebElement)driver.findElement(By.id(id))).getId()); ((RobotRemoteWebDriver)this.driver).execute(DriverCommand.TOUCH_SINGLE_TAP, params); }catch(Exception ex) { return false; } return true; }
public boolean tapByXPath(String xpath) { try { Map<String, ?> params = ImmutableMap.of("element", ((RemoteWebElement)driver.findElement(By.xpath(xpath))).getId()); ((RobotRemoteWebDriver)this.driver).execute(DriverCommand.TOUCH_SINGLE_TAP, params); }catch(Exception ex) { return false; } return true; }
public boolean tap(By by) { try { Map<String, ?> params = ImmutableMap.of("element", ((RemoteWebElement)driver.findElement(by)).getId()); ((RobotRemoteWebDriver)this.driver).execute(DriverCommand.TOUCH_SINGLE_TAP, params); }catch(Exception ex) { return false; } return true; }
private RemoteWebElement getSelectedRemWebElement() { ComboBox comboBox = new ComboBox(element.getWebElement()); RemoteWebElement selected; try { selected = comboBox.findSelected(); } catch (NoSuchElementException e) { expand(); close(); selected = comboBox.findSelected(); } return selected; }
private RemoteWebElement setOwner(RemoteWebElement element) { if (driver != null) { element.setParent(driver); element.setFileDetector(driver.getFileDetector()); } return element; }
private void xpathContext(ExecutionContext script, StreamTokenizer tokenizer) throws Exception { Exception e; stype = SelectionType.None; selector = null; String sval = script.getExpandedString(tokenizer); System.out.println(sval); do { try { selection = (RemoteWebElement) driver.findElement(By.xpath(sval)); if (_not) { _test = _not = false; throw new Exception("not xpath " + sval + " is invalid on line " + tokenizer.lineno()); } selectionCommand = "xpath \"" + sval + "\""; stype = SelectionType.XPath; selector = sval; _test = true; return; } catch(Exception ex) { e = ex; sleep(100); } } while (_waitFor > 0 && (new Date()).getTime() < _waitFor); _waitFor = 0; _test = false; if (!_if) { if (_not) { _test = true; selection = null; _not = false; return; } throw new Exception("xpath " + sval + " is invalid on line " + tokenizer.lineno() + " " + e.getMessage()); } }
private void selectContext(StreamTokenizer tokenizer, ExecutionContext script) throws Exception { Exception e; stype = SelectionType.None; selector = null; String sval = script.getExpandedString(tokenizer); System.out.println(sval); do { try { selection = (RemoteWebElement) driver.findElement(By.cssSelector(sval)); if (_not) { _test = _not = false; throw new Exception("not selector " + sval + " is invalid on line " + tokenizer.lineno()); } selectionCommand = "select \"" + sval + "\""; stype = SelectionType.Select; selector = sval; _test = true; return; } catch(Exception ex) { e = ex; sleep(100); } } while (_waitFor > 0 && (new Date()).getTime() < _waitFor); _waitFor = 0; _test = false; if (!_if) { if (_not) { _test = true; selection = null; selector = null; _not = false; return; } throw new Exception("selector " + sval + " is invalid on line " + tokenizer.lineno() + " " + e.getMessage()); } }
private void setContextToField(ExecutionContext script, StreamTokenizer tokenizer) throws Exception { Exception e; String sval = script.getExpandedString(tokenizer); System.out.println(sval); String query = "//*[@test-id='"+sval+"']"; stype = SelectionType.None; selector = null; do { try { selection = (RemoteWebElement) driver.findElement(By.xpath(query)); if (_not) { _test = _not = false; throw new Exception("not test-id " + sval + " is invalid on line " + tokenizer.lineno()); } selectionCommand = "field \"" + sval + "\""; stype = SelectionType.Field; selector = query; _test = true; return; } catch(Exception ex) { e = ex; sleep(100); } } while (this._waitFor > 0 && (new Date()).getTime() < this._waitFor); _waitFor = 0; _test = false; if (!_if) { if (_not) { _test = true; selection = null; _not = false; return; } throw new Exception("field reference " + sval + " is invalid on line " + tokenizer.lineno() + " " + e.getMessage()); } }
protected void fillFileBox(RemoteWebElement fileBoxElement, String fileName) { if (fileName.isEmpty()) { fileBoxElement.clear(); } else { fileBoxElement.setFileDetector(new UselessFileDetector()); String newFilePath = new File(fileName).getAbsolutePath(); fileBoxElement.sendKeys(newFilePath); } }
@Override public Object apply(Object result) { if (result instanceof RemoteWebElement && !(result instanceof CachingRemoteWebElement)) { RemoteWebElement originalElement = (RemoteWebElement) result; result = createCachingWebElement(originalElement); } return super.apply(result); }
protected CachingRemoteWebElement createCachingWebElement(RemoteWebElement originalElement) { CachingRemoteWebElement element = new CachingRemoteWebElement(originalElement); // ensure we always set the correct parent and file detector element.setParent(driver); element.setFileDetector(driver.getFileDetector()); return element; }
@Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(SessionContext.getSession().getWebDriver().toString()); sb.append(" ").append(method.getName()); for (Object param : params) if (param instanceof WebElement && !(SessionContext.getSession().getWebDriver() instanceof EventFiringWebDriver)) sb.append(" ").append(((RemoteWebElement) param).getId()); else if (param instanceof WebElement && SessionContext.getSession().getWebDriver() instanceof EventFiringWebDriver) { sb.append(" ").append(((WebElement) param).getLocation()); } else { sb.append(" ").append(param.toString()); } return sb.toString(); }
@Ignore @Test public void deleteAllNotes() throws CandybeanException { openNotes(); List<WebElement> notes = iface.wd.findElements(By .id("com.evernote:id/title")); while (notes.size() != 0) { WebElement note = notes.get(0); HashMap<String, String> values = new HashMap<String, String>(); values.put("element", ((RemoteWebElement) note).getId()); ((JavascriptExecutor) iface.wd).executeScript("mobile: longClick", values); iface.pause(1000); WebElement footer = ((RemoteWebDriver) iface.wd) .findElementById("com.evernote:id/efab_menu_footer"); List<WebElement> footerItems = footer.findElements(By .className("android.widget.ImageButton")); WebElement moreOptions = footerItems.get(footerItems.size() - 1); moreOptions.click(); iface.pause(1000); WebElement deleteButton = iface.wd.findElements( By.id("com.evernote:id/item_title")).get(5); deleteButton.click(); iface.pause(1000); WebElement deleteConfirmation = iface.wd.findElement(By .id("android:id/button1")); deleteConfirmation.click(); iface.pause(1000); notes = iface.wd.findElements(By.id("com.evernote:id/title")); } assertEquals(iface.wd.findElements(By.id("com.evernote:id/title")).size(), 0); }
private void disableAutoComplete(){ // Display the settings in Google Earth Engine Code Editor (this emulates clicking on the settings icon) webDriverGee.findElementByClassName("settings-menu-button").click(); // Get the Div that is the parent of the one with text that contains Autocomplete RemoteWebElement autocompleteButton = (RemoteWebElement) webDriverGee.findElementByXPath("//div[contains(text(), \"Autocomplete\")]/.."); if(isAutocompleChecked(autocompleteButton)){ // Disable the Autocomplete of special characters autocompleteButton.click(); } }
private final JavascriptExecutor getJavascriptExecutor(SearchContext context) { JavascriptExecutor jse; if (context instanceof RemoteWebElement) { jse = (JavascriptExecutor) ((RemoteWebElement) context).getWrappedDriver(); } else { jse = (JavascriptExecutor) context; } return jse; }
private Map<String, Object> getTouchParameters(WebElement element, int x, int y) { Map<String, Object> params = Maps.newHashMap(); if (element != null) { params.put("element", ((RemoteWebElement) element).getId()); } params.put("x", x); params.put("y", y); return params; }
/** * Get the values of all table cells.</br> * * <b>Note:</b> If a table cell contains a checkbox - we will return 'checked' or 'notchecked' value. * * @return a two dimensional array containing all table cell values */ @PublicAtsApi public String[][] getAllValues() { new RealHtmlElementState(this).waitToBecomeExisting(); WebElement table = RealHtmlElementLocator.findElement(this); String scriptForHtml = generateScriptForGettingTableContent(".innerHTML"); Object returnedHtmlValue = ((JavascriptExecutor) webDriver).executeScript(scriptForHtml, table); String scriptForObjects = generateScriptForGettingTableContent(""); Object returnedObjectsValue = ((JavascriptExecutor) webDriver).executeScript(scriptForObjects, table); String[][] tableData = null; if (returnedHtmlValue != null && returnedHtmlValue instanceof List && returnedObjectsValue != null && returnedObjectsValue instanceof List) { List<?> htmlTable = (List<?>) returnedHtmlValue; List<?> objectsTable = (List<?>) returnedObjectsValue; // allocate space for a number of rows tableData = new String[htmlTable.size()][]; for (int iRow = 0; iRow < htmlTable.size(); iRow++) { if (htmlTable.get(iRow) instanceof List) { List<?> htmlRow = (List<?>) htmlTable.get(iRow); List<?> objectsRow = (List<?>) objectsTable.get(iRow); // allocate space for the cells of the current row tableData[iRow] = new String[htmlRow.size()]; for (int iColumn = 0; iColumn < htmlRow.size(); iColumn++) { Object htmlWebElement = htmlRow.get(iColumn); Object objectWebElement = objectsRow.get(iColumn); // some data cannot be presented in textual way - for example a checkbox String htmlValueString = htmlWebElement.toString() .toLowerCase() .replace("\r", "") .replace("\n", ""); if (htmlValueString.matches(".*<input.*type=.*[\"|']checkbox[\"|'].*>.*")) { // We assume this is a checkbox inside a table cell. // We will return either 'checked' or 'notchecked' tableData[iRow][iColumn] = htmlValueString.contains("checked") ? "checked" : "notchecked"; } else { // proceed in the regular way by returning the data visible to the user tableData[iRow][iColumn] = ((RemoteWebElement) objectWebElement).getText(); } } } } } else { log.warn("We could not get the content of table declared as: " + this.toString()); } return tableData; }
/** * Wrap WebElement in MobileElement * */ private static MobileElement w(WebElement element) { return new MobileElement((RemoteWebElement) element, driver); }
public static <T extends AdfComponent> T forElement(WebElement element) { RemoteWebElement rwe = (RemoteWebElement) element; RemoteWebDriver rwd = (RemoteWebDriver) rwe.getWrappedDriver(); String clientid = (String) rwd.executeScript(JS_FIND_ANCESTOR_COMPONENT, element); return forClientId(rwd, clientid); }
public RemoteWebElement getWebElement() { return this.webElement; }
public NativeAppElement(NativeAppDriver nativeAppDriver, By byLocator, WebElement webElement) { this.webElement = (RemoteWebElement) webElement; this.nativeAppDriver = nativeAppDriver; this.byLocator = byLocator; }
public void fillProfilePic(String fileName) { showPictureEditor(); RemoteWebElement ele = (RemoteWebElement) browser.driver.findElement(By.id("studentPhoto")); fillFileBox(ele, fileName); }
public CachingRemoteWebElement(RemoteWebElement element) { if (element != null) { setId(element.getId()); } }
/** * If an exception has thrown by selenium, this methods save a screen * capture. * * @param pjp ProceedingJoinPoint * @return Object object * @throws Throwable exception */ @Around(value = "exceptionCallPointcut()") public Object aroundExceptionCalls(ProceedingJoinPoint pjp) throws Throwable { Object retVal = null; try { retVal = pjp.proceed(); return retVal; } catch (Throwable ex) { WebDriver driver = null; if (ex instanceof WebDriverException) { logger.info("Got a selenium exception"); if (!(pjp.getThis() instanceof WebDriver)) { throw ex; } driver = (WebDriver) pjp.getThis(); } else if ((pjp.getTarget() instanceof SeleniumAssert) && (ex instanceof AssertionError)) { logger.info("Got a SeleniumAssert response"); SeleniumAssert as = (SeleniumAssert) pjp.getTarget(); Class<?> c = as.getClass().getSuperclass(); Field actual = c.getDeclaredField("actual"); actual.setAccessible(true); Object realActual = actual.get(as); if (realActual instanceof WebDriver) { driver = (WebDriver) actual.get(as); } else if (realActual instanceof ArrayList) { if (((ArrayList) realActual).get(0) instanceof RemoteWebElement) { driver = ((RemoteWebElement) ((ArrayList) realActual).get(0)).getWrappedDriver(); } } else if ((realActual instanceof PreviousWebElements) || (realActual instanceof Boolean) || (realActual instanceof String) || (realActual == null)) { driver = ((CommonG) ((SeleniumAssert) pjp.getTarget()).getCommonspec()).getDriver(); } else if (realActual instanceof RemoteWebElement) { driver = ((RemoteWebElement) actual.get(as)).getWrappedDriver(); } } if (driver != null) { logger.info("Trying to capture screenshots..."); CommonG common = null; if ((pjp.getThis() instanceof ThenGSpec) && (((ThenGSpec) pjp.getThis()).getCommonSpec() != null)) { common = ((ThenGSpec) pjp.getThis()).getCommonSpec(); } else if ((pjp.getTarget() instanceof SeleniumAssert) && ((SeleniumAssert) pjp.getTarget()).getCommonspec() != null) { common = ((CommonG) ((SeleniumAssert) pjp.getTarget()).getCommonspec()); } else { logger.info("Got no Selenium driver to capture a screen"); throw ex; } common.captureEvidence(driver, "framehtmlSource", "assert"); common.captureEvidence(driver, "htmlSource", "assert"); common.captureEvidence(driver, "screenCapture", "assert"); logger.info("Screenshots are available at target/executions"); } else { logger.info("Got no Selenium driver to capture a screen"); } throw ex; } }
public boolean isAutocompleChecked(RemoteWebElement autocompleteButton) { String buttonChecked = autocompleteButton.getAttribute("aria-checked"); return buttonChecked.equals("true" ); }