org.openqa.selenium.remote.DriverCommand Java Examples

The following examples show how to use org.openqa.selenium.remote.DriverCommand. 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: UtilsTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void providesRemoteAccessToWebStorage() {
  DesiredCapabilities caps = new DesiredCapabilities();
  caps.setCapability(CapabilityType.SUPPORTS_WEB_STORAGE, true);

  CapableDriver driver = mock(CapableDriver.class);
  when(driver.getCapabilities()).thenReturn(caps);

  WebStorage storage = Utils.getWebStorage(driver);

  LocalStorage localStorage = storage.getLocalStorage();
  SessionStorage sessionStorage = storage.getSessionStorage();

  localStorage.setItem("foo", "bar");
  sessionStorage.setItem("bim", "baz");

  verify(driver).execute(DriverCommand.SET_LOCAL_STORAGE_ITEM, ImmutableMap.of(
      "key", "foo", "value", "bar"));
  verify(driver).execute(DriverCommand.SET_SESSION_STORAGE_ITEM, ImmutableMap.of(
      "key", "bim", "value", "baz"));
}
 
Example #2
Source File: DriverCommandExecutor.java    From selenium with Apache License 2.0 6 votes vote down vote up
/**
 * Sends the {@code command} to the driver server for execution. The server will be started
 * if requesting a new session. Likewise, if terminating a session, the server will be shutdown
 * once a response is received.
 *
 * @param command The command to execute.
 * @return The command response.
 * @throws IOException If an I/O error occurs while sending the command.
 */
@Override
public Response execute(Command command) throws IOException {
  if (DriverCommand.NEW_SESSION.equals(command.getName())) {
    service.start();
  }

  try {
    return super.execute(command);
  } catch (Throwable t) {
    Throwable rootCause = Throwables.getRootCause(t);
    if (rootCause instanceof ConnectException &&
        "Connection refused".equals(rootCause.getMessage()) &&
        !service.isRunning()) {
      throw new WebDriverException("The driver server has unexpectedly died!", t);
    }
    Throwables.throwIfUnchecked(t);
    throw new WebDriverException(t);
  } finally {
    if (DriverCommand.QUIT.equals(command.getName())) {
      service.stop();
    }
  }
}
 
Example #3
Source File: FirefoxDriverTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGetMeaningfulExceptionOnBrowserDeath() throws Exception {
  FirefoxDriver driver2 = new FirefoxDriver();
  driver2.get(pages.formPage);

  // Grab the command executor
  CommandExecutor keptExecutor = driver2.getCommandExecutor();
  SessionId sessionId = driver2.getSessionId();

  try {
    Field field = RemoteWebDriver.class.getDeclaredField("executor");
    field.setAccessible(true);
    CommandExecutor spoof = mock(CommandExecutor.class);
    doThrow(new IOException("The remote server died"))
        .when(spoof).execute(ArgumentMatchers.any());

    field.set(driver2, spoof);

    driver2.get(pages.formPage);
    fail("Should have thrown.");
  } catch (UnreachableBrowserException e) {
    assertThat(e.getMessage()).contains("Error communicating with the remote browser");
  } finally {
    keptExecutor.execute(new Command(sessionId, DriverCommand.QUIT));
  }
}
 
Example #4
Source File: PerformanceLoggingMockTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void testMergesRemoteLogs() {
  final ExecuteMethod executeMethod = mock(ExecuteMethod.class);

  when(executeMethod.execute(
      DriverCommand.GET_LOG, ImmutableMap.of(RemoteLogs.TYPE_KEY, LogType.PROFILER)))
      .thenReturn(Arrays.asList(ImmutableMap.of(
        "level", Level.INFO.getName(),
        "timestamp", 1L,
        "message", "second")));

  LocalLogs localLogs = LocalLogs.getStoringLoggerInstance(singleton(LogType.PROFILER));
  RemoteLogs logs = new RemoteLogs(executeMethod, localLogs);
  localLogs.addEntry(LogType.PROFILER, new LogEntry(Level.INFO, 0, "first"));
  localLogs.addEntry(LogType.PROFILER, new LogEntry(Level.INFO, 2, "third"));

  List<LogEntry> entries = logs.get(LogType.PROFILER).getAll();
  assertThat(entries).hasSize(3);
  for (int i = 0; i < entries.size(); ++i) {
    assertThat(entries.get(i).getTimestamp()).isEqualTo(i);
  }
}
 
Example #5
Source File: JsonTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeAbleToConvertACommand() {
  SessionId sessionId = new SessionId("session id");
  Command original = new Command(
      sessionId,
      DriverCommand.NEW_SESSION,
      ImmutableMap.of("food", "cheese"));
  String raw = new Json().toJson(original);
  Command converted = new Json().toType(raw, Command.class);

  assertThat(converted.getSessionId().toString()).isEqualTo(sessionId.toString());
  assertThat(converted.getName()).isEqualTo(original.getName());

  assertThat(converted.getParameters().keySet()).hasSize(1);
  assertThat(converted.getParameters().get("food")).isEqualTo("cheese");
}
 
Example #6
Source File: JsonOutputTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldConvertAProxyCorrectly() {
  Proxy proxy = new Proxy();
  proxy.setHttpProxy("localhost:4444");

  MutableCapabilities caps = new DesiredCapabilities("foo", "1", Platform.LINUX);
  caps.setCapability(CapabilityType.PROXY, proxy);
  Map<String, ?> asMap = ImmutableMap.of("desiredCapabilities", caps);
  Command command = new Command(new SessionId("empty"), DriverCommand.NEW_SESSION, asMap);

  String json = convert(command.getParameters());

  JsonObject converted = new JsonParser().parse(json).getAsJsonObject();
  JsonObject capsAsMap = converted.get("desiredCapabilities").getAsJsonObject();

  assertThat(capsAsMap.get(CapabilityType.PROXY).getAsJsonObject().get("httpProxy").getAsString())
      .isEqualTo(proxy.getHttpProxy());
}
 
Example #7
Source File: JsonHttpCommandCodecTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void whenDecodingAnHttpRequestDoesNotRecreateWebElements() {
  Command command = new Command(
      new SessionId("1234567"),
      DriverCommand.EXECUTE_SCRIPT,
      ImmutableMap.of(
          "script", "",
          "args", Arrays.asList(ImmutableMap.of(OSS.getEncodedElementKey(), "67890"))));

  HttpRequest request = codec.encode(command);

  Command decoded = codec.decode(request);

  List<?> args = (List<?>) decoded.getParameters().get("args");

  Map<? ,?> element = (Map<?, ?>) args.get(0);
  assertThat(element.get(OSS.getEncodedElementKey())).isEqualTo("67890");
}
 
Example #8
Source File: QAFExtendedWebDriver.java    From qaf with MIT License 6 votes vote down vote up
@Override
public Object executeAsyncScript(String script, Object... args) {
	if (!isJavascriptEnabled()) {
		throw new UnsupportedOperationException(
				"You must be using an underlying instance of " + "WebDriver that supports executing javascript");
	}

	// Escape the quote marks
	script = script.replaceAll("\"", "\\\"");

	Iterable<Object> convertedArgs = Iterables.transform(Lists.newArrayList(args), new WebElementToJsonConverter());

	Map<String, ?> params = ImmutableMap.of("script", script, "args", Lists.newArrayList(convertedArgs));

	return execute(DriverCommand.EXECUTE_ASYNC_SCRIPT, params).getValue();
}
 
Example #9
Source File: QAFExtendedWebDriver.java    From qaf with MIT License 6 votes vote down vote up
@Override
public Object executeScript(String script, Object... args) {
	if (!getCapabilities().isJavascriptEnabled()) {
		throw new UnsupportedOperationException(
				"You must be using an underlying instance of WebDriver that supports executing javascript");
	}

	// Escape the quote marks
	script = script.replaceAll("\"", "\\\"");

	Iterable<Object> convertedArgs = Iterables.transform(Lists.newArrayList(args), new WebElementToJsonConverter());

	Map<String, ?> params = ImmutableMap.of("script", script, "args", Lists.newArrayList(convertedArgs));

	return execute(DriverCommand.EXECUTE_SCRIPT, params).getValue();
}
 
Example #10
Source File: QAFExtendedWebElement.java    From qaf with MIT License 6 votes vote down vote up
private void load() {
	if (null==id || (id == "-1")) {
		Map<String, ?> parameters = new HashMap<String, String>();
		CommandTracker commandTracker = new CommandTracker(DriverCommand.FIND_ELEMENT, parameters);
		if (parentElement == null) {
			beforeCommand(this, commandTracker);
			((QAFExtendedWebDriver) parent).load(this);
			afterCommand(this, commandTracker);
		} else {
			parentElement.load();
			beforeCommand(this, commandTracker);
			setId(parentElement.findElement(getBy()).id);
			afterCommand(this, commandTracker);
		}
		
	}
}
 
Example #11
Source File: ActiveSessionCommandExecutor.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public Response execute(Command command) throws IOException {
  if (DriverCommand.NEW_SESSION.equals(command.getName())) {
    if (active) {
      throw new WebDriverException("Cannot start session twice! " + session);
    }

    active = true;

    // We already have a running session.
    Response response = new Response(session.getId());
    response.setValue(session.getCapabilities());
    return response;
  }

  // The command is about to be sent to the session, which expects it to be
  // encoded as if it has come from the downstream end, not the upstream end.
  HttpRequest request = session.getDownstreamDialect().getCommandCodec().encode(command);

  HttpResponse httpResponse = session.execute(request);

  return session.getDownstreamDialect().getResponseCodec().decode(httpResponse);
}
 
Example #12
Source File: DeviceWebDriver.java    From xframium-java with GNU General Public License v3.0 6 votes vote down vote up
/**
 * _get context.
 *
 * @return the string
 */
private String _getContext()
{
    if ( webDriver != null )
    {
        try
        {
            if ( webDriver instanceof RemoteWebDriver )
            {
                RemoteExecuteMethod executeMethod = new RemoteExecuteMethod( (RemoteWebDriver) webDriver );
                return (String) executeMethod.execute( DriverCommand.GET_CURRENT_CONTEXT_HANDLE, null );
            }
            else if ( webDriver instanceof AppiumDriver )
            {
                return ((AppiumDriver) webDriver).getContext();
            }
        }
        catch ( Exception e )
        {
            log.warn( "Context Switches are not supported - " + e.getMessage() );
            contextSwitchSupported = false;
        }
    }

    return null;
}
 
Example #13
Source File: DeviceWebDriver.java    From xframium-java with GNU General Public License v3.0 5 votes vote down vote up
public WebDriver context( String newContext )
{
    setLastAction();
    if ( !contextSwitchSupported )
        return webDriver;

    if ( newContext == null || newContext.equals( currentContext ) )
        return webDriver;

    if ( webDriver != null )
    {

        if ( webDriver instanceof RemoteWebDriver )
        {
            log.info( "Switching context to " + newContext );
            RemoteExecuteMethod executeMethod = new RemoteExecuteMethod( (RemoteWebDriver) webDriver );
            Map<String, String> params = new HashMap<String, String>( 5 );
            params.put( "name", newContext );
            executeMethod.execute( DriverCommand.SWITCH_TO_CONTEXT, params );
        }
        else if ( webDriver instanceof AppiumDriver )
        {
            log.info( "Switching context to " + newContext );
            ((AppiumDriver) webDriver).context( newContext );
        }
        else
            return null;

        if ( newContext.equals( _getContext() ) )
            currentContext = newContext;
        else
            throw new IllegalStateException( "Could not change context to " + newContext + " against " + webDriver );
    }

    return webDriver;
}
 
Example #14
Source File: ChromeDriverClient.java    From AndroidRobot with Apache License 2.0 5 votes vote down vote up
public boolean tapByXPath(String xpath) {
	try {
		Map<String, ?> params = ImmutableMap.of("element", ((RemoteWebElement)driver.findElement(By.xpath(xpath))).getId());
		((RobotRemoteWebDriver)this.driver).execute(DriverCommand.TOUCH_SINGLE_TAP, params);
	}catch(Exception ex) {
		return false;
	}
	return true;
}
 
Example #15
Source File: ChromeDriverClient.java    From AndroidRobot with Apache License 2.0 5 votes vote down vote up
public boolean tapById(String id) {
	try{
		Map<String, ?> params = ImmutableMap.of("element", ((RemoteWebElement)driver.findElement(By.id(id))).getId());
		((RobotRemoteWebDriver)this.driver).execute(DriverCommand.TOUCH_SINGLE_TAP, params);
	}catch(Exception ex) {
		return false;
	}
	return true;
}
 
Example #16
Source File: AppiumDriver.java    From java-client with Apache License 2.0 5 votes vote down vote up
@Override
public String getContext() {
    String contextName =
            String.valueOf(execute(DriverCommand.GET_CURRENT_CONTEXT_HANDLE).getValue());
    if ("null".equalsIgnoreCase(contextName)) {
        return null;
    }
    return contextName;
}
 
Example #17
Source File: ScreenShotRemoteWebDriver.java    From seleniumtestsframework with Apache License 2.0 5 votes vote down vote up
public <X> X getScreenshotAs(final OutputType<X> target) throws WebDriverException {
    if ((Boolean) getCapabilities().getCapability(CapabilityType.TAKES_SCREENSHOT)) {
        String output = execute(DriverCommand.SCREENSHOT).getValue().toString();
        return target.convertFromBase64Png(output);
    }

    return null;
}
 
Example #18
Source File: AppiumDriver.java    From java-client with Apache License 2.0 5 votes vote down vote up
@Override
public ScreenOrientation getOrientation() {
    Response response = execute(DriverCommand.GET_SCREEN_ORIENTATION);
    String orientation = response.getValue().toString().toLowerCase();
    if (orientation.equals(ScreenOrientation.LANDSCAPE.value())) {
        return ScreenOrientation.LANDSCAPE;
    } else if (orientation.equals(ScreenOrientation.PORTRAIT.value())) {
        return ScreenOrientation.PORTRAIT;
    } else {
        throw new WebDriverException("Unexpected orientation returned: " + orientation);
    }
}
 
Example #19
Source File: RemoteLocationContext.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public Location location() {
  @SuppressWarnings("unchecked")
  Map<String, Number> result = (Map<String, Number>) executeMethod.execute(
      DriverCommand.GET_LOCATION, null);
  if (result == null) {
    return null;
  }
  return new Location(castToDouble(result.get("latitude")),
                      castToDouble(result.get("longitude")),
                      castToDouble(result.get("altitude")));
}
 
Example #20
Source File: RemoteLocalStorage.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public Set<String> keySet() {
  @SuppressWarnings("unchecked")
  Collection<String> result = (Collection<String>)
      executeMethod.execute(DriverCommand.GET_LOCAL_STORAGE_KEYS, null);
  return new HashSet<>(result);
}
 
Example #21
Source File: RemoteLocalStorage.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public String removeItem(String key) {
  String value = getItem(key);
  Map<String, String> args = ImmutableMap.of("key", key);
  executeMethod.execute(DriverCommand.REMOVE_LOCAL_STORAGE_ITEM, args);
  return value;
}
 
Example #22
Source File: RemoteSessionStorage.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public Set<String> keySet() {
  @SuppressWarnings("unchecked")
  Collection<String> result = (Collection<String>)
      executeMethod.execute(DriverCommand.GET_SESSION_STORAGE_KEYS, null);
  return new HashSet<>(result);
}
 
Example #23
Source File: RemoteSessionStorage.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public String removeItem(String key) {
  String value = getItem(key);
  Map<String, String> args = ImmutableMap.of("key", key);
  executeMethod.execute(DriverCommand.REMOVE_SESSION_STORAGE_ITEM, args);
  return value;
}
 
Example #24
Source File: TestOperaBlinkDriver.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public <X> X getScreenshotAs(OutputType<X> target) {
  // Get the screenshot as base64.
  String base64 = (String) execute(DriverCommand.SCREENSHOT).getValue();
  // ... and convert it.
  return target.convertFromBase64Png(base64);
}
 
Example #25
Source File: RemoteNetworkConnection.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public ConnectionType setNetworkConnection(
    ConnectionType type) {
  Map<String, ConnectionType> mode = ImmutableMap.of("type", type);
  return new ConnectionType(((Number) executeMethod.execute(DriverCommand.SET_NETWORK_CONNECTION,
                                                          ImmutableMap
                                                              .of("parameters", mode)))
                                .intValue());
}
 
Example #26
Source File: JsonHttpCommandCodec.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, ?> amendParameters(String name, Map<String, ?> parameters) {
  switch (name) {
    case DriverCommand.GET_CURRENT_WINDOW_SIZE:
    case DriverCommand.MAXIMIZE_CURRENT_WINDOW:
    case DriverCommand.SET_CURRENT_WINDOW_SIZE:
    case DriverCommand.SET_CURRENT_WINDOW_POSITION:
      return ImmutableMap.<String, Object>builder()
        .putAll(parameters)
        .put("windowHandle", "current")
        .put("handle", "current")
        .build();

    case DriverCommand.SET_TIMEOUT:
      if (parameters.size() != 1) {
        throw new InvalidArgumentException(
            "The JSON wire protocol only supports setting one time out at a time");
      }
      Map.Entry<String, ?> entry = parameters.entrySet().iterator().next();
      String type = entry.getKey();
      if ("pageLoad".equals(type)) {
        type = "page load";
      }
      return ImmutableMap.of("type", type, "ms", entry.getValue());

    case DriverCommand.SWITCH_TO_WINDOW:
      return ImmutableMap.<String, Object>builder()
        .put("name", parameters.get("handle"))
        .build();

    default:
      return parameters;
  }
}
 
Example #27
Source File: UtilsTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void providesRemoteAccessToAppCache() {
  DesiredCapabilities caps = new DesiredCapabilities();
  caps.setCapability(CapabilityType.SUPPORTS_APPLICATION_CACHE, true);

  CapableDriver driver = mock(CapableDriver.class);
  when(driver.getCapabilities()).thenReturn(caps);
  when(driver.execute(DriverCommand.GET_APP_CACHE_STATUS, null))
      .thenReturn(AppCacheStatus.CHECKING.name());

  ApplicationCache cache = Utils.getApplicationCache(driver);
  assertEquals(AppCacheStatus.CHECKING, cache.getStatus());
}
 
Example #28
Source File: TestChromeDriver.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public <X> X getScreenshotAs(OutputType<X> target) {
  // Get the screenshot as base64.
  String base64 = (String) execute(DriverCommand.SCREENSHOT).getValue();
  // ... and convert it.
  return target.convertFromBase64Png(base64);
}
 
Example #29
Source File: TestEdgeHtmlDriver.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public <X> X getScreenshotAs(OutputType<X> target) {
  // Get the screenshot as base64.
  String base64 = (String) execute(DriverCommand.SCREENSHOT).getValue();
  // ... and convert it.
  return target.convertFromBase64Png(base64);
}
 
Example #30
Source File: TestEdgeDriver.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public <X> X getScreenshotAs(OutputType<X> target) {
  // Get the screenshot as base64.
  String base64 = (String) execute(DriverCommand.SCREENSHOT).getValue();
  // ... and convert it.
  return target.convertFromBase64Png(base64);
}