下面列出了怎么用org.openqa.selenium.remote.DriverCommand的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* _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;
}
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);
}
}
}
@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();
}
@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();
}
/**
* 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();
}
}
}
@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));
}
}
@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);
}
}
@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");
}
@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());
}
@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");
}
@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);
}
@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"));
}
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;
}
public Set<String> getContextHandles()
{
setLastAction();
if ( contextHandles != null )
return contextHandles;
RemoteExecuteMethod executeMethod = new RemoteExecuteMethod( (RemoteWebDriver) webDriver );
List<String> handleList = (List<String>) executeMethod.execute( DriverCommand.GET_CONTEXT_HANDLES, null );
contextHandles = new HashSet<String>( 10 );
contextHandles.addAll( handleList );
return contextHandles;
}
private static void switchToContext(RemoteWebDriver driver, String context)
{
RemoteExecuteMethod executeMethod = new RemoteExecuteMethod(driver);
Map<String,String> params = new HashMap<>();
params.put("name", context);
executeMethod.execute(DriverCommand.SWITCH_TO_CONTEXT, params);
}
private static String getCurrentContextHandle(RemoteWebDriver driver)
{
RemoteExecuteMethod executeMethod = new RemoteExecuteMethod(driver);
String context = (String) executeMethod.execute(DriverCommand.GET_CURRENT_CONTEXT_HANDLE, null);
return context;
}
@Override
protected Response execute(String driverCommand, Map<String, ?> parameters) {
if (driverCommand.equalsIgnoreCase(DriverCommand.QUIT)) {
return new Response();
}
return super.execute(driverCommand, parameters);
}
@Override
public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {
Object takeScreenshot = getCapabilities().getCapability(CapabilityType.TAKES_SCREENSHOT);
if (null == takeScreenshot || (Boolean) takeScreenshot) {
String base64Str = execute(DriverCommand.SCREENSHOT).getValue().toString();
return target.convertFromBase64Png(base64Str);
}
return null;
}
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;
}
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;
}
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;
}
public boolean tap(By by) {
try {
Map<String, ?> params = ImmutableMap.of("element", ((RemoteWebElement)driver.findElement(by)).getId());
((RobotRemoteWebDriver)this.driver).execute(DriverCommand.TOUCH_SINGLE_TAP, params);
}catch(Exception ex) {
return false;
}
return true;
}
@Override
public WebDriver context(String name) {
checkNotNull(name, "Must supply a context name");
try {
execute(DriverCommand.SWITCH_TO_CONTEXT, ImmutableMap.of("name", name));
return this;
} catch (WebDriverException e) {
throw new NoSuchContextException(e.getMessage(), e);
}
}
@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);
}
}
@Override
public String getContext() {
String contextName =
String.valueOf(execute(DriverCommand.GET_CURRENT_CONTEXT_HANDLE).getValue());
if ("null".equalsIgnoreCase(contextName)) {
return null;
}
return contextName;
}
@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;
}
@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);
}
}
@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")));
}
@Override
public Set<String> keySet() {
@SuppressWarnings("unchecked")
Collection<String> result = (Collection<String>)
executeMethod.execute(DriverCommand.GET_LOCAL_STORAGE_KEYS, null);
return new HashSet<>(result);
}
@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;
}