下面列出了怎么用org.openqa.selenium.SessionNotCreatedException的API类实例代码及写法,或者点击链接到github查看源代码。
public void failsWhenRequestingNonCurrentPlatform() throws Throwable {
Platform[] values = Platform.values();
Platform otherPlatform = null;
for (Platform platform : values) {
if (Platform.getCurrent().is(platform)) {
continue;
}
otherPlatform = platform;
break;
}
DesiredCapabilities caps = new DesiredCapabilities("java", "1.0", otherPlatform);
try {
driver = new JavaDriver(caps, caps);
throw new MissingException(SessionNotCreatedException.class);
} catch (SessionNotCreatedException e) {
}
}
public SeleniumHelper getSeleniumHelper() {
if (helper == null) {
DriverFactory currentFactory = getFactory();
if (currentFactory == null) {
throw new StopTestException("Cannot use Selenium before configuring how to start a driver (for instance using SeleniumDriverSetup)");
} else {
try {
WebDriver driver = currentFactory.createDriver();
postProcessDriver(driver);
SeleniumHelper newHelper = createHelper(driver);
newHelper.setWebDriver(driver, getDefaultTimeoutSeconds());
setSeleniumHelper(newHelper);
} catch (SessionNotCreatedException e) {
throw new StopTestException(e.getMessage(), e);
}
}
}
return helper;
}
@BeforeClass
public static void beforeClass() throws Exception {
final String ip = startAppiumServer();
if (service == null || !service.isRunning()) {
throw new AppiumServerHasNotBeenStartedLocallyException("An appium server node is not started!");
}
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, PLATFORM_VERSION);
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, DEVICE_NAME);
capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.IOS_XCUI_TEST);
//sometimes environment has performance problems
capabilities.setCapability(IOSMobileCapabilityType.LAUNCH_TIMEOUT, 500000);
capabilities.setCapability("commandTimeouts", "120000");
capabilities.setCapability(MobileCapabilityType.APP, testAppZip().toAbsolutePath().toString());
try {
driver = new IOSDriver<>(new URL("http://" + ip + ":" + PORT + "/wd/hub"), capabilities);
} catch (SessionNotCreatedException e) {
capabilities.setCapability("useNewWDA", true);
driver = new IOSDriver<>(new URL("http://" + ip + ":" + PORT + "/wd/hub"), capabilities);
}
}
@Test
public void shouldProperlyPopulateAnError() {
WebDriverException exception = new SessionNotCreatedException("me no likey");
Json json = new Json();
Map<String, Object> payload = ImmutableMap.of(
"value", json.toType(json.toJson(exception), Json.MAP_TYPE),
"status", ErrorCodes.SESSION_NOT_CREATED);
InitialHandshakeResponse initialResponse = new InitialHandshakeResponse(
0,
500,
payload);
assertThatExceptionOfType(SessionNotCreatedException.class)
.isThrownBy(() -> new JsonWireProtocolResponse().getResponseFunction().apply(initialResponse))
.withMessageContaining("me no likey");
}
@Test
public void shouldProperlyPopulateAnError() {
Map<String, ?> payload = ImmutableMap.of(
"value", ImmutableMap.of(
"error", "session not created",
"message", "me no likey",
"stacktrace", "I have no idea what went wrong"));
InitialHandshakeResponse initialResponse = new InitialHandshakeResponse(
0,
500,
payload);
assertThatExceptionOfType(SessionNotCreatedException.class)
.isThrownBy(() -> new W3CHandshakeResponse().getResponseFunction().apply(initialResponse))
.withMessageContaining("me no likey")
.satisfies(e -> assertThat(e.getAdditionalInformation()).contains("I have no idea what went wrong"));
}
public Supplier<CreateSessionResponse> onReserve(CreateSessionRequest sessionRequest) {
if (getStatus() != AVAILABLE) {
throw new IllegalStateException("Node is not available");
}
currentStatus = RESERVED;
return () -> {
try {
CreateSessionResponse sessionResponse = node.newSession(sessionRequest)
.orElseThrow(
() -> new SessionNotCreatedException(
"Unable to create session for " + sessionRequest));
onStart(sessionResponse.getSession());
return sessionResponse;
} catch (Throwable t) {
currentStatus = AVAILABLE;
currentSession = null;
throw t;
}
};
}
public Supplier<CreateSessionResponse> reserve(CreateSessionRequest sessionRequest) {
Require.nonNull("Session creation request", sessionRequest);
Lock write = lock.writeLock();
write.lock();
try {
Slot toReturn = slots.stream()
.filter(slot -> slot.isSupporting(sessionRequest.getCapabilities()))
.filter(slot -> slot.getStatus() == AVAILABLE)
.findFirst()
.orElseThrow(() -> new SessionNotCreatedException("Unable to reserve an instance"));
return toReturn.onReserve(sessionRequest);
} finally {
write.unlock();
}
}
@Test
public void shouldNotStartASessionIfTheCapabilitiesAreNotSupported() {
CombinedHandler handler = new CombinedHandler();
LocalSessionMap sessions = new LocalSessionMap(tracer, bus);
handler.addHandler(handler);
Distributor distributor = new LocalDistributor(
tracer,
bus,
new PassthroughHttpClient.Factory(handler),
sessions,
null);
handler.addHandler(distributor);
Node node = createNode(caps, 1, 0);
handler.addHandler(node);
distributor.add(node);
ImmutableCapabilities unmatched = new ImmutableCapabilities("browserName", "transit of venus");
try (NewSessionPayload payload = NewSessionPayload.create(unmatched)) {
assertThatExceptionOfType(SessionNotCreatedException.class)
.isThrownBy(() -> distributor.newSession(createRequest(payload)));
}
}
/**
* Quits browser at the end of the tests. This will be envoked per thread/browser instance created.
*
* @param browser is the browser instance to quit. Will not quit if argument is null.
*/
protected void quitBrowser(final T browser) {
if (browser != null) {
try {
browser.quit();
} catch (SessionNotCreatedException e) {
LOGGER.warn("Attempting to quit browser instance that has already exited.");
}
}
}
@Test
public void shouldHandleScenarioWhenBrowserHasAlreadyQuit() {
doThrow(new SessionNotCreatedException("Session not created")).when(browser).quit();
config.quitBrowser(browser);
verify(browser, times(1)).quit();
}
public void failsWhenRequestingANonJavaDriver() throws Throwable {
DesiredCapabilities caps = new DesiredCapabilities("xjava", "1.0", Platform.getCurrent());
try {
driver = new JavaDriver(caps, caps);
throw new MissingException(SessionNotCreatedException.class);
} catch (SessionNotCreatedException e) {
}
}
public void failsWhenRequestingUnsupportedCapability() throws Throwable {
DesiredCapabilities caps = new DesiredCapabilities("java", "1.0", Platform.getCurrent());
caps.setCapability("rotatable", true);
try {
driver = new JavaDriver(caps, caps);
throw new MissingException(SessionNotCreatedException.class);
} catch (SessionNotCreatedException e) {
}
}
@Test
public void ifCreateDriverThrowsAnExceptionTheExceptionIsRethrownAsStopTestException() {
String message = "driver is not compatible!";
expectedEx.expect(StopTestException.class);
expectedEx.expectMessage(message);
when(driverFactory.createDriver()).thenThrow(new SessionNotCreatedException(message));
driverManager.getSeleniumHelper();
}
private boolean check(Supplier<Capabilities> capabilitiesSupplier,
BiPredicate<By, Class<? extends WebElement>> filter,
By by) {
service = AppiumDriverLocalService.buildDefaultService();
Capabilities caps = capabilitiesSupplier.get();
DesiredCapabilities fixedCaps = new DesiredCapabilities(caps);
fixedCaps.setCapability("commandTimeouts", "120000");
try {
driver = new AppiumDriver<>(service, fixedCaps);
} catch (SessionNotCreatedException e) {
fixedCaps.setCapability("useNewWDA", true);
driver = new AppiumDriver<>(service, fixedCaps);
}
return filter.test(by, IOSElement.class);
}
@Override
public Optional<WebDriver> createDriver(Capabilities capabilities)
throws SessionNotCreatedException {
if (!isAvailable()) {
return Optional.empty();
}
if (capabilities.is(MARIONETTE)) {
return Optional.empty();
}
return Optional.of(new FirefoxDriver(capabilities));
}
@Override
public Optional<WebDriver> createDriver(Capabilities capabilities)
throws SessionNotCreatedException {
if (!isAvailable()) {
return Optional.empty();
}
if (!capabilities.is(MARIONETTE)) {
return Optional.empty();
}
return Optional.of(new FirefoxDriver(capabilities));
}
@Override
public Optional<WebDriver> createDriver(Capabilities capabilities)
throws SessionNotCreatedException {
if (!isAvailable()) {
return Optional.empty();
}
return Optional.of(new OperaDriver(capabilities));
}
@Override
public Optional<WebDriver> createDriver(Capabilities capabilities)
throws SessionNotCreatedException {
if (!isAvailable()) {
return Optional.empty();
}
return Optional.of(new EdgeHtmlDriver(new EdgeHtmlOptions().merge(capabilities)));
}
@Override
public Optional<WebDriver> createDriver(Capabilities capabilities)
throws SessionNotCreatedException {
if (!isAvailable() || !isSupporting(capabilities)) {
return Optional.empty();
}
WebDriver driver = new ChromeDriver(capabilities);
return Optional.of(driver);
}
@Override
public Optional<WebDriver> createDriver(Capabilities capabilities)
throws SessionNotCreatedException {
if (!isAvailable() || !isSupporting(capabilities)) {
return Optional.empty();
}
return Optional.of(new EdgeDriver(capabilities));
}
@Override
public Optional<WebDriver> createDriver(Capabilities capabilities)
throws SessionNotCreatedException {
if (!isAvailable()) {
return Optional.empty();
}
return Optional.of(new SafariDriver(capabilities));
}
@Override
public Optional<WebDriver> createDriver(Capabilities capabilities)
throws SessionNotCreatedException {
if (!isAvailable()) {
return Optional.empty();
}
return Optional.of(new SafariDriver(capabilities));
}
@Override
public Map<String, Object> asMap() {
Map<String, Object> toReturn = new TreeMap<>(super.asMap());
Map<String, Object> options = new TreeMap<>();
experimentalOptions.forEach(options::put);
if (binary != null) {
options.put("binary", binary);
}
options.put("args", unmodifiableList(new ArrayList<>(args)));
options.put(
"extensions",
unmodifiableList(Stream.concat(
extensionFiles.stream()
.map(file -> {
try {
return Base64.getEncoder().encodeToString(Files.readAllBytes(file.toPath()));
} catch (IOException e) {
throw new SessionNotCreatedException(e.getMessage(), e);
}
}),
extensions.stream()
).collect(toList())));
toReturn.put(CAPABILITY, unmodifiableMap(options));
return unmodifiableMap(toReturn);
}
@Override
public Optional<WebDriver> createDriver(Capabilities capabilities)
throws SessionNotCreatedException {
if (!isAvailable()) {
return Optional.empty();
}
return Optional.of(new InternetExplorerDriver(capabilities));
}
public Result createSession(HttpClient client, Command command)
throws IOException {
Capabilities desired = (Capabilities) command.getParameters().get("desiredCapabilities");
desired = desired == null ? new ImmutableCapabilities() : desired;
int threshold = (int) Math.min(Runtime.getRuntime().freeMemory() / 10, Integer.MAX_VALUE);
FileBackedOutputStream os = new FileBackedOutputStream(threshold);
try (
CountingOutputStream counter = new CountingOutputStream(os);
Writer writer = new OutputStreamWriter(counter, UTF_8);
NewSessionPayload payload = NewSessionPayload.create(desired)) {
payload.writeTo(writer);
try (InputStream rawIn = os.asByteSource().openBufferedStream();
BufferedInputStream contentStream = new BufferedInputStream(rawIn)) {
Optional<Result> result = createSession(client, contentStream, counter.getCount());
if (result.isPresent()) {
Result toReturn = result.get();
LOG.info(String.format("Detected dialect: %s", toReturn.dialect));
return toReturn;
}
}
} finally {
os.reset();
}
throw new SessionNotCreatedException(
String.format(
"Unable to create new remote session. " +
"desired capabilities = %s",
desired));
}
/**
* Actually create a new WebDriver session. The returned webdriver is not guaranteed to be a
* {@link RemoteWebDriver}.
*/
public WebDriver build() {
if (options.isEmpty() && additionalCapabilities.isEmpty()) {
throw new SessionNotCreatedException("Refusing to create session without any capabilities");
}
Plan plan = getPlan();
CommandExecutor executor;
if (plan.isUsingDriverService()) {
AtomicReference<DriverService> serviceRef = new AtomicReference<>();
executor = new SpecCompliantExecutor(
() -> {
if (serviceRef.get() != null && serviceRef.get().isRunning()) {
throw new SessionNotCreatedException(
"Attempt to start the underlying service more than once");
}
try {
DriverService service = plan.getDriverService();
serviceRef.set(service);
service.start();
return service.getUrl();
} catch (IOException e) {
throw new SessionNotCreatedException(e.getMessage(), e);
}
},
plan::writePayload,
() -> serviceRef.get().stop());
} else {
executor = new SpecCompliantExecutor(() -> remoteHost, plan::writePayload, () -> {});
}
return new RemoteWebDriver(executor, new ImmutableCapabilities());
}
private URL getUrl(int port) {
try {
return new URL(String.format("http://localhost:%s/wd/hub", port));
} catch (MalformedURLException e) {
throw new SessionNotCreatedException(e.getMessage(), e);
}
}
@Override
public CreateSessionResponse newSession(HttpRequest request)
throws SessionNotCreatedException {
HttpRequest upstream = new HttpRequest(POST, "/se/grid/distributor/session");
HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);
upstream.setContent(request.getContent());
HttpResponse response = client.execute(upstream);
return Values.get(response, CreateSessionResponse.class);
}
public ActiveSession createNewSession(NewSessionPayload payload) {
return payload.stream()
.map(caps -> {
for (Function<Capabilities, Capabilities> mutator : mutators) {
caps = mutator.apply(caps);
}
return caps;
})
.map(caps -> factories.stream()
.filter(factory -> factory.test(caps))
.map(factory -> factory.apply(
new CreateSessionRequest(
payload.getDownstreamDialects(),
caps,
ImmutableMap.of())))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst())
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst()
.orElseGet(
() -> fallback.apply(
new CreateSessionRequest(
payload.getDownstreamDialects(),
new ImmutableCapabilities(),
ImmutableMap.of()))
.orElseThrow(
() -> new SessionNotCreatedException(
"Unable to create session from " + payload))
);
}
@Test
public void creatingANewSessionWithoutANodeEndsInFailure() throws MalformedURLException {
Distributor distributor = new RemoteDistributor(
tracer,
new PassthroughHttpClient.Factory(local),
new URL("http://does.not.exist/"));
try (NewSessionPayload payload = NewSessionPayload.create(caps)) {
assertThatExceptionOfType(SessionNotCreatedException.class)
.isThrownBy(() -> distributor.newSession(createRequest(payload)));
}
}