Best Selenium code snippet using org.openqa.selenium.grid.node.Node.newSession
Source:NodeTest.java  
...88  public void shouldRefuseToCreateASessionIfNoFactoriesAttached() {89    Node local = LocalNode.builder(tracer, uri, sessions).build();90    HttpClient client = new PassthroughHttpClient<>(local);91    Node node = new RemoteNode(tracer, UUID.randomUUID(), uri, ImmutableSet.of(), client);92    Optional<Session> session = node.newSession(caps);93    assertThat(session.isPresent()).isFalse();94  }95  @Test96  public void shouldCreateASessionIfTheCorrectCapabilitiesArePassedToIt() {97    Optional<Session> session = node.newSession(caps);98    assertThat(session.isPresent()).isTrue();99  }100  @Test101  public void shouldOnlyCreateAsManySessionsAsFactories() {102    Node node = LocalNode.builder(tracer, uri, sessions)103        .add(caps, (c) -> new Session(new SessionId(UUID.randomUUID()), uri, c))104        .build();105    Optional<Session> session = node.newSession(caps);106    assertThat(session.isPresent()).isTrue();107    session = node.newSession(caps);108    assertThat(session.isPresent()).isFalse();109  }110  @Test111  public void willRefuseToCreateMoreSessionsThanTheMaxSessionCount() {112    Optional<Session> session = node.newSession(caps);113    assertThat(session.isPresent()).isTrue();114    session = node.newSession(caps);115    assertThat(session.isPresent()).isTrue();116    session = node.newSession(caps);117    assertThat(session.isPresent()).isFalse();118  }119  @Test120  public void newlyCreatedSessionsAreAddedToTheSessionMap() {121    Session expected = node.newSession(caps)122        .orElseThrow(() -> new RuntimeException("Session not created"));123    Session seen = sessions.get(expected.getId());124    assertThat(seen).isEqualTo(expected);125  }126  @Test127  public void stoppingASessionReducesTheNumberOfCurrentlyActiveSessions() {128    assertThat(local.getCurrentSessionCount()).isEqualTo(0);129    Session session = local.newSession(caps)130        .orElseThrow(() -> new RuntimeException("Session not created"));131    assertThat(local.getCurrentSessionCount()).isEqualTo(1);132    local.stop(session.getId());133    assertThat(local.getCurrentSessionCount()).isEqualTo(0);134  }135  @Test136  public void sessionsThatAreStoppedWillNotBeReturned() {137    Session expected = node.newSession(caps)138        .orElseThrow(() -> new RuntimeException("Session not created"));139    assertThat(sessions.get(expected.getId())).isEqualTo(expected);140    node.stop(expected.getId());141    assertThatExceptionOfType(NoSuchSessionException.class)142        .isThrownBy(() -> local.getSession(expected.getId()));143    assertThatExceptionOfType(NoSuchSessionException.class)144        .isThrownBy(() -> node.getSession(expected.getId()));145  }146  @Test147  public void stoppingASessionWillRemoveItFromTheSessionMap() {148    Session expected = node.newSession(caps)149        .orElseThrow(() -> new RuntimeException("Session not created"));150    assertThat(sessions.get(expected.getId())).isEqualTo(expected);151    node.stop(expected.getId());152    assertThatExceptionOfType(NoSuchSessionException.class)153        .isThrownBy(() -> sessions.get(expected.getId()));154  }155  @Test156  public void stoppingASessionThatDoesNotExistWillThrowAnException() {157    assertThatExceptionOfType(NoSuchSessionException.class)158        .isThrownBy(() -> local.stop(new SessionId(UUID.randomUUID())));159    assertThatExceptionOfType(NoSuchSessionException.class)160        .isThrownBy(() -> node.stop(new SessionId(UUID.randomUUID())));161  }162  @Test163  public void attemptingToGetASessionThatDoesNotExistWillCauseAnExceptionToBeThrown() {164    assertThatExceptionOfType(NoSuchSessionException.class)165        .isThrownBy(() -> local.getSession(new SessionId(UUID.randomUUID())));166    assertThatExceptionOfType(NoSuchSessionException.class)167        .isThrownBy(() -> node.getSession(new SessionId(UUID.randomUUID())));168  }169  @Test170  public void willRespondToWebDriverCommandsSentToOwnedSessions() throws IOException {171    AtomicBoolean called = new AtomicBoolean(false);172    class Recording extends Session implements CommandHandler {173      private Recording() {174        super(new SessionId(UUID.randomUUID()), uri, caps);175      }176      @Override177      public void execute(HttpRequest req, HttpResponse resp) {178        called.set(true);179      }180    }181    Node local = LocalNode.builder(tracer, uri, sessions)182        .add(caps, c -> new Recording())183        .build();184    Node remote = new RemoteNode(185        tracer,186        UUID.randomUUID(),187        uri,188        ImmutableSet.of(caps),189        new PassthroughHttpClient<>(local));190    Session session = remote.newSession(caps)191        .orElseThrow(() -> new RuntimeException("Session not created"));192    HttpRequest req = new HttpRequest(POST, String.format("/session/%s/url", session.getId()));193    remote.execute(req, new HttpResponse());194    assertThat(called.get()).isTrue();195  }196  @Test197  public void shouldOnlyRespondToWebDriverCommandsForSessionsTheNodeOwns() {198    Session session = node.newSession(caps)199        .orElseThrow(() -> new RuntimeException("Session not created"));200    HttpRequest req = new HttpRequest(POST, String.format("/session/%s/url", session.getId()));201    assertThat(local.test(req)).isTrue();202    assertThat(node.test(req)).isTrue();203    req = new HttpRequest(POST, String.format("/session/%s/url", UUID.randomUUID()));204    assertThat(local.test(req)).isFalse();205    assertThat(node.test(req)).isFalse();206  }207  @Test208  public void aSessionThatTimesOutWillBeStoppedAndRemovedFromTheSessionMap() {209    AtomicReference<Instant> now = new AtomicReference<>(Instant.now());210    Clock clock = new MyClock(now);211    Node node = LocalNode.builder(tracer, uri, sessions)212        .add(caps, c -> new Session(new SessionId(UUID.randomUUID()), uri, c))213        .sessionTimeout(Duration.ofMinutes(3))214        .advanced()215        .clock(clock)216        .build();217    Session session = node.newSession(caps)218        .orElseThrow(() -> new RuntimeException("Session not created"));219    now.set(now.get().plus(Duration.ofMinutes(5)));220    assertThatExceptionOfType(NoSuchSessionException.class)221        .isThrownBy(() -> node.getSession(session.getId()));222  }223  @Test224  public void shouldNotPropagateExceptionsWhenSessionCreationFails() {225    Node local = LocalNode.builder(tracer, uri, sessions)226        .add(caps, c -> {227          throw new SessionNotCreatedException("eeek");228        })229        .build();230    Optional<Session> session = local.newSession(caps);231    assertThat(session.isPresent()).isFalse();232  }233  private static class MyClock extends Clock {234    private final AtomicReference<Instant> now;235    public MyClock(AtomicReference<Instant> now) {236      this.now = now;237    }238    @Override239    public ZoneId getZone() {240      return ZoneId.systemDefault();241    }242    @Override243    public Clock withZone(ZoneId zone) {244      return this;...Source:CreateSessionTest.java  
...58        HttpClient.Factory.createDefault(),59        uri)60        .add(stereotype, new TestSessionFactory((id, caps) -> new Session(id, uri, caps)))61        .build();62    CreateSessionResponse sessionResponse = node.newSession(63        new CreateSessionRequest(64            ImmutableSet.of(W3C),65            stereotype,66            ImmutableMap.of()))67        .orElseThrow(() -> new AssertionError("Unable to create session"));68    Map<String, Object> all = json.toType(69        new String(sessionResponse.getDownstreamEncodedResponse(), UTF_8),70        MAP_TYPE);71    // Ensure that there's no status field (as this is used by the protocol handshake to determine72    // whether the session is using the JWP or the W3C dialect.73    assertThat(all.containsKey("status")).isFalse();74    // Now check the fields required by the spec75    Map<?, ?> value = (Map<?, ?>) all.get("value");76    assertThat(value.get("sessionId")).isInstanceOf(String.class);77    assertThat(value.get("capabilities")).isInstanceOf(Map.class);78  }79  @Test80  public void shouldOnlyAcceptAJWPPayloadIfConfiguredTo() {81  }82  @Test83  public void ifOnlyW3CPayloadSentAndRemoteEndIsJWPOnlyFailSessionCreationIfJWPNotConfigured() {84  }85  @Test86  public void ifOnlyJWPPayloadSentResponseShouldBeJWPOnlyIfJWPConfigured()87      throws URISyntaxException {88    String payload = json.toJson(ImmutableMap.of(89        "desiredCapabilities", ImmutableMap.of("cheese", "brie")));90    HttpRequest request = new HttpRequest(POST, "/session");91    request.setContent(utf8String(payload));92    URI uri = new URI("http://example.com");93    Node node = LocalNode.builder(94        DistributedTracer.builder().build(),95        new GuavaEventBus(),96        HttpClient.Factory.createDefault(),97        uri)98        .add(stereotype, new TestSessionFactory((id, caps) -> new Session(id, uri, caps)))99        .build();100    CreateSessionResponse sessionResponse = node.newSession(101        new CreateSessionRequest(102            ImmutableSet.of(OSS),103            stereotype,104            ImmutableMap.of()))105        .orElseThrow(() -> new AssertionError("Unable to create session"));106    Map<String, Object> all = json.toType(107        new String(sessionResponse.getDownstreamEncodedResponse(), UTF_8),108        MAP_TYPE);109    // The status field is used by local ends to determine whether or not the session is a JWP one.110    assertThat(all.get("status")).matches(obj -> ((Number) obj).intValue() == ErrorCodes.SUCCESS);111    // The session id is a top level field112    assertThat(all.get("sessionId")).isInstanceOf(String.class);113    // And the value should contain the capabilities.114    assertThat(all.get("value")).isInstanceOf(Map.class);115  }116  @Test117  public void shouldPreferUsingTheW3CProtocol() throws URISyntaxException {118    String payload = json.toJson(ImmutableMap.of(119        "desiredCapabilities", ImmutableMap.of(120            "cheese", "brie"),121        "capabilities", ImmutableMap.of(122            "alwaysMatch", ImmutableMap.of("cheese", "brie"))));123    HttpRequest request = new HttpRequest(POST, "/session");124    request.setContent(utf8String(payload));125    URI uri = new URI("http://example.com");126    Node node = LocalNode.builder(127        DistributedTracer.builder().build(),128        new GuavaEventBus(),129        HttpClient.Factory.createDefault(),130        uri)131        .add(stereotype, new TestSessionFactory((id, caps) -> new Session(id, uri, caps)))132        .build();133    CreateSessionResponse sessionResponse = node.newSession(134        new CreateSessionRequest(135            ImmutableSet.of(W3C),136            stereotype,137            ImmutableMap.of()))138        .orElseThrow(() -> new AssertionError("Unable to create session"));139    Map<String, Object> all = json.toType(140        new String(sessionResponse.getDownstreamEncodedResponse(), UTF_8),141        MAP_TYPE);142    // Ensure that there's no status field (as this is used by the protocol handshake to determine143    // whether the session is using the JWP or the W3C dialect.144    assertThat(all.containsKey("status")).isFalse();145    // Now check the fields required by the spec146    Map<?, ?> value = (Map<?, ?>) all.get("value");147    assertThat(value.get("sessionId")).isInstanceOf(String.class);...Source:RemoteNode.java  
...74                caps.getCapability(name),75                capabilities.getCapability(name))));76  }77  @Override78  public Optional<Session> newSession(Capabilities capabilities) {79    Objects.requireNonNull(capabilities, "Capabilities for session are not set");80    HttpRequest req = new HttpRequest(POST, "/se/grid/node/session");81    req.setContent(JSON.toJson(capabilities).getBytes(UTF_8));82    HttpResponse res = client.apply(req);83    return Optional.ofNullable(Values.get(res, Session.class));84  }85  @Override86  protected boolean isSessionOwner(SessionId id) {87    Objects.requireNonNull(id, "Session ID has not been set");88    HttpRequest req = new HttpRequest(GET, "/se/grid/node/owner/" + id);89    HttpResponse res = client.apply(req);90    return Values.get(res, Boolean.class) == Boolean.TRUE;91  }92  @Override...Source:LocalDistributor.java  
...35  public LocalDistributor(DistributedTracer tracer) {36    super(tracer);37  }38  @Override39  public Session newSession(NewSessionPayload payload) throws SessionNotCreatedException {40    // TODO: merge in the logic from the scheduler branch so we do something smarter41    Capabilities caps = payload.stream()42        .findFirst()43        .orElseThrow(() -> new SessionNotCreatedException("No capabilities found"));44    return nodes.stream()45        .filter(node -> node.isSupporting(caps))46        .findFirst()47        .map(host -> host.newSession(caps))48        .filter(Optional::isPresent)49        .map(Optional::get)50        .orElseThrow(() -> new SessionNotCreatedException("Unable to create new session: " + caps));51  }52  @Override53  public void add(Node node) {54    nodes.add(node);55  }56  @Override57  public void remove(UUID nodeId) {58    nodes.removeIf(node -> nodeId.equals(node.getId()));59  }60  @Override61  public DistributorStatus getStatus() {...newSession
Using AI Code Generation
1import org.openqa.selenium.grid.config.Config;2import org.openqa.selenium.grid.config.MapConfig;3import org.openqa.selenium.grid.config.TomlConfig;4import org.openqa.selenium.grid.node.Node;5import org.openqa.selenium.grid.node.local.LocalNode;6import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;7import org.openqa.selenium.grid.web.Routable;8import org.openqa.selenium.internal.Require;9import org.openqa.selenium.remote.tracing.Tracer;10import org.openqa.selenium.remote.tracing.config.TracerOptions;11import org.openqa.selenium.remote.tracing.zipkin.ZipkinTracer;12import org.openqa.selenium.remote.tracing.zipkin.ZipkinTracerOptions;13import org.openqa.selenium.remote.tracing.zipkin.ZipkinTracerOptions.ZipkinTracerOptionsBuilder;14import org.openqa.selenium.remote.tracing.zipkin.http.HttpZipkinTracerOptions;15import org.openqa.selenium.remote.tracing.zipkin.http.HttpZipkinTracerOptions.HttpZipkinTracerOptionsBuilder;16import org.openqa.selenium.remote.tracing.zipkin.http.HttpZipkinTracerOptions.HttpZipkinTracerOptionsBuilder.HttpZipkinTracerOptionsBuilderImpl;17import org.openqa.selenium.remote.tracing.zipkin.http.HttpZipkinTracerOptions.HttpZipkinTracerOptionsImpl;18import org.openqa.selenium.remote.tracing.zipkin.http.HttpZipkinTracerOptionsImpl;19import org.openqa.selenium.remote.tracing.zipkin.http.HttpZipkinTracerOptionsImpl.HttpZipkinTracerOptionsBuilderImpl;20import org.openqa.selenium.remote.tracing.zipkin.http.HttpZipkinTracerOptionsImpl.HttpZipkinTracerOptionsImplBuilder;21import org.openqa.selenium.remote.tracing.zipkin.http.HttpZipkinTracerOptionsImplBuilder;22import org.openqa.selenium.remote.tracing.zipkin.http.HttpZipkinTracerOptionsImplBuilder.HttpZipkinTracerOptionsBuilderImpl;23import org.openqa.selenium.remote.tracing.zipkin.http.HttpZipkinTracerOptionsImplBuilder.HttpZipkinTracerOptionsImplBuilderImpl;24import org.openqa.selenium.remote.tracing.zipkin.http.HttpZipkinTracerOptionsImplBuilderImpl;25import org.openqa.selenium.remote.tracing.zipkin.http.HttpZipkinTracerOptionsImplBuilderImpl.HttpZipkinTracerOptionsImplBuilderImplImpl;26import org.openqa.selenium.remote.tracing.zipkin.http.HttpZipkinTracerOptionsImplImpl;27import org.openqa.selenium.remote.tracing.zipkin.http.HttpZipkinTracerOptionsImplImpl.HttpZipkinTracerOptionsImplImplBuilder;28import org.openqa.selenium.remote.tracing.zipkin.http.HttpZipkinnewSession
Using AI Code Generation
1def node = new org.openqa.selenium.grid.node.Node(new URL(nodeURL))2def newSession = node.newSession(new ImmutableCapabilities(browserName, browserVersion, platformName))3sessionID = newSession.getId().toString()4sessionURL = newSession.getUri().toString()5def node = new org.openqa.selenium.grid.node.Node(new URL(nodeURL))6def newSession = node.newSession(new ImmutableCapabilities(browserName, browserVersion, platformName))7sessionID = newSession.getId().toString()8sessionURL = newSession.getUri().toString()9def node = new org.openqa.selenium.grid.node.Node(new URL(nodeURL))10def newSession = node.newSession(new ImmutableCapabilities(browserName, browserVersion, platformName))11sessionID = newSession.getId().toString()12sessionURL = newSession.getUri().toString()newSession
Using AI Code Generation
1NewSessionPayloadCodec newSessionPayloadCodec = new NewSessionPayloadCodec();2NewSessionPayload newSessionPayload = newSessionPayloadCodec.decode(3  new StringReader("{" +4    "\"capabilities\": {" +5      "\"alwaysMatch\": {" +6      "}," +7      "\"firstMatch\": [{}]" +8    "}," +9    "\"desiredCapabilities\": {" +10    "}" +11  "}"),12  MediaType.JSON_UTF_8);13NewSessionRequest newSessionRequest = new NewSessionRequest(newSessionPayload);14Node node = new Node();15Session session = node.newSession(newSessionRequest);16SessionId sessionId = session.getId();17SessionId sessionid = new SessionId(UUID.randomUUID());18org.openqa.selenium.grid.data.Session session = new org.openqa.selenium.grid.data.Session(19  new ImmutableCapabilities());20org.openqa.selenium.grid.data.Session session = new org.openqa.selenium.grid.data.Session(21  new ImmutableCapabilities(), 22  Instant.now());23org.openqa.selenium.grid.data.Session session = new org.openqa.selenium.grid.data.Session(24  new ImmutableCapabilities(), 25  Instant.now(), 26  Instant.now());LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.
Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.
What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.
Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.
Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.
How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.
Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.
Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!
