org.openqa.selenium.By.ById#com.gargoylesoftware.htmlunit.util.NameValuePair源码实例Demo

下面列出了org.openqa.selenium.By.ById#com.gargoylesoftware.htmlunit.util.NameValuePair 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: HtmlUnit-Android   文件: HttpWebConnection.java
private static Charset getCharset(final Charset charset, final List<NameValuePair> pairs) {
    for (final NameValuePair pair : pairs) {
        if (pair instanceof KeyDataPair) {
            final KeyDataPair pairWithFile = (KeyDataPair) pair;
            if (pairWithFile.getData() == null && pairWithFile.getFile() != null) {
                final String fileName = pairWithFile.getFile().getName();
                for (int i = 0; i < fileName.length(); i++) {
                    if (fileName.codePointAt(i) > 127) {
                        return charset;
                    }
                }
            }
        }
    }
    return null;
}
 
源代码2 项目: htmlunit   文件: HtmlForm2Test.java
private void submitParams(final String controls) throws Exception {
    final String html = "<html><head><title>foo</title></head><body>\n"
        + "<form id='form1' method='post'>\n"
        + controls
        + "</form></body></html>";

    final WebDriver driver = loadPage2(html);
    driver.findElement(new ById("mySubmit")).click();

    final List<NameValuePair> requestedParams = getMockWebConnection().getLastWebRequest().getRequestParameters();
    Collections.sort(requestedParams, Comparator.comparing(NameValuePair::getName));

    assertEquals(getExpectedAlerts().length, requestedParams.size());

    for (int i = 0; i < requestedParams.size(); i++) {
        assertEquals(getExpectedAlerts()[i],
                requestedParams.get(i).getName() + '#' + requestedParams.get(i).getValue());
    }
}
 
源代码3 项目: htmlunit   文件: HtmlImage2Test.java
private void isDisplayed(final String src) throws Exception {
    try (InputStream is = getClass().getClassLoader().getResourceAsStream("testfiles/tiny-jpg.img")) {
        final byte[] directBytes = IOUtils.toByteArray(is);
        final URL urlImage = new URL(URL_FIRST, "img.jpg");
        final List<NameValuePair> emptyList = Collections.emptyList();
        getMockWebConnection().setResponse(urlImage, directBytes, 200, "ok", "image/jpg", emptyList);

        getMockWebConnection().setDefaultResponse("Error: not found", 404, "Not Found", MimeType.TEXT_HTML);
    }

    final String html = "<html><head><title>Page A</title></head>\n"
            + "<body>\n"
            + "  <img id='myImg' " + src + " >\n"
            + "</body></html>";

    final WebDriver driver = loadPage2(html);

    final boolean displayed = driver.findElement(By.id("myImg")).isDisplayed();
    assertEquals(Boolean.parseBoolean(getExpectedAlerts()[0]), displayed);
}
 
源代码4 项目: htmlunit   文件: CookieManagerTest.java
/**
 * A cookie set with document.cookie without path applies only for the current path
 * and overrides cookie previously set for this path.
 * @throws Exception if the test fails
 */
@Test
@Alerts("first=new")
public void cookieSetFromJSWithoutPathUsesCurrentLocation() throws Exception {
    final List<NameValuePair> responseHeader1 = new ArrayList<>();
    responseHeader1.add(new NameValuePair("Set-Cookie", "first=1"));

    final String html = "<html>\n"
        + "<head></head>\n"
        + "<body><script>\n"
        + "  document.cookie = 'first=new';\n"
        + "  location.replace('/a/b/-');\n"
        + "</script></body>\n"
        + "</html>";

    getMockWebConnection().setDefaultResponse(HTML_ALERT_COOKIE);
    final URL firstUrl = new URL(URL_FIRST, "/a/b");
    getMockWebConnection().setResponse(firstUrl, html, 200, "Ok", MimeType.TEXT_HTML, responseHeader1);

    loadPageWithAlerts2(firstUrl);
}
 
源代码5 项目: htmlunit   文件: FormData.java
/**
 * @param name the name of the field to check
 * @return the first value found for the give name
 */
@JsxFunction({CHROME, FF, FF68, FF60})
public String get(final String name) {
    if (StringUtils.isEmpty(name)) {
        return null;
    }

    final Iterator<NameValuePair> iter = requestParameters_.iterator();
    while (iter.hasNext()) {
        final NameValuePair pair = iter.next();
        if (name.equals(pair.getName())) {
            return pair.getValue();
        }
    }
    return null;
}
 
源代码6 项目: htmlunit   文件: FormData.java
/**
 * @param name the name of the field to check
 * @return the first value found for the give name
 */
@JsxFunction({CHROME, FF, FF68, FF60})
public Scriptable getAll(final String name) {
    if (StringUtils.isEmpty(name)) {
        return Context.getCurrentContext().newArray(this, 0);
    }

    final List<Object> values = new ArrayList<>();
    final Iterator<NameValuePair> iter = requestParameters_.iterator();
    while (iter.hasNext()) {
        final NameValuePair pair = iter.next();
        if (name.equals(pair.getName())) {
            values.add(pair.getValue());
        }
    }

    final Object[] stringValues = values.toArray(new Object[values.size()]);
    return Context.getCurrentContext().newArray(this, stringValues);
}
 
源代码7 项目: htmlunit   文件: FormData.java
/**
 * @param name the name of the field to check
 * @return true if the name exists
 */
@JsxFunction({CHROME, FF, FF68, FF60})
public boolean has(final String name) {
    if (StringUtils.isEmpty(name)) {
        return false;
    }

    final Iterator<NameValuePair> iter = requestParameters_.iterator();
    while (iter.hasNext()) {
        final NameValuePair pair = iter.next();
        if (name.equals(pair.getName())) {
            return true;
        }
    }
    return false;
}
 
源代码8 项目: htmlunit   文件: HtmlPageTest.java
/**
 * Test auto-refresh from a response header.
 * @throws Exception if the test fails
 */
@Test
public void refresh_HttpResponseHeader() throws Exception {
    final String firstContent = "<html><head><title>first</title>\n"
        + "</head><body></body></html>";
    final String secondContent = "<html><head><title>second</title></head><body></body></html>";

    final WebClient client = getWebClient();

    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setResponse(URL_FIRST, firstContent, 200, "OK", MimeType.TEXT_HTML, Collections
            .singletonList(new NameValuePair("Refresh", "2;URL=" + URL_SECOND)));
    webConnection.setResponse(URL_SECOND, secondContent);
    client.setWebConnection(webConnection);

    final HtmlPage page = client.getPage(URL_FIRST);

    assertEquals("second", page.getTitleText());
}
 
源代码9 项目: htmlunit   文件: WebClient3Test.java
/**
 * @throws Exception if an error occurs
 */
@Test
@Alerts({"Executed", "later"})
// TODO [IE]ERRORPAGE real IE displays own error page if response is to small
public void execJavascriptOnErrorPages() throws Exception {
    final String errorHtml = "<html>\n"
            + "<head>\n"
            + "</head>\n"
            + "<body>\n"
            + "<script type='text/javascript'>\n"
            + "  alert('Executed');\n"
            + "  setTimeout(\"alert('later')\", 10);\n"
            + "</script>\n"
            + "</body></html>\n";

    final MockWebConnection conn = getMockWebConnection();
    conn.setResponse(URL_FIRST, errorHtml, 404, "Not Found", MimeType.TEXT_HTML, new ArrayList<NameValuePair>());

    loadPageWithAlerts2(URL_FIRST, 42);
}
 
源代码10 项目: HtmlUnit-Android   文件: XMLHttpRequest.java
/**
 * Returns the labels and values of all the HTTP headers.
 * @return the labels and values of all the HTTP headers
 */
@JsxFunction
public String getAllResponseHeaders() {
    if (state_ == UNSENT || state_ == OPENED) {
        return "";
    }
    if (webResponse_ != null) {
        final StringBuilder builder = new StringBuilder();
        for (final NameValuePair header : webResponse_.getResponseHeaders()) {
            builder.append(header.getName()).append(": ").append(header.getValue()).append("\r\n");
        }
        if (getBrowserVersion().hasFeature(XHR_ALL_RESPONSE_HEADERS_APPEND_CRLF)) {
            builder.append("\r\n");
        }
        return builder.toString();
    }

    LOG.error("XMLHttpRequest.getAllResponseHeaders() was called without a response available (readyState: "
        + state_ + ").");
    return null;
}
 
源代码11 项目: htmlunit   文件: WebClient6Test.java
/**
 * Regression test for bug 3035155.
 * Bug was fixes in HttpClient 4.1.
 * @throws Exception if an error occurs
 */
@Test
public void redirect302UrlsInQuery() throws Exception {
    final String html = "<html><body><a href='redirect.html'>redirect</a></body></html>";

    final URL url = new URL(URL_FIRST, "page2.html");
    getMockWebConnection().setResponse(url, html);

    final List<NameValuePair> headers = new ArrayList<>();
    headers.add(new NameValuePair("Location", "/page2.html?param=http%3A//somwhere.org"));
    getMockWebConnection().setDefaultResponse("", 302, "Found", null, headers);

    final WebDriver driver = loadPage2(html);
    driver.findElement(By.tagName("a")).click();
    assertEquals(url + "?param=http%3A//somwhere.org", driver.getCurrentUrl());
}
 
源代码12 项目: htmlunit   文件: HtmlFileInput.java
/**
 * {@inheritDoc}
 */
@Override
public NameValuePair[] getSubmitNameValuePairs() {
    if (files_ == null || files_.length == 0) {
        return new NameValuePair[] {new KeyDataPair(getNameAttribute(), null, null, null, (Charset) null)};
    }

    final List<NameValuePair> list = new ArrayList<>();
    for (File file : files_) {
        String contentType;
        if (contentType_ == null) {
            contentType = getPage().getWebClient().getBrowserVersion().getUploadMimeType(file);
            if (StringUtils.isEmpty(contentType)) {
                contentType = MimeType.APPLICATION_OCTET_STREAM;
            }
        }
        else {
            contentType = contentType_;
        }
        final Charset charset = getPage().getCharset();
        final KeyDataPair keyDataPair = new KeyDataPair(getNameAttribute(), file, null, contentType, charset);
        keyDataPair.setData(data_);
        list.add(keyDataPair);
    }
    return list.toArray(new NameValuePair[list.size()]);
}
 
源代码13 项目: htmlunit   文件: CookieManagerTest.java
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("first=1")
public void cookie2() throws Exception {
    final List<NameValuePair> responseHeader1 = new ArrayList<>();
    responseHeader1.add(new NameValuePair("Set-Cookie", "first=1"));
    getMockWebConnection().setResponse(URL_FIRST, HTML_ALERT_COOKIE, 200, "OK", MimeType.TEXT_HTML,
            responseHeader1);

    loadPageWithAlerts2(URL_FIRST);

    final List<NameValuePair> responseHeader2 = new ArrayList<>();
    responseHeader2.add(new NameValuePair("Set-Cookie", "second=2"));
    getMockWebConnection().setResponse(URL_FIRST, HTML_ALERT_COOKIE, 200, "OK", MimeType.TEXT_HTML,
            responseHeader2);

    setExpectedAlerts("first=1; second=2");
    loadPageWithAlerts2(URL_FIRST);
}
 
源代码14 项目: htmlunit   文件: HtmlSubmitInputTest.java
/**
 * @throws Exception if the test fails
 */
@Test
public void submit() throws Exception {
    final String html
        = "<html><head><title>foo</title></head><body>\n"
        + "<form id='form1' method='post'>\n"
        + "<input type='submit' name='aButton' value='foo'/>\n"
        + "<input type='suBMit' name='button' value='foo'/>\n"
        + "<input type='submit' name='anotherButton' value='foo'/>\n"
        + "</form></body></html>";

    final WebDriver driver = loadPageWithAlerts2(html);

    final WebElement button = driver.findElement(By.name("button"));
    button.click();

    assertTitle(driver, "foo");

    assertEquals(Collections.singletonList(new NameValuePair("button", "foo")),
        getMockWebConnection().getLastParameters());
}
 
源代码15 项目: htmlunit   文件: WebClientTest.java
private void redirection_AdditionalHeadersMaintained(final int statusCode) throws Exception {
    final WebClient client = getWebClient();
    final MockWebConnection conn = new MockWebConnection();
    client.setWebConnection(conn);

    final List<NameValuePair> headers = asList(new NameValuePair("Location", URL_SECOND.toString()));
    conn.setResponse(URL_FIRST, "", statusCode, "", MimeType.TEXT_HTML, headers);
    conn.setResponse(URL_SECOND, "<html><body>abc</body></html>");

    final WebRequest request = new WebRequest(URL_FIRST);
    request.setAdditionalHeader("foo", "bar");
    client.getPage(request);

    assertEquals(URL_SECOND, conn.getLastWebRequest().getUrl());
    assertEquals("bar", conn.getLastAdditionalHeaders().get("foo"));
}
 
源代码16 项目: HtmlUnit-Android   文件: WebClient.java
private WebResponse makeWebResponseForDataUrl(final WebRequest webRequest) throws IOException {
    final URL url = webRequest.getUrl();
    final List<NameValuePair> responseHeaders = new ArrayList<>();
    final DataURLConnection connection;
    try {
        connection = new DataURLConnection(url);
    }
    catch (final DecoderException e) {
        throw new IOException(e.getMessage());
    }
    responseHeaders.add(new NameValuePair(HttpHeader.CONTENT_TYPE_LC,
        connection.getMediaType() + ";charset=" + connection.getCharset()));

    try (InputStream is = connection.getInputStream()) {
        final DownloadedContent downloadedContent =
                HttpWebConnection.downloadContent(is, getOptions().getMaxInMemory());
        final WebResponseData data = new WebResponseData(downloadedContent, 200, "OK", responseHeaders);
        return new WebResponse(data, url, webRequest.getHttpMethod(), 0);
    }
}
 
源代码17 项目: jenkins-test-harness   文件: JenkinsRule.java
private List<NameValuePair> extractHeaders(HttpURLConnection conn) {
    List<NameValuePair> headers = new ArrayList<NameValuePair>();
    Set<Map.Entry<String,List<String>>> headerFields = conn.getHeaderFields().entrySet();
    for (Map.Entry<String,List<String>> headerField : headerFields) {
        String name = headerField.getKey();
        if (name != null) { // Yes, the header name can be null.
            List<String> values = headerField.getValue();
            for (String value : values) {
                if (value != null) {
                    headers.add(new NameValuePair(name, value));
                }
            }
        }
    }
    return headers;
}
 
private void params(MockHttpServletRequest request, UriComponents uriComponents) {
	uriComponents.getQueryParams().forEach((name, values) -> {
		String urlDecodedName = urlDecode(name);
		values.forEach(value -> {
			value = (value != null ? urlDecode(value) : "");
			request.addParameter(urlDecodedName, value);
		});
	});
	for (NameValuePair param : this.webRequest.getRequestParameters()) {
		request.addParameter(param.getName(), param.getValue());
	}
}
 
源代码19 项目: htmlunit   文件: HTMLImageElementTest.java
/**
 * @throws Exception if an error occurs
 */
@Test
@Alerts({"done;onload;", "2"})
public void img_download_onloadAfter() throws Exception {
    try (InputStream is = getClass().getClassLoader().getResourceAsStream("testfiles/tiny-jpg.img")) {
        final byte[] directBytes = IOUtils.toByteArray(is);
        final URL urlImage = new URL(URL_FIRST, "img.jpg");
        final List<NameValuePair> emptyList = Collections.emptyList();
        getMockWebConnection().setResponse(urlImage, directBytes, 200, "ok", "image/jpg", emptyList);
    }

    final String html = "<html><body>\n"
        + "<script>\n"
        + "  var i = new Image();\n"
        + "  i.src = 'img.jpg';\n"
        + "  document.title += 'done;';\n"
        + "  i.onload = function() { document.title += 'onload;'; };\n"
        + "</script></body></html>";

    final int count = getMockWebConnection().getRequestCount();
    final WebDriver driver = getWebDriver();
    if (driver instanceof HtmlUnitDriver) {
        ((HtmlUnitDriver) driver).setDownloadImages(true);
    }
    loadPage2(html);

    assertTitle(driver, getExpectedAlerts()[0]);
    assertEquals(Integer.parseInt(getExpectedAlerts()[1]), getMockWebConnection().getRequestCount() - count);
    assertEquals(URL_FIRST + "img.jpg", getMockWebConnection().getLastWebRequest().getUrl());
}
 
源代码20 项目: htmlunit   文件: HTMLImageElementTest.java
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts(DEFAULT = {"true", "true", "true", "true"},
        IE = {"false", "false", "false", "true"})
public void complete() throws Exception {
    try (InputStream is = getClass().getClassLoader().getResourceAsStream("testfiles/tiny-jpg.img")) {
        final byte[] directBytes = IOUtils.toByteArray(is);

        final URL urlImage = new URL(URL_SECOND, "img.jpg");
        final List<NameValuePair> emptyList = Collections.emptyList();
        getMockWebConnection().setResponse(urlImage, directBytes, 200, "ok", "image/jpg", emptyList);
        getMockWebConnection().setDefaultResponse("Test");
    }

    final String html = "<html><head>\n"
        + "<script>\n"
        + "  function showInfo(imageId) {\n"
        + "    var img = document.getElementById(imageId);\n"
        + "    alert(img.complete);\n"
        + "  }\n"
        + "  function test() {\n"
        + "    showInfo('myImage1');\n"
        + "    showInfo('myImage2');\n"
        + "    showInfo('myImage3');\n"
        + "    showInfo('myImage4');\n"
        + "  }\n"
        + "</script>\n"
        + "</head><body onload='test()'>\n"
        + "  <img id='myImage1' >\n"
        + "  <img id='myImage2' src=''>\n"
        + "  <img id='myImage3' src='" + URL_SECOND + "'>\n"
        + "  <img id='myImage4' src='" + URL_SECOND + "img.jpg'>\n"
        + "</body></html>";
    final WebDriver driver = getWebDriver();
    if (driver instanceof HtmlUnitDriver) {
        ((HtmlUnitDriver) driver).setDownloadImages(true);
    }

    loadPageWithAlerts2(html);
}
 
源代码21 项目: htmlunit   文件: CookieManagerTest.java
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("key1=; key2=")
public void emptyCookie() throws Exception {
    final List<NameValuePair> responseHeader = new ArrayList<>();
    responseHeader.add(new NameValuePair("Set-Cookie", "key1="));
    responseHeader.add(new NameValuePair("Set-Cookie", "key2="));
    getMockWebConnection().setDefaultResponse(HTML_ALERT_COOKIE, 200, "OK", MimeType.TEXT_HTML, responseHeader);

    loadPageWithAlerts2(URL_FIRST);
}
 
public void defend(int gameId, String test) throws FailingHttpStatusCodeException, IOException {
	WebRequest defendRequest = new WebRequest(new URL("http://localhost:8080" + Paths.BATTLEGROUND_GAME),
			HttpMethod.POST);
	// curl -X POST \
	// --data "formType=createTest&gameId=${gameId}" \
	// --data-urlencode [email protected]${test} \
	// --cookie "${cookie}" --cookie-jar "${cookie}" \
	// -w @curl-format.txt \
	// -s ${CODE_DEFENDER_URL}/multiplayergame
	defendRequest.setRequestParameters(Arrays.asList(new NameValuePair[] {
			new NameValuePair("formType", "createTest"), new NameValuePair("gameId", "" + gameId),
			// TODO Encoded somehow ?
			new NameValuePair("test", "" + test) }));
	browser.getPage(defendRequest);
}
 
private void params(MockHttpServletRequest request, UriComponents uriComponents) {
	uriComponents.getQueryParams().forEach((name, values) -> {
		String urlDecodedName = urlDecode(name);
		values.forEach(value -> {
			value = (value != null ? urlDecode(value) : "");
			request.addParameter(urlDecodedName, value);
		});
	});
	for (NameValuePair param : this.webRequest.getRequestParameters()) {
		request.addParameter(param.getName(), param.getValue());
	}
}
 
源代码24 项目: htmlunit   文件: HTMLIFrameElement3Test.java
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts({"loaded", "[object HTMLDocument]"})
public void csp_SelfDifferentPath() throws Exception {
    retrictByHeader(
            new NameValuePair(HttpHeader.CONTENT_SECURIRY_POLICY, "frame-ancestors 'self';"),
            new URL(URL_FIRST, "/path2/content.html"));
}
 
@Test
public void buildRequestParameterMapViaWebRequestDotSetRequestParametersWithSingleRequestParam() {
	webRequest.setRequestParameters(asList(new NameValuePair("name", "value")));

	MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

	assertThat(actualRequest.getParameterMap().size(), equalTo(1));
	assertThat(actualRequest.getParameter("name"), equalTo("value"));
}
 
@Test
public void buildRequestParameterMapViaWebRequestDotSetRequestParametersWithSingleRequestParamWithNullValue() {
	webRequest.setRequestParameters(asList(new NameValuePair("name", null)));

	MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

	assertThat(actualRequest.getParameterMap().size(), equalTo(1));
	assertThat(actualRequest.getParameter("name"), nullValue());
}
 
@Test
public void buildRequestParameterMapViaWebRequestDotSetRequestParametersWithSingleRequestParamWithValueSetToSpace() {
	webRequest.setRequestParameters(asList(new NameValuePair("name", " ")));

	MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

	assertThat(actualRequest.getParameterMap().size(), equalTo(1));
	assertThat(actualRequest.getParameter("name"), equalTo(" "));
}
 
源代码28 项目: HtmlUnit-Android   文件: MockWebConnection.java
private static RawResponseData buildRawResponseData(final String content, Charset charset, final int statusCode,
        final String statusMessage, final String contentType, final List<NameValuePair> headers) {

    if (charset == null) {
        charset = ISO_8859_1;
    }
    return new RawResponseData(content, charset, statusCode, statusMessage, contentType, headers);
}
 
源代码29 项目: htmlunit   文件: HtmlImageInputTest.java
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("§§URL§§abcd/img.gif")
public void lineBreaksInUrl() throws Exception {
    try (InputStream is = getClass().getClassLoader().getResourceAsStream("testfiles/tiny-gif.img")) {
        final byte[] directBytes = IOUtils.toByteArray(is);
        final URL urlImage = new URL(URL_SECOND, "abcd/img.gif");
        final List<NameValuePair> emptyList = Collections.emptyList();
        getMockWebConnection().setResponse(urlImage, directBytes, 200, "ok", "image/gif", emptyList);
    }

    final String html
        = "<html><head>\n"
        + "<script>\n"
        + "  function test() {\n"
        + "    var input = document.getElementById('myInput');\n"
        + "    alert(input.src);\n"
        + "  }\n"
        + "</script>\n"
        + "</head>\n"
        + "<body onload='test()'>\n"
        + "  <input id='myInput' type='image' src='" + URL_SECOND + "a\rb\nc\r\nd/img.gif'>\n"
        + "</body>\n"
        + "</html>";

    expandExpectedAlertsVariables(URL_SECOND);
    loadPageWithAlerts2(html);
}
 
源代码30 项目: htmlunit   文件: WebResponse.java
/**
 * Returns the value of the specified response header.
 * @param headerName the name of the header whose value is to be returned
 * @return the header value, {@code null} if no response header exists with this name
 */
public String getResponseHeaderValue(final String headerName) {
    for (final NameValuePair pair : responseData_.getResponseHeaders()) {
        if (pair.getName().equalsIgnoreCase(headerName)) {
            return pair.getValue();
        }
    }
    return null;
}