Java Code Examples for org.openqa.selenium.SessionNotCreatedException

The following examples show how to use org.openqa.selenium.SessionNotCreatedException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: marathonv5   Source File: JavaDriverTest.java    License: Apache License 2.0 6 votes vote down vote up
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) {
    }
}
 
Example 2
Source Project: hsac-fitnesse-fixtures   Source File: DriverManager.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 3
Source Project: java-client   Source File: AppIOSTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 4
Source Project: selenium   Source File: JsonWireProtocolResponseTest.java    License: Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example 5
Source Project: selenium   Source File: W3CHandshakeResponseTest.java    License: Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example 6
Source Project: selenium   Source File: Slot.java    License: Apache License 2.0 6 votes vote down vote up
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;
    }
  };
}
 
Example 7
Source Project: selenium   Source File: Host.java    License: Apache License 2.0 6 votes vote down vote up
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();
  }
}
 
Example 8
Source Project: selenium   Source File: DistributorTest.java    License: Apache License 2.0 6 votes vote down vote up
@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)));
  }
}
 
Example 9
Source Project: jmeter-plugins-webdriver   Source File: WebDriverConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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.");
        }
    }
}
 
Example 10
@Test
public void shouldHandleScenarioWhenBrowserHasAlreadyQuit() {
    doThrow(new SessionNotCreatedException("Session not created")).when(browser).quit();

    config.quitBrowser(browser);

    verify(browser, times(1)).quit();
}
 
Example 11
Source Project: marathonv5   Source File: JavaDriverTest.java    License: Apache License 2.0 5 votes vote down vote up
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) {
    }
}
 
Example 12
Source Project: marathonv5   Source File: JavaDriverTest.java    License: Apache License 2.0 5 votes vote down vote up
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) {
    }
}
 
Example 13
Source Project: hsac-fitnesse-fixtures   Source File: DriverManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 14
Source Project: java-client   Source File: IOSElementGenerationTest.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 15
Source Project: selenium   Source File: GeckoDriverInfo.java    License: Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example 16
Source Project: selenium   Source File: XpiDriverInfo.java    License: Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example 17
Source Project: selenium   Source File: OperaDriverInfo.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Optional<WebDriver> createDriver(Capabilities capabilities)
    throws SessionNotCreatedException {
  if (!isAvailable()) {
    return Optional.empty();
  }

  return Optional.of(new OperaDriver(capabilities));
}
 
Example 18
Source Project: selenium   Source File: EdgeHtmlDriverInfo.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Optional<WebDriver> createDriver(Capabilities capabilities)
    throws SessionNotCreatedException {
  if (!isAvailable()) {
    return Optional.empty();
  }

  return Optional.of(new EdgeHtmlDriver(new EdgeHtmlOptions().merge(capabilities)));
}
 
Example 19
Source Project: selenium   Source File: ChromeDriverInfo.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 20
Source Project: selenium   Source File: EdgeDriverInfo.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Optional<WebDriver> createDriver(Capabilities capabilities)
    throws SessionNotCreatedException {
  if (!isAvailable() || !isSupporting(capabilities)) {
    return Optional.empty();
  }

  return Optional.of(new EdgeDriver(capabilities));
}
 
Example 21
Source Project: selenium   Source File: SafariDriverInfo.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Optional<WebDriver> createDriver(Capabilities capabilities)
    throws SessionNotCreatedException {
  if (!isAvailable()) {
    return Optional.empty();
  }

  return Optional.of(new SafariDriver(capabilities));
}
 
Example 22
Source Project: selenium   Source File: SafariTechPreviewDriverInfo.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Optional<WebDriver> createDriver(Capabilities capabilities)
    throws SessionNotCreatedException {
  if (!isAvailable()) {
    return Optional.empty();
  }

  return Optional.of(new SafariDriver(capabilities));
}
 
Example 23
Source Project: selenium   Source File: ChromiumOptions.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 24
Source Project: selenium   Source File: InternetExplorerDriverInfo.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Optional<WebDriver> createDriver(Capabilities capabilities)
    throws SessionNotCreatedException {
  if (!isAvailable()) {
    return Optional.empty();
  }

  return Optional.of(new InternetExplorerDriver(capabilities));
}
 
Example 25
Source Project: selenium   Source File: ProtocolHandshake.java    License: Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 26
Source Project: selenium   Source File: RemoteWebDriverBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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());
}
 
Example 27
Source Project: selenium   Source File: DockerSessionFactory.java    License: Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 28
Source Project: selenium   Source File: RemoteDistributor.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 29
Source Project: selenium   Source File: NewSessionPipeline.java    License: Apache License 2.0 5 votes vote down vote up
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))
      );
}
 
Example 30
Source Project: selenium   Source File: DistributorTest.java    License: Apache License 2.0 5 votes vote down vote up
@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)));
  }
}