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); } } }
@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; }
/** * 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); }
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()); }
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); } } }
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); } } }
@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(); }
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(); } }
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(); }
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; } }; }
@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); }
@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()); }
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()); }
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); }
@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); }
@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(); }
@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()); }
@Test public void htmlUnit() { WebDriver driver = new HtmlUnitDriver(); driver.get("http://surenpi.com"); driver.quit(); }
@Override @PublicAtsApi public void start() { webDriver = new HtmlUnitDriver(this.browserVersion); webDriver.setJavascriptEnabled(true); setProxyIfAvailable(); fixHtmlUnitBehaviour(); log.info("Openning URL: " + url); webDriver.get(url); }
@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(); }
/** * {@inheritDoc} */ @Override public HtmlUnitDriver start(Capabilities other) { Capabilities capabilities = this.mergeCapabilities(other); if (capabilities == null) { return new HtmlUnitDriver(); } return new HtmlUnitDriver(capabilities); }
public static WebDriver getHtmlUnitDriver() { HtmlUnitDriver driver = new HtmlUnitDriver(); driver.setJavascriptEnabled(true); return driver; }
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]; }
/** * 用枚举类型列出浏览器列表,用于设置浏览器类型的函数参数 * @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; }
@Test public void testCanInstantiateAndDismissAStandardDriverByName() { WebDriver driver = factory.getDriver(BrowserType.HTMLUNIT); assertThat(driver, instanceOf(HtmlUnitDriver.class)); assertFalse(factory.isEmpty()); factory.dismissDriver(driver); assertTrue(factory.isEmpty()); }
@Test public void testCanInstantiateAndDismissAStandardDriver() { WebDriver driver = factory.getDriver(DesiredCapabilities.htmlUnit()); assertThat(driver, instanceOf(HtmlUnitDriver.class)); assertFalse(factory.isEmpty()); factory.dismissDriver(driver); assertTrue(factory.isEmpty()); }
@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 } }); }
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); }
@Override public WebDriver createDriver() throws Exception { final HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.BEST_SUPPORTED); driver.setJavascriptEnabled(true); manage(driver); return driver; }
@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)); }
@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; }
@Before public void setUp() throws Exception { setupTestesIntegracao.setupComDados(); baseUrl = "http://localhost:" + port + "/"; driver = new HtmlUnitDriver(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); }
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; }
@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(); }
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; }
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; }
@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; }