Java Code Examples for org.openqa.selenium.WebDriverException

The following are top voted examples for showing how to use org.openqa.selenium.WebDriverException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Sqawsh   File: SharedDriver.java   View source code 13 votes vote down vote up
@After
public void embedScreenshot(Scenario scenario) {
  try {
    if (!scenario.isFailed()) {
      // Take a screenshot only in the failure case
      return;
    }

    String webDriverType = System.getProperty("WebDriverType");
    if (!webDriverType.equals("HtmlUnit")) {
      // HtmlUnit does not support screenshots
      byte[] screenshot = getScreenshotAs(OutputType.BYTES);
      scenario.embed(screenshot, "image/png");
    }
  } catch (WebDriverException somePlatformsDontSupportScreenshots) {
    scenario.write(somePlatformsDontSupportScreenshots.getMessage());
  }
}
 
Example 2
Project: bromium   File: ActionExecutor.java   View source code 11 votes vote down vote up
private void executeIgnoringExceptions(WebDriver webDriver, WebDriverAction webDriverAction) {
    int i = 0;

    while (i < dependencies.getMaxRetries()) {
        try {
            webDriverAction.execute(webDriver, dependencies.getReplayingState(), dependencies.getEventSynchronizer());
            return;
        } catch (WebDriverException ex) {
            logger.error("Could not make it from first try because of {}", ex.toString());
            i++;
            try {
                Thread.sleep(dependencies.getMeasurementsPrecisionMilli());
            } catch (InterruptedException e) {
                throw dependencies.webDriverActionExecutionException("Interrupted while waiting to retry", e);
            }
        }
    }

    throw new TimeoutException("Could not execute the action! " + webDriverAction.getName());
}
 
Example 3
Project: Selenium-Foundation   File: SearchContextWait.java   View source code 8 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected RuntimeException timeoutException(String message, Throwable lastException) {
    TimeoutException ex = new TimeoutException(message, lastException);
    ex.addInfo(WebDriverException.DRIVER_INFO, context.getClass().getName());
    WebDriver driver = WebDriverUtils.getDriver(context);
    if (driver instanceof RemoteWebDriver) {
        RemoteWebDriver remote = (RemoteWebDriver) driver;
        if (remote.getSessionId() != null) {
            ex.addInfo(WebDriverException.SESSION_ID, remote.getSessionId().toString());
        }
        if (remote.getCapabilities() != null) {
            ex.addInfo("Capabilities", remote.getCapabilities().toString());
        }
    }
    throw ex;
}
 
Example 4
Project: marathonv5   File: JavaProfile.java   View source code 8 votes vote down vote up
public String getAgentJar() {
    String prefix = launchType.getPrefix();
    if (System.getenv(MARATHON_AGENT + ".file") != null) {
        return System.getenv(MARATHON_AGENT + ".file");
    }
    if (System.getProperty(MARATHON_AGENT + ".file") != null) {
        return System.getProperty(MARATHON_AGENT + ".file");
    }
    String path = findFile(new String[] { ".", "marathon-" + prefix + "-agent", "../marathon-" + prefix + "-agent",
            "../../marathonv4/marathon-" + prefix + "/marathon-" + prefix + "-agent", System.getProperty(PROP_HOME, "."),
            dirOfMarathonJavaDriverJar }, "marathon-" + prefix + "-agent.*.jar");
    if (path != null) {
        Logger.getLogger(JavaProfile.class.getName()).info("Using " + path + " for agent");
        return path;
    }
    throw new WebDriverException("Unable to find marathon-agent.jar. Set " + MARATHON_AGENT + ".file"
            + " environment variable to point to the jar file: " + new File(".").getAbsolutePath());
}
 
Example 5
Project: site-infrastructure-tests   File: VisitorIDServiceMinVersionTestCase.java   View source code 8 votes vote down vote up
@Override
protected void runTest() throws Throwable {
	try {
		// check whether DTM has been loaded on the page
		Object response = _page
				.executeJavaScript("(typeof Visitor !== 'undefined') ? Visitor.version : 'unavailable'")
				.getJavaScriptResult();

		// make sure the element exists
		if (String.class.isAssignableFrom(response.getClass()) && !((String) response).equals("unavailable")) {
			boolean result = Tools.testVersionNotOlderThanBaseVersion((String) response, _minVersion);
			assertTrue(Tools.MCVID + " min version should be " + _minVersion, result);
		} else {
			fail(Tools.MCVID + " version not available");
		}
	} catch (WebDriverException we) {
		fail(Tools.MCVID + " not found");
	}
}
 
Example 6
Project: Selenium-Foundation   File: PageSourceUtils.java   View source code 7 votes vote down vote up
/**
 * Produce page source from the specified driver.
 * 
 * @param optDriver optional web driver object
 * @param reason impetus for capture request; may be 'null'
 * @param logger SLF4J logger object
 * @return page source; if capture fails, an empty string is returned
 */
public static String getArtifact(Optional<WebDriver> optDriver, Throwable reason, Logger logger) {
    if (canGetArtifact(optDriver, logger)) {
        try {
            WebDriver driver = optDriver.get();
            StringBuilder sourceBuilder = new StringBuilder(driver.getPageSource());
            insertBaseElement(sourceBuilder, driver);
            insertBreakpointInfo(sourceBuilder, reason);
            insertOriginalUrl(sourceBuilder, driver);
            return sourceBuilder.toString();
        } catch (WebDriverException e) {
            logger.warn("The driver is capable of producing page source, but failed.", e);
        }
    }
    return "";
}
 
Example 7
Project: bromium   File: ActionExecutorTest.java   View source code 7 votes vote down vote up
@Test
public void ifTooManyAttemtpsActionTimesOut() throws IOException, URISyntaxException {
    int maxRetries = 3;
    ActionExecutor webDriverActionExecutionBase = getWebDriverActionExecutionBase(10, maxRetries);
    Iterator<WebDriverAction> webDriverActionIterator = mock(Iterator.class);
    TestScenarioActions testScenarioSteps = mock(TestScenarioActions.class);
    when(testScenarioSteps.iterator()).thenReturn(webDriverActionIterator);
    TestScenario testScenario = mock(TestScenario.class);
    when(testScenario.steps()).thenReturn(testScenarioSteps);
    when(webDriverActionIterator.hasNext()).thenReturn(true, false);
    WebDriverAction firstAction = mock(WebDriverAction.class);
    doThrow(new WebDriverException("Exception occured!")).when(firstAction).execute(any(), any(), any());
    when(webDriverActionIterator.next()).thenReturn(firstAction);
    ExecutionReport report = webDriverActionExecutionBase.execute(testScenario);
    assertEquals(AutomationResult.TIMEOUT, report.getAutomationResult());
    verify(firstAction, times(maxRetries)).execute(any(), any(), any());
}
 
Example 8
Project: Habanero   File: ScreenShotHook.java   View source code 7 votes vote down vote up
/**
 * <p>
 * Takes screen-shot if the scenario fails
 * </p>
 *
 * @param scenario will be the individual scenario's within the Feature files
 * @throws InterruptedException Exception thrown if there is an interuption within the JVM
 */
@After()
public void afterTest(Scenario scenario) throws InterruptedException {
    LOG.info("Taking screenshot IF Test Failed");
    System.out.println("Taking screenshot IF Test Failed (sysOut)");
    if (scenario.isFailed()) {
        try {
            System.out.println("Scenario FAILED... screen shot taken");
            scenario.write(getDriver().getCurrentUrl());
            byte[] screenShot = ((TakesScreenshot) getDriver()).getScreenshotAs(OutputType.BYTES);
            scenario.embed(screenShot, "image/png");
        } catch (WebDriverException e) {
            LOG.error(e.getMessage());
        }
    }
}
 
Example 9
Project: bobcat   File: AemImageSetterHelper.java   View source code 7 votes vote down vote up
private void executeJavascript(String imagePlaceholderId) {
  frameSwitcher.switchTo("/");
  JavascriptExecutor js = (JavascriptExecutor) webDriver;
  LOG.debug("executing javascript with argument: '{}'", imagePlaceholderId);

  bobcatWait.withTimeout(Timeouts.MEDIUM).until(driver -> {
    boolean executedSuccessfully = false;
    do {
      try {
        String javaScript = getJavascriptToExecute();
        js.executeScript(javaScript, imagePlaceholderId);
        executedSuccessfully = true;
      } catch (WebDriverException wde) {
        LOG.warn("error while executing JavaScript: '{}'", wde.getMessage(), wde);
      } catch (IOException ioe) {
        String msg = "error while loading JavaScript from file: " + IMAGE_SETTER_JS_FILENAME;
        LOG.error(msg, ioe);
        throw new BobcatRuntimeException(msg);
      }
    } while (!executedSuccessfully);
    return executedSuccessfully;
  }, DELAY_BEFORE_RETRY_IN_SECONDS);
  frameSwitcher.switchBack();
}
 
Example 10
Project: site-infrastructure-tests   File: DataLayerElementDelayedValueTestCase.java   View source code 7 votes vote down vote up
@Override
protected void runTest() throws Throwable {
	try {
		// sleep
		Thread.sleep(_delay);

		// get the value of the dl element from the page
		Object response = _page.executeJavaScript(_elementName).getJavaScriptResult();

		// make sure the element exists
		if (String.class.isAssignableFrom(response.getClass())) {
			assertEquals("Data Layer element " + _elementName + " value should be " + _elementExpectedValue
					+ "after " + _delay + "ms", _elementExpectedValue, (String) response);
		} else {
			fail("Data Layer element " + _elementName + " does not exist");
		}
	} catch (WebDriverException we) {
		fail("Data Layer element " + _elementName + " does not exist");
	}
}
 
Example 11
Project: site-infrastructure-tests   File: DataLayerElementDelayedExistsTestCase.java   View source code 7 votes vote down vote up
@Override
protected void runTest() throws Throwable {
	// wait
	Thread.sleep(_milliseconds);

	try {
		// get the value of the dl element from the page
		Object response = _page.executeJavaScript("(typeof " + _elementName + " !== 'undefined')")
				.getJavaScriptResult();

		// make sure the element exists
		if (Boolean.class.isAssignableFrom(response.getClass())) {
			assertTrue("Data Layer element " + _elementName + " must exist after " + _milliseconds + "ms",
					(Boolean) response);
		} else {
			fail("Data Layer element " + _elementName + " does not exist");
		}
	} catch (WebDriverException we) {
		fail("Data Layer element " + _elementName + " does not exist");
	}

}
 
Example 12
Project: site-infrastructure-tests   File: DataLayerNumericElementDelayedValueTestCase.java   View source code 7 votes vote down vote up
@Override
protected void runTest() throws Throwable {
	try {
		// sleep
		Thread.sleep(_delay);

		// get the value of the dl element from the page
		Object response = _page.executeJavaScript(_elementName).getJavaScriptResult();

		// make sure the element exists
		if (Long.class.isAssignableFrom(response.getClass())) {
			assertEquals("Data Layer element " + _elementName + " numeric value should be " + _elementExpectedValue
					+ "after " + _delay + "ms", _elementExpectedValue, (Long) response);
		} else {
			fail("Data Layer element " + _elementName + " does not exist");
		}
	} catch (WebDriverException we) {
		fail("Data Layer element " + _elementName + " does not exist");
	}
}
 
Example 13
Project: snippets   File: CustomConditions.java   View source code 7 votes vote down vote up
public static ExpectedCondition<Boolean> ajaxCompleted() {
    return new ExpectedCondition<Boolean>() {
        boolean result;
        @Override
        public Boolean apply(WebDriver driver) {
            try {
                result = (Boolean) ((JavascriptExecutor) driver).executeScript("return typeof($) !== 'undefined' && $.active == 0");
                //System.out.println("Ajax return $.active == 0  is: '" + result + "'");
            } catch (WebDriverException e) {
                return false;
            }
            return result;
        }
        public String toString() {
            return "Ajax return $.active == 0  is: '" + result + "'";
        }
    };
}
 
Example 14
Project: qaf   File: QAFExtendedWebElement.java   View source code 7 votes vote down vote up
public boolean isPresent() {
	if (StringUtils.isNotBlank(id) && id != "-1" && cacheable) {
		return true;
	}
	try {
		List<WebElement> eles = null;
		if ((parentElement != null)) {
			if (!parentElement.isPresent()) {
				return false;
			}
			eles = parentElement.findElements(getBy());

		} else {
			eles = getWrappedDriver().findElements(getBy());
		}
		if ((eles != null) && (eles.size() > 0)) {
			if (StringUtils.isBlank(id)) {
				id = ((QAFExtendedWebElement) eles.get(0)).id;
			}
			return true;
		}
		return false;
	} catch (WebDriverException e) {
		return false;
	}
}
 
Example 15
Project: qaf   File: ElementList.java   View source code 7 votes vote down vote up
public void waitForIndex(final int index) {
	new QAFWebDriverWait()
			.withMessage(String.format("Wait timeout for list of %s with size %d",
					description, index + 1))
			.until(new ExpectedCondition<QAFExtendedWebDriver, Boolean>() {
				@SuppressWarnings("unchecked")
				@Override
				public Boolean apply(QAFExtendedWebDriver driver) {
					try {
						clear();
						addAll((Collection<T>) context.findElements(by));
						return size() > index;
					} catch (WebDriverException e) {
						return false;
					}
				}
			});
}
 
Example 16
Project: qaf   File: QAFTestBase.java   View source code 7 votes vote down vote up
private void init() {
	if (ApplicationProperties.DRIVER_NAME.getStringVal("").equalsIgnoreCase("")) {
		System.err.println("Driver not configured!... \nUsing " + STBArgs.browser_str.getDefaultVal()
				+ " as default value. Please configure driver to be used using '"
				+ ApplicationProperties.DRIVER_NAME.key + "' property");
	}
	stb = initStbArgs();
	logger.info("Initializing Driver..." + STBArgs.allToString(stb));
	// uiDriver = new UiDriverFactory().get(commandLog, stb);
	DriverInitExpectedCondition driverInitExpectedCondition = new DriverInitExpectedCondition(
			(ArrayList<LoggingBean>) getLog(), stb);
	UiDriver uiDriver = new UiDriverInitializer()
			.withTimeout(ApplicationProperties.DRIVER_INIT_TIMEOUT.getIntVal(0), TimeUnit.SECONDS)
			.pollingEvery(10, TimeUnit.SECONDS).withMessage(driverInitExpectedCondition)
			.ignoring(WebDriverException.class).until(driverInitExpectedCondition);

	setUiDriver(uiDriver);
	logger.info("driver init done");
}
 
Example 17
Project: selenium-cucumber-framework   File: BrowserFactory.java   View source code 7 votes vote down vote up
public static WebDriver selectLocalBrowser() {
	switch (browser) {
	case Chrome:
		return new ChromeDriver();
	case Firefox:
		return new FirefoxDriver();
	case IE:
		return new InternetExplorerDriver();
	case Opera:
		return new OperaDriver();
	case Safari:
		return new SafariDriver();
	default:
		throw new WebDriverException("No browser specified");
	}
}
 
Example 18
Project: bdd-test-automation-for-mobile   File: SetupTeardownSteps.java   View source code 7 votes vote down vote up
@After
public void tearDown(Scenario scenario) {
    if (scenario.isFailed()) {
        try {
            logger.info("Test failed, taking screenshot");
            byte[] screenshot = ((TakesScreenshot) new Augmenter().augment(getAppiumDriver()))
                    .getScreenshotAs(OutputType.BYTES);
            scenario.embed(screenshot, "image/png");
        }
        catch (WebDriverException wde) {
            System.err.println(wde.getMessage());
        }
        catch (ClassCastException cce) {
            cce.printStackTrace();
        }
    }
    application.tearDown();
}
 
Example 19
Project: aet   File: AetSocketLock.java   View source code 7 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
public void lock(long timeoutInMillis) {
  synchronized (syncObject) {
    // Calculate the 'exit time' for our wait loop.
    long maxWait = System.currentTimeMillis() + timeoutInMillis + ADDITIONAL_TIMEOUT_IN_MILLIS;

    // Attempt to acquire the lock until something goes wrong or we run out of time.
    do {
      try {
        if (isLockOnInetSocketAddressFree(address)) {
          return;
        }
        // Randomness or retry! Something from my past (Paul H) :
        // http://www.wattystuff.net/amateur/packet/whatispacket.htm (search for random in page)
        Thread.sleep((long) (DELAY_BETWEEN_SOCKET_CHECKS * Math.random()));
      } catch (InterruptedException | IOException e) {
        throw new WebDriverException(e);
      }
    } while (System.currentTimeMillis() < maxWait);

    throw new WebDriverException(String.format("Unable to bind to locking port %d within %d ms",
        address.getPort(), timeoutInMillis + ADDITIONAL_TIMEOUT_IN_MILLIS));
  }
}
 
Example 20
Project: seleniumtestsframework   File: AbstractWebDriverFactory.java   View source code 7 votes vote down vote up
public void cleanUp() {
    try {
        if (driver != null) {
            try {
                TestLogging.log("quiting webdriver" + Thread.currentThread().getId());
                driver.quit();
            } catch (WebDriverException ex) {
                TestLogging.log("Exception encountered when quiting driver: "
                        + WebUIDriver.getWebUIDriver().getConfig().getBrowser().name() + ":" + ex.getMessage());
            }

            driver = null;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 21
Project: seleniumtestsframework   File: IEDriverFactory.java   View source code 7 votes vote down vote up
@Override
public void cleanUp() {
    try {
        if (driver != null) {
            try {
                driver.quit();
            } catch (WebDriverException ex) {
                ex.printStackTrace();
            }

            driver = null;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 22
Project: seleniumtestsframework   File: FirefoxDriverFactory.java   View source code 7 votes vote down vote up
/**
 * Create webDriver, capture socket customexception and retry with timeout.
 *
 * @return  WebDriver
 */
protected WebDriver createWebDriverWithTimeout() {
    long time = 0;
    while (time < getTimeout()) {
        try {
            driver = createNativeDriver();
            return driver;
        } catch (WebDriverException ex) {
            if (ex.getMessage().contains("SocketException")
                    || ex.getMessage().contains("Failed to connect to binary FirefoxBinary")
                    || ex.getMessage().contains("Unable to bind to locking port 7054 within 45000 ms")) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) { }

                time++;
            } else {
                throw new RuntimeException(ex);
            }
        }
    }

    throw new RuntimeException("Got customexception when creating webDriver with socket timeout 1 minute");
}
 
Example 23
Project: seleniumtestsframework   File: MarionetteDriverFactory.java   View source code 7 votes vote down vote up
/**
 * Create webDriver, capture socket customexception and retry with timeout.
 *
 * @return  WebDriver
 */
protected WebDriver createWebDriverWithTimeout() {
    long time = 0;
    while (time < getTimeout()) {
        try {
            driver = createNativeDriver();
            return driver;
        } catch (WebDriverException ex) {
            if (ex.getMessage().contains("SocketException")
                    || ex.getMessage().contains("Failed to connect to binary FirefoxBinary")
                    || ex.getMessage().contains("Unable to bind to locking port 7054 within 45000 ms")) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) { }

                time++;
            } else {
                throw new RuntimeException(ex);
            }
        }
    }

    throw new RuntimeException("Got customexception when creating webDriver with socket timeout 1 minute");
}
 
Example 24
Project: seleniumtestsframework   File: WebUIDriver.java   View source code 7 votes vote down vote up
public static void cleanUp() {
    IWebDriverFactory iWebDriverFactory = getWebUIDriver().webDriverBuilder;
    if (iWebDriverFactory != null) {
        iWebDriverFactory.cleanUp();
    } else {
        WebDriver driver = driverSession.get();
        if (driver != null) {
            try {
                driver.quit();
            } catch (WebDriverException ex) {
                ex.printStackTrace();
            }

            driver = null;
        }
    }

    driverSession.remove();
    uxDriverSession.remove();
}
 
Example 25
Project: jbehave-vaadin-example   File: AddressbookSteps.java   View source code 7 votes vote down vote up
private Predicate<WebDriver> vaadinIsReady() {
	return new Predicate<WebDriver>() {
		@Override
		public boolean apply(WebDriver driver) {
			try {
				JavascriptExecutor executor = (JavascriptExecutor) webDriver;
				return (Boolean) executor.executeScript(//
						" if(!window.vaadin) { return false;}" + //
								"for (var client in window.vaadin.clients) { " + //
								" if (window.vaadin.clients[client].isActive()) { " + //
								"   return false;" + //
								"  }" + //
								"}" + //
								"return true;");
			} catch (WebDriverException e) {
				if ((e.getMessage() != null) && e.getMessage().contains("window.vaadin is undefined")) {
					return false;
				} else {
					throw e;
				}
			}
		}
	};
}
 
Example 26
Project: rise   File: RiseWait.java   View source code 7 votes vote down vote up
private <V> V untilSucessful(final Supplier<V> operation, Predicate<V> isSuccessful,
        Function<Throwable, RuntimeException> exceptionProducer) {
    Instant end = Instant.now().plus(interval);
    Throwable lastThrowable;
    while (true) {
        try {
            V result = operation.get();
            if (isSuccessful.test(result))
                return result;
            else
                lastThrowable = null;
        } catch (Throwable t) {
            lastThrowable = t;
        }
        if (Instant.now().isAfter(end)) {
            throw exceptionProducer.apply(lastThrowable);
        }

        try {
            Thread.sleep(interval.toMillis());
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new WebDriverException(e);
        }
    }
}
 
Example 27
Project: Gepard   File: WebDriverUtil.java   View source code 7 votes vote down vote up
/**
 * By using the default URL, creates a WebDriver object and Selenium object as well.
 *
 * @param baseUrl is the default URL for the browser, must not be null!
 * @return withthe new WebDriver object
 */
public WebDriver buildWebDriverInstance(final String baseUrl) {
    if (browserString == null) {
        throw new SimpleGepardException("No browser to be used was specified.");
    }

    DesiredCapabilities capabilities = detectCapabilities();

    try {
        webDriver = new RemoteWebDriver(buildWebDriverUrl(), capabilities);
        selenium = new WebDriverBackedSelenium(webDriver, baseUrl);
        selenium.setTimeout(DEFAULT_TIMEOUT); //set the default timeout
    } catch (WebDriverException | SeleniumException e) {
        throw new SimpleGepardException(e.getLocalizedMessage());
    }
    // hide all open windows on Mac, it is necessary to hide 'always on top' windows, otherwise useless screenshots will be created from desktop
    if (getBrowserType() == BrowserEnum.Safari) {
        selenium.keyPressNative(String.valueOf(KeyEvent.VK_F11));
    }

    return webDriver;
}
 
Example 28
Project: Gepard   File: WebDriverUtil.java   View source code 7 votes vote down vote up
/**
 * Destroys the WebDriver object of this util class, as necessary.
 */
public void destroyWebDriverInstance() {
    if (webDriver != null) {
        webDriver.close();
        try {
            Thread.sleep(WEB_DRIVER_SHUTDOWN_DELAY);
            webDriver.quit(); //close all opened browser window
        } catch (Exception e) {
            if (!(e instanceof WebDriverException)) {
                throw new SimpleGepardException("Issue occurred meanwhile waiting for WebDriver Quit.", e);
            }
        }
        webDriver = null;
    }
    selenium = null;
}
 
Example 29
Project: marathonv5   File: JavaProfile.java   View source code 6 votes vote down vote up
public String findCommand(String command) {
    if (vmCommand != null) {
        return vmCommand;
    }
    if (javaHome != null) {
        File homeFolder = new File(javaHome);
        if (!homeFolder.exists() || !homeFolder.isDirectory()) {
            throw new WebDriverException(String.format("%s: No such directory", homeFolder));
        }
        File binFolder = new File(javaHome, "bin");
        if (!binFolder.exists() || !binFolder.isDirectory()) {
            throw new WebDriverException(String.format("%s: No bin directory found in home directory", binFolder));
        }
        File java = new File(binFolder, Platform.getCurrent().is(Platform.WINDOWS) ? command + ".exe" : command);
        if (!java.exists() || !java.isFile()) {
            throw new WebDriverException(String.format("%s: No such file", java));
        }
        return java.getAbsolutePath();
    }
    return command;
}
 
Example 30
Project: marathonv5   File: JavaProfile.java   View source code 6 votes vote down vote up
public String getRecorderJar() {
    if (System.getenv(MARATHON_RECORDER + ".file") != null) {
        return System.getenv(MARATHON_RECORDER + ".file");
    }
    if (System.getProperty(MARATHON_RECORDER + ".file") != null) {
        return System.getProperty(MARATHON_RECORDER + ".file");
    }
    String prefix = launchType.getPrefix();
    String path = findFile(new String[] { ".", "marathon-" + prefix + "-recorder", "../marathon-" + prefix + "-recorder",
            System.getProperty(PROP_HOME, "."), dirOfMarathonJavaDriverJar }, "marathon-" + prefix + "-recorder.*.jar");
    if (path != null) {
        Logger.getLogger(JavaProfile.class.getName()).info("Using " + path + " for recorder");
        return path;
    }
    throw new WebDriverException("Unable to find marathon-recorder.jar. Set " + MARATHON_RECORDER
            + " environment variable to point to the jar file");
}
 
Example 31
Project: marathonv5   File: JavaDriverTest.java   View source code 6 votes vote down vote up
public void executeAsyncScriptWithoutCallback() throws Throwable {
    try {
        driver = new JavaDriver();
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override public void run() {
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
        WebElement element1 = driver.findElement(By.name("text-field"));
        ((JavascriptExecutor) driver).executeAsyncScript("$1.setText(\"hello world\");", element1);
        throw new MissingException(WebDriverException.class);
    } catch (WebDriverException e) {
    } finally {
        JavaElementFactory.reset();
    }
}
 
Example 32
Project: cucumber-framework-java   File: StartingSteps.java   View source code 6 votes vote down vote up
@After
public void afterScenario( Scenario scenario ) throws Exception
{
    try
    {
        attachLog();

        if( scenario.isFailed() )
        {
            try
            {
                scenario.write( "Current Page URL is " + getDriver().getCurrentUrl() );
                byte[] screenshot;
                try
                {
                    screenshot = ( ( TakesScreenshot ) getDriver() ).getScreenshotAs( OutputType.BYTES );
                } catch( ClassCastException weNeedToAugmentOurDriverObject )
                {
                    screenshot = ( ( TakesScreenshot ) new Augmenter().augment( getDriver() ) ).getScreenshotAs( OutputType.BYTES );
                }
                String relativeScrnShotPath = takeScreenshot().substring(takeScreenshot().indexOf("screenshots"));
                Reporter.addScreenCaptureFromPath(relativeScrnShotPath, getDriver().getCurrentUrl());
            } catch( WebDriverException somePlatformsDontSupportScreenshots )
            {
                System.err.println( somePlatformsDontSupportScreenshots.getMessage() );
            }
        }
    } finally
    {
        closeDriverObjects();
    }
}
 
Example 33
Project: cucumber-framework-java   File: SessionContextManager.java   View source code 6 votes vote down vote up
/**
 * Clear context.
 */
public void clear() {
    if (controller != null) {
        try {
            controller.quit();
        } catch (WebDriverException wde) {
            logger.warn("Exception caught calling controller.quit(): \""+wde.getMessage()+"\" additional info: "+wde.getAdditionalInformation());
        }
    }
    controller = null;
    verify = null;
    isWebDriver = false;
    if (paramsRegistry != null) {
        paramsRegistry.clear();
    }

    Thread.currentThread().setName("Context - Inactive");
    logger.info("Context closed, controller shutdown");
}
 
Example 34
Project: devtools-driver   File: IOSServerManager.java   View source code 6 votes vote down vote up
public ServerSideSession getSession(String sessionId) {
  // first, check if the session stopped already
  if (stoppedSessionIds.contains(sessionId)) {
    throw newSessionStoppedException(sessionId);
  }

  // check if the session is in the process of stopping
  for (ServerSideSession session : sessions) {
    if (session.getSessionId().equals(sessionId)) {
      if (session.getSessionState() == SessionState.STOPPED) {
        throw newSessionStoppedException(sessionId);
      } else {
        return session;
      }
    }
  }

  throw new WebDriverException("Cannot find session " + sessionId + " on the server.");
}
 
Example 35
Project: devtools-driver   File: WebInspectorHelper.java   View source code 6 votes vote down vote up
private RemoteWebElement retrieveDocumentAndCheckReady(long deadline) {
  RemoteWebElement element = null;
  String readyState = "";
  while (!readyState.equals("complete")) {
    if (deadline > 0 && System.currentTimeMillis() > deadline) {
      throw new TimeoutException("Timeout waiting to get the document.");
    }

    try {
      if (element == null) {
        element = retrieveDocument();
      }
      readyState = element.getRemoteObject().call(".readyState");
    } catch (WebDriverException e) {
      log.info("Caught exception waiting for document to be ready. Retrying...: " + e);
      element = null;
    }
  }
  return element;
}
 
Example 36
Project: devtools-driver   File: WebInspectorHelper.java   View source code 6 votes vote down vote up
private JsonObject getResponseBody(JsonObject response) {
  JsonObject body = null;
  try {
    body =
        response.containsKey("result")
            ? response.getJsonObject("result")
            : response.getJsonObject("object");
  } catch (Exception e) {
    throw new WebDriverException(e);
  }

  if (body == null) {
    throw new RuntimeException("Error parsting " + response);
  }
  return body;
}
 
Example 37
Project: devtools-driver   File: ServerStatusHandler.java   View source code 6 votes vote down vote up
@Override
public Response handle() throws Exception {
  JSONObject res = generateStatus();

  Set<ServerSideSession> sessions = getServer().getSessions();
  Response resp = new Response();

  resp.setStatus(0);
  resp.setValue(res);
  if (sessions.size() == 0) {
    resp.setSessionId(null);
  } else if (sessions.size() == 1) {
    resp.setSessionId(sessions.iterator().next().getSessionId());
  } else {
    throw new WebDriverException("NI multi sessions per server.");
  }
  return resp;
}
 
Example 38
Project: devtools-driver   File: ToCSSSelectorConverter.java   View source code 6 votes vote down vote up
public static String convertToCSSSelector(String type, String value) {
  if ("css selector".equals(type)) {
    return value;
  }
  if ("id".equals(type)) {
    // return "#" + value; // doesn't work for id starting with an int.
    return "[id='" + value + "']";
  }
  if ("tag name".equals(type)) {
    return value;
  }
  if ("class name".equals(type)) {
    // detect composite class name
    if (isCompoundName(value)) {
      throw new InvalidSelectorException("Compound class names aren't allowed");
    }
    return "." + value;
  }
  if ("class name".equals(type)) {
    return "." + value;
  }
  if ("name".equals(type)) {
    return "[name='" + value + "']";
  }
  throw new WebDriverException("NI , selector type " + type);
}
 
Example 39
Project: bromium   File: ActionExecutorTest.java   View source code 6 votes vote down vote up
@Test
public void properlyHandlesInterruptedExceptionBetweenRetries() throws IOException, URISyntaxException, InterruptedException {
    ActionExecutor webDriverActionExecutionBase = getWebDriverActionExecutionBase(10);
    Iterator<WebDriverAction> webDriverActionIterator = mock(Iterator.class);
    TestScenarioActions testScenarioSteps = mock(TestScenarioActions.class);
    when(testScenarioSteps.iterator()).thenReturn(webDriverActionIterator);
    TestScenario testScenario = mock(TestScenario.class);
    when(testScenario.steps()).thenReturn(testScenarioSteps);
    WebDriverAction firstAction = mock(WebDriverAction.class);
    doThrow(new WebDriverException("Something happened!")).when(firstAction).execute(any(), any(), any());
    when(webDriverActionIterator.hasNext()).thenReturn(true, false);
    when(firstAction.expectsHttpRequest()).thenReturn(true);
    PowerMockito.mockStatic(Thread.class);
    PowerMockito.doThrow(new InterruptedException()).when(Thread.class);
    Thread.sleep(anyLong());
    when(webDriverActionIterator.next()).thenReturn(firstAction);
    ExecutionReport report = webDriverActionExecutionBase.execute(testScenario);
    assertEquals(AutomationResult.INTERRUPTED, report.getAutomationResult());
}
 
Example 40
Project: willtest   File: Utils.java   View source code 6 votes vote down vote up
public static void assumeHavingFirefoxConfigured() {
    try {
        new FirefoxBinary();
    }
    catch ( WebDriverException e ) {
        if ( e.getMessage().contains("Cannot find firefox binary in PATH") ) {
            assumeThat(
                    "Please define the path to your firefox executable using " +
                            DefaultFirefoxBinaryProvider.FIREFOX_BINARY_LOCATION_SYSTEM_PROPERTY_KEY +
                            " system property, or add your firefox executable to the PATH variable! " +
                            "This is just an assumption to keep our build green.",
                    System.getProperty(DefaultFirefoxBinaryProvider.FIREFOX_BINARY_LOCATION_SYSTEM_PROPERTY_KEY),
                    is(notNullValue()));
        } else {
            throw e;
        }
    }
}