Java Code Examples for org.openqa.selenium.WebDriver

The following are top voted examples for showing how to use org.openqa.selenium.WebDriver. 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: Cognizant-Intelligent-Test-Scripter   File: WebDriverFactory.java   View source code 6 votes vote down vote up
private static WebDriver checkEmulators(String browserName, DesiredCapabilities caps, ProjectSettings settings,
        Boolean isGrid, String remoteUrl) {
    Emulator emulator = settings.getEmulators().getEmulator(browserName);
    if (emulator != null) {
        switch (emulator.getType()) {
            case "Duplicate":
                return create(emulator.getDriver(), caps, settings, isGrid, remoteUrl);
            case "Emulator":
                if (emulator.getDriver().equals("Chrome")) {
                    return checkAndSetSize(
                            create(emulator.getDriver(), getChromeUAECaps(caps, emulator), settings, isGrid, remoteUrl),
                            emulator.getSize());
                } else {
                    return checkAndSetSize(
                            create(emulator.getDriver(), getFFUAECaps(caps, emulator), settings, isGrid, remoteUrl),
                            emulator.getSize());
                }
            case "Chrome Emulator":
                return create("Chrome", getChromeEmulatorCaps(caps, emulator.getDriver()), settings, isGrid, remoteUrl);
            case "Remote URL": {
                return createRemoteDriver(emulator.getRemoteUrl(), caps, settings.getDriverSettings().useProxy(), settings.getDriverSettings());
            }
        }
    }
    return null;
}
 
Example 2
Project: Selenium-Foundation   File: ComponentContainerTest.java   View source code 6 votes vote down vote up
/**
 * Create mocked {@link WebElement} object.
 * 
 * @param type element type
 * @param value element value
 * @param isCheckbox 'true' is checkbox is desired; otherwise 'false'
 * @return mocked WebElement object
 */
private static WebElement mockElement(String type, String value, boolean isCheckbox) {
    WebElement element = mock(WebElement.class, withSettings().extraInterfaces(WrapsDriver.class));
    when(element.getTagName()).thenReturn(type);
    if (isCheckbox) {
        when(element.getAttribute("type")).thenReturn("checkbox");
        when(element.getAttribute("value")).thenReturn("isSelected: " + value);
        when(element.isSelected()).thenReturn(Boolean.parseBoolean(value));
    } else {
        when(element.getAttribute("type")).thenReturn("text");
        when(element.getAttribute("value")).thenReturn(value);
        when(element.isSelected()).thenReturn(false);
    }

    WebDriver driver = mockDriver();
    when(((WrapsDriver) element).getWrappedDriver()).thenReturn(driver);
    return element;
}
 
Example 3
Project: selenium-toys   File: AbstractDownloadingWebDriverFactory.java   View source code 6 votes vote down vote up
@Override
public WebDriver create(final Map<String, Object> options) {
  new Initialization(() -> {
    beforeInitialization(options);

    final File workDirectory = getWorkDirectory(options);
    final String expectedVersion = (String) options.get(EXPECTED_VERSION);
    final boolean forceUpdate = Boolean.parseBoolean((String) options.get(FORCE_UPDATE));
    final File webDriverExecutable =
        new DownloadWebDriverExecutable(workDirectory, getWebDriverExecutableFromWorkDirectory,
            getLatestVersion, downloadExpectedVersion).get(expectedVersion, forceUpdate);
    new SystemPropertyWebDriverExecutableSetup(systemPropertyForExecutable, webDriverExecutable)
        .setup();
    webDriver = instantiateWebDriver(options);
    new WebDriverShutdownHook(webDriver).install();

    afterInitialization(options);
  }).initialize();
  return webDriver;
}
 
Example 4
Project: teasy   File: TeasyElementFinder.java   View source code 6 votes vote down vote up
private <T extends TeasyElement> List<T> getElements(By locator, Function<WebDriver, List<WebElement>> condition, TeasyElementType type) {
    List<WebElement> webElements;
    try {
        webElements = fluentWait.waitFor(condition);
    } catch (AssertionError ignoredToReturnEmptyList) {
        return new ArrayList<>();
    }
    if (webElements == null) {
        return new ArrayList<>();
    }
    if (context == null) {
        return wrapList(webElements, locator, type);
    } else {
        return wrapList(context, webElements, locator, type);
    }
}
 
Example 5
Project: Spring-Security-Third-Edition   File: SeleniumTestUtilities.java   View source code 6 votes vote down vote up
public static WebDriver getFirefoxDriver()
            throws Exception
	{
        baseDir = new File(".").getPath();
        System.out.println("******** " + baseDir);

        String path = "src/test/resources/geckodriver";
        System.out.println("******** " + path);
		System.setProperty("webdriver.gecko.driver", path);

        DesiredCapabilities capabilities =  DesiredCapabilities.firefox();
		capabilities.setCapability("marionette", true);
        capabilities.setCapability("networkConnectionEnabled", true);
        capabilities.setCapability("browserConnectionEnabled", true);


        WebDriver driver = new RemoteWebDriver(
                new URL("http://localhost:4444"),
                capabilities);

//		WebDriver driver = new MarionetteDriver(capabilities);

		return driver;
	}
 
Example 6
Project: crawler   File: WebDriverManager.java   View source code 6 votes vote down vote up
public void load(SeleniumAction... actions){
	WebDriver driver=null;
	try {
		driver=webDriverPool.get();
		WebDriver.Options manage = driver.manage();
		manage.window().maximize();
		for(SeleniumAction action:actions){
			action.execute(driver);
		}
	} catch (InterruptedException e) {
		e.printStackTrace();
		log.error("",e);
	}finally{
		if(driver!=null){
			webDriverPool.returnToPool(driver);
		}
	}
}
 
Example 7
Project: Actitime-Framework   File: ReportNGReport.java   View source code 6 votes vote down vote up
/**
 * This method captures a screenshot
 **/
public static void captureScreenshot(WebDriver driver, String screenshotName) {
	try {
		TakesScreenshot ts = (TakesScreenshot) driver;
		File source = ts.getScreenshotAs(OutputType.FILE);
		FileUtils.copyFile(source, new File(dirPath + "/ " + screenshotName
				+ "_" + strDateStamp

				+ ".png"));
		String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";
		System.setProperty(ESCAPE_PROPERTY, "false");
		URL path = new File(dirPath + "/ " + screenshotName + "_"
				+ strDateStamp + ".png").toURI().toURL();
		String test = "<a href=" + path + "> click to open screenshot of "
				+ screenshotName + "</a>";
		Reporter.log(screenshotName + test + "<br>");
		Reporter.log("<br>");
	}

	catch (Exception e) {
		System.out.println("Exception while taking screenshot "
				+ e.getMessage());
	}
}
 
Example 8
Project: Cognizant-Intelligent-Test-Scripter   File: CommonMethods.java   View source code 5 votes vote down vote up
private boolean isAlertPresent(WebDriver Driver) {
    try {
        Driver.switchTo().alert();
        return true;
    } catch (NoAlertPresentException e) {
        Logger.getLogger(this.getClass().getName()).log(Level.OFF, e.getMessage(), e);
        return false;
    }
}
 
Example 9
Project: selenium-camp-17   File: Java7WebDriverFactory.java   View source code 5 votes vote down vote up
public static WebDriver getDriverUsingIf(DesiredCapabilities desiredCapabilities) {
	if (desiredCapabilities == null) {
		throw new IllegalStateException("DesiredCapabilities are missing!");
	}

	final String browser = desiredCapabilities.getBrowserName();

	if (CHROME.equalsIgnoreCase(browser)) {
		return new ChromeDriver(desiredCapabilities);
	} else if (FIREFOX.equalsIgnoreCase(browser)) {
		return new FirefoxDriver(desiredCapabilities);
	} else if (browser.isEmpty()) {
		throw new IllegalStateException("'browser' capability is missing!");
	}

	throw new IllegalArgumentException(desiredCapabilities.getBrowserName() + " browser is not supported!");
}
 
Example 10
Project: teasy   File: ElementsHaveText.java   View source code 5 votes vote down vote up
@Nullable
@Override
public Boolean apply(@Nullable WebDriver webDriver) {
    List<String> actualTexts = new ArrayList<>();
    errorElements = new ArrayList<>();
    boolean isCorrect = true;
    for (TeasyElement el : elements) {
        actualTexts.add(el.getText());
        if (!text.equals(el.getText())) {
            isCorrect = false;
            errorElements.add(el);
        }
    }
    return isCorrect;
}
 
Example 11
Project: webdriver-supplier   File: MockWDFactory.java   View source code 5 votes vote down vote up
@Override
public WebDriver createDriver(final Browser browser, final XmlConfig config) {
    final RemoteWebDriver driver = mock(RemoteWebDriver.class);
    when(driver.getScreenshotAs(OutputType.BYTES)).thenReturn(new byte[]{1, 2, 3});
    doReturn(new SessionId(randomAlphanumeric(14))).when(driver).getSessionId();
    return driver;
}
 
Example 12
Project: Spring-Security-Third-Edition   File: SeleniumTestUtilities.java   View source code 5 votes vote down vote up
public static WebDriver getChromeDriver()
{
       String path = "src/test/resources/chromedriver";
	System.setProperty("webdriver.chrome.driver", path);

	DesiredCapabilities capabilities = DesiredCapabilities.chrome();
       capabilities.setCapability("networkConnectionEnabled", true);
       capabilities.setCapability("browserConnectionEnabled", true);

       return new ChromeDriver(capabilities);
}
 
Example 13
Project: dashboard1b   File: SeleniumUtils.java   View source code 5 votes vote down vote up
static public void esperaCargaPaginaNoTexto(WebDriver driver, String texto, int timeout)
{
	Boolean resultado = 
			(new WebDriverWait(driver, timeout)).until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[contains(text(),'" + texto + "')]")));

	assertTrue(resultado);	
}
 
Example 14
Project: Selenium-Foundation   File: ScreenshotUtils.java   View source code 5 votes vote down vote up
/**
 * Determine if the specified driver is capable of taking screenshots.
 * 
 * @param optDriver optional web driver object
 * @param logger SLF4J logger object
 * @return 'true' if driver can take screenshots; otherwise 'false
 */
public static boolean canGetArtifact(Optional<WebDriver> optDriver, Logger logger) {
    if (optDriver.isPresent()) {
        WebDriver driver = optDriver.get();
        if (driver instanceof TakesScreenshot) {
            return true;
        } else {
            String message = "This driver is not capable of taking a screenshot.  If a screenshot is desired, use"
                    + " a WebDriver implementation that supports screenshots. For more information, see https://"
                    + "seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/TakesScreenshot.html";
            logger.warn(message);
        }
    }
    return false;
}
 
Example 15
Project: willtest   File: EventListenerExample.java   View source code 5 votes vote down vote up
@Test
public void testEventListenerWithError() {
    WebDriver webDriver = rule.getWebDriver();
    webDriver.get("https://github.com");
    WebElement searchInput = webDriver.findElement(By.cssSelector(".header-search-input"));
    searchInput.sendKeys("will", "test");
    searchInput.sendKeys(Keys.ENTER);
    String searchKeyword = webDriver.findElement(By.cssSelector(".header-search-input")).getAttribute("value");
    assertThat(searchKeyword, is("foooooo"));
}
 
Example 16
Project: selenium-components   File: AbstractSeleniumPage.java   View source code 5 votes vote down vote up
public String getScreenshot()
{
    WebDriver driver = environment.getDriver();

    if (driver instanceof TakesScreenshot)
    {
        return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64);
    }

    return null;
}
 
Example 17
Project: givemeadriver   File: WebDriverContainerTest.java   View source code 5 votes vote down vote up
@Test
public void cleanupThreadClosesTheDriver() {
    // given
    container.WEB_DRIVER = mock(WebDriver.class);
    WebDriverContainer.WebDriverCleanupThread cleanupThread = container.new WebDriverCleanupThread();
    // when
    cleanupThread.run();
    // then
    assertThat(container.WEB_DRIVER).isNull();

}
 
Example 18
Project: Spring-Security-Third-Edition   File: SeleniumTestUtilities.java   View source code 5 votes vote down vote up
public static WebDriver getChromeDriver(String pathToChromeExecutable)
{
	String path = System.getProperty("user.dir") + "\\Drivers\\chromedriver.exe";
	System.setProperty("webdriver.chrome.driver",path);

	Map<String, Object> chromeOptions = new HashMap<String, Object>();
	chromeOptions.put("binary", pathToChromeExecutable);
	DesiredCapabilities capabilities = DesiredCapabilities.chrome();
	capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);

	return new ChromeDriver(capabilities);
}
 
Example 19
Project: participationSystem3b   File: SeleniumUtils.java   View source code 5 votes vote down vote up
static public List<WebElement> EsperaCargaPagina(WebDriver driver, String criterio, String id, int timeout)
{
	String busqueda;
	if (criterio.equals("id")) busqueda = "//*[contains(@id,'" + id + "')]";
	else if (criterio.equals("class")) busqueda = "//*[contains(@class,'" + id + "')]";
	else busqueda = "//*[contains(text(),'" + id + "')]";
	return EsperaCargaPaginaxpath(driver, busqueda, timeout);
}
 
Example 20
Project: selenium-toys   File: TypeTest.java   View source code 5 votes vote down vote up
@Test
public void onTest() {
  final WebDriver webDriver = Mockito.mock(WebDriver.class);
  final WebElement webElement = Mockito.mock(WebElement.class);

  final Type type = new Type(webDriver, "text", () -> {});
  final By byId = By.id("id");
  Mockito.when(webDriver.findElement(byId)).thenReturn(webElement);
  type.on(byId);
  Mockito.verify(webElement).sendKeys("text");
}
 
Example 21
Project: AutomationFrameworkTPG   File: WebDriverInstance.java   View source code 5 votes vote down vote up
public WebDriver getDriver() {
	if (driver == null) {
		DriverProperties driverProperties = getDriverProperties();
		driver = driverProperties.setDriver(driverProperties.getAppURL());
	}
	return driver;
}
 
Example 22
Project: POM_HYBRID_FRAMEOWRK   File: WebButton.java   View source code 5 votes vote down vote up
/**
 * Web button click.
 *
 * @param driver the driver
 * @param logger the logger
 * @param element the element
 */
public static void webButtonClick(WebDriver driver, ExtentTest logger, WebElement element) {
	try {
		if (element != null && element.isEnabled()) {
			element.click();
		}
	} catch (Exception e) {
		}
}
 
Example 23
Project: participationSystem3b   File: SeleniumUtils.java   View source code 5 votes vote down vote up
static public void ClickSubopcionMenuHover(WebDriver driver, String submenu, String opcionclick)
{
	//Pasamos el raton por el submenu de Gestion de alumnos	para
	//que aparezca el menu desplegable
	Actions builder = new Actions(driver);
	WebElement hoverElement = driver.findElement(By.id(submenu));
	builder.moveToElement(hoverElement).perform();		
	//Pinchamos la opcion opcionclick
	By locator = By.id(opcionclick);
	driver.findElement(locator).click();			
}
 
Example 24
Project: satisfy   File: SatisfyBaseStepListener.java   View source code 5 votes vote down vote up
public SatisfyBaseStepListener(final Class<? extends WebDriver> driverClass,
                               final File outputDirectory,
                               final Configuration configuration) {
    this(outputDirectory);
    this.driver = getProxyFactory().proxyFor(driverClass);
    this.configuration = configuration;
}
 
Example 25
Project: Cognizant-Intelligent-Test-Scripter   File: WebDriverFactory.java   View source code 5 votes vote down vote up
private static WebDriver checkAndSetSize(WebDriver driver, String size) {
    if (driver != null) {
        if (size.matches("[0-9]+ x [0-9]+")) {
            int w = Integer.valueOf(size.split("x")[0].trim());
            int h = Integer.valueOf(size.split("x")[1].trim());
            driver.manage().window().setSize(new Dimension(w, h));
        }
    }
    return driver;
}
 
Example 26
Project: Java-Data-Science-Cookbook   File: WebdataExtractionSelenium.java   View source code 5 votes vote down vote up
public static void main(String[] args) {
       WebDriver driver = new FirefoxDriver();
       driver.get("http://cogenglab.csd.uwo.ca/rushdi.htm");

       WebElement webElement = driver.findElement(By.xpath("//*[@id='content']"));
	System.out.println(webElement.getText());
	
}
 
Example 27
Project: selenium-jupiter   File: DriverHandler.java   View source code 5 votes vote down vote up
public String getName() {
    String name = "";
    Optional<Method> testMethod = context.getTestMethod();
    if (testMethod.isPresent()) {
        name = testMethod.get().getName();
    }
    name += "_" + parameter.getName() + "_"
            + object.getClass().getSimpleName();
    if (WebDriver.class.isAssignableFrom(object.getClass())) {
        name += "_" + ((RemoteWebDriver) object).getSessionId();
    }
    return name;
}
 
Example 28
Project: crawler   File: PhantomjsWebDriverPool.java   View source code 5 votes vote down vote up
public void returnToPool(WebDriver webDriver) {
	if (shutdowned.get()) {
		webDriver.quit();
		webDriver = null;
	} else {
		Set<String> handles = webDriver.getWindowHandles();
		if (handles.size() > 1) {
			int index = 0;
			for (String handle : handles) {
				if (index == 0) {
					index++;
					continue;
				}
				WindowUtil.changeWindowTo(webDriver, handle);
				webDriver.close();
				index++;
			}
		}
		synchronized (shutdowned) {
			if(!shutdowned.get()){
				innerQueue.add(webDriver);
			}else{
				webDriver.quit();
				webDriver = null;
			}
		}
	}
}
 
Example 29
Project: KITE   File: NoAdapterTestTest.java   View source code 5 votes vote down vote up
public void tearDown() throws Exception {
  // Close all the browsers
  for (WebDriver webDriver : this.webDriverList)
    try {
      webDriver.quit();
    } catch (Exception e) {
      e.printStackTrace();
    }
}
 
Example 30
Project: selenium-jupiter   File: TemplateTwoBrowsersTest.java   View source code 5 votes vote down vote up
@TestTemplate
void templateTest(WebDriver driver1, WebDriver driver2) {
    driver1.get("https://bonigarcia.github.io/selenium-jupiter/");
    driver2.get("https://bonigarcia.github.io/selenium-jupiter/");
    assertThat(driver1.getTitle(),
            containsString("A JUnit 5 extension for Selenium WebDriver"));
    assertThat(driver2.getTitle(),
            containsString("A JUnit 5 extension for Selenium WebDriver"));
}
 
Example 31
Project: autotest   File: WebTestBase.java   View source code 5 votes vote down vote up
/**
 * 切换到新窗口
 *
 * @param driver
 */
public void switchToNewWindow(WebDriver driver) {
    String[] handles = new String[driver.getWindowHandles().size()];
    driver.getWindowHandles().toArray(handles);// 把list转换成数组
    int i = handles.length;
    driver.switchTo().window(handles[i - 1]);// 切换窗口
}
 
Example 32
Project: Selenium-Foundation   File: ScreenshotUtils.java   View source code 5 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 byte[] getArtifact(Optional<WebDriver> optDriver, Throwable reason, Logger logger) {
    if (canGetArtifact(optDriver, logger)) {
        try {
            WebDriver driver = optDriver.get();
            return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
        } catch (WebDriverException e) {
            logger.warn("The driver is capable of taking a screenshot, but it failed.", e);
        }
    }
    return new byte[0];
}
 
Example 33
Project: Cognizant-Intelligent-Test-Scripter   File: GalenWrapper.java   View source code 5 votes vote down vote up
public synchronized static File takeScreenShot(WebDriver Driver) {
    try {
        return GalenUtils.makeFullScreenshot(Driver);
    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(GalenWrapper.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}
 
Example 34
Project: bootstrap   File: AbstractSequentialSeleniumTest.java   View source code 5 votes vote down vote up
/**
 * Sequentially run the desired capabilities.
 */
protected void runSequential() { // NOPMD -- thread
	final WebDriver[] drivers = new WebDriver[repeatedCapabilities.length];
	final boolean[] success = new boolean[repeatedCapabilities.length];
	for (int index = 0; index < repeatedCapabilities.length; index++) {
		final int driverIndex = index;
		final DesiredCapabilities capability = repeatedCapabilities[driverIndex];
		success[driverIndex] = false;
		runSequentialIndex(drivers, success, driverIndex, capability);
	}

	final List<String> faillures = checkResults(success);
	Assert.assertTrue("All browsers test failed", faillures.size() != success.length);
	Assert.assertEquals("Some browsers test failed", 0, faillures.size());
}
 
Example 35
Project: redirector   File: FlavorRulesTemplatesShowPage.java   View source code 4 votes vote down vote up
public FlavorRulesTemplatesShowPage(WebDriver webDriver) {
    super(webDriver);
}
 
Example 36
Project: msa-cucumber-appium   File: MobileApp.java   View source code 4 votes vote down vote up
public static WebDriver getDriver() {
    return driver.get();
}
 
Example 37
Project: teasy   File: VisibleElementWaitFor.java   View source code 4 votes vote down vote up
public VisibleElementWaitFor(TeasyElement element, TeasyFluentWait<WebDriver> fluentWait) {
    this.element = element;
    this.fluentWait = fluentWait;
}
 
Example 38
Project: Selenium-Foundation   File: ScreenshotArtifact.java   View source code 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public byte[] getArtifact(ITestResult result) {
    Optional<WebDriver> optDriver = DriverManager.nabDriver(result.getInstance());
    return ScreenshotUtils.getArtifact(optDriver, result.getThrowable(), LOGGER);
}
 
Example 39
Project: Java_Good   File: SessionHelper.java   View source code 4 votes vote down vote up
public SessionHelper(WebDriver wd) {
    super(wd);
}
 
Example 40
Project: testing_security_development_enterprise_systems   File: LoginPageObject.java   View source code 4 votes vote down vote up
public LoginPageObject(WebDriver driver) {
    super(driver);

    assertEquals("Login", driver.getTitle());
    assertFalse(isLoggedIn());
}