Java Code Examples for org.openqa.selenium.htmlunit.HtmlUnitDriver

The following are top voted examples for showing how to use org.openqa.selenium.htmlunit.HtmlUnitDriver. 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: ats-framework   File: HiddenHtmlPrompt.java   Source Code and License 10 votes vote down vote up
public HiddenHtmlPrompt( UiDriver uiDriver ) {

        super(uiDriver);

        HiddenBrowserDriver browserDriver = (HiddenBrowserDriver) uiDriver;
        HtmlUnitDriver driver = (HtmlUnitDriver) browserDriver.getInternalObject(InternalObjectsEnum.WebDriver.name());
        Field webClientField = null;
        boolean fieldAccessibleState = false;
        try {

            TargetLocator targetLocator = driver.switchTo();
            webClientField = targetLocator.getClass().getDeclaringClass().getDeclaredField("webClient");
            fieldAccessibleState = webClientField.isAccessible();
            webClientField.setAccessible(true);
            webClient = (WebClient) webClientField.get(targetLocator.defaultContent());

        } catch (Exception e) {

            throw new SeleniumOperationException("Error retrieving internal Selenium web client", e);
        } finally {

            if (webClientField != null) {
                webClientField.setAccessible(fieldAccessibleState);
            }
        }
    }
 
Example 2
Project: atsd-web-test   File: ExportServiceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testHttpCsv() {
    String uri = "/export?settings=%7B%22m%22%3A%22jvm_memory_used_percent%22%2C%22si%22%3A%225-MINUTE%22%2C%22t%22%3A%22HISTORY%22%2C%22f%22%3A%22CSV%22%2C%22np%22%3A-1%2C%22v%22%3Afalse%2C%22tf%22%3A%22LOCAL%22%2C%22ms%22%3Afalse%2C%22ro%22%3Afalse%2C%22te%22%3A%5B%5D%2C%22am%22%3Afalse%7D";
    AtsdTest.driver.quit();//will use htmlwebdriver instead of phantomjs for this test
    AtsdTest.driver = new HtmlUnitDriver();
    AtsdTest.driver.navigate().to(AtsdTest.url);
    Assert.assertEquals(this.generateAssertMessage("Should get login page"), driver.getTitle(), LoginService.title);
    LoginService ls = new LoginService(AtsdTest.driver);
    ls.login(AtsdTest.login, AtsdTest.password);
    AtsdTest.driver.navigate().to(AtsdTest.url + uri);
    String[] src = AtsdTest.driver.getPageSource().split("\n");
    String head = src[0];
    String body = src[1];
    Assert.assertTrue("Csv file is incorrect", head.trim().equals("Timestamp,Value,Metric,Entity,host") && body.contains("jvm_memory_used_percent"));
    AtsdTest.driver.quit();
    AtsdTest.driver = null;

}
 
Example 3
Project: NoraUi   File: DriverFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Generates a htmlunit webdriver.
 *
 * @return
 *         A htmlunit webdriver
 */
private WebDriver generateHtmlUnitDriver() {
    logger.info("Generating HtmlUnit driver...");
    final DesiredCapabilities capabilities = DesiredCapabilities.htmlUnit();
    capabilities.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);
    capabilities.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT);
    capabilities.setJavascriptEnabled(true);

    setLoggingLevel(capabilities);

    // Proxy configuration
    if (Context.getProxy().getProxyType() != ProxyType.UNSPECIFIED && Context.getProxy().getProxyType() != ProxyType.AUTODETECT) {
        capabilities.setCapability(CapabilityType.PROXY, Context.getProxy());
    }
    return new HtmlUnitDriver(capabilities);
}
 
Example 4
Project: ats-framework   File: HiddenHtmlElement.java   Source Code and License 6 votes vote down vote up
public HiddenHtmlElement( UiDriver uiDriver,
                          UiElementProperties properties ) {

    super(uiDriver, properties);
    String matchingRules[] = properties.checkTypeAndRules(this.getClass().getSimpleName(),
                                                          "HiddenHtml",
                                                          RULES_DUMMY);

    // generate the XPath of this HTML element
    String xpath = HtmlElementLocatorBuilder.buildXpathLocator(matchingRules,
                                                               properties,
                                                               new String[]{},
                                                               "*");
    properties.addInternalProperty(HtmlElementLocatorBuilder.PROPERTY_ELEMENT_LOCATOR, xpath);

    HiddenBrowserDriver browserDriver = (HiddenBrowserDriver) uiDriver;
    htmlUnitDriver = (HtmlUnitDriver) browserDriver.getInternalObject(InternalObjectsEnum.WebDriver.name());
}
 
Example 5
Project: ats-framework   File: HiddenHtmlAlert.java   Source Code and License 6 votes vote down vote up
public HiddenHtmlAlert( UiDriver uiDriver ) {

        super(uiDriver);

        HiddenBrowserDriver browserDriver = (HiddenBrowserDriver) uiDriver;
        HtmlUnitDriver driver = (HtmlUnitDriver) browserDriver.getInternalObject(InternalObjectsEnum.WebDriver.name());
        Field webClientField = null;
        boolean fieldAccessibleState = false;
        try {

            TargetLocator targetLocator = driver.switchTo();
            webClientField = targetLocator.getClass().getDeclaringClass().getDeclaredField("webClient");
            fieldAccessibleState = webClientField.isAccessible();
            webClientField.setAccessible(true);
            webClient = (WebClient) webClientField.get(targetLocator.defaultContent());
        } catch (Exception e) {

            throw new SeleniumOperationException("Error retrieving internal Selenium web client", e);
        } finally {

            if (webClientField != null) {
                webClientField.setAccessible(fieldAccessibleState);
            }
        }
    }
 
Example 6
Project: ats-framework   File: HiddenHtmlConfirm.java   Source Code and License 6 votes vote down vote up
public HiddenHtmlConfirm( UiDriver uiDriver ) {

        super(uiDriver);

        HiddenBrowserDriver browserDriver = (HiddenBrowserDriver) uiDriver;
        HtmlUnitDriver driver = (HtmlUnitDriver) browserDriver.getInternalObject(InternalObjectsEnum.WebDriver.name());
        Field webClientField = null;
        boolean fieldAccessibleState = false;
        try {

            TargetLocator targetLocator = driver.switchTo();
            webClientField = targetLocator.getClass().getDeclaringClass().getDeclaredField("webClient");
            fieldAccessibleState = webClientField.isAccessible();
            webClientField.setAccessible(true);
            webClient = (WebClient) webClientField.get(targetLocator.defaultContent());

        } catch (Exception e) {

            throw new SeleniumOperationException("Error retrieving internal Selenium web client", e);
        } finally {

            if (webClientField != null) {
                webClientField.setAccessible(fieldAccessibleState);
            }
        }
    }
 
Example 7
Project: CS1632_Summer2017   File: RedditTestNoLogs.java   Source Code and License 6 votes vote down vote up
@BeforeClass
   public static void setUpDriver() {

// Note that the logging level is a Java standard (thus the
// use of a java.util class instead of something specific
// to Selenium.  You can modify these levels yourself if,
// for example, you would like to see only SEVERE errors.
// They can be set to ALL (show all messages) or OFF (no messages)
// or to any minimum level from FINEST (most verbose) to SEVERE
// (only show the most egregious of errors).
// A full lists of levels and descriptions are located at:
// https://docs.oracle.com/javase/7/docs/api/java/util/logging/Level.html

java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF); 
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
driver = new HtmlUnitDriver(); 

   }
 
Example 8
Project: chr-krenn-fhj-ws2016-sd14-pse   File: BaseUITest.java   Source Code and License 6 votes vote down vote up
WebDriver start(Capabilities capabilities) {
    switch (this) {
        case FIREFOX:
            return new FirefoxDriver(capabilities);
        case HTML_UNIT:
            return new HtmlUnitDriver(capabilities);
        case CHROME:
            return new ChromeDriver(capabilities);
        case EDGE:
            return new EdgeDriver(capabilities);
        case INTERNET_EXPLORER:
            return new InternetExplorerDriver(capabilities);
        case SAFARI:
            return new SafariDriver(capabilities);
        default:
            throw new AssertionError();
    }
}
 
Example 9
Project: SeleniumCucumber   File: GenericHelper.java   Source Code and License 6 votes vote down vote up
public String takeScreenShot(String name) throws IOException {

		if (driver instanceof HtmlUnitDriver) {
			oLog.fatal("HtmlUnitDriver Cannot take the ScreenShot");
			return "";
		}

		File destDir = new File(ResourceHelper.getResourcePath("screenshots/")
				+ DateTimeHelper.getCurrentDate());
		if (!destDir.exists())
			destDir.mkdir();

		File destPath = new File(destDir.getAbsolutePath()
				+ System.getProperty("file.separator") + name + ".jpg");
		try {
			FileUtils
					.copyFile(((TakesScreenshot) driver)
							.getScreenshotAs(OutputType.FILE), destPath);
		} catch (IOException e) {
			oLog.error(e);
			throw e;
		}
		oLog.info(destPath.getAbsolutePath());
		return destPath.getAbsolutePath();
	}
 
Example 10
Project: jscoverproxy-maven-plugin   File: JSCoverProxyMavenMojo.java   Source Code and License 6 votes vote down vote up
private WebDriver getWebClient(int portForJSCoverProxy) {
    Proxy proxy = new Proxy().setHttpProxy("localhost:" + portForJSCoverProxy);
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability(CapabilityType.PROXY, proxy);
    caps.setJavascriptEnabled(true);
    caps.setBrowserName(BrowserType.HTMLUNIT);
    return new HtmlUnitDriver(caps) {
        @Override
        protected WebClient modifyWebClient(WebClient client) {
            client.setScriptPreProcessor((htmlPage, sourceCode, sourceName, lineNumber, htmlElement) -> {
                if(removeJsSnippets != null && !removeJsSnippets.isEmpty()) {
                    for(String toReplace : removeJsSnippets) {
                        sourceCode = sourceCode.replace(toReplace, "");
                    }
                    return sourceCode;
                } else {
                    return sourceCode;
                }

            });
            return client;
        }
    };
}
 
Example 11
Project: awesome-agile   File: AwesomeAgileFunctionalTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  System.out.println("Fake Google OAuth2 server up at: " + fakeGoogleServer.getEndpoint());
  System.out.println("Fake Hackpad server up at: " + fakeHackpadServer.getEndpoint());
  System.out.println("AwesomeAgile web application up at: " + getEndpoint());
  fakeGoogleServer.setClientId(CLIENT_ID);
  fakeGoogleServer.setClientSecret(CLIENT_SECRET);
  fakeGoogleServer.setRedirectUriPrefixes(
      ImmutableList.of("http://localhost:" + port + "/"));
  fakeGoogleServer.setPerson(createUser());
  fakeHackpadServer.setClientId(HACKPAD_CLIENT_ID);
  fakeHackpadServer.setClientSecret(HACKPAD_CLIENT_SECRET);
  fakeHackpadServer.getHackpads().clear();
  fakeHackpadServer.addHackpad(
      new PadIdentity(DEFINITION_OF_READY_TEMPLATE_ID),
      DEFINITION_OF_READY_CONTENTS);
  fakeHackpadServer.addHackpad(
      new PadIdentity(DEFINITION_OF_DONE_TEMPLATE_ID),
      DEFINITION_OF_DONE_CONTENTS);

  driver = new HtmlUnitDriver(BrowserVersion.CHROME);
  driver.setJavascriptEnabled(true);
}
 
Example 12
Project: awesome-agile   File: AwesomeAgileFunctionalTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testDashboardReopenBrowser() throws Exception {
  LandingPage landingPage = PageFactory.initElements(driver, LandingPage.class);
  landingPage.loginWithGoogle(getEndpoint());
  assertThat(driver.getWindowHandles(), hasSize(1));
  landingPage.createDefinitionOfReady();

  HtmlUnitDriver driverTwo = new HtmlUnitDriver(BrowserVersion.CHROME);
  driverTwo.setJavascriptEnabled(true);

  // Open a completely new browser with no cookies
  // Verify that view button is visible for this same user,
  // and we're able to open his Definition of ready hackpad
  LandingPage landingPageTwo = PageFactory.initElements(driverTwo, LandingPage.class);
  landingPageTwo.loginWithGoogle(getEndpoint());
  landingPageTwo.waitForDefinitionOfReady();
  assertTrue(landingPageTwo.isDefinitionOfReadyViewable());
  landingPageTwo.viewDefinitionOfReady();
  String newWindow = Iterables.getFirst(Sets.difference(
      driverTwo.getWindowHandles(),
      ImmutableSet.of(driverTwo.getWindowHandle())), null);
  driverTwo.switchTo().window(newWindow);
  HackpadPage hackpadPage = PageFactory.initElements(driverTwo, HackpadPage.class);
  assertEquals(DEFINITION_OF_READY_CONTENTS, hackpadPage.getContent());
}
 
Example 13
Project: awesome-agile   File: AwesomeAgileFunctionalTest.java   Source Code and License 6 votes vote down vote up
private static void assertDefinitionOfReadyContents(HtmlUnitDriver driver, String contents) {
  // Refresh the dashboard for user #1; he should have definition of ready viewable
  LandingPage landingPage = PageFactory.initElements(driver, LandingPage.class);
  driver.navigate().refresh();
  String currentWindow = driver.getWindowHandle();
  landingPage.waitForDefinitionOfReady();
  assertTrue(landingPage.isDefinitionOfReadyViewable());
  landingPage.viewDefinitionOfReady();

  // Verify definition of ready contents for user #1
  String newWindow = Iterables.getFirst(Sets.difference(
      driver.getWindowHandles(),
      ImmutableSet.of(currentWindow)), null);
  driver.switchTo().window(newWindow);
  HackpadPage hackpadPage = PageFactory.initElements(driver, HackpadPage.class);
  assertEquals(contents, hackpadPage.getContent());
}
 
Example 14
Project: WebCollector   File: DemoSelenium.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Executor executor = new Executor() {
        @Override
        public void execute(CrawlDatum datum, CrawlDatums next) throws Exception {
            
            HtmlUnitDriver driver = new HtmlUnitDriver();
            driver.setJavascriptEnabled(true);
            
            driver.get(datum.url());
            
            List<WebElement> elementList = driver.findElementsByCssSelector("h3.vrTitle a");
            for(WebElement element:elementList){
                System.out.println("title:"+element.getText());
            }
        }
    };

    //创建一个基于伯克利DB的DBManager
    DBManager manager = new BerkeleyDBManager("crawl");
    //创建一个Crawler需要有DBManager和Executor
    Crawler crawler = new Crawler(manager, executor);
    crawler.addSeed("https://www.sogou.com/web?query=%E6%B7%98%E5%AE%9D");
    crawler.start(1);
}
 
Example 15
Project: appengine   File: WebDriverFactoryTest.java   Source Code and License 6 votes vote down vote up
@Test
public void buildWebDriver() throws Exception {
	MockitoAnnotations.initMocks(this);

	PowerMockito.whenNew(FirefoxDriver.class).withNoArguments().thenReturn(firefoxDriver);
	WebDriver driver = WebDriverFactory.createDriver("firefox");
	assertTrue(driver instanceof FirefoxDriver);

	PowerMockito.whenNew(InternetExplorerDriver.class).withNoArguments().thenReturn(internetExplorerDriver);
	driver = WebDriverFactory.createDriver("ie");
	assertTrue(driver instanceof InternetExplorerDriver);

	PowerMockito.whenNew(ChromeDriver.class).withNoArguments().thenReturn(chromerDriver);
	driver = WebDriverFactory.createDriver("chrome");
	assertTrue(driver instanceof ChromeDriver);

	PowerMockito.whenNew(HtmlUnitDriver.class).withArguments(true).thenReturn(htmlUnitDriver);
	driver = WebDriverFactory.createDriver("htmlunit");
	assertTrue(driver instanceof HtmlUnitDriver);

	PowerMockito.whenNew(RemoteWebDriver.class)
			.withArguments(new URL("http://localhost:4444/wd/hub"), DesiredCapabilities.firefox())
			.thenReturn(remoteWebDriver);
	driver = WebDriverFactory.createDriver("remote:localhost:4444:firefox");
	assertTrue(driver instanceof RemoteWebDriver);
}
 
Example 16
Project: Learning-Spring-Boot-2.0-Second-Edition   File: WebDriverAutoConfigurationTests.java   Source Code and License 5 votes vote down vote up
@Test
public void fallbackToNonGuiModeWhenAllBrowsersDisabled() {
	load(new Class[]{},
		"com.greglturnquist.webdriver.firefox.enabled:false",
		"com.greglturnquist.webdriver.safari.enabled:false",
		"com.greglturnquist.webdriver.chrome.enabled:false");

	WebDriver driver = context.getBean(WebDriver.class);
	assertThat(ClassUtils.isAssignable(TakesScreenshot.class,
		driver.getClass())).isFalse();
	assertThat(ClassUtils.isAssignable(HtmlUnitDriver.class,
		driver.getClass())).isTrue();
}
 
Example 17
Project: mastering-junit5   File: LocalWebDriverTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testWithHeadlessBrowsers(HtmlUnitDriver htmlUnit,
        PhantomJSDriver phantomjs) {
    htmlUnit.get("https://bonigarcia.github.io/selenium-jupiter/");
    phantomjs.get("https://bonigarcia.github.io/selenium-jupiter/");

    assertTrue(htmlUnit.getTitle().contains("JUnit 5 extension"));
    assertNotNull(phantomjs.getPageSource());
}
 
Example 18
Project: phoenix.webui.framework   File: DriverTest.java   Source Code and License 5 votes vote down vote up
@Test
public void htmlUnit()
{
	WebDriver driver = new HtmlUnitDriver();
	driver.get("http://surenpi.com");
	driver.quit();
}
 
Example 19
Project: ats-framework   File: HiddenBrowserDriver.java   Source Code and License 5 votes vote down vote up
@Override
@PublicAtsApi
public void start() {

    webDriver = new HtmlUnitDriver(this.browserVersion);
    webDriver.setJavascriptEnabled(true);

    setProxyIfAvailable();

    fixHtmlUnitBehaviour();

    log.info("Openning URL: " + url);
    webDriver.get(url);
}
 
Example 20
Project: givemeadriver   File: GiveMeADriverTest.java   Source Code and License 5 votes vote down vote up
@Test
public void createHtmlUnitDriver() {
    WebDriver driver = GiveMeADriver.create();
    assertThat(driver).isInstanceOf(HtmlUnitDriver.class);
    assertThat(GiveMeADriver.current()).isEqualTo(driver);
    GiveMeADriver.close();
    exception.expect(IllegalStateException.class);
    GiveMeADriver.current();

}
 
Example 21
Project: Java-Testing-Toolbox   File: HtmlUnitConfiguration.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public HtmlUnitDriver start(Capabilities other) {
    Capabilities capabilities = this.mergeCapabilities(other);

    if (capabilities == null) {
        return new HtmlUnitDriver();
    }

    return new HtmlUnitDriver(capabilities);
}
 
Example 22
Project: Mastering-Software-Testing-with-JUnit-5   File: LocalWebDriverTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testWithHeadlessBrowsers(HtmlUnitDriver htmlUnit,
        PhantomJSDriver phantomjs) {
    htmlUnit.get("https://bonigarcia.github.io/selenium-jupiter/");
    phantomjs.get("https://bonigarcia.github.io/selenium-jupiter/");

    assertTrue(htmlUnit.getTitle().contains("JUnit 5 extension"));
    assertNotNull(phantomjs.getPageSource());
}
 
Example 23
Project: Spring-Security-Third-Edition   File: SeleniumTestUtilities.java   Source Code and License 5 votes vote down vote up
public static WebDriver getHtmlUnitDriver()
{
	HtmlUnitDriver driver = new HtmlUnitDriver();
	driver.setJavascriptEnabled(true);

	return driver;
}
 
Example 24
Project: Spring-Security-Third-Edition   File: SeleniumTestUtilities.java   Source Code and License 5 votes vote down vote up
public static WebDriver getHtmlUnitDriver()
{
	HtmlUnitDriver driver = new HtmlUnitDriver();
	driver.setJavascriptEnabled(true);

	return driver;
}
 
Example 25
Project: Spring-Security-Third-Edition   File: SeleniumTestUtilities.java   Source Code and License 5 votes vote down vote up
public static WebDriver getHtmlUnitDriver()
{
	HtmlUnitDriver driver = new HtmlUnitDriver();
	driver.setJavascriptEnabled(true);

	return driver;
}
 
Example 26
Project: photometric-data-retriever   File: Main.java   Source Code and License 5 votes vote down vote up
public String getIdFromForm(String query) {
    WebDriver driver = new HtmlUnitDriver();
    driver.get("http://www.astrouw.edu.pl/asas/i_aasc/aasc_form.php?catsrc=asas3");
    driver.findElement(By.name("coo")).sendKeys(query);
    driver.findElement(By.name("submit")).submit();
    driver.close();
    driver.getWindowHandles().forEach(w -> {
        driver.switchTo().window(w);
    });
    Document doc = Jsoup.parse(driver.getPageSource());
    String href = doc.getElementsByTag("a").first().attr("href");
    return href.split("/")[3].split(",")[0];
}
 
Example 27
Project: PatatiumWebUi   File: TestBaseCase.java   Source Code and License 5 votes vote down vote up
/**
 * 用枚举类型列出浏览器列表,用于设置浏览器类型的函数参数
 * @author zheng
 *
 */
private WebDriver setDriver(String browsername)
{
	switch (browsername)
	{

		case "FirefoxDriver" :
			System.setProperty("webdriver.firefox.bin", "C:/Program Files (x86)/Mozilla Firefox/firefox.exe");
			FirefoxProfile firefoxProfile=new FirefoxProfile();
			//设置默认下载路径
			firefoxProfile.setPreference("browser.download.folderList", 2);
			firefoxProfile.setPreference("browser.download.dir", "D:\\自动化测试下载文件");
			//加载firebug插件
			firefoxProfile.setPreference("extensions.firebug.currentVersion", "2.0.13");
			firefoxProfile.setPreference("extensions.firebug.allPagesActivation", "none");
			//加载firepath插件
			firefoxProfile.setPreference("extensions.firepath.currentVersion", "0.9.7.1.1");
			firefoxProfile.setPreference("extensions.firepath.allPagesActivation", "on");
			this.driver=new FirefoxDriver(firefoxProfile);
			break;
		case "ChormeDriver":
			System.setProperty("webdriver.chrome.driver", "resource\\chromedriver.exe");
			this.driver=new ChromeDriver();
			break;
		case "InternetExplorerDriver":
			System.setProperty("webdriver.ie.driver", "resource\\IEDriverServer_Win32_2.48.0\\IEDriverServer.exe");
			DesiredCapabilities dc = DesiredCapabilities.internetExplorer();
			dc.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
			dc.setCapability("ignoreProtectedModeSettings", true);
			this.driver=new InternetExplorerDriver(dc);
			break;
		case "HtmlUnitDriver":
			this.driver=new HtmlUnitDriver();
			break;
		default:
			this.driver=new FirefoxDriver();
			break;
	}
	return driver;
}
 
Example 28
Project: webdriver-factory   File: AbstractWebDriverPoolTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCanInstantiateAndDismissAStandardDriverByName() {
  WebDriver driver = factory.getDriver(BrowserType.HTMLUNIT);
  assertThat(driver, instanceOf(HtmlUnitDriver.class));
  assertFalse(factory.isEmpty());

  factory.dismissDriver(driver);
  assertTrue(factory.isEmpty());
}
 
Example 29
Project: webdriver-factory   File: AbstractWebDriverPoolTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCanInstantiateAndDismissAStandardDriver() {
  WebDriver driver = factory.getDriver(DesiredCapabilities.htmlUnit());
  assertThat(driver, instanceOf(HtmlUnitDriver.class));
  assertFalse(factory.isEmpty());

  factory.dismissDriver(driver);
  assertTrue(factory.isEmpty());
}
 
Example 30
Project: webdrivermanager   File: OtherWebDriverTest.java   Source Code and License 5 votes vote down vote up
@Parameters(name = "{index}: {0} {1}")
public static Collection<Object[]> data() {
    return asList(new Object[][] {
            { SafariDriver.class, WebDriverException.class },
            { EventFiringWebDriver.class, InstantiationException.class },
            { HtmlUnitDriver.class, null },
            { RemoteWebDriver.class, IllegalAccessException.class } });
}
 
Example 31
Project: awesome-agile   File: AwesomeAgileFunctionalTest.java   Source Code and License 5 votes vote down vote up
private static void closeWindowsExceptFor(HtmlUnitDriver driver, String currentWindow) {
  Set<String> difference = ImmutableSet.copyOf(Sets.difference(
      driver.getWindowHandles(),
      ImmutableSet.of(currentWindow)));
  for (String window : difference) {
    driver.switchTo().window(window).close();
  }
  driver.switchTo().window(currentWindow);
}
 
Example 32
Project: alex   File: HtmlUnitDriverConfig.java   Source Code and License 5 votes vote down vote up
@Override
public WebDriver createDriver() throws Exception {
    final HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.BEST_SUPPORTED);
    driver.setJavascriptEnabled(true);
    manage(driver);
    return driver;
}
 
Example 33
Project: alex   File: MoveMouseActionTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldReturnFAILEDIfNodeCouldNotBeClicked() {
    WebSiteConnector connector = mock(WebSiteConnector.class);
    WebDriver driver = mock(HtmlUnitDriver.class);
    when(connector.getElement(node)).thenThrow(new NoSuchElementException(""));
    given(connector.getDriver()).willReturn(driver);

    assertEquals(ExecuteResult.FAILED, c.execute(connector));
}
 
Example 34
Project: seleniumtestsframework   File: HtmlUnitDriverFactory.java   Source Code and License 5 votes vote down vote up
@Override
public WebDriver createWebDriver() {
    DriverConfig cfg = this.getWebDriverConfig();

    driver = new HtmlUnitDriver(new HtmlUnitCapabilitiesFactory().createCapabilities(cfg));

    // Implicit Waits. The default value is 5 seconds.
    setImplicitWaitTimeout(cfg.getImplicitWaitTimeout());
    if (cfg.getPageLoadTimeout() >= 0) {
        TestLogging.log("htmlunit doesn't support pageLoadTimeout");
    }

    this.setWebDriver(driver);
    return driver;
}
 
Example 35
Project: portal-de-servicos   File: BuscaUITest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    setupTestesIntegracao.setupComDados();
    baseUrl = "http://localhost:" + port + "/";

    driver = new HtmlUnitDriver();
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
 
Example 36
Project: maker   File: TungParser.java   Source Code and License 5 votes vote down vote up
public static String quicklyPartAjaxHtml(final String url, final String expression) {
  String _xblockexpression = null;
  {
    final HtmlUnitDriver webDriver = new HtmlUnitDriver(true);
    webDriver.get(url);
    final WebElement webElement = webDriver.findElementByCssSelector(expression);
    webDriver.close();
    _xblockexpression = webElement.getText();
  }
  return _xblockexpression;
}
 
Example 37
Project: poseidon   File: UserJourney.java   Source Code and License 5 votes vote down vote up
@BeforeMethod
public void setUp() throws Exception {

    final String chrome_driver = System.getenv("CHROME_DRIVER");
    if (chrome_driver != null) {
        System.setProperty("webdriver.chrome.driver", chrome_driver);
        webDriver = new ChromeDriver();
    } else {
        webDriver = new HtmlUnitDriver();
    }
    wait = new WebDriverWait(webDriver, 10);
    webDriver.get("http://localhost:8080");
    webDriver.manage().window().maximize();
}
 
Example 38
Project: fitnessefixtures   File: CheckContentElementOnHtmlPage.java   Source Code and License 5 votes vote down vote up
public List doTable(List<List<String>> fitnesse_table) throws InterruptedException { 
  	System.out.println("------------------------------ Check content element on html page Fixture ------------------------------------------");
  		  
  	//Get url
  	url = fitnesse_table.get(0).get(1);
  	//Get element identifier
  	element_identifier = fitnesse_table.get(1).get(1);
  	
  	//populate return row with 'pass'
	return_row.add("pass"); //return "pass" in next cell
	return_row.add("pass"); //return "pass" in next cell
  	//First 2 rows green
	getTextAndReturnPass (fitnesse_table.get(0));
	getTextAndReturnPass (fitnesse_table.get(1));

    // Create a new instance of the driver    
  	driver = new HtmlUnitDriver();
 	System.out.println("driver = htmlunit");  		  		
  	System.out.println("url = " + url);
  	System.out.println("element = " + element_identifier);
 
    // And now use this to visit url
 	driver.get(url);
 	element = driver.findElement(By.id(element_identifier));

 	element_text = element.getText();
  	System.out.println("element text = " + element_text);
 	Thread.sleep(500);
	driver.quit();
	
	CompareExpectedTableWithPageTable (fitnesse_table);
	return return_table;
}
 
Example 39
Project: fitnessefixtures   File: CheckContentTableOnHtmlPage.java   Source Code and License 5 votes vote down vote up
public List doTable(List<List<String>> fitnesse_table) throws InterruptedException { 
  	System.out.println("------------------------------ Check Content Table On HTML Page ------------------------------------------");
  	
  	//Get url
  	url = fitnesse_table.get(0).get(1);
  	//Get element identifier
  	element_identifier = fitnesse_table.get(1).get(1);
  	
  	//populate return row with 'pass'
  	//First row green
	getTextAndReturnPass (fitnesse_table.get(0));
  	//Second row green
	getTextAndReturnPass (fitnesse_table.get(1));
		  	
  	// Create a new instance of the driver    
  	driver = new HtmlUnitDriver();
 	System.out.println("driver = htmlunit");  		  		
 	System.out.println("url = " + url);
  	System.out.println("element = " + element_identifier);
 
    // And now use this to visit url
 	driver.get(url);
 	element = driver.findElement(By.id(element_identifier));
    element_text = element.getText();
 	Thread.sleep(500);
	driver.quit();
	  
	//Return number of columns in fitnesse table
	number_of_table_columns = fitnesse_table.get(2).size();	  
	CompareExpectedTableWithPageTable (fitnesse_table);
	return return_table;
}
 
Example 40
Project: guiceberry   File: PetStoreEnv4CanonicalSameJvmControllablePotm.java   Source Code and License 5 votes vote down vote up
@Provides
WebDriver getWebDriver(@PortNumber int portNumber, TestId testId) {
  WebDriver driver = new HtmlUnitDriver();
  driver.get("http://localhost:" + portNumber);
  driver.manage().addCookie(
      new Cookie(TestId.COOKIE_NAME, testId.toString()));
  return driver;
}
 
Example 41
Project: guiceberry   File: PetStoreEnv3CookiesControlledPotm.java   Source Code and License 5 votes vote down vote up
@Provides
WebDriver getWebDriver(@PortNumber int portNumber, TestId testId) {
  WebDriver driver = new HtmlUnitDriver();
  // !!! HERE !!!
  driver.get("http://localhost:" + portNumber);
  driver.manage().addCookie(
      new Cookie(TestId.COOKIE_NAME, testId.toString()));
  return driver;
}
 
Example 42
Project: guiceberry   File: PetStoreEnv4InjectionController.java   Source Code and License 5 votes vote down vote up
@Provides @TestScoped
WebDriver getWebDriver(@PortNumber int portNumber, TestId testId) {
  WebDriver driver = new HtmlUnitDriver();
  driver.get("http://localhost:" + portNumber);
  driver.manage().addCookie(new Cookie(TestId.COOKIE_NAME, testId.toString()));
  return driver;
}
 
Example 43
Project: guiceberry   File: PetStoreEnv3CookiesOverride.java   Source Code and License 5 votes vote down vote up
@Provides @TestScoped
WebDriver getWebDriver(@PortNumber int portNumber, TestId testId) {
  WebDriver driver = new HtmlUnitDriver();
  // !!! HERE !!!
  driver.get("http://localhost:" + portNumber);
  driver.manage().addCookie(new Cookie(TestId.COOKIE_NAME, testId.toString()));
  return driver;
}
 
Example 44
Project: elpaaso-core   File: CommonHtmlUnitDriverStepHelper.java   Source Code and License 5 votes vote down vote up
public CommonHtmlUnitDriverStepHelper(HtmlUnitDriver webDriver, URL webappURL, URL populatePageURL) {
	logger.debug("DriverSteps init webappURL: {}   -populatePageURL: {} ", webappURL, populatePageURL);
	this.webDriver = webDriver;
	this.webappURL = webappURL;
	this.populatePageURL = populatePageURL;
	initWebDriver();
}
 
Example 45
Project: seauto   File: AbstractConfigurableDriverProvider.java   Source Code and License 5 votes vote down vote up
/**
 * Screenshooter for HTMLUnit. It saves the html source to disk following the
 * same pattern as the screenshot path. The HTMLUnit session is transfered to
 * PhantomJs, which takes the screenshot, and is destroyed. The original
 * driver is not destroyed
 * 
 * Note: Javascript events, current page changes, etc.. are not saved and are
 * not captured in the screenshots taken.
 * 
 * @param path
 *          - where to save the file. This assumes a png file will be
 *          generated
 * @param baseUrl
 *          - used to transfer the cookies to the phantomjs driver properly.
 * 
 * @see #getPhantomJsWebDriver()
 */
public void saveScreenshotForHtmlUnit(String path, String baseUrl)
{
  final WebDriver driver = this.get();

  if (!(driver instanceof HtmlUnitDriver)) {
    LOG.warn("Wrong driver called screenshooter for HTMLUnit driver, default to regular screenshooter");
    this.saveScreenshotAs(path);
    return;
  }

  PhantomJSDriver phantomJs = (PhantomJSDriver) getPhantomJsWebDriver();

  try {
    phantomJs.get(baseUrl);
    String url = driver.getCurrentUrl();
    LOG.debug("Url: {}", url);

    for (Cookie cookie : driver.manage().getCookies()) {
      LOG.debug("Cookie: {}", cookie.toString());
      phantomJs.manage().addCookie(cookie);
    }

    phantomJs.get(url);

    // set current thread to phantomjs, and take screenshot in the default way
    this.set(phantomJs);
    LOG.debug("HTML Screenshot taken: {}", this.saveScreenshotAs(path));
  }
  finally {
    // set back original driver for this thread
    this.set(driver);

    phantomJs.close();
    phantomJs.quit();
  }
}
 
Example 46
Project: seauto   File: AbstractConfigurableDriverProvider.java   Source Code and License 5 votes vote down vote up
/**
 * Takes screenshot of the current driver. Screeshot will be skipped if
 * test.config.driver.screenshots.allow is set to false.
 * 
 * @param path location where the screenshot should be saved at
 * @return true if succeeded, false otherwise
 */
@Override
public boolean saveScreenshotAs(String path)
{

  if(!Boolean.valueOf(System.getProperty(ALLOW_SCREENSHOTS, "true"))) {
    LOG.debug("Skipping screenshot");
    return false;
  }

  WebDriver driver = this.get();

  if (driver instanceof HtmlUnitDriver) {
    LOG.info("Additional work needs to be done to take screenshots with HTMLUnit driver, skipping. " + "Email the SeAuto user list for more information.");
    return false;
  }

  if (driver instanceof TakesScreenshot) {
    File dstFile = new File(path);
    File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    try {
      FileUtils.copyFile(srcFile, dstFile);
    }
    catch (IOException e) {
      throw new RuntimeException("Can't save screenshot!", e);
    }
    return true;
  }
  return false;

}
 
Example 47
Project: seauto   File: AbstractConfigurableDriverProvider.java   Source Code and License 5 votes vote down vote up
/**
 * Default implementation of getting a local HTMLUnit Driver
 * 
 * @return {@link WebDriver} for HTMLUnit
 */
protected WebDriver getHtmlUnitWebDriver()
{
  // Set to firefox 24 to emulate a friendly javascript engine
  HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_38);
  driver.setJavascriptEnabled(true);
  return driver;
}
 
Example 48
Project: hmrc4j   File: AbstractUserRestrictedIT.java   Source Code and License 5 votes vote down vote up
protected void initializeTokenStore() throws Exception {
    final Optional<URL> authorizeUrl = createHmrc().getAuthorizeUrl(getScope());
    final HtmlUnitDriver browser = new HtmlUnitDriver();
    browser.setJavascriptEnabled(true);
    browser.get(authorizeUrl.map(URL::toString).orElseThrow(() -> new IllegalStateException("no authorize url found")));
    browser.findElement(By.id("userId")).sendKeys("user1");
    browser.findElement(By.id("password")).sendKeys("password1");
    browser.findElement(By.tagName("button")).click();
    browser.findElement(By.id("authorise")).click();
    while (!initialized) {
        Thread.sleep(100);
    }
}
 
Example 49
Project: PageObjectEvaluator   File: PageObjectEvaluator.java   Source Code and License 5 votes vote down vote up
private Object populatePageObject(Class clazz) {
    WebDriver driver = new HtmlUnitDriver();
    driver.get(evaluationConfig.getHtmlFilePath());
    Object pageObject = PageFactory.initElements(driver, clazz);
    tryToInjectWebDriver(pageObject, driver);
    return pageObject;
}
 
Example 50
Project: web-traffic-simulator   File: BrowserThread.java   Source Code and License 5 votes vote down vote up
private static WebDriver getBrowser(final String browser, final DesiredCapabilities capabilities) {
	switch (browser) {
	case BROWSER_HTMLUNIT:
		return new HtmlUnitDriver(capabilities);
	case BROWSER_CHROME:
		return new ChromeDriver(capabilities);
	}
	throw new RuntimeException("No browser specified! Use " + browser + " parameter.");
}
 
Example 51
Project: edemocracia   File: BatePapoEdemoEntrarESair.java   Source Code and License 5 votes vote down vote up
public void carregarJanela(DesiredCapabilities cap, int cont) throws Exception {
//		WebDriver driver = new FirefoxDriver(cap);
		 WebDriver driver = new HtmlUnitDriver();
         driver.get(Configuracoes.getURLDaSala());

		try {
			WebElement element = driver.findElement(By.name("nome"));
			element.sendKeys(USUARIO + cont);
			element = driver.findElement(By.name("email"));
			element.sendKeys(EMAIL + cont);
			element = driver.findElement(By.name("uf"));
			// element.sendKeys();

			Select Select = new Select(element);
			Select.selectByIndex(3);

			element = driver.findElement(By.name("comando"));
			element.submit();
			Actions act = new Actions(driver);
			act.contextClick();

		    Thread.sleep(20000);

			element = driver.findElement(By.cssSelector("a#_cdchatroom_WAR_cdchatportlet_leave"));
			element.click();
			
		} catch (NoSuchElementException e) {
			throw new Exception("aconteceu algum problema inesperado ao tentar entrar no chat", e);
		}

	}
 
Example 52
Project: edemocracia   File: BatePapoEdemoEntrar.java   Source Code and License 5 votes vote down vote up
public void carregarJanela(DesiredCapabilities cap, int cont) throws Exception {
//		WebDriver driver = new FirefoxDriver(cap);
		 WebDriver driver = new HtmlUnitDriver();

		driver.get(Configuracoes.getURLDaSala());

		try {
			WebElement element = driver.findElement(By.name("nome"));
			element.sendKeys(USUARIO + cont);
			
			element = driver.findElement(By.name("email"));
			element.sendKeys(EMAIL + cont);
			
			element = driver.findElement(By.name("uf"));
			Select Select = new Select(element);
			Select.selectByIndex(3);

			element = driver.findElement(By.name("comando"));
			element.submit();
			Actions act = new Actions(driver);
			act.contextClick();


		} catch (NoSuchElementException e) {
			throw new Exception("aconteceu algum problema inesperado ao tentar entrar no chat", e);
		}

	}
 
Example 53
Project: sniffy   File: BaseTomcatIT.java   Source Code and License 5 votes vote down vote up
@Test
@Issue("issues/321")
public void testSniffyInjectedPath() {

    WebDriver webDriver = new HtmlUnitDriver(true);

    webDriver.navigate().to("http://127.0.0.1:8081/test/index.html");

    assertFalse(webDriver.findElement(By.id("sniffy-iframe")).isDisplayed());
    webDriver.findElement(By.className("sniffy-widget-icon-container")).click();
    assertTrue(webDriver.findElement(By.id("sniffy-iframe")).isDisplayed());

    webDriver.quit();
}
 
Example 54
Project: sniffy   File: BaseTomcatIT.java   Source Code and License 5 votes vote down vote up
@Test
@Issue("issues/319")
public void testSniffyInjectedToUrlWithQueryParameters() {

    WebDriver webDriver = new HtmlUnitDriver(true);

    webDriver.navigate().to("http://127.0.0.1:8081/test?foo=bar");

    assertFalse(webDriver.findElement(By.id("sniffy-iframe")).isDisplayed());
    webDriver.findElement(By.className("sniffy-widget-icon-container")).click();
    assertTrue(webDriver.findElement(By.id("sniffy-iframe")).isDisplayed());

    webDriver.quit();
}
 
Example 55
Project: redsniff   File: WebDriverFactory.java   Source Code and License 5 votes vote down vote up
public Duration getInitialAjaxDelayForDriver() {
    WebDriver webDriver = activeDriver();
    if (webDriver instanceof HtmlUnitDriver) {
        return null;
      //new Duration(0, MILLISECONDS);
    } else if (webDriver instanceof ChromeDriver) {
        return null;
    } else {
        return new Duration(1, SECONDS);
    }
}
 
Example 56
Project: bl4ckb0t   File: LinkTitle.java   Source Code and License 5 votes vote down vote up
@Override
public void handle(String channel, String user, String link) throws Exception
{
	HtmlUnitDriver driver = new HtmlUnitDriver();
	String title = "";

	if(link.startsWith("www."))
		link = "http://" + link;

	driver.get(link);
	title = driver.getTitle();
	driver.quit();

	if(link.startsWith("http://"))
		link = link.substring(7);
	else if(link.startsWith("https://"))
		link = link.substring(8);

	if(link.length() > 21)
	{
		link = link.substring(0, 21);
		link += "...";
	}

	if(title.equals("") || title.equals("null"))
		Utilities.sendMessage(channel, l10n.translate("notFound", channel).replace("#link", link));
	else
		Utilities.sendMessage(channel, l10n.translate("available", channel).replace("#link", link).replace("#title", title));
}
 
Example 57
Project: kpme   File: KPMESeleniumTestCase.java   Source Code and License 5 votes vote down vote up
@Override
public void setUp() throws Exception {
    if (System.getProperty("basedir") == null) {
        System.setProperty("basedir", System.getProperty("user.dir") + "/");
    }
    
	super.setUp();

	GlobalVariables.setMessageMap(new MessageMap());
	
	final boolean needsSpring = false;
	if (needsSpring) {
		transactionalLifecycle = new TransactionalLifecycle();
		//transactionalLifecycle.setTransactionManager(KRADServiceLocatorInternal.getTransactionManager());
		transactionalLifecycle.start();
	}

    new ClearDatabaseLifecycle().start();

	new LoadDatabaseDataLifeCycle(this.getClass()).start();

    //lets try to create a user session
    GlobalVariables.setUserSession(new UserSession("admin"));

       DesiredCapabilities capabilities = new DesiredCapabilities();
       capabilities.setCapability(CapabilityType.SUPPORTS_JAVASCRIPT, true);
       capabilities.setCapability(CapabilityType.BROWSER_NAME, BrowserVersion.FIREFOX_17);
       driver = new HtmlUnitDriver(capabilities);
}
 
Example 58
Project: TechnologyConversationsBddSteps   File: WebStepsTest.java   Source Code and License 5 votes vote down vote up
@Before
public final void before() {
    if (steps.getWebDriver() == null) {
        steps.setWebDriver(new BddVariable("htmlunit"));
    }
    if (!(steps.getWebDriver() instanceof HtmlUnitDriver)) {
        steps.setWebDriver(new BddVariable("htmlunit"));
    }
    steps.setBaseUrl(null);
    steps.setParams(null);
    steps.setConfigTimeout(new BddVariable("0"));
    steps.open(new BddVariable(indexUrl));
    steps.setSize(new BddVariable("100"), new BddVariable("100"));
    CommonSteps.setVariableMap(null);
}
 
Example 59
Project: CAPS   File: ProxySeleniumIntegrationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void withoutProxyHttp() throws Exception {
    DesiredCapabilities caps = DesiredCapabilities.htmlUnit();
    WebDriver d = new HtmlUnitDriver(caps);
    d.navigate().to("http://localhost:" + PORT_TESTSERVER_HTTP);
    assertTrue("Expected that the cert list will be empty", d.getPageSource().startsWith("Cert: 0"));
}
 
Example 60
Project: CAPS   File: ProxySeleniumIntegrationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void withoutProxySsl() throws Exception {
    DesiredCapabilities caps = DesiredCapabilities.htmlUnit();
    caps.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
    WebDriver d = new HtmlUnitDriver(caps);
    d.navigate().to("https://localhost:" + PORT_TESTSERVER_SSL);
    assertTrue("Expected that the cert list will be empty", d.getPageSource().startsWith("Cert: 0"));
}