下面列出了org.apache.http.message.BasicHttpEntityEnclosingRequest#org.openqa.selenium.remote.SessionId 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void shouldForwardTextMessageToServer() throws URISyntaxException, InterruptedException {
HttpClient.Factory clientFactory = HttpClient.Factory.createDefault();
// Create a backend server which will capture any incoming text message
AtomicReference<String> text = new AtomicReference<>();
CountDownLatch latch = new CountDownLatch(1);
Server<?> backend = createBackendServer(latch, text, "");
// Push a session that resolves to the backend server into the session map
SessionId id = new SessionId(UUID.randomUUID());
sessions.add(new Session(id, backend.getUrl().toURI(), new ImmutableCapabilities()));
// Now! Send a message. We expect it to eventually show up in the backend
WebSocket socket = clientFactory.createClient(proxyServer.getUrl())
.openSocket(new HttpRequest(GET, String.format("/session/%s/cdp", id)), new WebSocket.Listener(){});
socket.sendText("Cheese!");
assertThat(latch.await(5, SECONDS)).isTrue();
assertThat(text.get()).isEqualTo("Cheese!");
socket.close();
}
public static String[] getHostNameAndPort(String hostName, int port, SessionId session) {
String[] hostAndPort = new String[2];
String errorMsg = "Failed to acquire remote webdriver node and port info. Root cause: \n";
try {
HttpHost host = new HttpHost(hostName, port);
CloseableHttpClient client = HttpClients.createSystem();
URL sessionURL = new URL("http://" + hostName + ":" + port + "/grid/api/testsession?session=" + session);
BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm());
HttpResponse response = client.execute(host, r);
String url = extractUrlFromResponse(response);
if (url != null) {
URL myURL = new URL(url);
if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {
hostAndPort[0] = myURL.getHost();
hostAndPort[1] = Integer.toString(myURL.getPort());
}
}
} catch (Exception e) {
Logger.getLogger(GridInfoExtractor.class.getName()).log(Level.SEVERE, null, errorMsg + e);
}
return hostAndPort;
}
@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 shouldBeAbleToConvertACommand() {
SessionId sessionId = new SessionId("some id");
String commandName = "some command";
Map<String, Object> parameters = new HashMap<>();
parameters.put("param1", "value1");
parameters.put("param2", "value2");
Command command = new Command(sessionId, commandName, parameters);
String json = convert(command);
JsonObject converted = new JsonParser().parse(json).getAsJsonObject();
assertThat(converted.has("sessionId")).isTrue();
JsonPrimitive sid = converted.get("sessionId").getAsJsonPrimitive();
assertThat(sid.getAsString()).isEqualTo(sessionId.toString());
assertThat(commandName).isEqualTo(converted.get("name").getAsString());
assertThat(converted.has("parameters")).isTrue();
JsonObject pars = converted.get("parameters").getAsJsonObject();
assertThat(pars.entrySet()).hasSize(2);
assertThat(pars.get("param1").getAsString()).isEqualTo(parameters.get("param1"));
assertThat(pars.get("param2").getAsString()).isEqualTo(parameters.get("param2"));
}
/**
* Get driver by WebElement.
*
* @param sessionId
* - session id to be used for searching a desired driver
*
* @return default WebDriver
*/
public static WebDriver getDriver(SessionId sessionId) {
for (CarinaDriver carinaDriver : driversPool) {
WebDriver drv = carinaDriver.getDriver();
if (drv instanceof EventFiringWebDriver) {
EventFiringWebDriver eventFirDriver = (EventFiringWebDriver) drv;
drv = eventFirDriver.getWrappedDriver();
}
SessionId drvSessionId = ((RemoteWebDriver) drv).getSessionId();
if (drvSessionId != null) {
if (sessionId.equals(drvSessionId)) {
return drv;
}
}
}
throw new DriverPoolException("Unable to find driver using sessionId artifacts. Returning default one!");
}
@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
protected ServicedSession newActiveSession(
DriverService service,
Dialect downstream,
Dialect upstream,
HttpHandler codec,
SessionId id,
Map<String, Object> capabilities) {
return new ServicedSession(
service,
downstream,
upstream,
codec,
id,
capabilities);
}
/**
* This returns the log records storied in the corresponding log file. This does *NOT* clear the
* log records in the file.
*
* @param sessionId session-id for which the file logs needs to be returned.
* @return A List of LogRecord objects, which can be <i>null</i>.
* @throws IOException IO exception can occur with reading the log file
*/
public List<LogRecord> getLogRecords(SessionId sessionId) throws IOException {
LogFile logFile = sessionToLogFileMap.get(sessionId);
if (logFile == null) {
return new ArrayList<>();
}
List<LogRecord> logRecords = new ArrayList<>();
try {
logFile.openLogReader();
ObjectInputStream logObjInStream = logFile.getLogReader();
LogRecord tmpLogRecord;
while (null != (tmpLogRecord = (LogRecord) logObjInStream
.readObject())) {
logRecords.add(tmpLogRecord);
}
} catch (IOException | ClassNotFoundException ex) {
logFile.closeLogReader();
return logRecords;
}
logFile.closeLogReader();
return logRecords;
}
@Test
public void handlesWellFormedAndSuccessfulCrossDomainRpcs()
throws IOException, ServletException {
final SessionId sessionId = createSession();
WebDriver driver = testSessions.get(sessionId).getWrappedDriver();
Map<String, Object> json = ImmutableMap.of(
"method", "POST",
"path", String.format("/session/%s/url", sessionId),
"data", ImmutableMap.of("url", "http://www.google.com"));
FakeHttpServletResponse response = sendCommand("POST", "/xdrpc", json);
verify(driver).get("http://www.google.com");
assertEquals(HttpServletResponse.SC_OK, response.getStatus());
assertEquals("application/json; charset=utf-8",
response.getHeader("content-type"));
Map<String, Object> jsonResponse = this.json.toType(response.getBody(), MAP_TYPE);
assertEquals(ErrorCodes.SUCCESS, ((Number) jsonResponse.get("status")).intValue());
assertEquals(sessionId.toString(), jsonResponse.get("sessionId"));
assertNull(jsonResponse.get("value"));
}
@Test
public void shouldBeAbleToRegisterACustomNode() throws URISyntaxException {
URI sessionUri = new URI("http://example:1234");
Node node = new CustomNode(
bus,
UUID.randomUUID(),
externalUrl.toURI(),
c -> new Session(new SessionId(UUID.randomUUID()), sessionUri, c));
handler.addHandler(node);
distributor.add(node);
wait.until(obj -> distributor.getStatus().hasCapacity());
DistributorStatus.NodeSummary summary = getOnlyElement(distributor.getStatus().getNodes());
assertEquals(1, summary.getStereotypes().get(CAPS).intValue());
}
@Override
public HttpResponse executeWebDriverCommand(HttpRequest req) {
// True enough to be good enough
SessionId id = getSessionId(req.getUri()).map(SessionId::new)
.orElseThrow(() -> new NoSuchSessionException("Cannot find session: " + req));
SessionSlot slot = currentSessions.getIfPresent(id);
if (slot == null) {
throw new NoSuchSessionException("Cannot find session with id: " + id);
}
HttpResponse toReturn = slot.execute(req);
if (req.getMethod() == DELETE && req.getUri().equals("/session/" + id)) {
stop(id);
}
return toReturn;
}
@Test
public void canCreateAJdbcBackedSessionMap() throws URISyntaxException {
SessionMap sessions = getSessionMap();
Session expected = new Session(
new SessionId(UUID.randomUUID()),
new URI("http://example.com/foo"),
new ImmutableCapabilities("key", "value"));
sessions.add(expected);
SessionMap reader = getSessionMap();
Session seen = reader.get(expected.getId());
assertThat(seen).isEqualTo(expected);
}
public AllHandlers(NewSessionPipeline pipeline, ActiveSessions allSessions) {
this.allSessions = Require.nonNull("Active sessions", allSessions);
this.json = new Json();
this.additionalHandlers = ImmutableMap.of(
HttpMethod.DELETE, ImmutableList.of(),
HttpMethod.GET, ImmutableList.of(
handler("/session/{sessionId}/log/types",
params -> new GetLogTypes(json, allSessions.get(new SessionId(params.get("sessionId"))))),
handler("/sessions", params -> new GetAllSessions(allSessions, json)),
handler("/status", params -> new Status(json))
),
HttpMethod.POST, ImmutableList.of(
handler("/session", params -> new BeginSession(pipeline, allSessions, json)),
handler("/session/{sessionId}/file",
params -> new UploadFile(json, allSessions.get(new SessionId(params.get("sessionId"))))),
handler("/session/{sessionId}/log",
params -> new GetLogsOfType(json, allSessions.get(new SessionId(params.get("sessionId"))))),
handler("/session/{sessionId}/se/file",
params -> new UploadFile(json, allSessions.get(new SessionId(params.get("sessionId")))))
));
}
private static void setGridParams(FramesTransparentWebDriver driver) {
try {
SessionId sessionId = ((RemoteWebDriver) driver.getDriver()).getSessionId();
TestParamsHolder.setSessionId(sessionId);
String nodeIp = Configuration.runWithGrid ? new GridApi(new URL(Configuration.gridHubUrl), sessionId).getNodeIp() : InetAddress.getLocalHost().getHostAddress();
TestParamsHolder.setNodeIP(nodeIp);
} catch (Throwable ignored) {
Report.jenkins("Throwable occurs when set node id.", ignored);
}
}
public synchronized void attachToCurrentThread(SessionId sessionId) {
ThreadKey threadId = new ThreadKey();
if (threadToSessionMap.get(threadId) == null
|| threadToSessionMap.get(threadId).equals(sessionId)) {
threadToSessionMap.put(threadId, sessionId);
sessionToThreadMap.put(sessionId, threadId);
}
transferThreadTempLogsToSessionLogs(sessionId);
}
@Test
public void testThreadToSessionMappingOnTwoInitialNullSessions()
throws IOException {
PerSessionLogHandler handler = createPerSessionLogHandler();
LogRecord firstRecord = new LogRecord(Level.INFO, "First Log Record");
LogRecord secondRecord = new LogRecord(Level.INFO, "Second Log Record");
LogRecord anotherRecord = new LogRecord(Level.INFO,
"Another Log Record");
LogRecord oneMoreRecord = new LogRecord(Level.INFO,
"One More Log Record");
SessionId sessionIdOne = new SessionId("session-1");
SessionId sessionIdTwo = new SessionId("session-2");
handler.publish(firstRecord);
handler.attachToCurrentThread(sessionIdOne);
handler.publish(secondRecord);
handler.detachFromCurrentThread();
handler.publish(anotherRecord);
handler.attachToCurrentThread(sessionIdTwo);
handler.publish(oneMoreRecord);
assertMessagesLoggedForSessionId(handler, sessionIdOne,
firstRecord.getMessage(), "Second Log Record");
assertMessagesLoggedForSessionId(handler, sessionIdTwo,
"Another Log Record", "One More Log Record");
}
/**
* This returns Selenium Remote Control logs associated with the sessionId.
*
* @param sessionId session-id for which the RC logs will be returned.
* @return String RC logs for the sessionId
* @throws IOException when the elves go bad
*/
public synchronized String getLog(SessionId sessionId) throws IOException {
// TODO(chandra): Provide option to clear logs after getLog()
String logs = formattedRecords(sessionId);
logs = "\n<RC_Logs RC_Session_ID=" + sessionId + ">\n" + logs
+ "\n</RC_Logs>\n";
return logs;
}
private void singleTestExcution(WebDriver driver, int index) {
driver.get("https://en.wikipedia.org/wiki/Main_Page");
String title = driver.getTitle();
assertTrue(title.equals("Wikipedia, the free encyclopedia"));
SessionId sessionId = ((RemoteWebDriver) driver).getSessionId();
System.out.println(index + " -- " + sessionId + " -- " + title);
}
@Test
public void shouldReturnNullWhenSessionIsNotPresent() {
ActiveSessions sessions = new ActiveSessions(10, MINUTES);
ActiveSession session = sessions.get(new SessionId("1234567890"));
assertNull(session);
}
@Test
public void shouldBeAbleToConvertASelenium3CommandToASelenium2Command() {
SessionId expectedId = new SessionId("thisisakey");
// In selenium 2, the sessionId is an object. In selenium 3, it's a straight string.
String raw = "{\"sessionId\": \"" + expectedId.toString() + "\", " +
"\"name\": \"some command\"," +
"\"parameters\": {}}";
Command converted = new Json().toType(raw, Command.class);
assertThat(converted.getSessionId()).isEqualTo(expectedId);
}
@Test
public void shouldAddScreenshotIfPresent() {
Response response = Responses.failure(
new SessionId("cheese"),
new RuntimeException("boo"),
Optional.of("hello"));
System.out.println("response = " + response);
}
@Override
public List<SessionInfo> handle() {
Set<SessionId> sessions = allSessions.getSessions();
List<SessionInfo> sessionInfo =
sessions.stream().map(id -> new SessionInfo(id, allSessions.get(id).getCapabilities()))
.collect(Collectors.toList());
return ImmutableList.copyOf(sessionInfo);
}
@Override
public void stop(SessionId id) throws NoSuchSessionException {
Require.nonNull("Session ID", id);
HttpRequest req = new HttpRequest(DELETE, "/se/grid/node/session/" + id);
HttpTracing.inject(tracer, tracer.getCurrentContext(), req);
HttpResponse res = client.execute(req);
Values.get(res, Void.class);
}
@Test
public void canExtractSessionIdFromPathParameters() {
HttpRequest request = new HttpRequest(GET, "/foo/bar/baz");
codec.defineCommand("foo", GET, "/foo/:sessionId/baz");
Command decoded = codec.decode(request);
assertThat(decoded.getSessionId()).isEqualTo(new SessionId("bar"));
}
@Test
public void testShouldNotCopyThreadTempLogsToSessionLogsIfNoLogRecordForThreadPresent()
throws IOException {
PerSessionLogHandler handler = createPerSessionLogHandler();
SessionId sessionId = new SessionId("session");
handler.transferThreadTempLogsToSessionLogs(sessionId);
assertNoMessageLoggedForSessionId(handler, sessionId);
}
@Test
public void testPopulationOfSessionLog() throws IOException {
PerSessionLogHandler handler = createPerSessionLogHandler();
SessionId sessionId = new SessionId("session-1");
handler.attachToCurrentThread(sessionId);
LogRecord firstRecord = new LogRecord(Level.INFO, "First Log Record");
handler.publish(firstRecord);
LogEntries entries = handler.getSessionLog(sessionId);
assertEquals("Session log should contain one entry", 1, entries.getAll().size());
assertEquals("Session log should contain logged entry",
firstRecord.getMessage(), entries.getAll().get(0).getMessage());
}
/**
* Gets all logs for a session.
*
* @param sessionId The id of the session.
* @return The logs for the session, ordered after log types in a session logs object.
*/
public synchronized SessionLogs getAllLogsForSession(SessionId sessionId) {
SessionLogs sessionLogs = new SessionLogs();
if (perSessionDriverEntries.containsKey(sessionId)) {
Map<String, LogEntries> typeToEntriesMap = perSessionDriverEntries.get(sessionId);
for (String logType : typeToEntriesMap.keySet()) {
sessionLogs.addLog(logType, typeToEntriesMap.get(logType));
}
perSessionDriverEntries.remove(sessionId);
}
return sessionLogs;
}
DockerSession(
Container container,
Tracer tracer,
HttpClient client,
SessionId id,
URL url,
Capabilities capabilities,
Dialect downstream,
Dialect upstream) {
super(tracer, client, id, url, downstream, upstream, capabilities);
this.container = Require.nonNull("Container", container);
}