Java Code Examples for org.openqa.selenium.WebDriver#quit()

The following examples show how to use org.openqa.selenium.WebDriver#quit() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: upload_file.java    From at.info-knowledge-base with MIT License 6 votes vote down vote up
static public void main(String[] args) {
	// Creating webdriver
	System.setProperty("webdriver.ie.driver", "C:\\WORK\\IEDriverServer_Win32_2.37.0\\IEDriverServer.exe");
	WebDriver driver = new InternetExplorerDriver();

// Opening page. In this case - local HTML file.
   	driver.get("file://C:/WORK/test.html");

   	// Find element that uploads file.
   	WebElement fileInput = driver.findElement(By.id("file"));

   	// Set direct path to local file that needs to be uploaded. 
   	// That also can be a direct link to file in web, like - https://www.google.com.ua/images/srpr/logo11w.png
   	fileInput.sendKeys("file://C:/WORK/lenna.png");

   	// find button that sends form and click it.
   	driver.findElement(By.id("submit")).click();

   	// Closing driver and session
   	driver.quit();
}
 
Example 2
Source File: RemoteThreadWebDriverMapImpl.java    From IridiumApplicationTesting with MIT License 6 votes vote down vote up
@Override
public synchronized void shutdown() {
	for (final WebDriver webDriver : threadIdToDriverMap.values()) {
		try {
			webDriver.quit();
		} catch (final Exception ignored) {
			// do nothing and continue closing the other webdrivers
		}
	}

	/*
		Clear the map
	 */
	threadIdToCapMap.clear();

	/*
		Reset the list of available configurations
	 */
	currentCapability = 0;
	currentUrl = 0;
}
 
Example 3
Source File: IAmTheDriver.java    From Selenium-WebDriver-3-Practical-Guide-Second-Edition with MIT License 6 votes vote down vote up
public static void main(String... args){

        System.setProperty("webdriver.chrome.driver",
                "./src/test/resources/drivers/chromedriver");

        WebDriver driver = new ChromeDriver();

        try {
            EventFiringWebDriver eventFiringDriver = new
                    EventFiringWebDriver(driver);
            IAmTheEventListener eventListener = new IAmTheEventListener();
            eventFiringDriver.register(eventListener);
            eventFiringDriver.get("http://www.google.com");
            eventFiringDriver.get("http://www.facebook.com");
            eventFiringDriver.navigate().back();
        } finally {
            driver.close();
            driver.quit();
        }
    }
 
Example 4
Source File: WebDriverCache.java    From neodymium-library with MIT License 6 votes vote down vote up
/**
 * This function can be used within a function of a JUnit test case that is annotated with @AfterClass to clear the
 * WebDriverCache of the WebDrivers ready for reuse.
 * <p>
 * <b>Attention:</b> It is save to run this function during a sequential test execution. It can have repercussions
 * (e.g. longer test duration) in a parallel execution environment.
 *
 * <pre>
 * &#64;AfterClass
 * public void afterClass()
 * {
 *     WebDriverCache.quitCachedBrowsers();
 * }
 * </pre>
 **/
public static void quitCachedBrowsers()
{
    Collection<CachingContainer> allWebdriver = instance.getAllWebDriverAndProxy();
    for (CachingContainer cont : allWebdriver)
    {
        try
        {
            WebDriver wd = cont.getWebDriver();
            LOGGER.debug("Quit web driver: " + wd.toString());
            wd.quit();
            BrowserUpProxy proxy = cont.getProxy();
            if (proxy != null)
            {
                proxy.stop();
            }
            instance.removeWebDriverAndProxy(wd);
        }
        catch (Exception e)
        {
            LOGGER.debug("Error on quitting web driver", e);
        }
    }
}
 
Example 5
Source File: WebUIDriver.java    From seleniumtestsframework with Apache License 2.0 6 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 6
Source File: LocalExecutionTest.java    From demo-java with MIT License 6 votes vote down vote up
@Test
public void localExecution() {
    // Options:
    //
    // 1. Specify location of driver
    // System.setProperty("webdriver.chrome.driver", "lib/drivers/chromedriver");
    //
    // 2. Add driver to PATH ENV
    //
    // 3. Use Driver manager:
    WebDriverManager.chromedriver().setup();

    // Start session (opens browser)
    WebDriver driver = new ChromeDriver();

    // Quit session (closes browser)
    driver.quit();
}
 
Example 7
Source File: FirefoxDriverTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBeAbleToStartMoreThanOneInstanceOfTheFirefoxDriverSimultaneously() {
  WebDriver secondDriver = new FirefoxDriver();

  try {
    driver.get(pages.xhtmlTestPage);
    secondDriver.get(pages.formPage);

    assertThat(driver.getTitle()).isEqualTo("XHTML Test Page");
    assertThat(secondDriver.getTitle()).isEqualTo("We Leave From Here");
  } finally {
    secondDriver.quit();
  }
}
 
Example 8
Source File: CaptureVideo.java    From at.info-knowledge-base with MIT License 5 votes vote down vote up
public static void main(String[] argv) {
	// initialize web driver
	WebDriver driver = new FirefoxDriver();
	driver.get("http://automated-testing.info");

	// capture video
	initScreen();
	startVideoCapturing();
	stopVideoCapturing();

	// initialize web driver
	driver.quit();
}
 
Example 9
Source File: DriverTest.java    From phoenix.webui.framework with Apache License 2.0 5 votes vote down vote up
@Test
public void htmlUnit()
{
	WebDriver driver = new HtmlUnitDriver();
	driver.get("http://surenpi.com");
	driver.quit();
}
 
Example 10
Source File: LocalThreadWebDriverMapImpl.java    From IridiumApplicationTesting with MIT License 5 votes vote down vote up
@Override
public synchronized void shutdown() {
	for (final WebDriver webdriver : threadIdToDriverMap.values()) {
		try {
			if (!WEB_DRIVER_FACTORY.leaveWindowsOpen()) {
				webdriver.quit();
			}
		} catch (final Exception ignored) {
			// do nothing and continue closing the other webdrivers
		}
	}

       /*
           Clear the map
        */
	threadIdToDriverMap.clear();
	threadIdToCapMap.clear();

	/*
		Attempt to delete all the temp folders
	 */
	getTempFolders().forEach(FileUtils::deleteQuietly);

       /*
           Reset the list of available configurations
        */
	currentUrl = 0;
}
 
Example 11
Source File: FirstFirefoxTest.java    From webDriverExperiments with MIT License 5 votes vote down vote up
@Test
/*
  * Physical browsers have to be closed, otherwise you will
  * have a bunch of browsers open on your screen.
  *
  * .close to close single window and browser if it is the last window
  * .quit to close browser and all windows
  */
public void firefoxIsSupportedByWebDriver(){
    WebDriver driver = new FirefoxDriver();

    driver.get("http://www.compendiumdev.co.uk/selenium");

    assertTrue(driver.getTitle().startsWith(
            "Selenium Simplified"));

    driver.close();

    // for early version combinations of Firefox and WebDriver we didn't need
    // .quit - I have added this line for the combination of WebDriver 2.31.0
    // and Firefox 20. According to the API we should not need to do a .quit
    // after a .close if there was only 1 window open. But sometimes the browser
    // version advances ahead of the WebDriver version and minor incompatibilities
    // happen.
    // Added the line below because of incompatibilite between 2.31.0 and Firefox 20
    // where a single window browser does not close when run from the IDE.
    driver.quit();
}
 
Example 12
Source File: WebDriverTestCase.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Closes the drivers.
 * @throws Exception If an error occurs
 */
@AfterClass
public static void shutDownAll() throws Exception {
    for (WebDriver driver : WEB_DRIVERS_.values()) {
        driver.quit();
    }
    WEB_DRIVERS_.clear();

    shutDownRealBrowsers();

    stopWebServers();
}
 
Example 13
Source File: CustomDriverProviderTests.java    From akita with Apache License 2.0 5 votes vote down vote up
@Test
void createChromeDriverTest() {
    System.setProperty("browser", "chrome");
    CustomDriverProvider customDriverProvider = new CustomDriverProvider();
    WebDriver currentDriver;
    currentDriver = customDriverProvider.createDriver(new DesiredCapabilities());
    assertThat(currentDriver.getClass().getName(), is("org.openqa.selenium.chrome.ChromeDriver"));
    currentDriver.quit();
}
 
Example 14
Source File: BaseTest.java    From at.info-knowledge-base with MIT License 5 votes vote down vote up
private void disposeDriver(final Thread thread) {
    ALL_REMOTE_DRIVERS_THREADS.remove(thread);
    final WebDriver driver = THREAD_REMOTE_DRIVER.remove(thread.getId());
    if (driver != null) {
        driver.quit();
    }
}
 
Example 15
Source File: ThreadLocalSingleWebDriverPool.java    From webdriver-factory with Apache License 2.0 5 votes vote down vote up
private synchronized void dismissDriversInFinishedThreads() {
  List<WebDriver> stale = driverToThread.entrySet().stream()
    .filter((entry) -> !entry.getValue().isAlive())
    .map(Map.Entry::getKey).collect(Collectors.toList());

  for (WebDriver driver : stale) {
    try {
      driver.quit();
    } finally {
      driverToKeyMap.remove(driver);
      driverToThread.remove(driver);
    }
  }
}
 
Example 16
Source File: BasicTest.java    From Mastering-Selenium-WebDriver-3.0-Second-Edition with MIT License 4 votes vote down vote up
private void googleExampleThatSearchesFor(final String searchString) {

        WebDriver driver = new FirefoxDriver();

        driver.get("http://www.google.com");

        WebElement searchField = driver.findElement(By.name("q"));

        searchField.clear();
        searchField.sendKeys(searchString);

        System.out.println("Page title is: " + driver.getTitle());

        searchField.submit();

        WebDriverWait wait = new WebDriverWait(driver, 10, 100);
        wait.until(pageTitleStartsWith(searchString));

        System.out.println("Page title is: " + driver.getTitle());

        driver.quit();
    }
 
Example 17
Source File: WebDriverManager.java    From QVisual with Apache License 2.0 4 votes vote down vote up
public static void closeDriver(WebDriver driver) {
    if (driver != null) {
        driver.quit();
    }
}
 
Example 18
Source File: HTMLLauncher.java    From selenium with Apache License 2.0 4 votes vote down vote up
/**
 * Launches a single HTML Selenium test suite.
 *
 * @param browser - the browserString ("*firefox", "*iexplore" or an executable path)
 * @param startURL - the start URL for the browser
 * @param suiteURL - the relative URL to the HTML suite
 * @param outputFile - The file to which we'll output the HTML results
 * @param timeoutInSeconds - the amount of time (in seconds) to wait for the browser to finish
 * @return PASS or FAIL
 * @throws IOException if we can't write the output file
 */
public String runHTMLSuite(
  String browser,
  String startURL,
  String suiteURL,
  File outputFile,
  long timeoutInSeconds,
  String userExtensions) throws IOException {
  File parent = outputFile.getParentFile();
  if (parent != null && !parent.exists()) {
    parent.mkdirs();
  }
  if (outputFile.exists() && !outputFile.canWrite()) {
    throw new IOException("Can't write to outputFile: " + outputFile.getAbsolutePath());
  }
  long timeoutInMs = 1000L * timeoutInSeconds;
  if (timeoutInMs < 0) {
    log.warning("Looks like the timeout overflowed, so resetting it to the maximum.");
    timeoutInMs = Long.MAX_VALUE;
  }

  WebDriver driver = null;
  try {
    driver = createDriver(browser);
    URL suiteUrl = determineSuiteUrl(startURL, suiteURL);

    driver.get(suiteUrl.toString());
    Selenium selenium = new WebDriverBackedSelenium(driver, startURL);
    selenium.setTimeout(String.valueOf(timeoutInMs));
    if (userExtensions != null) {
      selenium.setExtensionJs(userExtensions);
    }
    List<WebElement> allTables = driver.findElements(By.id("suiteTable"));
    if (allTables.isEmpty()) {
      throw new RuntimeException("Unable to find suite table: " + driver.getPageSource());
    }
    Results results = new CoreTestSuite(suiteUrl.toString()).run(driver, selenium, new URL(startURL));

    HTMLTestResults htmlResults = results.toSuiteResult();
    try (Writer writer = Files.newBufferedWriter(outputFile.toPath())) {
      htmlResults.write(writer);
    }

    return results.isSuccessful() ? "PASSED" : "FAILED";
  } finally {
    if (server != null) {
      try {
        server.stop();
      } catch (Exception e) {
        // Nothing sane to do. Log the error and carry on
        log.log(Level.INFO, "Exception shutting down server. You may ignore this.", e);
      }
    }

    if (driver != null) {
      driver.quit();
    }
  }
}
 
Example 19
Source File: EbayIdTokenValidatorTest.java    From ebay-oauth-java-client with Apache License 2.0 4 votes vote down vote up
public String getIdTokenResponseUrl(String nonce) throws InterruptedException {
    // Optional, if not specified, WebDriver will search your path for chromedriver.
    System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");

    WebDriver driver = new ChromeDriver();
    OAuth2Api authApi = new OAuth2Api();
    String idTokenUrl = authApi.generateIdTokenUrl(EXECUTION_ENV, Optional.of("current-page"), nonce);

    driver.get(idTokenUrl);
    Thread.sleep(5000);

    WebElement userId = (new WebDriverWait(driver, 10))
            .until(ExpectedConditions.visibilityOf(driver.findElement(By.cssSelector("input[type='text']:not([name='userid_otp']):not([name='otp'])"))));

    WebElement password = driver.findElement(By.cssSelector("input[type='password']"));
    userId.sendKeys(CRED_USERNAME);
    password.sendKeys(CRED_PASSWORD);
    WebElement sgnBt = null;
    try {
        sgnBt = driver.findElement(By.name("sgnBt"));
    } catch (NoSuchElementException e) {
        // ignore exception
    }
    if (sgnBt == null) {
        sgnBt = driver.findElement(By.id("sgnBt"));
    }

    sgnBt.submit();
    Thread.sleep(5000);

    String url = null;
    if (driver.getCurrentUrl().contains("id_token=")) {
        printDetailedLog("Id Token Obtained");
        url = driver.getCurrentUrl();
    } else {
        WebElement agreeBtn = (new WebDriverWait(driver, 10))
                .until(ExpectedConditions.visibilityOf(driver.findElement(By.id("submit"))));

        agreeBtn.submit();
        Thread.sleep(5000);
        url = driver.getCurrentUrl();
    }
    driver.quit();
    printDetailedLog(url);
    return url;
}
 
Example 20
Source File: ATHJUnitRunner.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Override
protected Statement methodInvoker(FrameworkMethod method, Object test) {
    Statement next =  super.methodInvoker(method, test);
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            LoginPage loginPage = injector.getInstance(LoginPage.class);

            Login methodLogin = method.getAnnotation(Login.class);

            // determine whether test should login first or not
            // first check test method, then walk up hierarchy at class level only
            if(methodLogin != null ) {
                if(!methodLogin.disable()) {
                    loginPage.login();
                }
            } else {
                Class<?> clazz = test.getClass();

                while (clazz != null) {
                    Login classLogin = clazz.getAnnotation(Login.class);

                    if (classLogin != null) {
                        if (!classLogin.disable()) {
                            loginPage.login();
                        }
                        break;
                    }

                    clazz = clazz.getSuperclass();
                }
            }

            try {
                if (LocalDriver.isSauceLabsMode()) {
                    logger.info("SauceOnDemandSessionID=" + ((RemoteWebDriver) LocalDriver.getDriver()).getSessionId().toString());
                }

                next.evaluate();
                outputConsoleLogs();
                LocalDriver.executeSauce("job-result=passed");
            } catch (Exception e) {
                LocalDriver.executeSauce("job-result=failed");
                writeScreenShotCause(e, test, method);
                outputConsoleLogs();
                throw e;
            }

            WebDriver driver = injector.getInstance(WebDriver.class);
            driver.close();
            driver.quit();
        }
    };
}