Java Code Examples for org.openqa.selenium.remote.http.HttpResponse#setStatus()

The following examples show how to use org.openqa.selenium.remote.http.HttpResponse#setStatus() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProtocolHandshakeTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void requestShouldIncludeJsonWireProtocolCapabilities() throws IOException {
  Map<String, Object> params = singletonMap("desiredCapabilities", new ImmutableCapabilities());
  Command command = new Command(null, DriverCommand.NEW_SESSION, params);

  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(utf8String(
      "{\"value\": {\"sessionId\": \"23456789\", \"capabilities\": {}}}"));
  RecordingHttpClient client = new RecordingHttpClient(response);

  new ProtocolHandshake().createSession(client, command);

  Map<String, Object> json = getRequestPayloadAsMap(client);

  assertThat(json.get("desiredCapabilities")).isEqualTo(EMPTY_MAP);
}
 
Example 2
Source File: ProtocolHandshakeTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void requestShouldIncludeSpecCompliantW3CCapabilities() throws IOException {
  Map<String, Object> params = singletonMap("desiredCapabilities", new ImmutableCapabilities());
  Command command = new Command(null, DriverCommand.NEW_SESSION, params);

  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(utf8String(
      "{\"value\": {\"sessionId\": \"23456789\", \"capabilities\": {}}}"));
  RecordingHttpClient client = new RecordingHttpClient(response);

  new ProtocolHandshake().createSession(client, command);

  Map<String, Object> json = getRequestPayloadAsMap(client);

  List<Map<String, Object>> caps = mergeW3C(json);

  assertThat(caps).isNotEmpty();
}
 
Example 3
Source File: ProtocolHandshakeTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void firstMatchSeparatesCapsForDifferentBrowsers() throws IOException {
  Capabilities caps = new ImmutableCapabilities(
      "moz:firefoxOptions", EMPTY_MAP,
      "browserName", "chrome");

  Map<String, Object> params = singletonMap("desiredCapabilities", caps);
  Command command = new Command(null, DriverCommand.NEW_SESSION, params);

  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(utf8String(
      "{\"sessionId\": \"23456789\", \"status\": 0, \"value\": {}}"));
  RecordingHttpClient client = new RecordingHttpClient(response);

  new ProtocolHandshake().createSession(client, command);

  Map<String, Object> handshakeRequest = getRequestPayloadAsMap(client);

  List<Map<String, Object>> capabilities = mergeW3C(handshakeRequest);

  assertThat(capabilities).contains(
      singletonMap("moz:firefoxOptions", EMPTY_MAP),
      singletonMap("browserName", "chrome"));
}
 
Example 4
Source File: WrapExceptions.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public HttpHandler apply(HttpHandler next) {
  return req -> {
    try {
      return next.execute(req);
    } catch (Throwable cause) {
      HttpResponse res = new HttpResponse();
      res.setStatus(errors.getHttpStatusCode(cause));

      res.addHeader("Content-Type", JSON_UTF_8.toString());
      res.addHeader("Cache-Control", "none");

      res.setContent(asJson(errors.encode(cause)));

      return res;
    }
  };
}
 
Example 5
Source File: ProtocolHandshakeTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void doesNotCreateFirstMatchForNonW3CCaps() throws IOException {
  Capabilities caps = new ImmutableCapabilities(
      "cheese", EMPTY_MAP,
      "moz:firefoxOptions", EMPTY_MAP,
      "browserName", "firefox");

  Map<String, Object> params = singletonMap("desiredCapabilities", caps);
  Command command = new Command(null, DriverCommand.NEW_SESSION, params);

  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(utf8String(
      "{\"sessionId\": \"23456789\", \"status\": 0, \"value\": {}}"));
  RecordingHttpClient client = new RecordingHttpClient(response);

  new ProtocolHandshake().createSession(client, command);

  Map<String, Object> handshakeRequest = getRequestPayloadAsMap(client);

  List<Map<String, Object>> w3c = mergeW3C(handshakeRequest);

  assertThat(w3c).hasSize(1);
  // firstMatch should not contain an object for Chrome-specific capabilities. Because
  // "chromeOptions" is not a W3C capability name, it is stripped from any firstMatch objects.
  // The resulting empty object should be omitted from firstMatch; if it is present, then the
  // Firefox-specific capabilities might be ignored.
  assertThat(w3c.get(0))
      .containsKey("moz:firefoxOptions")
      .containsEntry("browserName", "firefox");
}
 
Example 6
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeJsonResponseWithTrailingNullBytes() {
  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(utf8String("{\"status\":0,\"value\":\"foo\"}\0\0"));

  Response decoded = codec.decode(response);
  assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.SUCCESS);
  assertThat(decoded.getValue()).isEqualTo("foo");
}
 
Example 7
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeUtf16EncodedResponse() {
  HttpResponse httpResponse = new HttpResponse();
  httpResponse.setStatus(200);
  httpResponse.setHeader(CONTENT_TYPE, JSON_UTF_8.withCharset(UTF_16).toString());
  httpResponse.setContent(string("{\"status\":0,\"value\":\"水\"}", UTF_16));

  Response response = codec.decode(httpResponse);
  assertThat(response.getValue()).isEqualTo("水");
}
 
Example 8
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeJsonResponseMissingContentType() {
  Response response = new Response();
  response.setStatus(ErrorCodes.SUCCESS);
  response.setValue(ImmutableMap.of("color", "red"));

  HttpResponse httpResponse = new HttpResponse();
  httpResponse.setStatus(HTTP_OK);
  httpResponse.setContent(asJson(response));

  Response decoded = codec.decode(httpResponse);
  assertThat(decoded.getStatus()).isEqualTo(response.getStatus());
  assertThat(decoded.getSessionId()).isEqualTo(response.getSessionId());
  assertThat(decoded.getValue()).isEqualTo(response.getValue());
}
 
Example 9
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeNonJsonResponse_5xx() {
  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_INTERNAL_ERROR);
  response.setContent(utf8String("{\"foobar\"}"));

  Response decoded = codec.decode(response);
  assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.UNHANDLED_ERROR);
  assertThat(decoded.getValue()).isEqualTo("{\"foobar\"}");
}
 
Example 10
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeNonJsonResponse_4xx() {
  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_BAD_REQUEST);
  response.setContent(utf8String("{\"foobar\"}"));

  Response decoded = codec.decode(response);
  assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.UNKNOWN_COMMAND);
  assertThat(decoded.getValue()).isEqualTo("{\"foobar\"}");
}
 
Example 11
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeNonJsonResponse_204() {
  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_NO_CONTENT);

  Response decoded = codec.decode(response);
  assertThat(decoded.getStatus()).isNull();
  assertThat(decoded.getValue()).isNull();
}
 
Example 12
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeNonJsonResponse_200() {
  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(utf8String("{\"foobar\"}"));

  Response decoded = codec.decode(response);
  assertThat(decoded.getStatus().longValue()).isEqualTo(0);
  assertThat(decoded.getValue()).isEqualTo("{\"foobar\"}");
}
 
Example 13
Source File: W3CHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
private HttpResponse createValidResponse(int statusCode, Map<String, ?> data) {
  byte[] contents = new Json().toJson(data).getBytes(UTF_8);

  HttpResponse response = new HttpResponse();
  response.setStatus(statusCode);
  response.addHeader("Content-Type", "application/json; charset=utf-8");
  response.addHeader("Cache-Control", "no-cache");
  response.addHeader("Content-Length", String.valueOf(contents.length));
  response.setContent(bytes(contents));

  return response;
}
 
Example 14
Source File: NettyMessages.java    From selenium with Apache License 2.0 5 votes vote down vote up
public static HttpResponse toSeleniumResponse(Response response) {
  HttpResponse toReturn = new HttpResponse();

  toReturn.setStatus(response.getStatusCode());

  toReturn.setContent(! response.hasResponseBody()
                      ? empty()
                      : memoize(response::getResponseBodyAsStream));

  response.getHeaders().names().forEach(
      name -> response.getHeaders(name).forEach(value -> toReturn.addHeader(name, value)));

  return toReturn;
}
 
Example 15
Source File: ProtocolHandshakeTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldParseWireProtocolNewSessionResponse() throws IOException {
  Map<String, Object> params = singletonMap("desiredCapabilities", new ImmutableCapabilities());
  Command command = new Command(null, DriverCommand.NEW_SESSION, params);

  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(utf8String(
      "{\"sessionId\": \"23456789\", \"status\": 0, \"value\": {}}"));
  RecordingHttpClient client = new RecordingHttpClient(response);

  ProtocolHandshake.Result result = new ProtocolHandshake().createSession(client, command);
  assertThat(result.getDialect()).isEqualTo(Dialect.OSS);
}
 
Example 16
Source File: ProtocolHandshakeTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldParseW3CNewSessionResponse() throws IOException {
  Map<String, Object> params = singletonMap("desiredCapabilities", new ImmutableCapabilities());
  Command command = new Command(null, DriverCommand.NEW_SESSION, params);

  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(utf8String(
      "{\"value\": {\"sessionId\": \"23456789\", \"capabilities\": {}}}"));
  RecordingHttpClient client = new RecordingHttpClient(response);

  ProtocolHandshake.Result result = new ProtocolHandshake().createSession(client, command);
  assertThat(result.getDialect()).isEqualTo(Dialect.W3C);
}
 
Example 17
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConvertElementReferenceToRemoteWebElement() {
  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(asJson(ImmutableMap.of(
      "status", 0,
      "value", ImmutableMap.of(Dialect.OSS.getEncodedElementKey(), "345678"))));

  Response decoded = codec.decode(response);
  assertThat(((RemoteWebElement) decoded.getValue()).getId()).isEqualTo("345678");
}
 
Example 18
Source File: ReactorMessages.java    From selenium with Apache License 2.0 5 votes vote down vote up
public static HttpResponse toSeleniumResponse(Response response) {
  HttpResponse toReturn = new HttpResponse();

  toReturn.setStatus(response.getStatusCode());

  toReturn.setContent(! response.hasResponseBody()
                      ? empty()
                      : memoize(response::getResponseBodyAsStream));

  response.getHeaders().names().forEach(
      name -> response.getHeaders(name).forEach(value -> toReturn.addHeader(name, value)));

  return toReturn;
}
 
Example 19
Source File: ProtocolConverterTest.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldConvertAnException() throws IOException {
  // Json upstream, w3c downstream
  SessionId sessionId = new SessionId("1234567");

  HttpHandler handler = new ProtocolConverter(
      tracer,
      HttpClient.Factory.createDefault().createClient(new URL("http://example.com/wd/hub")),
      W3C,
      OSS) {
    @Override
    protected HttpResponse makeRequest(HttpRequest request) {
      HttpResponse response = new HttpResponse();

      response.setHeader("Content-Type", MediaType.JSON_UTF_8.toString());
      response.setHeader("Cache-Control", "none");

     String payload = new Json().toJson(
         ImmutableMap.of(
             "sessionId", sessionId.toString(),
             "status", UNHANDLED_ERROR,
             "value", new WebDriverException("I love cheese and peas")));
      response.setContent(utf8String(payload));
      response.setStatus(HTTP_INTERNAL_ERROR);

      return response;
    }
  };

  Command command = new Command(
      sessionId,
      DriverCommand.GET,
      ImmutableMap.of("url", "http://example.com/cheese"));

  HttpRequest w3cRequest = new W3CHttpCommandCodec().encode(command);

  HttpResponse resp = handler.execute(w3cRequest);

  assertEquals(MediaType.JSON_UTF_8, MediaType.parse(resp.getHeader("Content-type")));
  assertEquals(HTTP_INTERNAL_ERROR, resp.getStatus());

  Map<String, Object> parsed = json.toType(string(resp), MAP_TYPE);
  assertNull(parsed.get("sessionId"));
  assertTrue(parsed.containsKey("value"));
  @SuppressWarnings("unchecked") Map<String, Object> value =
      (Map<String, Object>) parsed.get("value");
  System.out.println("value = " + value.keySet());
  assertEquals("unknown error", value.get("error"));
  assertTrue(((String) value.get("message")).startsWith("I love cheese and peas"));
}
 
Example 20
Source File: UploadHandler.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Override
public HttpResponse execute(HttpRequest req) throws UncheckedIOException {
  HttpResponse res = new HttpResponse();
  res.setHeader("Content-Type", "text/html");
  res.setStatus(HTTP_OK);

  StringBuilder content = new StringBuilder();

  // I mean. Seriously. *sigh*
  try {
    String decoded = URLDecoder.decode(
        string(req),
        Charset.defaultCharset().displayName());

    String[] splits = decoded.split("\r\n");

    // First line is the boundary marker
    String boundary = splits[0];
    List<Map<String, Object>> allParts = new ArrayList<>();
    Map<String, Object> values = new HashMap<>();
    boolean inHeaders = true;
    for (int i = 1; i < splits.length; i++) {
      if ("".equals(splits[i])) {
        inHeaders = false;
        continue;
      }

      if (splits[i].startsWith(boundary)) {
        inHeaders = true;
        allParts.add(values);
        continue;
      }

      if (inHeaders && splits[i].toLowerCase().startsWith("content-disposition:")) {
        for (String keyValue : Splitter.on(';').trimResults().omitEmptyStrings().split(splits[i])) {
          Matcher matcher = Pattern.compile("(\\S+)\\s*=.*\"(.*?)\".*").matcher(keyValue);
          if (matcher.find()) {
            values.put(matcher.group(1), matcher.group(2));
          }
        }
      } else if (!inHeaders) {
        String c = (String) values.getOrDefault("content", "");
        c += splits[i];
        values.put("content", c);
      }
    }

    Object value = allParts.stream()
        .filter(map -> "upload".equals(map.get("name")))
        .findFirst()
        .map(map -> map.get("content"))
        .orElseThrow(() -> new RuntimeException("Cannot find uploaded data"));

    content.append(value);
  } catch (UnsupportedEncodingException e) {
    throw new UncheckedIOException(e);
  }

  // Slow down the upload so we can verify WebDriver waits.
  try {
    Thread.sleep(2500);
  } catch (InterruptedException ignored) {
  }

  content.append("<script>window.top.window.onUploadDone();</script>");

  res.setContent(utf8String(content.toString()));

  return res;
}