下面列出了怎么用org.openqa.selenium.remote.HttpCommandExecutor的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Returns an {@link HttpCommandExecutor} to a Selenium grid (e.g. SauceLabs) that contains basic authentication for
* access
*
* @param testEnvironment
* The {@link TestEnvironment} to the grid
* @return {@link HttpCommandExecutor} to Selenium grid augmented with credentials
* @throws MalformedURLException
* if the given gridUrl is invalid
*/
protected static HttpCommandExecutor createGridExecutor(String testEnvironment) throws MalformedURLException
{
TestEnvironment testEnvironmentProperties = MultibrowserConfiguration.getInstance().getTestEnvironment(testEnvironment);
if (testEnvironmentProperties == null)
{
throw new IllegalArgumentException("No properties found for test environment: \"" + testEnvironment + "\"");
}
final Map<String, CommandInfo> additionalCommands = new HashMap<String, CommandInfo>(); // just a dummy
URL gridUrl = new URL(testEnvironmentProperties.getUrl());
return new HttpCommandExecutor(additionalCommands, gridUrl, new NeodymiumProxyHttpClientFactory(testEnvironmentProperties));
}
@Override
public String getVncURL(WebDriver driver) {
String vncURL = null;
if (driver instanceof RemoteWebDriver && "true".equals(Configuration.getCapability("enableVNC"))) {
// TODO: resolve negative case when VNC is not supported
final RemoteWebDriver rwd = (RemoteWebDriver) driver;
String protocol = R.CONFIG.get(vnc_protocol);
String host = R.CONFIG.get(vnc_host);
String port = R.CONFIG.get(vnc_port);
// If VNC host/port not set user them from Selenium
if (StringUtils.isEmpty(host) || StringUtils.isEmpty(port)) {
host = ((HttpCommandExecutor) rwd.getCommandExecutor()).getAddressOfRemoteServer().getHost();
port = String.valueOf(((HttpCommandExecutor) rwd.getCommandExecutor()).getAddressOfRemoteServer().getPort());
}
vncURL = String.format(R.CONFIG.get("vnc_desktop"), protocol, host, port, rwd.getSessionId().toString());
}
return vncURL;
}
private RemoteWebDriver createRemoteDriver(Capabilities capabilities) {
AqualityServices.getLocalizedLogger().info("loc.browser.grid");
ClientFactory clientFactory = new ClientFactory();
CommandExecutor commandExecutor = new HttpCommandExecutor(
ImmutableMap.of(),
browserProfile.getRemoteConnectionUrl(),
clientFactory);
RemoteWebDriver driver = getDriver(RemoteWebDriver.class, commandExecutor, capabilities);
driver.setFileDetector(new LocalFileDetector());
return driver;
}
public static HttpCommandExecutor getProxyExecutor(URL url, Properties prop) {
prop = decrypt(prop);
String proxyHost = prop.getProperty("proxyHost");
int proxyPort = Integer.valueOf(prop.getProperty("proxyPort"));
String proxyUserDomain = prop.getProperty("proxyUserDomain");
String proxyUser = prop.getProperty("proxyUser");
String proxyPassword = prop.getProperty("proxyPassword");
HttpClientBuilder builder = HttpClientBuilder.create();
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
new NTCredentials(proxyUser, proxyPassword, getWorkstation(), proxyUserDomain));
if (url.getUserInfo() != null && !url.getUserInfo().isEmpty()) {
credsProvider.setCredentials(new AuthScope(url.getHost(), (url.getPort() > 0 ? url.getPort() : url.getDefaultPort())),
new UsernamePasswordCredentials(proxyUser, proxyPassword));
}
builder.setProxy(proxy);
builder.setDefaultCredentialsProvider(credsProvider);
//HttpClient.Factory factory = new SimpleHttpClientFactory(builder);
HttpClient.Factory factory = new SimpleHttpClientFactory(new okhttp3.OkHttpClient.Builder());
return new HttpCommandExecutor(new HashMap<>(), url, factory);
}
/**
* Patch for
* https://github.com/CognizantQAHub/Cognizant-Intelligent-Test-Scripter/issues/7
* Based on
* https://github.com/mozilla/geckodriver/issues/759#issuecomment-308522851
*
* @param fDriver FirefoxDriver
*/
private static void addGeckoDriverAddon(FirefoxDriver fDriver) {
if (SystemDefaults.getClassesFromJar.get() && SystemDefaults.debugMode.get()) {
if (FilePath.getFireFoxAddOnPath().exists()) {
HttpCommandExecutor ce = (HttpCommandExecutor) fDriver.getCommandExecutor();
String url = ce.getAddressOfRemoteServer() + "/session/" + fDriver.getSessionId() + "/moz/addon/install";
addGeckoDriverAddon(FilePath.getFireFoxAddOnPath(), url);
}
}
}
private void defineCustomCommand(String name, CommandInfo info) {
try {
Method defineCommand = HttpCommandExecutor.class.getDeclaredMethod("defineCommand", String.class, CommandInfo.class);
defineCommand.setAccessible(true);
defineCommand.invoke(((RemoteWebDriver) this.driver).getCommandExecutor(), name, info);
} catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
/**
* Creates a new instance based on command {@code executor} and {@code capabilities}.
*
* @param executor is an instance of {@link HttpCommandExecutor}
* or class that extends it. Default commands or another vendor-specific
* commands may be specified there.
* @param capabilities take a look at {@link Capabilities}
*/
public AppiumDriver(HttpCommandExecutor executor, Capabilities capabilities) {
super(executor, capabilities);
this.executeMethod = new AppiumExecutionMethod(this);
locationContext = new RemoteLocationContext(executeMethod);
super.setErrorHandler(errorHandler);
this.remoteAddress = executor.getAddressOfRemoteServer();
this.setElementConverter(new JsonToMobileElementConverter(this));
}
private static void getIPOfNode(TestCaseExecution tCExecution) {
try {
Session session = tCExecution.getSession();
HttpCommandExecutor ce = (HttpCommandExecutor) ((RemoteWebDriver) session.getDriver()).getCommandExecutor();
SessionId sessionId = ((RemoteWebDriver) session.getDriver()).getSessionId();
String hostName = ce.getAddressOfRemoteServer().getHost();
int port = ce.getAddressOfRemoteServer().getPort();
HttpHost host = new HttpHost(hostName, port);
HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
URL sessionURL = new URL(RobotServerService.getBaseUrl(session.getHost(), session.getPort()) + "/grid/api/testsession?session=" + sessionId);
BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm());
HttpResponse response = client.execute(host, r);
if (!response.getStatusLine().toString().contains("403")
&& !response.getEntity().getContentType().getValue().contains("text/html")) {
InputStream contents = response.getEntity().getContent();
StringWriter writer = new StringWriter();
IOUtils.copy(contents, writer, "UTF8");
JSONObject object = new JSONObject(writer.toString());
if (object.has("proxyId")) {
URL myURL = new URL(object.getString("proxyId"));
if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {
tCExecution.setRobotHost(myURL.getHost());
tCExecution.setRobotPort(String.valueOf(myURL.getPort()));
}
} else {
LOG.debug("'proxyId' json data not available from remote Selenium Server request : " + writer.toString());
}
}
} catch (IOException | JSONException ex) {
LOG.error(ex.toString(), ex);
}
}
private static void setCommand(CommandExecutor executor) throws Exception {
CommandInfo cmd = new CommandInfo("/session/:sessionId/chromium/send_command_and_get_result", POST);
Method defineCommand = HttpCommandExecutor.class.getDeclaredMethod("defineCommand", String.class, CommandInfo.class);
defineCommand.setAccessible(true);
defineCommand.invoke(executor, "sendCommand", cmd);
}
@NotNull
@Override
public synchronized FeatureState getDesiredCapabilitiesForThread(@NotNull final String name) {
try {
/*
Return the previous generated details if they exist
*/
if (threadIdToCapMap.containsKey(name)) {
return threadIdToCapMap.get(name);
}
/*
Some validation checking
*/
if (originalDesiredCapabilities.isEmpty()) {
throw new ConfigurationException("There are no desired capabilities defined. "
+ "Check the configuration profiles have the required information in them");
}
/*
We have allocated our available configurations
*/
final int urlCount = Math.max(originalApplicationUrls.size(), 1);
if (currentUrl >= urlCount) {
throw new ConfigurationException("Configuration pool has been exhausted!");
}
/*
Get the details that the requesting thread will need
*/
final DesiredCapabilities desiredCapabilities =
originalDesiredCapabilities.get(currentCapability);
final UrlMapping url = originalApplicationUrls.isEmpty()
? null : originalApplicationUrls.get(currentUrl);
final Map<String, String> dataSet = originalDataSets.containsKey(currentDataset)
? new HashMap<>(originalDataSets.get(currentDataset)) : new HashMap<>();
/*
Disable popup blocker
*/
desiredCapabilities.setCapability("disable-popup-blocking", true);
/*
Tick over to the next url when all the capabilities have been consumed
*/
++currentCapability;
if (currentCapability >= originalDesiredCapabilities.size()) {
++currentDataset;
if (currentDataset >= getMaxDataSets()) {
currentDataset = 0;
currentCapability = 0;
++currentUrl;
}
}
/*
Associate the new details with the thread
*/
final String remoteAddress =
"http://" + browserStackUsername + ":" + browserStackAccessToken + URL;
final HttpCommandExecutor executor = new HttpCommandExecutor(
ImmutableMap.of(),
new URL(remoteAddress));
final WebDriver webDriver = new RemoteWebDriver(executor, desiredCapabilities);
threadIdToDriverMap.put(name, webDriver);
final FeatureState featureState = new FeatureStateImpl(
url, dataSet, reportDirectory, new ArrayList<>());
threadIdToCapMap.put(name, featureState);
return featureState;
} catch (final MalformedURLException ex) {
/*
This shouldn't happen
*/
throw new ConfigurationException(
"The url that was built to contact BrowserStack was invalid", ex);
}
}
public WindowsDriver(HttpCommandExecutor executor, Capabilities capabilities) {
super(executor, updateDefaultPlatformName(capabilities, WINDOWS));
}
/**
* Creates a new instance based on command {@code executor} and {@code capabilities}.
*
* @param executor is an instance of {@link HttpCommandExecutor}
* or class that extends it. Default commands or another vendor-specific
* commands may be specified there.
* @param capabilities take a look at {@link Capabilities}
*/
public AndroidDriver(HttpCommandExecutor executor, Capabilities capabilities) {
super(executor, updateDefaultPlatformName(capabilities, ANDROID_PLATFORM));
}
/**
* Creates a new instance based on command {@code executor} and {@code capabilities}.
*
* @param executor is an instance of {@link HttpCommandExecutor}
* or class that extends it. Default commands or another vendor-specific
* commands may be specified there.
* @param capabilities take a look at {@link Capabilities}
*/
public IOSDriver(HttpCommandExecutor executor, Capabilities capabilities) {
super(executor, updateDefaultPlatformName(capabilities, IOS_DEFAULT_PLATFORM));
}