コード例 #1
0
ファイル: Event3Test.java プロジェクト: xinl/HTMLUnit
  /**
   * Test for event bubbling in IE.
   *
   * @throws Exception if the test fails
   */
  @Test
  @Browsers(Browser.IE)
  @NotYetImplemented // TODO: in IE no click event can be registered for the window
  @Alerts({"span bubbling", "div", "div bubbling"})
  public void testIE_EventBubbling() throws Exception {
    final String content =
        "<html><head><title>foo</title>\n"
            + "<script>\n"
            + "function t(_s) {\n"
            + "     return function() { alert(_s) };\n"
            + "}\n"
            + "function init() {\n"
            + "  window.attachEvent('onclick', t('window bubbling'));\n"
            + "  var oDiv = document.getElementById('theDiv');\n"
            + "  oDiv.attachEvent('onclick', t('div bubbling'));\n"
            + "  var oSpan = document.getElementById('theSpan');\n"
            + "  oSpan.attachEvent('onclick', t('span bubbling'));\n"
            + "}\n"
            + "</script>\n"
            + "</head><body onload='init()'>\n"
            + "<div onclick=\"alert('div')\" id='theDiv'>\n"
            + "<span id='theSpan'>blabla</span>\n"
            + "</div>\n"
            + "</body></html>";

    final List<String> collectedAlerts = new ArrayList<String>();
    final HtmlPage page = loadPage(getBrowserVersion(), content, collectedAlerts);
    page.getHtmlElementById("theSpan").click();

    assertEquals(getExpectedAlerts(), collectedAlerts);
  }
コード例 #2
0
  public void testRenderFacetRequired03() throws Exception {

    // facet not required and not present
    client.setThrowExceptionOnFailingStatusCode(false);
    HtmlPage page = getPage("/faces/composite/renderfacetrequired03.xhtml");
    assertTrue(!page.asText().contains("Unable to find facet named 'header'"));
  }
コード例 #3
0
  public void testLogInWithOpenIDAndSignUp() throws Exception {
    openid = createServer();

    realm = new HudsonPrivateSecurityRealm(true);
    hudson.setSecurityRealm(realm);

    WebClient wc = new WebClient();
    // Workaround failing ajax requests to build queue
    wc.setThrowExceptionOnFailingAjax(false);

    // Login with OpenID as an unregistered user
    HtmlPage login = wc.goTo("federatedLoginService/openid/login?from=/");
    login
        .getDocumentElement()
        .getOneHtmlElementByAttribute("a", "title", "log in with OpenID")
        .click();
    HtmlForm loginForm = getFormById(login, "openid_form");
    loginForm.getInputByName("openid").setValueAttribute(openid.url);
    HtmlPage signUp = (HtmlPage) loginForm.submit();

    // Sign up user
    HtmlForm signUpForm =
        getFormByAction(signUp, "/securityRealm/createAccountWithFederatedIdentity");
    signUpForm.getInputByName("password1").setValueAttribute("x");
    signUpForm.getInputByName("password2").setValueAttribute("x");
    HtmlPage loggedIn = submit(signUpForm);

    assertNotNull(loggedIn.getAnchorByHref("/logout"));
    assertNotNull(loggedIn.getAnchorByHref("/user/aliceW"));

    wc.goTo("logout");

    // Re-login
    login(wc);
  }
コード例 #4
0
 /** Verify that the bean is successfully resolved */
 public void testReplaceLifecycle() throws Exception {
   HtmlPage page = getPage("/faces/test.jsp");
   String pageText = page.asText();
   assertTrue(-1 != pageText.indexOf("beforePhase"));
   // Ensure the phaseListener is only called once.
   assertTrue(!pageText.matches("(?s).*beforePhase.*beforePhase.*"));
 }
コード例 #5
0
  /** @throws Exception if the test fails */
  @Test
  @Alerts(FF = "[object SVGFEFuncBElement]", IE = "[object HTMLGenericElement]")
  public void simpleScriptable() throws Exception {
    final String html =
        HtmlPageTest.STANDARDS_MODE_PREFIX_
            + "<html><head>\n"
            + "<script>\n"
            + "  function test() {\n"
            + "    alert(document.getElementById('myId'));\n"
            + "  }\n"
            + "</script>\n"
            + "</head><body onload='test()'>\n"
            + "  <svg xmlns='http://www.w3.org/2000/svg' version='1.1'>\n"
            + "    <feFuncB id='myId'/>\n"
            + "  </svg>\n"
            + "</body></html>";

    final WebDriver driver = loadPageWithAlerts2(html);
    if (driver instanceof HtmlUnitDriver) {
      final HtmlPage page = (HtmlPage) getWebWindowOf((HtmlUnitDriver) driver).getEnclosedPage();
      if ("[object SVGFEFuncBElement]".equals(getExpectedAlerts()[0])) {
        assertTrue(SvgFeFuncBLight.class.isInstance(page.getElementById("myId")));
      } else {
        assertTrue(HtmlUnknownElement.class.isInstance(page.getElementById("myId")));
      }
    }
  }
コード例 #6
0
ファイル: TestEditing.java プロジェクト: paulcadman/reviki
  private void testInvalidSessionIdHelper(
      final String button,
      final String name,
      final String failMsg,
      final boolean fakeAppendedSessionId)
      throws IOException, JaxenException {
    HtmlPage editPage = clickEditLink(getWikiPage(name));
    final HtmlForm form = editPage.getFormByName(ID_EDIT_FORM);
    final HtmlInput sessionId = form.getInputByName("sessionId");
    sessionId.setValueAttribute(FAKE_SESSION_ID);
    if (fakeAppendedSessionId) {
      form.setActionAttribute(name + ";jsessionid=" + FAKE_SESSION_ID);
    }
    final HtmlTextArea content = form.getTextAreaByName("content");
    final String expectedContent = "http://www.example.com";
    content.setText(expectedContent);

    editPage = (HtmlPage) form.getInputByValue(button).click();

    try {
      getAnchorByHrefContains(editPage, expectedContent);
      fail(failMsg);
    } catch (NoSuchElementException e) {
    }
  }
コード例 #7
0
ファイル: TestEditing.java プロジェクト: paulcadman/reviki
  public void testPreviewDiffBug() throws Exception {
    // https://bugs.corefiling.com/show_bug.cgi?id=13510
    // Old versions of the diff_match_patch package have a bug in the diff_cleanupSemantic method
    // The two comparison strings need to be well crafted to trigger the bug.
    String name = uniqueWikiPageName("PreviewPageTest");
    String content =
        "="
            + NEWLINE_TEXTAREA
            + "This is a lis of things that someone be doing if"
            + NEWLINE_TEXTAREA
            + "===Wiki"
            + NEWLINE_TEXTAREA;
    String newContent = "||" + NEWLINE_TEXTAREA + "==";

    HtmlPage edited = editWikiPage(name, content, "", "", true);
    HtmlPage editPage = clickEditLink(edited);
    HtmlForm form = editPage.getFormByName(ID_EDIT_FORM);
    HtmlTextArea contentArea = form.getTextAreaByName("content");
    contentArea.setText(newContent);
    editPage = (HtmlPage) form.getInputByValue("Preview").click();

    form = editPage.getFormByName(ID_EDIT_FORM);
    contentArea = form.getTextAreaByName("content");
    assertEquals(newContent + NEWLINE_TEXTAREA, contentArea.getText());
  }
コード例 #8
0
 /** @throws Exception if the test fails */
 @Test(expected = FailingHttpStatusCodeException.class)
 public void failureByClickLink() throws Exception {
   final String html = "<html><body><a href='doesntExist'>go</a></body></html>";
   getMockWebConnection().setDefaultResponse("", 404, "Not found", "text/html");
   final HtmlPage page = loadPageWithAlerts(html);
   page.getAnchors().get(0).click();
 }
コード例 #9
0
 @Issue("JENKINS-18641")
 @Test
 public void display() throws Exception {
   User.get("bob");
   JenkinsRule.WebClient wc = j.createWebClient();
   HtmlPage page;
   try {
     page = wc.goTo("asynchPeople");
   } catch (FailingHttpStatusCodeException x) {
     System.err.println(x.getResponse().getResponseHeaders());
     System.err.println(x.getResponse().getContentAsString());
     throw x;
   }
   assertEquals(0, wc.waitForBackgroundJavaScript(120000));
   boolean found = false;
   for (DomElement table : page.getElementsByTagName("table")) {
     if (table.getAttribute("class").contains("progress-bar")) {
       found = true;
       assertEquals("display: none;", table.getAttribute("style"));
       break;
     }
   }
   assertTrue(found);
   /* TODO this still fails occasionally, for reasons TBD (I think because User.getAll sometimes is empty):
   assertNotNull(page.getElementById("person-bob"));
   */
 }
コード例 #10
0
ファイル: Event3Test.java プロジェクト: xinl/HTMLUnit
  /**
   * Tests that event fires on key press.
   *
   * @throws Exception if the test fails
   */
  @Test
  public void testEventOnKeyDown() throws Exception {
    final String html =
        "<html><head></head><body>\n"
            + "<button type='button' id='clickId'>Click Me</button>\n"
            + "<script>\n"
            + "function handler(_e) {\n"
            + "  var e = _e ? _e : window.event;\n"
            + "  if (e.keyCode == 65)\n"
            + "    alert('pass');\n"
            + "  else\n"
            + "    alert('fail:' + e.keyCode);\n"
            + "}\n"
            + "document.getElementById('clickId').onkeydown = handler;\n"
            + "document.getElementById('clickId').onclick = handler;</script>\n"
            + "</body></html>";

    final List<String> collectedAlerts = new ArrayList<String>();
    final HtmlPage page = loadPage(getBrowserVersion(), html, collectedAlerts);
    final HtmlElement element = page.getHtmlElementById("clickId");
    element.type('A');
    element.type('B');
    element.click();
    final String[] expectedAlerts = {"pass", "fail:66", "fail:undefined"};
    assertEquals(expectedAlerts, collectedAlerts);
  }
  @Test(groups = {"notLoggedIn"})
  public void testUserFilterWithAjaxDeny() throws Exception {
    clickOnBasePage("tynamoLoginLink");
    loginAction();
    clickOnBasePage("contributed");
    // now go log out in a different "window"
    HtmlPage indexPage = webClient.getPage(BASEURI);
    indexPage.getHtmlElementById("tynamoLogoutLink").click();

    // Clicking on this link should make an ajax request, but HTMLUnit doesn't like it and sends a
    // non-ajax request
    HtmlElement ajaxLink = (HtmlElement) page.getElementById("ajaxLink");
    URL ajaxUrl = new URL(APP_HOST_PORT + ajaxLink.getAttribute("href"));
    WebRequest ajaxRequest = new WebRequest(ajaxUrl);
    ajaxRequest.setAdditionalHeader("X-Requested-With", "XMLHttpRequest");

    Page jsonLoginResponse = webClient.getPage(ajaxRequest);
    String ajaxLoginResp = jsonLoginResponse.getWebResponse().getContentAsString();
    JSONObject jsonResp = new JSONObject(ajaxLoginResp);
    String ajaxRedirectUrl = jsonResp.getJSONObject("_tapestry").getString("redirectURL");
    assertTrue(
        ajaxRedirectUrl.startsWith(APP_CONTEXT + "security/login"),
        "The ajax redirect response '"
            + ajaxRedirectUrl
            + "' did not start with '"
            + APP_CONTEXT
            + "security/login'");
    page = webClient.getPage(APP_HOST_PORT + ajaxRedirectUrl);
    assertLoginPage();
  }
コード例 #12
0
ファイル: Event3Test.java プロジェクト: xinl/HTMLUnit
  /** @throws Exception if an error occurs */
  @Test
  public void preventDefault() throws Exception {
    final String html =
        "<html><head><title>First</title>\n"
            + "<script>\n"
            + "function block(e) {\n"
            + "  if (e && e.preventDefault)\n"
            + "    e.preventDefault();\n"
            + "  else\n"
            + "    return false;\n"
            + "}\n"
            + "\n"
            + "function test() {\n"
            + "  document.getElementById('myForm').onsubmit = block;\n"
            + "}\n"
            + "</script>\n"
            + "</head><body onload='test()'>\n"
            + "<form id='myForm' action='doesnt_exist.html'>\n"
            + "  <input type='submit' id='mySubmit' value='Continue'></p>\n"
            + "</form>"
            + "</body></html>";

    final HtmlPage page = loadPageWithAlerts(html);
    final HtmlPage page2 = page.getHtmlElementById("mySubmit").click();
    assertEquals(getDefaultUrl(), page2.getWebResponse().getWebRequest().getUrl());
  }
コード例 #13
0
ファイル: Event3Test.java プロジェクト: xinl/HTMLUnit
  /** @throws Exception if an error occurs */
  @Test
  @Browsers(Browser.FF)
  @Alerts({"capturing", "at target", "bubbling"})
  public void testEventPhase() throws Exception {
    final String html =
        "<html><head><script>\n"
            + "  function init() {\n"
            + "    var form = document.forms[0];\n"
            + "    form.addEventListener('click', alertPhase, true);\n"
            + "    form.addEventListener('click', alertPhase, false);\n"
            + "  }\n"
            + "  function alertPhase(e) {\n"
            + "    switch (e.eventPhase) {\n"
            + "      case 1: alert('capturing'); break;\n"
            + "      case 2: alert('at target'); break;\n"
            + "      case 3: alert('bubbling'); break;\n"
            + "      default: alert('unknown');\n"
            + "    }\n"
            + "  }\n"
            + "</script></head>\n"
            + "<body onload='init()'>\n"
            + "<form><input type='button' onclick='alertPhase(event)' id='b'></form>\n"
            + "</body></html>";

    final List<String> actual = new ArrayList<String>();
    final HtmlPage page = loadPage(getBrowserVersion(), html, actual);
    final HtmlButtonInput button = page.getHtmlElementById("b");
    button.click();
    assertEquals(getExpectedAlerts(), actual);
  }
コード例 #14
0
ファイル: Event3Test.java プロジェクト: xinl/HTMLUnit
  private void testFF_StopPropagation(final String cancelMethod) throws Exception {
    final String content =
        "<html><head><title>foo</title>\n"
            + "<script>\n"
            + "var counter = 0;\n"
            + "function t(_s) {\n"
            + "  return function(e) { alert(_s); counter++; if (counter >= 4) e."
            + cancelMethod
            + "; };\n"
            + "}\n"
            + "function init() {\n"
            + "  window.addEventListener('click', t('window capturing'), true);\n"
            + "  var oDiv = document.getElementById('theDiv');\n"
            + "  oDiv.addEventListener('click', t('div capturing'), true);\n"
            + "  var oSpan = document.getElementById('theSpan');\n"
            + "  oSpan.addEventListener('click', t('span capturing'), true);\n"
            + "}\n"
            + "</script>\n"
            + "</head><body onload='init()'>\n"
            + "<div onclick=\"alert('div')\" id='theDiv'>\n"
            + "<span id='theSpan'>blabla</span>\n"
            + "</div>\n"
            + "</body></html>";

    final List<String> collectedAlerts = new ArrayList<String>();
    final HtmlPage page = loadPage(getBrowserVersion(), content, collectedAlerts);
    page.getHtmlElementById("theSpan").click();
    final String[] expectedAlerts1 = {"window capturing", "div capturing", "span capturing", "div"};
    assertEquals(expectedAlerts1, collectedAlerts);
    collectedAlerts.clear();

    page.getHtmlElementById("theSpan").click();
    final String[] expectedAlerts2 = {"window capturing"};
    assertEquals(expectedAlerts2, collectedAlerts);
  }
コード例 #15
0
 /**
  * @param ticker The ticker of the stock to look up.
  * @throws ConnectionException if it has problems connecting to Yahoo.
  * @return The value of the given stock, as %CompanyName: %Value.
  */
 public String getStockValue(String ticker) throws ConnectionException {
   try {
     final HtmlPage lookup =
         client.getPage(
             new StringBuilder("http://www.google.com/finance?q=").append(ticker).toString());
     final DomElement pricediv =
         lookup.getFirstByXPath("//div[@id = 'price-panel']/div/span/span");
     final DomElement compname =
         lookup.getFirstByXPath("//div[@class = 'appbar-snippet-primary']/span");
     return new StringBuilder(compname.getTextContent())
         .append(": ")
         .append(pricediv.getTextContent())
         .toString();
   } catch (IOException | FailingHttpStatusCodeException e) {
     System.out.println(
         new StringBuilder("Exception in retrieval.")
             .append("InternetConnection.getStockValue(")
             .append(ticker)
             .append(")")
             .toString());
     System.out.println(e.toString());
   }
   throw new ConnectionException(
       new StringBuilder("Unable to find data for ").append(ticker).toString());
 }
コード例 #16
0
ファイル: TestDriverFra.java プロジェクト: faddison/JTorn
 public static HtmlPage trainStrength(HtmlPage page, int amount) throws IOException {
   System.out.println("Training " + amount + " strength...");
   for (DomNode n : page.getElementById("divStrength").getDescendants()) {
     // System.out.println(n.toString());
     HtmlTextInput textInput;
     HtmlSubmitInput submitInput;
     if (n.toString()
         .contains("HtmlTextInput[<input type=\"text\" value=\"1\" id=\"t\" name=\"t\">]")) {
       textInput = (HtmlTextInput) n;
       textInput.setValueAttribute(Integer.toString(amount));
       System.out.println(textInput.toString());
     } else if (n.toString()
         .contains("HtmlSubmitInput[<input type=\"submit\" value=\"Train\">]")) {
       submitInput = (HtmlSubmitInput) n;
       page = submitInput.click();
       System.out.println(submitInput.toString());
     }
   }
   /*
   System.out.println(this.user.getUsername()+"-"+"Training "+amount+" strength...");
   HtmlTextInput amountInput = (HtmlTextInput) page.getByXPath("/html/body/div[4]/table/tbody/tr/td[2]/center/div[2]/div/div[2]/div[3]/div[1]/div[1]/div[2]/form/table/tbody/tr/td[1]/input[1]").get(0);
   amountInput.setValueAttribute(Integer.toString(amount));
   HtmlElement e = (HtmlElement) page.getByXPath("/html/body/div[4]/table/tbody/tr/td[2]/center/div[2]/div/div[2]/div[3]/div[1]/div[1]/div[2]/form/table/tbody/tr/td[3]/input").get(0);
   e.click();
   */
   System.out.println(page.asText());
   return page;
 }
コード例 #17
0
ファイル: TestEditing.java プロジェクト: paulcadman/reviki
  public void testPreview() throws Exception {
    String name = uniqueWikiPageName("PreviewPageTest");
    HtmlPage editPage = clickEditLink(getWikiPage(name));
    HtmlForm form = editPage.getFormByName(ID_EDIT_FORM);
    HtmlInput minorEdit = form.getInputByName("minorEdit");
    assertFalse(minorEdit.isChecked());
    minorEdit.setChecked(true);
    HtmlInput description = form.getInputByName("description");
    String expectedDescription = "My test change";
    description.setValueAttribute(expectedDescription);
    HtmlTextArea content = form.getTextAreaByName("content");
    String expectedContent = "http://www.example.com";
    content.setText(expectedContent);

    // Now if we preview we should get the previewed text rendered, and in
    // the edit area.  The other options should be preserved too.
    editPage = (HtmlPage) form.getInputByValue("Preview").click();
    form = editPage.getFormByName(ID_EDIT_FORM);
    minorEdit = form.getInputByName("minorEdit");
    description = form.getInputByName("description");
    content = form.getTextAreaByName("content");
    assertEquals(expectedDescription, description.getValueAttribute());
    assertTrue(minorEdit.isChecked());
    assertEquals(expectedContent + NEWLINE_TEXTAREA, content.getText());
    // This checks for the rendering...
    assertNotNull(editPage.getAnchorByHref(expectedContent));
  }
コード例 #18
0
 /**
  * Loads an XML document from the specified location.
  *
  * @param xmlSource a string containing a URL that specifies the location of the XML file
  * @return true if the load succeeded; false if the load failed
  */
 @JsxFunction
 public boolean load(final String xmlSource) {
   if (async_) {
     if (LOG.isDebugEnabled()) {
       LOG.debug("XMLDocument.load(): 'async' is true, currently treated as false.");
     }
   }
   try {
     final HtmlPage htmlPage = (HtmlPage) getWindow().getWebWindow().getEnclosedPage();
     final WebRequest request = new WebRequest(htmlPage.getFullyQualifiedUrl(xmlSource));
     final WebResponse webResponse =
         getWindow().getWebWindow().getWebClient().loadWebResponse(request);
     final XmlPage page = new XmlPage(webResponse, getWindow().getWebWindow(), false);
     setDomNode(page);
     return true;
   } catch (final IOException e) {
     final XMLDOMParseError parseError = getParseError();
     parseError.setErrorCode(-1);
     parseError.setFilepos(1);
     parseError.setLine(1);
     parseError.setLinepos(1);
     parseError.setReason(e.getMessage());
     parseError.setSrcText("xml");
     parseError.setUrl(xmlSource);
     if (LOG.isDebugEnabled()) {
       LOG.debug("Error parsing XML from '" + xmlSource + "'", e);
     }
     return false;
   }
 }
コード例 #19
0
ファイル: TestEditing.java プロジェクト: paulcadman/reviki
 public void testEditAttributesNewPage() throws Exception {
   String name = uniqueWikiPageName("EditPageTest");
   HtmlPage edited =
       editWikiPage(name, "Initial Status: <<attr:status>>", "status = completed", "", true);
   String editedPageText = edited.asText();
   assertTrue(editedPageText.contains("Initial Status: completed"));
 }
コード例 #20
0
  // Check the actual facet page with true/true/true flags
  private void checkJstlIf02a() throws Exception {

    HtmlPage page = getPage("/faces/jsp/jstl-if-02.jsp?component=true&header=true&footer=true");
    assertEquals("Correct page title", "jstl-if-02", page.getTitleText());
    assertEquals(
        "Correct body element", "[First] [Header] [Second] [Footer] [Third]", getBodyText(page));
  }
コード例 #21
0
  Result proceed() {

    HtmlPage resultPage = null;
    try {
      resultPage = proceedImpl();
    } catch (IOException e) {
      return Result.FAILURE_COULD_NOT_LOAD_PAGE;
    }

    if (resultPage == null) {
      return Result.FAILURE_UNEXPECTED_LAYOUT;
    }

    this.followUpPage = resultPage;

    WebResponse response = resultPage.getWebResponse();

    if (response == null) {
      return Result.FAILURE_COULD_NOT_LOAD_PAGE;
    }

    if (responseValidator.isExceptedResponse(response)) {

      this.result = produceResult(resultPage);

      return Result.SUCCESS;
    }

    return Result.FAILURE_WRONG_RESPONSE;
  }
コード例 #22
0
  // Check the actual conditional page with a "true" flag
  private void checkJstlIf04a() throws Exception {

    HtmlPage page = getPage("/faces/jsp/jstl-if-04.jsp?cond=true");
    assertEquals("Correct page title", "jstl-if-04", page.getTitleText());
    assertEquals(
        "Correct body element", "[1] [2] [3] { [4a] [4b] [4c] } [5] [6] [7]", getBodyText(page));
  }
コード例 #23
0
  @Test
  public void testSetValueListLayout() throws Exception {
    HtmlPage page = environment.getPage("/autocompleteListLayoutTest.jsf");
    HtmlElement autocompleteList = page.getElementById("form:myAutocompleteList");
    Assert.assertNotNull(autocompleteList);

    List<?> countryList = autocompleteList.getByXPath("div/div/div/ul/li");
    Assert.assertEquals(30, countryList.size());

    HtmlInput input = (HtmlInput) page.getElementById("form:myAutocompleteInput");
    Assert.assertNotNull(input);
    input.type("be");

    for (int i = 0; i < 20; i++) {
      synchronized (page) {
        autocompleteList = page.getElementById("form:myAutocompleteList");
        Assert.assertNotNull(autocompleteList);

        countryList = autocompleteList.getByXPath("div/div/div/ul/li");

        if (countryList.size() == 5) {
          break;
        } else {
          page.wait(500);
        }
      }
    }

    Assert.assertEquals(5, countryList.size());
  }
コード例 #24
0
  public void discoverInputs(WebClient client, String url) {

    HashMap<String, List<HtmlElement>> urlToInput = new HashMap<String, List<HtmlElement>>();
    List<HtmlElement> inputs = new ArrayList<HtmlElement>();

    try {

      HtmlPage page = client.getPage(url);
      List<HtmlElement> elements = page.getTabbableElements();

      for (HtmlElement element : elements) {
        if (element instanceof HtmlInput || element instanceof HtmlTextArea) {
          inputs.add(element);
        }
      }

      urlToInput.put(url, inputs);

      System.out.println("----------------------------------------------------------------");
      System.out.println("Inputs Discovered:");
      for (Map.Entry<String, List<HtmlElement>> input : urlToInput.entrySet()) {
        System.out.println("URL: " + input.getKey());
        for (HtmlElement element : input.getValue()) {
          System.out.println(" -> Input: " + element.toString());
        }
      }

    } catch (Exception excep) {

      System.out.println("Exception found.");
      excep.printStackTrace();
    }
  }
コード例 #25
0
  public void testValidators() throws Exception {
    try {
      getPage(
          "/faces/setApplicationMapProperty.xhtml?name=javax.faces.VALIDATE_EMPTY_FIELDS&value=true");

      HtmlPage page = getPage("/faces/composite/validator.xhtml");
      HtmlSubmitInput submit = (HtmlSubmitInput) getInputContainingGivenId(page, "form:submit");
      assertNotNull(submit);
      page = submit.click();

      final String[] inputIds = {
        "form:c0:input",
        "form:c1:nesting:aw1:input",
        "form:c2:nesting:aw2:input",
        "form:c3:nesting:aw3:nesting:aw1:input",
        "form:c4:nesting:aw4:nesting:aw1:input"
      };

      String pageText = page.asText();
      for (String inputId : inputIds) {
        String message = "validator invoked: " + inputId;
        assertTrue(pageText.contains(message));
      }
    } finally {
      getPage("/faces/clearApplicationMapProperty.xhtml?name=javax.faces.VALIDATE_EMPTY_FIELDS");
    }
  }
コード例 #26
0
 /** Verify that the required validator works for SelectOne */
 public void testSelectOneNoValue() throws Exception {
   HtmlPage page = getPage("/faces/jsp/selectOneNoValue.jsp");
   List list = getAllElementsOfGivenClass(page, null, HtmlSubmitInput.class);
   HtmlSubmitInput button = (HtmlSubmitInput) list.get(0);
   page = (HtmlPage) button.click();
   assertTrue(-1 != page.asText().indexOf("equired"));
 }
コード例 #27
0
 @Test
 public void testDecoratedFactories() throws Exception {
   HtmlPage page = webClient.getPage(webUrl);
   String pageXml = page.asXml();
   assertTrue(pageXml.contains("MyFacesContextFactory$MyFacesContext"));
   assertTrue(pageXml.contains("MyExceptionHandlerFactory$MyExceptionHandler"));
 }
コード例 #28
0
  public void testImageInsideCollection() throws Exception {
    execute("CRUD.new");
    execute("Collection.new", "viewObject=xava_view_section0_ingredients");
    execute("ImageEditor.changeImage", "newImageProperty=image");
    assertNoErrors();
    assertAction("LoadImage.loadImage");
    String imageUrl = System.getProperty("user.dir") + "/test-images/cake.gif";
    setFileValue("newImage", imageUrl);
    execute("LoadImage.loadImage");
    assertNoErrors();

    HtmlPage page = (HtmlPage) getWebClient().getCurrentWindow().getEnclosedPage();
    URL url = page.getWebResponse().getRequestSettings().getUrl();

    String urlPrefix = url.getProtocol() + "://" + url.getHost() + ":" + url.getPort();

    HtmlImage image = (HtmlImage) page.getElementsByName(decorateId("image")).get(0);
    String imageURL = null;
    if (image.getSrcAttribute().startsWith("/")) {
      imageURL = urlPrefix + image.getSrcAttribute();
    } else {
      String urlBase = Strings.noLastToken(url.getPath(), "/");
      imageURL = urlPrefix + urlBase + image.getSrcAttribute();
    }
    WebResponse response = getWebClient().getPage(imageURL).getWebResponse();
    assertTrue("Image not obtained", response.getContentAsString().length() > 0);
    assertEquals("Result is not an image", "image", response.getContentType());
  }
コード例 #29
0
ファイル: QueueTest.java プロジェクト: stevenzyk/hudson
  public void testFileItemPersistence() throws Exception {
    // TODO: write a synchronous connector?
    byte[] testData = new byte[1024];
    for (int i = 0; i < testData.length; i++) testData[i] = (byte) i;

    Server server = new Server();
    SocketConnector connector = new SocketConnector();
    server.addConnector(connector);

    ServletHandler handler = new ServletHandler();
    handler.addServletWithMapping(new ServletHolder(new FileItemPersistenceTestServlet()), "/");
    server.addHandler(handler);

    server.start();

    localPort = connector.getLocalPort();

    try {
      WebClient wc = new WebClient();
      HtmlPage p = (HtmlPage) wc.getPage("http://localhost:" + localPort + '/');
      HtmlForm f = p.getFormByName("main");
      HtmlFileInput input = (HtmlFileInput) f.getInputByName("test");
      input.setData(testData);
      f.submit();
    } finally {
      server.stop();
    }
  }
コード例 #30
0
ファイル: Event3Test.java プロジェクト: xinl/HTMLUnit
  private void testEventOnClick_Shift_Ctrl_Alt(
      final boolean shiftKey,
      final boolean ctrlKey,
      final boolean altKey,
      final String[] expectedAlerts)
      throws Exception {
    final String htmlContent =
        "<html><head><title>foo</title></head><body>\n"
            + "<form id='form1'>\n"
            + "    <button name='button' type='button' id='button'>Push me</button>\n"
            + "</form>\n"
            + "<script>\n"
            + "function handler(_e) {\n"
            + "  var e = _e ? _e : window.event;\n"
            + "  alert(e.shiftKey + ',' + e.ctrlKey + ',' + e.altKey);\n"
            + "}\n"
            + "document.getElementById('button').onclick = handler;\n"
            + "</script>\n"
            + "</body></html>";
    final List<String> collectedAlerts = new ArrayList<String>();
    final HtmlPage page = loadPage(getBrowserVersion(), htmlContent, collectedAlerts);
    final HtmlButton button = page.getHtmlElementById("button");

    final HtmlPage secondPage = button.click(shiftKey, ctrlKey, altKey);

    assertEquals(expectedAlerts, collectedAlerts);

    assertSame(page, secondPage);
  }