@Test public void testAjaxViewScope() throws Exception { HtmlPage page = webClient.getPage(webUrl + "faces/issue2754.xhtml"); HtmlTextInput input = (HtmlTextInput) page.getHtmlElementById("input"); HtmlSubmitInput button = (HtmlSubmitInput) page.getElementById("button"); page = button.click(); webClient.waitForBackgroundJavaScript(60000); assertTrue(page.asText().contains("input: Validation Error: Value is required")); input.type("hello"); webClient.waitForBackgroundJavaScript(60000); page = button.click(); webClient.waitForBackgroundJavaScript(60000); assertTrue(!page.asText().contains("input: Validation Error: Value is required")); }
@Override protected String getCallbackUrl(final WebClient webClient, final HtmlPage authorizationPage) throws Exception { webClient.waitForBackgroundJavaScript(5000); HtmlForm form = authorizationPage.getForms().get(0); final HtmlTextInput login = form.getInputByName("login_email"); login.setValueAttribute("*****@*****.**"); final HtmlPasswordInput passwd = form.getInputByName("login_password"); passwd.setValueAttribute("testpwdscribeup"); HtmlButton submit = form.getButtonByName(""); HtmlPage confirmPage = submit.click(); confirmPage = (HtmlPage) confirmPage.refresh(); webClient.waitForBackgroundJavaScript(5000); form = confirmPage.getForms().get(0); HtmlButton submit2 = form.getButtonByName("allow_access"); final HtmlPage callbackPage = submit2.click(); final String callbackUrl = callbackPage.getUrl().toString(); logger.debug("callbackUrl : {}", callbackUrl); return callbackUrl; }
/** * This test verifies that an attribute named 'readonly' can be successfully updated from a * partial response (over Ajax). */ @Test public void testUpdateAttributeNamedReadonly() throws Exception { HtmlPage page = webClient.getPage(webUrl + "faces/attributeNameIsReadonly.xhtml"); HtmlTextInput input = (HtmlTextInput) page.getElementById("form1:foo"); assertTrue(input.isReadOnly() == false); HtmlSubmitInput button = (HtmlSubmitInput) page.getElementById("form1:button"); page = button.click(); webClient.waitForBackgroundJavaScript(60000); input = (HtmlTextInput) page.getElementById("form1:foo"); assertTrue(input.isReadOnly() == true); }
@Test public void testLabelAjaxBehavior() throws Exception { webClient.setJavaScriptEnabled(true); webClient.setJavaScriptTimeout(60000); HtmlPage page = webClient.getPage(webUrl + "/faces/label.xhtml"); HtmlElement label = page.getHtmlElementById("label2"); page = (HtmlPage) label.mouseOver(); webClient.waitForBackgroundJavaScript(60000); assertTrue(page.asXml().contains("label2 Event: begin")); assertTrue(page.asXml().contains("label2 Event: complete")); assertTrue(page.asXml().contains("label2 Event: success")); }
@Test public void testFieldSetAjaxBehavior() throws Exception { webClient.setJavaScriptEnabled(true); webClient.setJavaScriptTimeout(60000); HtmlPage page = webClient.getPage(webUrl + "/faces/fieldset.xhtml"); HtmlFieldSet fieldset = (HtmlFieldSet) page.getHtmlElementById("fieldset4"); page = fieldset.click(); webClient.waitForBackgroundJavaScript(60000); assertTrue(page.asXml().contains("fieldset4 Event: begin")); assertTrue(page.asXml().contains("fieldset4 Event: complete")); assertTrue(page.asXml().contains("fieldset4 Event: success")); }
/** * This test verifies that an attribute named 'checked' can be successfully updated from a partial * response (over Ajax). */ @Test public void testUpdateAttributeNamedChecked() throws Exception { HtmlPage page = webClient.getPage(webUrl + "faces/attributeNameIsChecked.xhtml"); HtmlCheckBoxInput cbox = (HtmlCheckBoxInput) page.getElementById("form1:foo"); assertTrue(cbox.isChecked() == false); assertTrue(page.asXml().contains("foo")); HtmlSubmitInput button = (HtmlSubmitInput) page.getElementById("form1:button"); page = button.click(); webClient.waitForBackgroundJavaScript(60000); cbox = (HtmlCheckBoxInput) page.getElementById("form1:foo"); assertTrue(cbox.isChecked() == true); }
public static void homePage(String url) { String str; // 创建一个webclient WebClient webClient = new WebClient(); // webClient.getWebConsole().setLogger(null); // //htmlunit 对css和javascript的支持不好,所以请关闭之 webClient.getOptions().setCssEnabled(false); // webClient.getOptions().setUseInsecureSSL(true); webClient.getOptions().setThrowExceptionOnFailingStatusCode(false); // webClient.getCookieManager().setCookiesEnabled(true); webClient.setAjaxController(new NicelyResynchronizingAjaxController()); webClient.getOptions().setThrowExceptionOnScriptError(false); webClient.waitForBackgroundJavaScript(1000); webClient.waitForBackgroundJavaScriptStartingBefore(1000); // 获取页面 HtmlPage page = null; int times = 10; try { page = webClient.getPage(url); for (int i = 0; i < times; i++) { synchronized (page) { page.wait(2000); } if (page.getByXPath("//object") != null) { System.out.println("***************************yes**********************"); for (int j = 0; j < page.getByXPath("//object").size(); j++) { System.out.println(page.getByXPath("//object").get(j)); } break; } System.out.println("***************************no***************************"); } } catch (Exception e) { e.printStackTrace(); } // 获取页面的TITLE // str = page.getTitleText(); // System.out.println(str); // //获取页面的XML代码 // System.out.println("***************************start***************************"); // System.out.println(page.asXml()); // System.out.println("***************************end***************************"); // //获取页面的文本 // str = page.asText(); // System.out.println(str); }
@Test public void shouldIncludeUnloadJSInSavedReport() throws Exception { File jsonFile = new File(getReportDir() + "/jscoverage.json"); if (jsonFile.exists()) jsonFile.delete(); HtmlPage page = webClient.getPage("http://localhost:9001/jscoverage.html?index.html"); page.getHtmlElementById("summaryTab").click(); webClient.waitForBackgroundJavaScript(2000); assertEquals("77%", page.getElementById("summaryTotal").getTextContent()); verifyCoverage(page, "/root.js", "80%", "50%", "100%"); verifyCoverage(page, "/level1/level1.js", "75%", "50%", "N/A"); page.getHtmlElementById("storeTab").click(); webClient.waitForBackgroundJavaScript(500); HtmlElement storeButton = page.getHtmlElementById("storeButton"); storeButton.click(); webClient.waitForBackgroundJavaScript(2000); String result = page.getElementById("storeDiv").getTextContent(); assertThat( result, containsString("Coverage data stored at " + new File(getReportDir()).getPath())); String json = ioUtils.toString(jsonFile); assertThat(json, containsString("/root.js")); assertThat(json, containsString("/level1/level2/level2.js")); String url = "file:///" + new File(getReportDir() + "/jscoverage.html").getAbsolutePath(); page = webClient.getPage(url); webClient.waitForBackgroundJavaScript(1000); assertEquals("53%", page.getElementById("summaryTotal").getTextContent()); assertEquals("33%", page.getElementById("branchSummaryTotal").getTextContent()); assertEquals("50%", page.getElementById("functionSummaryTotal").getTextContent()); verifyCoverage(page, "/root.js", "80%", "50%", "100%"); verifyCoverage(page, "/level1/level1.js", "75%", "50%", "N/A"); verifyCoverage(page, "/level1/level2/level2.js", "0%", "0%", "0%"); }
public static WebClient buildWebClient() { WebClient webClient = new WebClient(BrowserVersion.FIREFOX_10); webClient.setAjaxController(new NicelyResynchronizingAjaxController()); webClient.getOptions().setCssEnabled(true); webClient.getOptions().setJavaScriptEnabled(true); webClient.getOptions().setUseInsecureSSL(true); webClient.setCssErrorHandler( new ErrorHandler() { @Override public void warning(CSSParseException exception) throws CSSException { // nothing to do here } @Override public void error(CSSParseException exception) throws CSSException { // todo: log or throw exception } @Override public void fatalError(CSSParseException exception) throws CSSException { // todo: log or throw exception } }); webClient.setIncorrectnessListener( new IncorrectnessListener() { @Override public void notify(String message, Object origin) { // todo: analyze and throw exception } }); webClient.waitForBackgroundJavaScript(100000); webClient.getOptions().setThrowExceptionOnScriptError(false); webClient.getOptions().setRedirectEnabled(true); return webClient; }
/** * Runs the test and keeps the results. * * @throws IOException If there're errors reading the test file. */ public void run() throws IOException { try { startTime = new Date().getTime(); browser.setAjaxController(new NicelyResynchronizingAjaxController()); browser.setJavaScriptEnabled(true); HtmlPage page = browser.getPage(testUrl); // This is to avoid errors when background JS hasn't updated the DOM yet // while we're trying to access it. // See: http://htmlunit.sourceforge.net/faq.html browser.waitForBackgroundJavaScript(10000); readTests(page); readResults(page); } catch (IOException ex) { throw (IOException) new IOException("Cannot read the test resource.").initCause(ex); } catch (ScriptException scriptEx) { error = new QUnitException(scriptEx); } }
public static void main(String[] args) throws Exception { Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF); String app = System.getProperty("application.url", "http://*****:*****@tests.list").openStream(), "utf-8")); String marker = in.readLine(); if (!marker.equals("---")) { throw new RuntimeException("Oops"); } root = new File(in.readLine()); selenium = in.readLine(); tests = new ArrayList<String>(); String line; while ((line = in.readLine()) != null) { tests.add(line); } in.close(); } catch (Exception e) { System.out.println("~ The application does not start. There are errors: " + e); System.exit(-1); } // Let's tweak WebClient WebClient firephoque = new WebClient(BrowserVersion.INTERNET_EXPLORER_8); firephoque.setPageCreator( new DefaultPageCreator() { @Override public Page createPage(WebResponse wr, WebWindow ww) throws IOException { Page page = createHtmlPage(wr, ww); return page; } }); firephoque.setThrowExceptionOnFailingStatusCode(false); firephoque.setAlertHandler( new AlertHandler() { public void handleAlert(Page page, String string) { try { Window window = (Window) page.getEnclosingWindow().getScriptObject(); window.custom_eval( "parent.selenium.browserbot.recordedAlerts.push('" + string.replace("'", "\\'") + "');"); } catch (Exception e) { e.printStackTrace(); } } }); firephoque.setConfirmHandler( new ConfirmHandler() { public boolean handleConfirm(Page page, String string) { try { Window window = (Window) page.getEnclosingWindow().getScriptObject(); Object result = window.custom_eval( "parent.selenium.browserbot.recordedConfirmations.push('" + string.replace("'", "\\'") + "');" + "var result = parent.selenium.browserbot.nextConfirmResult;" + "parent.selenium.browserbot.nextConfirmResult = true;" + "result"); return (Boolean) result; } catch (Exception e) { e.printStackTrace(); return false; } } }); firephoque.setPromptHandler( new PromptHandler() { public String handlePrompt(Page page, String string) { try { Window window = (Window) page.getEnclosingWindow().getScriptObject(); Object result = window.custom_eval( "parent.selenium.browserbot.recordedPrompts.push('" + string.replace("'", "\\'") + "');" + "var result = !parent.selenium.browserbot.nextConfirmResult ? null : parent.selenium.browserbot.nextPromptResult;" + "parent.selenium.browserbot.nextConfirmResult = true;" + "parent.selenium.browserbot.nextPromptResult = '';" + "result"); return (String) result; } catch (Exception e) { e.printStackTrace(); return ""; } } }); firephoque.setThrowExceptionOnScriptError(false); // Go! int maxLength = 0; for (String test : tests) { String testName = test.replace(".class", "").replace(".test.html", "").replace(".", "/").replace("$", "/"); if (testName.length() > maxLength) { maxLength = testName.length(); } } System.out.println("~ " + tests.size() + " test" + (tests.size() != 1 ? "s" : "") + " to run:"); System.out.println("~"); firephoque.openWindow(new URL(app + "/@tests/init"), "headless"); boolean ok = true; for (String test : tests) { long start = System.currentTimeMillis(); String testName = test.replace(".class", "").replace(".test.html", "").replace(".", "/").replace("$", "/"); System.out.print("~ " + testName + "... "); for (int i = 0; i < maxLength - testName.length(); i++) { System.out.print(" "); } System.out.print(" "); URL url; if (test.endsWith(".class")) { url = new URL(app + "/@tests/" + test); } else { url = new URL( app + "" + selenium + "?baseUrl=" + app + "&test=/@tests/" + test + ".suite&auto=true&resultsUrl=/@tests/" + test); } firephoque.openWindow(url, "headless"); firephoque.waitForBackgroundJavaScript(5 * 60 * 1000); int retry = 0; while (retry < 5) { if (new File(root, test.replace("/", ".") + ".passed.html").exists()) { System.out.print("PASSED "); break; } else if (new File(root, test.replace("/", ".") + ".failed.html").exists()) { System.out.print("FAILED ! "); ok = false; break; } else { if (retry++ == 4) { System.out.print("ERROR ? "); ok = false; break; } else { Thread.sleep(1000); } } } // int duration = (int) (System.currentTimeMillis() - start); int seconds = (duration / 1000) % 60; int minutes = (duration / (1000 * 60)) % 60; if (minutes > 0) { System.out.println(minutes + " min " + seconds + "s"); } else { System.out.println(seconds + "s"); } } firephoque.openWindow( new URL(app + "/@tests/end?result=" + (ok ? "passed" : "failed")), "headless"); }
@Override public HtmlPage getData() { // TODO Auto-generated method stub MainDataBean mainDataBean = (MainDataBean) UserBeanFactory.getBeanFactoryObject().getBean("mainDataBean"); String URL = mainDataBean.getRedBusUrl(); URL = "https://www.redbus.in/"; ClientFactory cf = (ClientFactory) UserBeanFactory.getBeanFactoryObject().getBean("clientFactory"); WebClient client = cf.getWebClient(); // try { // client.getOptions().setJavaScriptEnabled(true); // client.getOptions().setThrowExceptionOnScriptError(false); // new InterceptWebConnection(client); // HtmlPage page = client.getPage(URL); // client.waitForBackgroundJavaScript(10000); // System.out.print(page.asXml()); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } String html; try { // client.getOptions().setUseInsecureSSL(true); // client.se // client.getOptions().setJavaScriptEnabled(true); // client.getOptions().setThrowExceptionOnScriptError(false); new InterceptWebConnection(client); // client.addRequestHeader("Host", "www.redbus.in"); // client.addRequestHeader("Referer", "https://www.redbus.in/"); // Booking/SelectBus.aspx?fromCityId=248&toCityId=134&doj=12-Dec-2015&busType=Any&opId=0 HtmlPage page = client.getPage("https://www.redbus.in/"); client.waitForBackgroundJavaScript(1000); DomElement source = page.getElementById("txtSource"); DomElement destination = page.getElementById("txtDestination"); DomElement date = page.getElementById("txtOnwardCalendar"); DomElement search = page.getElementById("searchBtn"); // List<DomElement> inputs = (List<DomElement>) // page.getByXPath("//input[@class='XXinput']"); // HtmlTextInput source=null,destination=null,date1=null; // for (DomElement domElement : inputs) { // System.out.println("Coming into sourrce"); // if(domElement.getAttribute("id").equals("txtSource")){ // System.out.println("Coming into sourrce"); // source = (HtmlTextInput) domElement; // }else if (domElement.getAttribute("id").equals("txtDestination")){ // System.out.println("Coming into destination"); // destination =(HtmlTextInput) domElement; // } // } // List<DomElement> Cal_inputs = (List<DomElement>) page.getByXPath("//input[@class='XXinput // calendar']"); // HtmlElement searchButton = (HtmlElement) page.getFirstByXPath("//button[@class='RB // Xbutton']"); // for (DomElement domElement : Cal_inputs) { // if(domElement.getAttribute("id").equals("txtOnwardCalendar")){ // System.out.println("Coming into calandar"); // date1 =(HtmlTextInput) domElement; // } // } source.setAttribute("value", "Visakapatnam"); // source.setValueAttribute("Visakapatnam"); destination.setAttribute("value", "Vijayawada"); // destination.setValueAttribute("Vijayawada"); date.setAttribute("value", "12-12-2015"); // date.setValueAttribute("27-10-2015"); // client.getOptions().setThrowExceptionOnScriptError(false); // client.getOptions().setThrowExceptionOnFailingStatusCode(false); // HtmlPage page1 = search.click(); client.waitForBackgroundJavaScript(200); html = page1.asXml(); System.out.println(html); } catch (Exception e) { e.printStackTrace(); } return null; }