Java Code Examples for org.openqa.selenium.remote.Response#getValue()

The following examples show how to use org.openqa.selenium.remote.Response#getValue() . 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: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAttemptToConvertAnExceptionIntoAnActualExceptionInstance() {
  Response response = new Response();
  response.setStatus(ErrorCodes.ASYNC_SCRIPT_TIMEOUT);
  WebDriverException exception = new ScriptTimeoutException("I timed out");
  response.setValue(exception);

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

  Response decoded = codec.decode(httpResponse);
  assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.ASYNC_SCRIPT_TIMEOUT);

  WebDriverException seenException = (WebDriverException) decoded.getValue();
  assertThat(seenException.getClass()).isEqualTo(exception.getClass());
  assertThat(seenException.getMessage().startsWith(exception.getMessage())).isTrue();
}
 
Example 2
Source File: UploadFileTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldWriteABase64EncodedZippedFileToDiskAndKeepName() throws Exception {
  ActiveSession session = mock(ActiveSession.class);
  when(session.getId()).thenReturn(new SessionId("1234567"));
  when(session.getFileSystem()).thenReturn(tempFs);
  when(session.getDownstreamDialect()).thenReturn(Dialect.OSS);

  File tempFile = touch(null, "foo");
  String encoded = Zip.zip(tempFile);

  UploadFile uploadFile = new UploadFile(new Json(), session);
  Map<String, Object> args = ImmutableMap.of("file", encoded);
  HttpRequest request = new HttpRequest(HttpMethod.POST, "/session/%d/se/file");
  request.setContent(asJson(args));
  HttpResponse response = uploadFile.execute(request);

  Response res = new Json().toType(string(response), Response.class);
  String path = (String) res.getValue();
  assertTrue(new File(path).exists());
  assertTrue(path.endsWith(tempFile.getName()));
}
 
Example 3
Source File: W3CHttpResponseCodec.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
protected Object getValueToEncode(Response response) {
  HashMap<Object, Object> toReturn = new HashMap<>();
  Object value = response.getValue();
  if (value instanceof WebDriverException) {
    HashMap<Object, Object> exception = new HashMap<>();
    exception.put(
        "error",
        response.getState() != null ?
        response.getState() :
        errorCodes.toState(response.getStatus()));
    exception.put("message", ((WebDriverException) value).getMessage());
    exception.put("stacktrace", Throwables.getStackTraceAsString((WebDriverException) value));
    if (value instanceof UnhandledAlertException) {
      HashMap<String, Object> data = new HashMap<>();
      data.put("text", ((UnhandledAlertException) value).getAlertText());
      exception.put("data", data);
    }

    value = exception;
  }
  toReturn.put("value", value);
  return toReturn;
}
 
Example 4
Source File: ExecuteCommand.java    From opentest with MIT License 6 votes vote down vote up
@Override
public void run() {
    String command = this.readStringArgument("command");
    Map<String, Object> commandArgs = this.readMapArgument("commandArgs", null);

    Response response = this.driver.execute(command, commandArgs);
    
    String sessionId = response.getSessionId();
    String state = response.getState();
    int status = response.getStatus();
    Object value = response.getValue();
    
    this.writeOutput("sessionId", sessionId);
    this.writeOutput("state", state);
    this.writeOutput("status", status);
    this.writeOutput("value", value);
}
 
Example 5
Source File: SafariDriver.java    From selenium with Apache License 2.0 5 votes vote down vote up
/**
 * Open either a new tab or window, depending on what is requested, and return the window handle
 * without switching to it.
 *
 * @return The handle of the new window.
 */
@Beta
public String newWindow(WindowType type) {
  Response response = execute(
      "SAFARI_NEW_WINDOW",
      singletonMap("newTab", type == WindowType.TAB));

  return (String) response.getValue();
}
 
Example 6
Source File: W3CHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldPopulateTheAlertTextIfThrowingAnUnhandledAlertException() {
  Map<String, Map<String, Serializable>> data = ImmutableMap.of(
      "value", ImmutableMap.of(
          "error", "unexpected alert open",
          "message", "Modal dialog present",
          "stacktrace", "",
          "data", ImmutableMap.of("text", "cheese")));

  HttpResponse response = createValidResponse(500, data);
  Response decoded = new W3CHttpResponseCodec().decode(response);

  UnhandledAlertException ex = (UnhandledAlertException) decoded.getValue();
  assertThat(ex.getAlertText()).isEqualTo("cheese");
}
 
Example 7
Source File: JsonTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRecognizeStringState() {
  Response response = new Json()
      .toType(
          "{\"state\":\"success\",\"value\":\"cheese\"}",
          Response.class);
  assertThat(response.getState()).isEqualTo("success");
  assertThat(response.getStatus().intValue()).isEqualTo(0);
  String value = (String) response.getValue();
  assertThat(value).isEqualTo("cheese");
}
 
Example 8
Source File: JsonTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRecognizeStringStatus() {
  Response response = new Json().toType(
      "{\"status\":\"success\",\"value\":\"cheese\"}",
      Response.class);

  assertThat(response.getStatus().intValue()).isEqualTo(0);
  assertThat(response.getState()).isEqualTo(new ErrorCodes().toState(0));
  String value = (String) response.getValue();
  assertThat(value).isEqualTo("cheese");
}
 
Example 9
Source File: JsonTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRecognizeNumericStatus() {
  Response response = new Json().toType(
      "{\"status\":0,\"value\":\"cheese\"}",
      Response.class);

  assertThat(response.getStatus().intValue()).isEqualTo(0);
  assertThat(response.getState()).isEqualTo(new ErrorCodes().toState(0));
  String value = (String) response.getValue();
  assertThat(value).isEqualTo("cheese");
}
 
Example 10
Source File: JsonTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void decodingResponseWithNumbersInValueObject() {
  Response response = new Json().toType(
      "{\"status\":0,\"value\":{\"width\":96,\"height\":46.19140625}}",
      Response.class);

  @SuppressWarnings("unchecked")
  Map<String, Number> value = (Map<String, Number>) response.getValue();
  assertThat(value.get("width").intValue()).isEqualTo(96);
  assertThat(value.get("height").intValue()).isEqualTo(46);
  assertThat(value.get("height").doubleValue()).isCloseTo(46.19140625, byLessThan(0.00001));
}
 
Example 11
Source File: JsonTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConvertAResponseWithAnElementInIt() {
  String json =
      "{\"value\":{\"value\":\"\",\"text\":\"\",\"selected\":false,\"enabled\":true,\"id\":\"three\"},\"context\":\"con\",\"sessionId\":\"sess\"}";
  Response converted = new Json().toType(json, Response.class);

  Map<String, Object> value = (Map<String, Object>) converted.getValue();
  assertThat(value).containsEntry("id", "three");
}
 
Example 12
Source File: AppiumDriver.java    From java-client with Apache License 2.0 5 votes vote down vote up
@Override
public DeviceRotation rotation() {
    Response response = execute(DriverCommand.GET_SCREEN_ROTATION);
    DeviceRotation deviceRotation =
            new DeviceRotation((Map<String, Number>) response.getValue());
    if (deviceRotation.getX() < 0 || deviceRotation.getY() < 0 || deviceRotation.getZ() < 0) {
        throw new WebDriverException("Unexpected orientation returned: " + deviceRotation);
    }
    return deviceRotation;
}
 
Example 13
Source File: AppiumDriver.java    From java-client with Apache License 2.0 5 votes vote down vote up
@Override
public Set<String> getContextHandles() {
    Response response = execute(DriverCommand.GET_CONTEXT_HANDLES);
    Object value = response.getValue();
    try {
        List<String> returnedValues = (List<String>) value;
        return new LinkedHashSet<>(returnedValues);
    } catch (ClassCastException ex) {
        throw new WebDriverException(
                "Returned value cannot be converted to List<String>: " + value, ex);
    }
}
 
Example 14
Source File: Browser.java    From selenium-shutterbug with MIT License 5 votes vote down vote up
public Object executeCustomCommand(String commandName) {
    try {
        Method execute = RemoteWebDriver.class.getDeclaredMethod("execute", String.class);
        execute.setAccessible(true);
        Response res = (Response) execute.invoke(this.driver, commandName);
        return res.getValue();
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}
 
Example 15
Source File: Browser.java    From selenium-shutterbug with MIT License 5 votes vote down vote up
public Object sendCommand(String cmd, Object params) {
    try {
        Method execute = RemoteWebDriver.class.getDeclaredMethod("execute", String.class, Map.class);
        execute.setAccessible(true);
        Response res = (Response) execute.invoke(driver, "sendCommand", ImmutableMap.of("cmd", cmd, "params", params));
        return res.getValue();
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}
 
Example 16
Source File: W3CHttpResponseCodec.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Override
public Response decode(HttpResponse encodedResponse) {
  String content = string(encodedResponse).trim();
  log.fine(String.format(
    "Decoding response. Response code was: %d and content: %s",
    encodedResponse.getStatus(),
    content));
  String contentType = nullToEmpty(encodedResponse.getHeader(CONTENT_TYPE));

  Response response = new Response();

  // Are we dealing with an error?
  // {"error":"no such alert","message":"No tab modal was open when attempting to get the dialog text"}
  if (HTTP_OK != encodedResponse.getStatus()) {
    log.fine("Processing an error");
    if (HTTP_BAD_METHOD == encodedResponse.getStatus()) {
      response.setStatus(ErrorCodes.UNKNOWN_COMMAND);
      response.setValue(content);
    } else {
      Map<String, Object> obj = json.toType(content, MAP_TYPE);

      Object w3cWrappedValue = obj.get("value");
      if (w3cWrappedValue instanceof Map && ((Map<?, ?>) w3cWrappedValue).containsKey("error")) {
        //noinspection unchecked
        obj = (Map<String, Object>) w3cWrappedValue;
      }

      String message = "An unknown error has occurred";
      if (obj.get("message") instanceof String) {
        message = (String) obj.get("message");
      }

      String error = "unknown error";
      if (obj.get("error") instanceof String) {
        error = (String) obj.get("error");
      }

      response.setState(error);
      response.setStatus(errorCodes.toStatus(error, Optional.of(encodedResponse.getStatus())));

      // For now, we'll inelegantly special case unhandled alerts.
      if ("unexpected alert open".equals(error) &&
          HTTP_INTERNAL_ERROR == encodedResponse.getStatus()) {
        String text = "";
        Object data = obj.get("data");
        if (data != null) {
          Object rawText = ((Map<?, ?>) data).get("text");
          if (rawText instanceof String) {
            text = (String) rawText;
          }
        }
        response.setValue(new UnhandledAlertException(message, text));
      } else {
        response.setValue(createException(error, message));
      }
    }
    return response;
  }

  response.setState("success");
  response.setStatus(ErrorCodes.SUCCESS);
  if (!content.isEmpty()) {
    if (contentType.startsWith("application/json") || Strings.isNullOrEmpty("")) {
      Map<String, Object> parsed = json.toType(content, MAP_TYPE);
      if (parsed.containsKey("value")) {
        Object value = parsed.get("value");
        response.setValue(value);
      } else {
        // Assume that the body of the response was the response.
        response.setValue(json.toType(content, OBJECT_TYPE));
      }
    }
  }

  if (response.getValue() instanceof String) {
    // We normalise to \n because Java will translate this to \r\n
    // if this is suitable on our platform, and if we have \r\n, java will
    // turn this into \r\r\n, which would be Bad!
    response.setValue(((String) response.getValue()).replace("\r\n", "\n"));
  }

  return response;
}
 
Example 17
Source File: CommandExecutionHelper.java    From java-client with Apache License 2.0 4 votes vote down vote up
private static <T> T handleResponse(Response response) {
    if (response != null) {
        return (T) response.getValue();
    }
    return null;
}
 
Example 18
Source File: QAFExtendedWebElement.java    From qaf with MIT License 4 votes vote down vote up
@Override
public String getCssValue(String propertyName) {
	Response response = execute("getElementValueOfCssProperty",
			ImmutableMap.of("id", id, "propertyName", propertyName));
	return ((String) response.getValue());
}
 
Example 19
Source File: ExecutesDriverScript.java    From java-client with Apache License 2.0 3 votes vote down vote up
/**
 * Run a set of scripts in scope of the current session.
 * This allows multiple web driver commands to be executed within one request
 * and may significantly speed up the automation script performance in
 * distributed client-server environments with high latency.
 * Read http://appium.io/docs/en/commands/session/execute-driver for more details.
 *
 * @since Appium 1.14
 * @param script the web driver script to execute (it should
 *               be a valid webdriverio code snippet by default
 *               unless another option is provided)
 * @param options additional scripting options
 * @return The script result
 * @throws org.openqa.selenium.WebDriverException if there was a failure while executing the script
 */
default ScriptValue executeDriverScript(String script, @Nullable ScriptOptions options) {
    Map<String, Object> data = new HashMap<>();
    data.put("script", checkNotNull(script));
    if (options != null) {
        data.putAll(options.build());
    }
    Response response = execute(EXECUTE_DRIVER_SCRIPT, data);
    //noinspection unchecked
    Map<String, Object> value = (Map<String, Object>) response.getValue();
    //noinspection unchecked
    return new ScriptValue(value.get("result"), (Map<String, Object>) value.get("logs"));
}
 
Example 20
Source File: HasSettings.java    From java-client with Apache License 2.0 3 votes vote down vote up
/**
 * Get settings stored for this test session It's probably better to use a
 * convenience function, rather than use this function directly. Try finding
 * the method for the specific setting you want to read.
 *
 * @return JsonObject, a straight-up hash of settings.
 */
@SuppressWarnings("unchecked")
default Map<String, Object> getSettings() {
    Map.Entry<String, Map<String, ?>> keyValuePair = getSettingsCommand();
    Response response = execute(keyValuePair.getKey(), keyValuePair.getValue());
    return (Map<String, Object>) response.getValue();
}