How to use newSession method of org.openqa.selenium.grid.node.local.LocalNode class

Best Selenium code snippet using org.openqa.selenium.grid.node.local.LocalNode.newSession

Source:NodeTest.java Github

copy

Full Screen

...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;...

Full Screen

Full Screen

Source:CreateSessionTest.java Github

copy

Full Screen

...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(payload.getBytes(UTF_8));92 URI uri = new URI("http://example.com");93 Node node = LocalNode.builder(94 DistributedTracer.builder().build(),95 ZeroMqEventBus.create(new ZContext(), "inproc://cst-pub", "inproc://cst-sub", true),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(payload.getBytes(UTF_8));125 URI uri = new URI("http://example.com");126 Node node = LocalNode.builder(127 DistributedTracer.builder().build(),128 ZeroMqEventBus.create(new ZContext(), "inproc://cst-pub", "inproc://cst-sub", true),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);...

Full Screen

Full Screen

Source:DistributorTest.java Github

copy

Full Screen

...49 @Test50 public void creatingANewSessionWithoutANodeEndsInFailure() {51 try (NewSessionPayload payload = NewSessionPayload.create(caps)) {52 assertThatExceptionOfType(SessionNotCreatedException.class)53 .isThrownBy(() -> distributor.newSession(payload));54 }55 }56 @Test57 public void shouldBeAbleToAddANodeAndCreateASession() throws URISyntaxException {58 URI nodeUri = new URI("http://example:5678");59 URI routableUri = new URI("http://localhost:1234");60 LocalSessionMap sessions = new LocalSessionMap();61 LocalNode node = LocalNode.builder(tracer, routableUri, sessions)62 .add(caps, c -> new Session(new SessionId(UUID.randomUUID()), nodeUri, c))63 .build();64 Distributor distributor = new LocalDistributor(tracer);65 distributor.add(node);66 MutableCapabilities sessionCaps = new MutableCapabilities(caps);67 sessionCaps.setCapability("sausages", "gravy");68 try (NewSessionPayload payload = NewSessionPayload.create(sessionCaps)) {69 Session session = distributor.newSession(payload);70 assertThat(session.getCapabilities()).isEqualTo(sessionCaps);71 assertThat(session.getUri()).isEqualTo(routableUri);72 }73 }74 @Test75 public void shouldBeAbleToRemoveANode() throws URISyntaxException {76 URI nodeUri = new URI("http://example:5678");77 URI routableUri = new URI("http://localhost:1234");78 LocalSessionMap sessions = new LocalSessionMap();79 LocalNode node = LocalNode.builder(tracer, routableUri, sessions)80 .add(caps, c -> new Session(new SessionId(UUID.randomUUID()), nodeUri, c))81 .build();82 Distributor local = new LocalDistributor(tracer);83 distributor = new RemoteDistributor(tracer, new PassthroughHttpClient<>(local));84 distributor.add(node);85 distributor.remove(node.getId());86 try (NewSessionPayload payload = NewSessionPayload.create(caps)) {87 assertThatExceptionOfType(SessionNotCreatedException.class)88 .isThrownBy(() -> distributor.newSession(payload));89 }90 }91 @Test92 public void registeringTheSameNodeMultipleTimesOnlyCountsTheFirstTime()93 throws URISyntaxException {94 URI nodeUri = new URI("http://example:5678");95 URI routableUri = new URI("http://localhost:1234");96 LocalSessionMap sessions = new LocalSessionMap();97 LocalNode node = LocalNode.builder(tracer, routableUri, sessions)98 .add(caps, c -> new Session(new SessionId(UUID.randomUUID()), nodeUri, c))99 .build();100 local.add(node);101 local.add(node);102 DistributorStatus status = local.getStatus();...

Full Screen

Full Screen

Source:LocalNodeTest.java Github

copy

Full Screen

...50 Capabilities stereotype = new ImmutableCapabilities("cheese", "brie");51 node = LocalNode.builder(tracer, bus, clientFactory, uri, null)52 .add(stereotype, new TestSessionFactory((id, caps) -> new Session(id, uri, caps)))53 .build();54 CreateSessionResponse sessionResponse = node.newSession(55 new CreateSessionRequest(56 ImmutableSet.of(W3C),57 stereotype,58 ImmutableMap.of()))59 .orElseThrow(() -> new AssertionError("Unable to create session"));60 session = sessionResponse.getSession();61 }62 @Test63 public void shouldThrowIfSessionIsNotPresent() {64 assertThatExceptionOfType(NoSuchSessionException.class)65 .isThrownBy(() -> node.getSession(new SessionId("12345")));66 }67 @Test68 public void canRetrieveActiveSessionById() {...

Full Screen

Full Screen

newSession

Using AI Code Generation

copy

Full Screen

1def newSessionId = org.openqa.selenium.grid.node.local.LocalNode.newSession(2 org.openqa.selenium.grid.config.Config.builder().build(),3 org.openqa.selenium.grid.data.CreateSessionRequest.builder().desiredCapabilities(4 ).build()5def session = org.openqa.selenium.grid.node.local.LocalNode.startSession(6 org.openqa.selenium.grid.config.Config.builder().build(),7def browser = org.openqa.selenium.grid.node.local.LocalNode.getBrowser(8 org.openqa.selenium.grid.config.Config.builder().build(),9println browser.getPageSource()10browser.close()11org.openqa.selenium.grid.node.local.LocalNode.stopSession(12 org.openqa.selenium.grid.config.Config.builder().build(),13org.openqa.selenium.grid.node.local.LocalNode.stopNewSession(14 org.openqa.selenium.grid.config.Config.builder().build(),

Full Screen

Full Screen

newSession

Using AI Code Generation

copy

Full Screen

1String sessionId = newSession();2driver.quit();3public String newSession() throws IOException {4 String body = "{\"desiredCapabilities\": {\"browserName\": \"chrome\"}}";5 String response = post(url, body);6 String sessionId = getSessionId(response);7 return sessionId;8}9public String getSessionId(String response) throws IOException {10 JsonNode jsonNode = new ObjectMapper().readTree(response);11 return jsonNode.get("sessionId").asText();12}13public String post(String url, String body) throws IOException {14 URL obj = new URL(url);15 HttpURLConnection con = (HttpURLConnection) obj.openConnection();16 con.setRequestMethod("POST");17 con.setRequestProperty("Content-Type", "application/json");18 con.setDoOutput(true);19 DataOutputStream wr = new DataOutputStream(con.getOutputStream());20 wr.writeBytes(body);21 wr.flush();22 wr.close();23 int responseCode = con.getResponseCode();24 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));25 String inputLine;26 StringBuffer response = new StringBuffer();27 while ((inputLine = in.readLine()) != null) {28 response.append(inputLine);29 }30 in.close();31 return response.toString();32}

Full Screen

Full Screen

Selenium 4 Tutorial:

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.

Chapters:

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  7. 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.

Selenium 101 certifications:

LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful