List of usage examples for org.openqa.selenium WebDriverException getMessage
@Override
public String getMessage()
From source file:io.selendroid.nativetests.NativeElementFindingTest.java
License:Apache License
@Test public void shouldNotFindElementsByCss() throws Exception { openStartActivity();/* w w w . ja v a 2s .co m*/ try { driver().findElements(By.cssSelector("button[id='linkId']")); Assert.fail("Finding Native elements by css selector is not supported."); } catch (WebDriverException e) { Assert.assertTrue(e.getMessage().contains("By locator ByCssSelector is curently not supported!")); } }
From source file:io.selendroid.nativetests.NativeElementInteractionTest.java
License:Apache License
@Test public void shouldSubmitAnElement() { openStartActivity();//from w w w . ja va 2s .c o m WebElement button = driver().findElement(By.id("waitingButtonTest")); try { button.submit(); Assert.fail(); } catch (WebDriverException e) { Assert.assertTrue(e.getMessage().contains("Submit is not supported for native elements.")); } }
From source file:nz.co.testamation.core.client.SeleniumBrowserDriver.java
License:Apache License
private void waitBeforeClick(By by) { waitForVisible(by);/*from w ww. j a v a 2s . co m*/ try { findElement(by).click(); } catch (WebDriverException ex) { if (ex.getMessage().contains("Element is not clickable")) { System.out.println("Element is not clickable, retrying..."); try { Thread.sleep(250); findElement(by).click(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }
From source file:org.aludratest.service.gui.web.selenium.selenium2.Selenium2Wrapper.java
License:Apache License
private void handleSeleniumException(Throwable e) { Throwable origException = e;//from w ww . j a v a2 s . co m String message = e.getMessage(); // check if there is a WebDriverException WebDriverException wde = null; while (e != null) { if (e instanceof WebDriverException) { wde = (WebDriverException) e; break; } e = e.getCause(); } if (wde != null) { if (message == null) { message = wde.getMessage(); } // "not clickable" exception Pattern p = Pattern.compile("(unknown error: )?(.* not clickable .*)"); Matcher m; if (message != null && (m = p.matcher(message)).find() && m.start() == 0) { throw new AutomationException(m.group(2), wde); } // NoSuchElementException if (wde instanceof NoSuchElementException) { throw new AutomationException("Element not found", wde); } // check for a time out if (wde instanceof TimeoutException) { throw new PerformanceFailure(wde.getMessage(), wde); } throw wde; } // otherwise, throw a technical exception throw new TechnicalException("Unknown exception when clicking element", origException); }
From source file:org.asqatasun.sebuilder.interpreter.TgTestRun.java
License:Open Source License
/** * //from www . java 2s. c o m * @param url */ private void getSourceCodeAndFireNewPage(String url) { try { try { Thread.sleep(500); } catch (InterruptedException ex) { throw new TestRunException(currentStep() + " failed.", ex, currentStep().toString(), stepIndex); } String sourceCode = getDriver().getPageSource(); /* ############################################################## * ACHTUNG !!!!!!!!!!!!!!!!!!!!!!!!!! * this sendKeys action is here to grab the focus on the page. * It is needed later by the js script to execute the focus() * method on each element. Without it, the focus is kept by the adress * bar. */ WebElement body = getDriver().findElementByTagName("html"); Map<String, String> jsScriptResult = Collections.EMPTY_MAP; try { body.sendKeys(Keys.TAB); jsScriptResult = executeJsScripts(); } catch (WebDriverException wde) { getLog().warn(wde.getMessage()); } /*##############################################################*/ /* byte[] snapshot = createPageSnapshot();*/ for (NewPageListener npl : newPageListeners) { npl.fireNewPage(url, sourceCode, null, jsScriptResult); } } catch (UnhandledAlertException uae) { getLog().warn(uae.getMessage()); throw new TestRunException(currentStep() + " failed.", uae, currentStep().toString(), stepIndex); } }
From source file:org.asqatasun.sebuilder.interpreter.TgTestRun.java
License:Open Source License
/** * //ww w . j a v a 2s . co m * @return */ private Map<String, String> executeJsScripts() { getLog().debug("Executing js"); Map<String, String> jsScriptResult = new HashMap<>(); for (Map.Entry<String, String> entry : jsScriptMap.entrySet()) { try { jsScriptResult.put(entry.getKey(), getDriver().executeScript(entry.getValue()).toString()); } catch (WebDriverException wde) { getLog().warn("Script " + entry.getKey() + " has failed"); getLog().warn(wde.getMessage()); } } getLog().debug("Js executed"); return jsScriptResult; }
From source file:org.auraframework.integration.test.ClientOutOfSyncUITest.java
License:Apache License
/** * This test verifies that changes to components which are dynamically received are correctly identified * after the client is restarted. This is complex to make work: dynamically received defs must be * persisted with sufficient versioning information which is later restored (during client restart / framework * init), then sent to the server so the server can detect the version change and trigger a client out-of-date * message.//w ww . j a v a2 s . c o m * * This test verifies the behavior by retrieving a component from the server, modifying its source on the server, * reloading the page, then requesting the same component from the server, asserting that the new source is returned. * Without persisting the component version on the client, the server would never know the client's version of * the component we're loading is out of date and after a page reload the old component would be displayed. * * See W-2909975 for additional details. */ // This tests persistent storage, exclude on Safari based browsers @ExcludeBrowsers({ BrowserType.SAFARI, BrowserType.IPAD, BrowserType.IPHONE }) public void _testReloadAfterMarkupChange() throws Exception { DefDescriptor<ComponentDef> cmpDesc = addSourceAutoCleanup(ComponentDef.class, String.format(baseComponentTag, "", "<div>cmp" + new Date().getTime() + "</div>")); DefDescriptor<ApplicationDef> appDesc = addSourceAutoCleanup(ApplicationDef.class, String.format( baseApplicationTag, "template='auraStorageTest:componentDefStorageTemplate'", "<ui:button label='loadCmp' press='{!c.loadCmp}'/><div id='container' aura:id='container'>app</div>" + "<aura:handler event='aura:initialized' action='{!c.initialized}'/>")); String cmpDefString = cmpDesc.getNamespace() + ":" + cmpDesc.getName(); DefDescriptor<?> controllerDesc = Aura.getDefinitionService().getDefDescriptor(appDesc, DefDescriptor.JAVASCRIPT_PREFIX, ControllerDef.class); addSourceAutoCleanup(controllerDesc, "{" + "loadCmp:function(cmp){$A.createComponent('" + cmpDefString + "', {}, function(newCmp){ cmp.find('container').set('v.body', newCmp); });}," + "initialized:function(cmp){window.initialized=true;}" + "}"); open(appDesc); // Retrieve cmp from server and wait for callback output getAuraUITestingUtil().findDomElement(By.cssSelector("button")).click(); getAuraUITestingUtil().waitUntil(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver d) { String text = getText(By.cssSelector("#container")); return text.startsWith("cmp"); } }, "Text of app never updated after retrieving component from server"); // Update the source of the component we retrieve from storage String newCmpText = "<div>cmpNew" + new Date().getTime() + "</div>"; updateStringSource(cmpDesc, String.format(baseComponentTag, "", newCmpText)); // Wait for dynamically received component def to be persisted. // ComponentDefStorage will exist because a dynamic cmp is fetched final String getPersistedDef = "var callback = arguments[arguments.length - 1];" + "if (!$A) { callback('Aura not initialized'); return; };" + "var storage = $A.storageService.getStorage('ComponentDefStorage');" + "if (!storage) { callback('No storage'); return; };" + "storage.get('markup://" + cmpDefString + "').then(function(item) { callback(item ? 'SUCCESS' : 'empty') });"; getAuraUITestingUtil().waitUntil(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver d) { d.manage().timeouts().setScriptTimeout(1, TimeUnit.SECONDS); Object result = ((JavascriptExecutor) getDriver()).executeAsyncScript(getPersistedDef); return "SUCCESS".equals(result); } }, "Definition never persisted on client after server call"); getDriver().navigate().refresh(); // After refresh, the page will fire the getApplication bootstrap action, which will get a ClientOutOfSync // as the response, dump the storages and reload. Instead of trying to wait for the double reload, wait for // Aura Fwk + the app to finish loading (window.initialize) then create def storage (which won't exist // because no dynamic defs have been received) and verify it is empty. getAuraUITestingUtil().waitUntil(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver d) { String script = "var callback = arguments[arguments.length - 1];" + "if (!window.initialized || !$A) { callback(null); return; }" + "if (!$A.storageService.getStorage('ComponentDefStorage')) {" + " $A.storageService.initStorage({name: 'ComponentDefStorage', persistent: true, secure: false, maxSize: 442368, expiration: 3600, debugLogging: true, clearOnInit: false});" + "}" + "var storage = $A.storageService.getStorage('ComponentDefStorage');" + "storage.getAll().then(" + " function(items){ callback(Object.keys(items)) }," + " function() { callback(null); }" + ")"; Object result = null; try { result = ((JavascriptExecutor) getDriver()).executeAsyncScript(script); } catch (WebDriverException e) { // If the page reloads during our script WebDriver will throw an error. if (!e.getMessage().contains("document unloaded while waiting for result")) { throw e; } } return result != null && ((ArrayList<?>) result).size() == 0; } }, "Storages never cleared after reload"); // The page will reload after the storage is cleared so wait for it to be fully initialized then retrieve // the original component from the server and verify it has the updated source. getAuraUITestingUtil().waitForAuraInit(); getAuraUITestingUtil().findDomElement(By.cssSelector("button")).click(); getAuraUITestingUtil().waitForElementTextContains(By.cssSelector("#container"), "cmpNew", true); }
From source file:org.auraframework.integration.test.util.WebDriverTestCase.java
License:Apache License
/** * Gather up useful info to add to a test failure. try to get * <ul>/*from w ww . j a v a2 s. com*/ * <li>any client js errors</li> * <li>last known js test function</li> * <li>running/waiting</li> * <li>a screenshot</li> * </ul> * * @param originalErr the test failure * @throws Throwable a new AssertionFailedError or UnexpectedError with the original and additional info */ private Throwable addAuraInfoToTestFailure(Throwable originalErr) { StringBuffer description = new StringBuffer(); if (originalErr != null) { String msg = originalErr.getMessage(); if (msg != null) { description.append(msg); } } description.append(String.format("\nBrowser: %s", currentBrowserType)); if (getAuraUITestingUtil() != null) { description.append("\nUser-Agent: " + getAuraUITestingUtil().getUserAgent()); } if (currentDriver == null) { description.append("\nTest failed before WebDriver was initialized"); } else { if (this instanceof PerfExecutorTestCase) { JSONArray json = this.getLastCollectedMetrics(); description.append("\nPerfMetrics: " + json + ';'); } description.append("\nWebDriver: " + currentDriver); description.append("\nJS state: "); try { String dump = (String) getAuraUITestingUtil() .getRawEval("return (window.$A && $A.test && $A.test.getDump())||'';"); if (dump.isEmpty()) { description.append("no errors detected"); } else { description.append(dump); } } catch (Throwable t) { description.append(t.getMessage()); } String screenshotsDirectory = System.getProperty("screenshots.directory"); if (screenshotsDirectory != null) { String screenshot = null; TakesScreenshot ts = (TakesScreenshot) currentDriver; try { screenshot = ts.getScreenshotAs(OutputType.BASE64); } catch (WebDriverException e) { description.append(String.format("%nScreenshot: {capture error: %s}", e.getMessage())); } if (screenshot != null) { String fileName = getClass().getName() + "." + getName() + "_" + currentBrowserType + ".png"; try { File path = new File(screenshotsDirectory + "/" + fileName); path.getParentFile().mkdirs(); byte[] bytes = Base64.decodeBase64(screenshot.getBytes()); FileOutputStream fos = new FileOutputStream(path); fos.write(bytes); fos.close(); String baseUrl = System.getProperty("screenshots.baseurl"); description.append(String.format("%nScreenshot: %s/%s", baseUrl, fileName)); } catch (Throwable t) { description.append(String.format("%nScreenshot: {save error: %s}", t.getMessage())); } } } try { description.append("\nApplication cache status: "); description.append(getAuraUITestingUtil().getRawEval( "var cache=window.applicationCache;return (cache===undefined || cache===null)?'undefined':cache.status;") .toString()); } catch (Exception ex) { description.append("error calculating status: " + ex); } description.append("\n"); if (SauceUtil.areTestsRunningOnSauce()) { String linkToJob = SauceUtil.getLinkToPublicJobInSauce(currentDriver); description.append("\nSauceLabs-recording: "); description.append((linkToJob != null) ? linkToJob : "{not available}"); } } // replace original exception with new exception with additional info Throwable newFailure; if (originalErr instanceof AssertionFailedError) { newFailure = new AssertionFailedError(description.toString()); } else { description.insert(0, originalErr.getClass() + ": "); newFailure = new UnexpectedError(description.toString(), originalErr.getCause()); } newFailure.setStackTrace(originalErr.getStackTrace()); return newFailure; }
From source file:org.auraframework.test.util.AuraUITestingUtil.java
License:Apache License
/** * Evaluate the given javascript in the current window. Upon completion, if the framework has loaded and is in a * test mode, then assert that there are no uncaught javascript errors. * <p>/*from w w w . ja v a2 s . c o m*/ * As an implementation detail, we accomplish this by wrapping the given javascript so that we can perform the error * check on each evaluation without doing a round-trip to the browser (which might be long in cases of remote test * runs). * * @return the result of calling {@link JavascriptExecutor#executeScript(String, Object...) with the given * javascript and args. */ public Object getEval(final String javascript, Object... args) { /** * Wrapping the javascript on the native Android browser is broken. By not using the wrapper we won't catch any * javascript errors here, but on passing cases this should behave the same functionally. See W-1481593. */ if (driver instanceof RemoteWebDriver && "android".equals(((RemoteWebDriver) driver).getCapabilities().getBrowserName())) { return getRawEval(javascript, args); } /** * Wrap the given javascript to evaluate and then check for any collected errors. Then, return the result and * errors back to the WebDriver. We must return as an array because * {@link JavascriptExecutor#executeScript(String, Object...)} cannot handle Objects as return values." */ String escapedJavascript = StringEscapeUtils.escapeEcmaScript(javascript); String wrapper = "var ret,scriptExecException;\n" + "try {\n" + String.format("var func = new Function('arguments', \"%s\");\n", escapedJavascript) + " ret = func.call(this, arguments);\n" + "} catch(e){\n" + " scriptExecException = e.message || e.toString();\n" + "}\n" + "var jstesterrors = (window.$A && window.$A.test) ? window.$A.test.getErrors() : '';\n" + "return [ret, jstesterrors, scriptExecException];"; try { Object obj = getRawEval(wrapper, args); Assert.assertTrue( "Expecting an instance of list, but get " + obj + ", when running: " + escapedJavascript, obj instanceof List); @SuppressWarnings("unchecked") List<Object> wrapResult = (List<Object>) obj; Assert.assertEquals("Wrapped javsascript execution expects an array of exactly 3 elements", 3, wrapResult.size()); Object exception = wrapResult.get(2); Assert.assertNull( "Following JS Exception occured while evaluating provided script:\n" + exception + "\n" + "Arguments: (" + Arrays.toString(args) + ")\n" + "Script:\n" + javascript + "\n", exception); String errors = (String) wrapResult.get(1); assertJsTestErrors(errors); rerunCount = 0; return wrapResult.get(0); } catch (WebDriverException e) { // shouldn't come here that often as we are also wrapping the js // script being passed to us in try/catch above Assert.fail("Script execution failed.\n" + "Exception type: " + e.getClass().getName() + "\n" + "Failure Message: " + e.getMessage() + "\n" + "Arguments: (" + Arrays.toString(args) + ")\n" + "Script:\n" + javascript + "\n"); throw e; } catch (NullPointerException npe) { // Although it should never happen, ios-driver is occasionally returning null when trying to execute the // wrapped javascript. Re-run the script a couple more times before failing. if (++rerunCount > 2) { Assert.fail("Script execution failed.\n" + "Failure Message: " + npe.getMessage() + "\n" + "Arguments: (" + Arrays.toString(args) + ")\n" + "Script:\n" + javascript + "\n"); } return getEval(javascript, args); } }
From source file:org.auraframework.util.AuraUITestingUtil.java
License:Apache License
/** * Evaluate the given javascript in the current window. Upon completion, if the framework has loaded and is in a * test mode, then assert that there are no uncaught javascript errors. * <p>/*ww w. ja va 2s . c om*/ * As an implementation detail, we accomplish this by wrapping the given javascript so that we can perform the error * check on each evaluation without doing a round-trip to the browser (which might be long in cases of remote test * runs). * * @return the result of calling {@link JavascriptExecutor#executeScript(String, Object...) with the given * javascript and args. */ public Object getEval(final String javascript, Object... args) { /** * Wrapping the javascript on the native Android browser is broken. By not using the wrapper we won't catch any * javascript errors here, but on passing cases this should behave the same functionally. See W-1481593. */ if (driver instanceof RemoteWebDriver && "android".equals(((RemoteWebDriver) driver).getCapabilities().getBrowserName())) { return getRawEval(javascript, args); } /** * Wrap the given javascript to evaluate and then check for any collected errors. Then, return the result and * errors back to the WebDriver. We must return as an array because * {@link JavascriptExecutor#executeScript(String, Object...)} cannot handle Objects as return values." */ String escapedJavascript = StringEscapeUtils.escapeEcmaScript(javascript); String wrapper = "var ret,scriptExecException;" + String.format("var func = new Function('arguments', \"%s\");\n", escapedJavascript) + "try\n{" + " ret = func.call(this, arguments);\n" + "}\n" + "catch(e){\n" + " scriptExecException = e.message || e.toString();\n" + "}\n" + // "var jstesterrors = (window.$A && window.$A.test) ? window.$A.test.getErrors() : '';\n" + "return [ret, jstesterrors, scriptExecException];"; try { @SuppressWarnings("unchecked") List<Object> wrapResult = (List<Object>) getRawEval(wrapper, args); Assert.assertEquals("Wrapped javsascript execution expects an array of exactly 3 elements", 3, wrapResult.size()); Object exception = wrapResult.get(2); Assert.assertNull( "Following JS Exception occured while evaluating provided script:\n" + exception + "\n" + "Arguments: (" + Arrays.toString(args) + ")\n" + "Script:\n" + javascript + "\n", exception); String errors = (String) wrapResult.get(1); assertJsTestErrors(errors); rerunCount = 0; return wrapResult.get(0); } catch (WebDriverException e) { // shouldn't come here that often as we are also wrapping the js // script being passed to us in try/catch above Assert.fail("Script execution failed.\n" + "Exception type: " + e.getClass().getName() + "\n" + "Failure Message: " + e.getMessage() + "\n" + "Arguments: (" + Arrays.toString(args) + ")\n" + "Script:\n" + javascript + "\n"); throw e; } catch (NullPointerException npe) { // Although it should never happen, ios-driver is occasionally returning null when trying to execute the // wrapped javascript. Re-run the script a couple more times before failing. if (++rerunCount > 2) { Assert.fail("Script execution failed.\n" + "Failure Message: " + npe.getMessage() + "\n" + "Arguments: (" + Arrays.toString(args) + ")\n" + "Script:\n" + javascript + "\n"); } return getEval(javascript, args); } }