org.openqa.selenium.SessionNotCreatedException Java Examples

The following examples show how to use org.openqa.selenium.SessionNotCreatedException. 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 File: JavaDriverTest.java    From marathonv5 with 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 File: JsonWireProtocolResponseTest.java    From selenium with 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 #3
Source File: DistributorTest.java    From selenium with 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 #4
Source File: DriverManager.java    From hsac-fitnesse-fixtures with 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 #5
Source File: W3CHandshakeResponseTest.java    From selenium with 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 File: AppIOSTest.java    From java-client with 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 #7
Source File: Slot.java    From selenium with 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 #8
Source File: Host.java    From selenium with 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 #9
Source File: DistributorTest.java    From selenium with 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)));
  }
}
 
Example #10
Source File: ProtocolHandshake.java    From selenium with 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 #11
Source File: RemoteWebDriverBuilder.java    From selenium with 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 #12
Source File: DockerSessionFactory.java    From selenium with 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 #13
Source File: RemoteDistributor.java    From selenium with 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 #14
Source File: NewSessionPipeline.java    From selenium with 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 #15
Source File: WebDriverConfigTest.java    From jmeter-plugins-webdriver with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleScenarioWhenBrowserHasAlreadyQuit() {
    doThrow(new SessionNotCreatedException("Session not created")).when(browser).quit();

    config.quitBrowser(browser);

    verify(browser, times(1)).quit();
}
 
Example #16
Source File: DistributorTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBeAbleToRemoveANode() throws URISyntaxException, MalformedURLException {
  URI nodeUri = new URI("http://example:5678");
  URI routableUri = new URI("http://localhost:1234");

  LocalSessionMap sessions = new LocalSessionMap(tracer, bus);
  LocalNode node = LocalNode.builder(tracer, bus, routableUri, routableUri, null)
      .add(caps, new TestSessionFactory((id, c) -> new Session(id, nodeUri, c)))
      .build();

  Distributor local = new LocalDistributor(
      tracer,
      bus,
      new PassthroughHttpClient.Factory(node),
      sessions,
      null);
  Distributor distributor = new RemoteDistributor(
      tracer,
      new PassthroughHttpClient.Factory(local),
      new URL("http://does.not.exist"));
  distributor.add(node);
  distributor.remove(node.getId());

  try (NewSessionPayload payload = NewSessionPayload.create(caps)) {
    assertThatExceptionOfType(SessionNotCreatedException.class)
        .isThrownBy(() -> distributor.newSession(createRequest(payload)));
  }
}
 
Example #17
Source File: DistributorTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotScheduleAJobIfAllSlotsAreBeingUsed() {
  SessionMap sessions = new LocalSessionMap(tracer, bus);

  CombinedHandler handler = new CombinedHandler();
  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);

  // Use up the one slot available
  try (NewSessionPayload payload = NewSessionPayload.create(caps)) {
    distributor.newSession(createRequest(payload));
  }

  // Now try and create a session.
  try (NewSessionPayload payload = NewSessionPayload.create(caps)) {
    assertThatExceptionOfType(SessionNotCreatedException.class)
        .isThrownBy(() -> distributor.newSession(createRequest(payload)));
  }
}
 
Example #18
Source File: DistributorTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void attemptingToStartASessionWhichFailsMarksAsTheSlotAsAvailable() {
  CombinedHandler handler = new CombinedHandler();

  SessionMap sessions = new LocalSessionMap(tracer, bus);
  handler.addHandler(sessions);

  URI uri = createUri();
  Node node = LocalNode.builder(tracer, bus, uri, uri, null)
      .add(caps, new TestSessionFactory((id, caps) -> {
        throw new SessionNotCreatedException("OMG");
      }))
      .build();
  handler.addHandler(node);

  Distributor distributor = new LocalDistributor(
      tracer,
      bus,
      new PassthroughHttpClient.Factory(handler),
      sessions,
      null);
  handler.addHandler(distributor);
  distributor.add(node);

  try (NewSessionPayload payload = NewSessionPayload.create(caps)) {
    assertThatExceptionOfType(SessionNotCreatedException.class)
        .isThrownBy(() -> distributor.newSession(createRequest(payload)));
  }

  assertThat(distributor.getStatus().hasCapacity()).isTrue();
}
 
Example #19
Source File: NodeTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotPropagateExceptionsWhenSessionCreationFails() {
  Node local = LocalNode.builder(tracer, bus, uri, uri, null)
      .add(caps, new TestSessionFactory((id, c) -> {
        throw new SessionNotCreatedException("eeek");
      }))
      .build();

  Optional<Session> session = local.newSession(createSessionRequest(caps))
      .map(CreateSessionResponse::getSession);

  assertThat(session).isNotPresent();
}
 
Example #20
Source File: ExceptionHandlerTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUnwrapAnExecutionException() {
  Exception noSession = new SessionNotCreatedException("This does not exist");
  Exception e = new ExecutionException(noSession);
  HttpResponse response = new ExceptionHandler(e).execute(new HttpRequest(HttpMethod.POST, "/session"));

  Map<String, Object> err = new Json().toType(string(response), MAP_TYPE);
  Map<?, ?> value = (Map<?, ?>) err.get("value");

  assertEquals(ErrorCodes.SESSION_NOT_CREATED, ((Number) err.get("status")).intValue());
  assertEquals("session not created", value.get("error"));
}
 
Example #21
Source File: OperaDriverInfo.java    From selenium with 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 #22
Source File: WebDriverConfig.java    From jmeter-plugins-webdriver with 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 #23
Source File: JavaDriverTest.java    From marathonv5 with 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 #24
Source File: JavaDriverTest.java    From marathonv5 with 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 #25
Source File: DriverManagerTest.java    From hsac-fitnesse-fixtures with 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 #26
Source File: IOSElementGenerationTest.java    From java-client with 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 #27
Source File: GeckoDriverInfo.java    From selenium with 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 #28
Source File: XpiDriverInfo.java    From selenium with 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 #29
Source File: InternetExplorerDriverInfo.java    From selenium with 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 #30
Source File: EdgeHtmlDriverInfo.java    From selenium with 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)));
}