下面列出了怎么用org.openqa.selenium.NoSuchSessionException的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public byte[] captureScreen() {
if (driver == null) {
return null;
}
if (!(driver instanceof TakesScreenshot)) {
return null;
}
try {
return ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.BYTES);
} catch (NoSuchSessionException e) {
// just do nothing if WebDriver instance is in invalid state
return null;
}
// TODO test should not fail when taking screen capture fails?
}
@Override
public byte[] captureScreen() {
if (fluent == null) {
return null;
}
WebDriver driver = fluent.getDriver();
if (driver == null) {
return null;
}
if (!(driver instanceof TakesScreenshot)) {
return null;
}
try {
return ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.BYTES);
} catch (NoSuchSessionException e) {
// just do nothing if WebDriver instance is in invalid state
return null;
}
}
@Override
public Session get(SessionId id) {
Require.nonNull("Session ID", id);
Lock readLock = lock.readLock();
readLock.lock();
try {
Session session = knownSessions.get(id);
if (session == null) {
throw new NoSuchSessionException("Unable to find session with ID: " + id);
}
return session;
} finally {
readLock.unlock();
}
}
@Override
public URI getUri(SessionId id) throws NoSuchSessionException {
Require.nonNull("Session ID", id);
RedisCommands<String, String> commands = connection.sync();
List<KeyValue<String, String>> rawValues = commands.mget(uriKey(id), capabilitiesKey(id));
String rawUri = rawValues.get(0).getValueOrElse(null);
if (rawUri == null) {
throw new NoSuchSessionException("Unable to find URI for session " + id);
}
try {
return new URI(rawUri);
} catch (URISyntaxException e) {
throw new NoSuchSessionException(String.format("Unable to convert session id (%s) to uri: %s", id, rawUri), e);
}
}
@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;
}
@Override
public void stop(SessionId id) throws NoSuchSessionException {
LOG.info("Stop has been called: " + id);
Require.nonNull("Session ID", id);
if (!isSessionOwner(id)) {
throw new NoSuchSessionException("Unable to find session " + id);
}
LOG.info("Quitting session " + id);
try {
driver.quit();
} catch (Exception e) {
// It's possible that the driver has already quit.
}
events.fire(new SessionClosedEvent(id));
LOG.info("Firing node drain complete message");
events.fire(new NodeDrainComplete(getId()));
}
@Override
public Optional<Consumer<Message>> apply(String uri, Consumer<Message> downstream) {
Objects.requireNonNull(uri);
Objects.requireNonNull(downstream);
Optional<SessionId> sessionId = HttpSessionId.getSessionId(uri).map(SessionId::new);
if (!sessionId.isPresent()) {
return Optional.empty();
}
try {
Session session = sessions.get(sessionId.get());
HttpClient client = clientFactory.createClient(ClientConfig.defaultConfig().baseUri(session.getUri()));
WebSocket upstream = client.openSocket(new HttpRequest(GET, uri), new ForwardingListener(downstream));
return Optional.of(upstream::send);
} catch (NoSuchSessionException e) {
LOG.info("Attempt to connect to non-existant session: " + uri);
return Optional.empty();
}
}
@Test
public void shouldAllowEntriesToBeRemovedByAMessage() {
local.add(expected);
bus.fire(new SessionClosedEvent(expected.getId()));
Wait<SessionMap> wait = new FluentWait<>(local).withTimeout(ofSeconds(2));
wait.until(sessions -> {
try {
sessions.get(expected.getId());
return false;
} catch (NoSuchSessionException e) {
return true;
}
});
}
@Test
public void shouldBeAbleToRemoveSessions() 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();
reader.remove(expected.getId());
try {
reader.get(expected.getId());
fail("Oh noes!");
} catch (NoSuchSessionException ignored) {
// This is expected
}
}
@Test
public void shouldBeAbleToRemoveSessions() throws URISyntaxException {
SessionMap sessions = new RedisBackedSessionMap(tracer, uri);
Session expected = new Session(
new SessionId(UUID.randomUUID()),
new URI("http://example.com/foo"),
new ImmutableCapabilities("cheese", "beyaz peynir"));
sessions.add(expected);
SessionMap reader = new RedisBackedSessionMap(tracer, uri);
reader.remove(expected.getId());
try {
reader.get(expected.getId());
fail("Oh noes!");
} catch (NoSuchSessionException ignored) {
// This is expected
}
}
@Test
public void aSessionThatTimesOutWillBeStoppedAndRemovedFromTheSessionMap() {
AtomicReference<Instant> now = new AtomicReference<>(Instant.now());
Clock clock = new MyClock(now);
Node node = LocalNode.builder(tracer, bus, uri, uri, null)
.add(caps, new TestSessionFactory((id, c) -> new Session(id, uri, c)))
.sessionTimeout(Duration.ofMinutes(3))
.advanced()
.clock(clock)
.build();
Session session = node.newSession(createSessionRequest(caps))
.map(CreateSessionResponse::getSession)
.orElseThrow(() -> new RuntimeException("Session not created"));
now.set(now.get().plus(Duration.ofMinutes(5)));
assertThatExceptionOfType(NoSuchSessionException.class)
.isThrownBy(() -> node.getSession(session.getId()));
}
/**
* Same as {@link #loadPageWithAlerts2(String)}... but doesn't verify the alerts.
* @param html the HTML to use
* @param url the url to use to load the page
* @param contentType the content type to return
* @param charset the charset
* @param serverCharset the charset at the server side.
* @return the web driver
* @throws Exception if something goes wrong
*/
protected final WebDriver loadPage2(String html, final URL url,
final String contentType, final Charset charset, final Charset serverCharset) throws Exception {
if (useStandards_ != null) {
if (html.startsWith(HtmlPageTest.STANDARDS_MODE_PREFIX_)) {
fail("HTML must not be prefixed with Standards Mode.");
}
if (useStandards_) {
html = HtmlPageTest.STANDARDS_MODE_PREFIX_ + html;
}
}
final MockWebConnection mockWebConnection = getMockWebConnection();
mockWebConnection.setResponse(url, html, contentType, charset);
startWebServer(mockWebConnection, serverCharset);
WebDriver driver = getWebDriver();
if (!(driver instanceof HtmlUnitDriver)) {
try {
resizeIfNeeded(driver);
}
catch (final NoSuchSessionException e) {
// maybe the driver was killed by the test before; setup a new one
shutDownRealBrowsers();
driver = getWebDriver();
resizeIfNeeded(driver);
}
}
driver.get(url.toExternalForm());
return driver;
}
/**
* Same as {@link #loadPage2(String, URL)}, but with additional servlet configuration.
* @param html the HTML to use for the default page
* @param url the URL to use to load the page
* @param servlets the additional servlets to configure with their mapping
* @return the web driver
* @throws Exception if something goes wrong
*/
protected final WebDriver loadPage2(final String html, final URL url,
final Map<String, Class<? extends Servlet>> servlets) throws Exception {
servlets.put("/*", MockWebConnectionServlet.class);
getMockWebConnection().setResponse(url, html);
MockWebConnectionServlet.MockConnection_ = getMockWebConnection();
startWebServer("./", null, servlets);
WebDriver driver = getWebDriver();
if (!(driver instanceof HtmlUnitDriver)) {
try {
resizeIfNeeded(driver);
}
catch (final NoSuchSessionException e) {
// maybe the driver was killed by the test before; setup a new one
shutDownRealBrowsers();
driver = getWebDriver();
resizeIfNeeded(driver);
}
}
driver.get(url.toExternalForm());
return driver;
}
private <R> R getValue(final String message, final Function<MobileElement, R> func) {
log.info(message, this.name);
try {
return func.apply(this.element);
} catch (final NoSuchSessionException e) {
fail(AppiumServerStoppedError.class, SERVER_STOPPED, e);
}
return null;
}
private void perform(final String action, final Consumer<MobileElement> consumer) {
checkElementEnabled();
log.info("{} element [{}]...", action, this.name);
try {
consumer.accept(this.element);
} catch (final NoSuchSessionException e) {
fail(AppiumServerStoppedError.class, SERVER_STOPPED, e);
}
}
private void captureScreenshot(final String path) {
LOG.info("Capturing screenshot and saving at [{}]...", path);
try {
final File srcFiler = this.driver.getScreenshotAs(OutputType.FILE);
copyFile(srcFiler, path);
} catch (final NoSuchSessionException e) {
fail(AppiumServerStoppedError.class, SERVER_STOPPED, e);
}
}
/**
* @author wasiqb
* @since Oct 20, 2018
*/
public void hideKeyboard() {
LOG.info("Hiding the keyboard...");
try {
if (this.driver.isKeyboardShown()) {
this.driver.hideKeyboard();
}
} catch (final NoSuchSessionException e) {
fail(AppiumServerStoppedError.class, SERVER_STOPPED, e);
}
}
private <T> T getValue(final String message, final Function<AndroidDriver<MobileElement>, T> action,
final Object... args) {
LOG.info(message, args);
try {
return action.apply(this.driver);
} catch (final NoSuchSessionException e) {
fail(AppiumServerStoppedError.class, SERVER_STOPPED, e);
}
return null;
}
private void perform(final String message, final Consumer<AndroidDriver<MobileElement>> action,
final Object... args) {
LOG.info(message, args);
try {
action.accept(this.driver);
} catch (final NoSuchSessionException e) {
fail(AppiumServerStoppedError.class, SERVER_STOPPED, e);
}
}
/**
* @param strategy
* @param keyName
* @author wasiq.bhamla
* @since 08-May-2017 3:21:20 PM
*/
public void hideKeyboard(final String strategy, final String keyName) {
log.info("Hiding keyboard on device using %s strategy for key {}...", strategy, keyName);
try {
if (this.driver.isKeyboardShown()) {
this.driver.hideKeyboard(strategy, keyName);
}
} catch (final NoSuchSessionException e) {
fail(AppiumServerStoppedError.class, SERVER_STOPPED, e);
}
}
/**
* @author wasiq.bhamla
* @since 26-Apr-2017 11:37:04 PM
*/
public void shake() {
log.info("Shaking the device...");
try {
this.driver.shake();
} catch (final NoSuchSessionException e) {
fail(AppiumServerStoppedError.class, SERVER_STOPPED, e);
}
}
/**
* Wrapper for interacting with a targeted driver that may or may not actually be present.
*/
private void attempt(Runnable action) {
try {
action.run();
} catch (NoSuchFrameException | NoSuchWindowException | NoSuchSessionException e) {
throw new FindableNotPresentException(this, e);
}
}
/**
* Wrapper for interacting with a targeted driver that may or may not actually be present.
* Returns a result.
*/
private <T> T attemptAndGet(Supplier<T> action) {
try {
return action.get();
} catch (NoSuchFrameException | NoSuchWindowException | NoSuchSessionException e) {
throw new FindableNotPresentException(this, e);
}
}
@Override
public Session get(SessionId id) throws NoSuchSessionException {
Require.nonNull("Session ID", id);
URI uri = getUri(id);
RedisCommands<String, String> commands = connection.sync();
String rawCapabilities = commands.get(capabilitiesKey(id));
Capabilities caps = rawCapabilities == null ?
new ImmutableCapabilities() :
JSON.toType(rawCapabilities, Capabilities.class);
return new Session(id, uri, caps);
}
@Override
public Session get(SessionId id) {
Require.nonNull("Session ID", id);
Session session = makeRequest(new HttpRequest(GET, "/se/grid/session/" + id), Session.class);
if (session == null) {
throw new NoSuchSessionException("Unable to find session with ID: " + id);
}
return session;
}
@Override
public URI getUri(SessionId id) throws NoSuchSessionException {
Require.nonNull("Session ID", id);
URI value = makeRequest(new HttpRequest(GET, "/se/grid/session/" + id + "/uri"), URI.class);
if (value == null) {
throw new NoSuchSessionException("Unable to find session with ID: " + id);
}
return value;
}
@Override
public Session getSession(SessionId id) throws NoSuchSessionException {
Require.nonNull("Session ID", id);
SessionSlot slot = currentSessions.getIfPresent(id);
if (slot == null) {
throw new NoSuchSessionException("Cannot find session with id: " + id);
}
return createExternalSession(slot.getSession(), externalUri);
}
@Override
public void stop(SessionId id) throws NoSuchSessionException {
Require.nonNull("Session ID", id);
SessionSlot slot = currentSessions.getIfPresent(id);
if (slot == null) {
throw new NoSuchSessionException("Cannot find session with id: " + id);
}
killSession(slot);
tempFileSystems.invalidate(id);
}
public ActiveSession getSession() {
if (isAvailable()) {
throw new NoSuchSessionException("Session is not running");
}
return currentSession;
}
@Override
public HttpResponse execute(HttpRequest req) throws UncheckedIOException {
if (currentSession == null) {
throw new NoSuchSessionException("No session currently running: " + req.getUri());
}
return currentSession.execute(req);
}