Best Selenium code snippet using org.openqa.selenium.grid.data.DistributorStatus.getNodes
Source:LocalDistributorTest.java
...108 false);109 distributor.add(localNode);110 DistributorStatus status = distributor.getStatus();111 //Check the size112 final Set<NodeStatus> nodes = status.getNodes();113 assertThat(nodes.size()).isEqualTo(1);114 //Check a couple attributes115 NodeStatus distributorNode = nodes.iterator().next();116 assertThat(distributorNode.getId()).isEqualByComparingTo(localNode.getId());117 assertThat(distributorNode.getUri()).isEqualTo(uri);118 }119 @Test120 public void testShouldNotAddNodeWithWrongSecret() {121 Secret secret = new Secret("my_secret");122 NewSessionQueue queue = new LocalNewSessionQueue(123 tracer,124 bus,125 new DefaultSlotMatcher(),126 Duration.ofSeconds(2),127 Duration.ofSeconds(2),128 registrationSecret);129 Distributor secretDistributor = new LocalDistributor(130 tracer,131 bus,132 clientFactory,133 new LocalSessionMap(tracer, bus),134 queue,135 new DefaultSlotSelector(),136 secret,137 Duration.ofMinutes(5),138 false);139 bus.fire(new NodeStatusEvent(localNode.getStatus()));140 DistributorStatus status = secretDistributor.getStatus();141 //Check the size142 final Set<NodeStatus> nodes = status.getNodes();143 assertThat(nodes.size()).isEqualTo(0);144 }145 @Test146 public void testRemoveNodeFromDistributor() {147 NewSessionQueue queue = new LocalNewSessionQueue(148 tracer,149 bus,150 new DefaultSlotMatcher(),151 Duration.ofSeconds(2),152 Duration.ofSeconds(2),153 registrationSecret);154 Distributor distributor = new LocalDistributor(155 tracer,156 bus,157 clientFactory,158 new LocalSessionMap(tracer, bus),159 queue,160 new DefaultSlotSelector(),161 registrationSecret,162 Duration.ofMinutes(5),163 false);164 distributor.add(localNode);165 //Check the size166 DistributorStatus statusBefore = distributor.getStatus();167 final Set<NodeStatus> nodesBefore = statusBefore.getNodes();168 assertThat(nodesBefore.size()).isEqualTo(1);169 //Recheck the status--should be zero170 distributor.remove(localNode.getId());171 DistributorStatus statusAfter = distributor.getStatus();172 final Set<NodeStatus> nodesAfter = statusAfter.getNodes();173 assertThat(nodesAfter.size()).isEqualTo(0);174 }175 @Test176 public void testAddSameNodeTwice() {177 NewSessionQueue queue = new LocalNewSessionQueue(178 tracer,179 bus,180 new DefaultSlotMatcher(),181 Duration.ofSeconds(2),182 Duration.ofSeconds(2),183 registrationSecret);184 Distributor distributor = new LocalDistributor(185 tracer,186 bus,187 clientFactory,188 new LocalSessionMap(tracer, bus),189 queue,190 new DefaultSlotSelector(),191 registrationSecret,192 Duration.ofMinutes(5),193 false);194 distributor.add(localNode);195 distributor.add(localNode);196 DistributorStatus status = distributor.getStatus();197 //Should only be one node after dupe check198 final Set<NodeStatus> nodes = status.getNodes();199 assertThat(nodes.size()).isEqualTo(1);200 }201 @Test202 public void shouldBeAbleToAddMultipleSessionsConcurrently() throws Exception {203 NewSessionQueue queue = new LocalNewSessionQueue(204 tracer,205 bus,206 new DefaultSlotMatcher(),207 Duration.ofSeconds(2),208 Duration.ofSeconds(2),209 registrationSecret);210 LocalDistributor distributor = new LocalDistributor(211 tracer,212 bus,213 clientFactory,214 new LocalSessionMap(tracer, bus),215 queue,216 new DefaultSlotSelector(),217 registrationSecret,218 Duration.ofMinutes(5),219 false);220 // Add one node to ensure that everything is created in that.221 Capabilities caps = new ImmutableCapabilities("browserName", "cheese");222 class VerifyingHandler extends Session implements HttpHandler {223 private VerifyingHandler(SessionId id, Capabilities capabilities) {224 super(id, uri, new ImmutableCapabilities(), capabilities, Instant.now());225 }226 @Override227 public HttpResponse execute(HttpRequest req) {228 Optional<SessionId> id = HttpSessionId.getSessionId(req.getUri()).map(SessionId::new);229 assertThat(id).isEqualTo(Optional.of(getId()));230 return new HttpResponse();231 }232 }233 // Only use one node.234 Node node = LocalNode.builder(tracer, bus, uri, uri, registrationSecret)235 .add(caps, new TestSessionFactory(VerifyingHandler::new))236 .add(caps, new TestSessionFactory(VerifyingHandler::new))237 .add(caps, new TestSessionFactory(VerifyingHandler::new))238 .maximumConcurrentSessions(3)239 .build();240 distributor.add(node);241 SessionRequest sessionRequest =242 new SessionRequest(243 new RequestId(UUID.randomUUID()),244 Instant.now(),245 Set.of(W3C),246 Set.of(new ImmutableCapabilities("browserName", "cheese")),247 Map.of(),248 Map.of());249 List<Callable<SessionId>> callables = new ArrayList<>();250 for (int i = 0; i < 3; i++) {251 callables.add(() -> {252 Either<SessionNotCreatedException, CreateSessionResponse> result =253 distributor.newSession(sessionRequest);254 if (result.isRight()) {255 CreateSessionResponse res = result.right();256 assertThat(res.getSession().getCapabilities().getBrowserName()).isEqualTo("cheese");257 return res.getSession().getId();258 } else {259 fail("Session creation failed", result.left());260 }261 return null;262 });263 }264 List<Future<SessionId>> futures = Executors.newFixedThreadPool(3).invokeAll(callables);265 for (Future<SessionId> future : futures) {266 SessionId id = future.get(2, TimeUnit.SECONDS);267 // Now send a random command.268 HttpResponse res = node.execute(new HttpRequest(GET, String.format("/session/%s/url", id)));269 assertThat(res.isSuccessful()).isTrue();270 }271 }272 @Test273 public void testDrainNodeFromDistributor() {274 NewSessionQueue queue = new LocalNewSessionQueue(275 tracer,276 bus,277 new DefaultSlotMatcher(),278 Duration.ofSeconds(2),279 Duration.ofSeconds(2),280 registrationSecret);281 Distributor distributor = new LocalDistributor(282 tracer,283 bus,284 clientFactory,285 new LocalSessionMap(tracer, bus),286 queue,287 new DefaultSlotSelector(),288 registrationSecret,289 Duration.ofMinutes(5),290 false);291 distributor.add(localNode);292 assertThat(localNode.isDraining()).isFalse();293 //Check the size - there should be one node294 DistributorStatus statusBefore = distributor.getStatus();295 Set<NodeStatus> nodesBefore = statusBefore.getNodes();296 assertThat(nodesBefore.size()).isEqualTo(1);297 NodeStatus nodeBefore = nodesBefore.iterator().next();298 assertThat(nodeBefore.getAvailability()).isNotEqualTo(DRAINING);299 distributor.drain(localNode.getId());300 assertThat(localNode.isDraining()).isTrue();301 //Recheck the status - there should still be no node, it is removed302 DistributorStatus statusAfter = distributor.getStatus();303 Set<NodeStatus> nodesAfter = statusAfter.getNodes();304 assertThat(nodesAfter.size()).isEqualTo(0);305 }306 @Test307 public void testDrainNodeFromNode() {308 assertThat(localNode.isDraining()).isFalse();309 NewSessionQueue queue = new LocalNewSessionQueue(310 tracer,311 bus,312 new DefaultSlotMatcher(),313 Duration.ofSeconds(2),314 Duration.ofSeconds(2),315 registrationSecret);316 Distributor distributor = new LocalDistributor(317 tracer,...
Source:AddingNodesTest.java
...95 .build();96 handler.addHandler(node);97 distributor.add(node);98 wait.until(obj -> distributor.getStatus().hasCapacity());99 DistributorStatus.NodeSummary summary = getOnlyElement(distributor.getStatus().getNodes());100 assertEquals(1, summary.getStereotypes().get(CAPS).intValue());101 }102 @Test103 public void shouldBeAbleToRegisterACustomNode() throws URISyntaxException {104 URI sessionUri = new URI("http://example:1234");105 Node node = new CustomNode(106 tracer,107 bus,108 UUID.randomUUID(),109 externalUrl.toURI(),110 c -> new Session(new SessionId(UUID.randomUUID()), sessionUri, c));111 handler.addHandler(node);112 distributor.add(node);113 wait.until(obj -> distributor.getStatus().hasCapacity());114 DistributorStatus.NodeSummary summary = getOnlyElement(distributor.getStatus().getNodes());115 assertEquals(1, summary.getStereotypes().get(CAPS).intValue());116 }117 @Test118 public void shouldBeAbleToRegisterNodesByListeningForEvents() throws URISyntaxException {119 URI sessionUri = new URI("http://example:1234");120 Node node = LocalNode.builder(tracer, bus, clientFactory, externalUrl.toURI())121 .add(CAPS, new TestSessionFactory((id, caps) -> new Session(id, sessionUri, caps)))122 .build();123 handler.addHandler(node);124 bus.fire(new NodeStatusEvent(node.getStatus()));125 wait.until(obj -> distributor.getStatus().hasCapacity());126 DistributorStatus.NodeSummary summary = getOnlyElement(distributor.getStatus().getNodes());127 assertEquals(1, summary.getStereotypes().get(CAPS).intValue());128 }129 @Test130 public void distributorShouldUpdateStateOfExistingNodeWhenNodePublishesStateChange()131 throws URISyntaxException {132 URI sessionUri = new URI("http://example:1234");133 Node node = LocalNode.builder(tracer, bus, clientFactory, externalUrl.toURI())134 .add(CAPS, new TestSessionFactory((id, caps) -> new Session(id, sessionUri, caps)))135 .build();136 handler.addHandler(node);137 bus.fire(new NodeStatusEvent(node.getStatus()));138 // Start empty139 wait.until(obj -> distributor.getStatus().hasCapacity());140 DistributorStatus.NodeSummary summary = getOnlyElement(distributor.getStatus().getNodes());141 assertEquals(1, summary.getStereotypes().get(CAPS).intValue());142 // Craft a status that makes it look like the node is busy, and post it on the bus.143 NodeStatus status = node.getStatus();144 NodeStatus crafted = new NodeStatus(145 status.getNodeId(),146 status.getUri(),147 status.getMaxSessionCount(),148 status.getStereotypes(),149 ImmutableSet.of(new NodeStatus.Active(CAPS, new SessionId(UUID.randomUUID()), CAPS)));150 bus.fire(new NodeStatusEvent(crafted));151 // We claimed the only slot is filled. Life is good.152 wait.until(obj -> !distributor.getStatus().hasCapacity());153 }154 static class CustomNode extends Node {...
Source:Grid.java
...63 }64 public String getVersion() {65 return version;66 }67 public List<Node> getNodes() {68 ImmutableList.Builder<Node> toReturn = ImmutableList.builder();69 for (NodeStatus status : distributorStatus.get().getNodes()) {70 Map<Capabilities, Integer> stereotypes = new HashMap<>();71 Map<org.openqa.selenium.grid.data.Session, Slot> sessions = new HashMap<>();72 for (Slot slot : status.getSlots()) {73 slot.getSession().ifPresent(session -> sessions.put(session, slot));74 int count = stereotypes.getOrDefault(slot.getStereotype(), 0);75 count++;76 stereotypes.put(slot.getStereotype(), count);77 }78 OsInfo osInfo = new OsInfo(79 status.getOsInfo().get("arch"),80 status.getOsInfo().get("name"),81 status.getOsInfo().get("version"));82 toReturn.add(new Node(83 status.getId(),84 status.getUri(),85 status.getAvailability(),86 status.getMaxSessionCount(),87 status.getSlots().size(),88 stereotypes,89 sessions,90 status.getVersion(),91 osInfo));92 }93 return toReturn.build();94 }95 public int getNodeCount() {96 return distributorStatus.get().getNodes().size();97 }98 public int getSessionCount() {99 return distributorStatus.get().getNodes().stream()100 .map(NodeStatus::getSlots)101 .flatMap(Collection::stream)102 .filter(slot -> slot.getSession().isPresent())103 .mapToInt(slot -> 1)104 .sum();105 }106 public int getTotalSlots() {107 return distributorStatus.get().getNodes().stream()108 .mapToInt(status -> status.getSlots().size())109 .sum();110 }111 public int getMaxSession() {112 return distributorStatus.get().getNodes().stream()113 .mapToInt(NodeStatus::getMaxSessionCount)114 .sum();115 }116 public int getSessionQueueSize() {117 return queueInfoList.size();118 }119 public List<String> getSessionQueueRequests() {120 // TODO: The Grid UI expects there to be a single capability per new session request, which is not correct121 return queueInfoList.stream()122 .map(set -> set.isEmpty() ? new ImmutableCapabilities() : set.iterator().next())123 .map(JSON::toJson)124 .collect(Collectors.toList());125 }126 public List<Session> getSessions() {127 List<Session> sessions = new ArrayList<>();128 for (NodeStatus status : distributorStatus.get().getNodes()) {129 for (Slot slot : status.getSlots()) {130 if (slot.getSession().isPresent()) {131 org.openqa.selenium.grid.data.Session session = slot.getSession().get();132 sessions.add(133 new org.openqa.selenium.grid.graphql.Session(134 session.getId().toString(),135 session.getCapabilities(),136 session.getStartTime(),137 session.getUri(),138 status.getId().toString(),139 status.getUri(),140 slot)141 );142 }...
Source:SessionData.java
...36 String sessionId = environment.getArgument("id");37 if (sessionId.isEmpty()) {38 throw new SessionNotFoundException("Session id is empty. A valid session id is required.");39 }40 Set<NodeStatus> nodeStatuses = distributorStatus.get().getNodes();41 SessionInSlot currentSession = findSession(sessionId, nodeStatuses);42 if (currentSession != null) {43 org.openqa.selenium.grid.data.Session session = currentSession.session;44 return new org.openqa.selenium.grid.graphql.Session(45 session.getId().toString(),46 session.getCapabilities(),47 session.getStartTime(),48 session.getUri(),49 currentSession.node.getId().toString(),50 currentSession.node.getUri(),51 currentSession.slot);52 } else {53 throw new SessionNotFoundException("No ongoing session found with the requested session id.",54 sessionId);...
getNodes
Using AI Code Generation
1import org.openqa.selenium.grid.data.DistributorStatus;2import org.openqa.selenium.grid.data.NodeStatus;3import org.openqa.selenium.grid.data.Session;4import org.openqa.selenium.grid.data.SessionId;5import org.openqa.selenium.remote.http.HttpClient;6import org.openqa.selenium.remote.http.HttpRequest;7import org.openqa.selenium.remote.http.HttpResponse;8import org.openqa.selenium.remote.tracing.DefaultTestTracer;9import org.openqa.selenium.remote.tracer.NoopTracer;10import java.net.URI;11import java.util.List;12import java.util.Map;13public class GetSessionStatus {14 public static void main(String[] args) {15 HttpRequest request = new HttpRequest("GET", "/status");16 HttpResponse response = client.execute(request);17 DistributorStatus status = new DistributorStatus(response, NoopTracer.getInstance());18 List<NodeStatus> nodes = status.getNodes();19 for (NodeStatus node : nodes) {20 List<SessionId> sessions = node.getSessions();21 for (SessionId session : sessions) {22 Map<String, Object> capabilities = session.getCapabilities();23 System.out.println(capabilities);24 }25 }26 }27}28{browserName=chrome, browserVersion=83.0.4103.116, chrome=83.0.4103.116, javascriptEnabled=true, networkConnectionEnabled=false, pageLoadStrategy=normal, platformName=linux, proxy=Proxy(), setWindowRect=true, strictFileInteractability=false, timeouts=Timeouts(), unhandledPromptBehavior=dismiss and notify, webdriver.remote.sessionid=5f3d0f5c
getNodes
Using AI Code Generation
1import org.openqa.selenium.grid.data.DistributorStatus;2import org.openqa.selenium.grid.data.NodeStatus;3import org.openqa.selenium.grid.data.Session;4import org.openqa.selenium.grid.data.SessionRequest;5import org.openqa.selenium.grid.data.Slot;6import org.openqa.selenium.grid.data.SlotId;7import org.openqa.selenium.grid.data.SlotMatch;8import org.openqa.selenium.grid.data.TestSession;9import org.openqa.selenium.grid.data.TestSlot;10import org.openqa.selenium.grid.node.Node;11import org.openqa.selenium.grid.node.local.LocalNode;12import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;13import org.openqa.selenium.grid.web.Values;14import org.openqa.selenium.internal.Require;15import org.openqa.selenium.json.Json;16import org.openqa.selenium.remote.http.HttpClient;17import org.openqa.selenium.remote.http.HttpRequest;18import org.openqa.selenium.remote.http.HttpResponse;19import org.openqa.selenium.remote.tracing.Tracer;20import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer;21import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracerOptions;22import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracerOptionsBuilder;23import org.openqa.selenium.remote.tracing.opentelemetry.jaeger.JaegerOptions;24import org.openqa.selenium.remote.tracing.opentelemetry.jaeger.JaegerOptionsBuilder;25import org.openqa.selenium.remote.tracing.opentelemetry.jaeger.JaegerSpanExporter;26import org.openqa.selenium.remote.tracing.opentelemetry.jaeger.JaegerSpanExporterBuilder;27import org.openqa.selenium.testing.drivers.Browser;28import java.io.IOException;29import java.net.URI;30import java.util.ArrayList;31import java.util.Collections;32import java.util.HashMap;33import java.util.List;34import java.util.Map;35import java.util.Optional;36import java.util.concurrent.TimeUnit;37import java.util.function.Function;38import java.util.stream.Collectors;39public class Main {40 public static void main(String[] args) throws IOException {41 Tracer tracer = OpenTelemetryTracer.create(42 OpenTelemetryTracerOptions.builder()43 .withServiceName("my-service")44 .withJaegerOptions(45 JaegerOptions.builder()46 .withServiceName("my-service")
getNodes
Using AI Code Generation
1import org.openqa.selenium.grid.data.DistributorStatus;2import org.openqa.selenium.grid.data.NodeStatus;3import org.openqa.selenium.grid.data.Session;4import org.openqa.selenium.grid.data.SessionId;5import org.openqa.selenium.grid.data.SessionRequest;6import org.openqa.selenium.grid.distributor.local.LocalDistributor;7import org.openqa.selenium.grid.node.local.LocalNode;8import org.openqa.selenium.grid.server.BaseServerOptions;9import org.openqa.selenium.grid.server.Server;10import org.openqa.selenium.grid.server.ServerSecrets;11import org.openqa.selenium.grid.web.Routable;12import org.openqa.selenium.grid.web.Routes;13import org.openqa.selenium.net.PortProber;14import org.openqa.selenium.remote.http.HttpClient;15import org.openqa.selenium.remote.http.HttpMethod;16import org.openqa.selenium.remote.http.HttpRequest;17import org.openqa.selenium.remote.http.HttpResponse;18import org.openqa.selenium.remote.tracing.DefaultTestTracer;19import org.openqa.selenium.remote.tracer.DefaultTracer;20import org.openqa.selenium.remote.tracer.Tracer;21import java.net.URI;22import java.time.Duration;23import java.util.List;24import java.util.logging.Logger;25public class GetNodes {26 private static final Logger LOG = Logger.getLogger(GetNodes.class.getName());27 public static void main(String[] args) throws Exception {28 Tracer tracer = DefaultTracer.createTracer(new DefaultTestTracer());29 ServerSecrets serverSecrets = new ServerSecrets(tracer);30 BaseServerOptions serverOptions = new BaseServerOptions();31 serverOptions.port = PortProber.findFreePort();32 Server<?> distributorServer = new Server<>(serverOptions, serverSecrets, new LocalDistributor.Factory(tracer), new BaseServerOptions());33 BaseServerOptions nodeOptions = new BaseServerOptions();34 nodeOptions.port = PortProber.findFreePort();35 Server<?> nodeServer = new Server<>(nodeOptions, serverSecret
getNodes
Using AI Code Generation
1package com.test;2import java.io.IOException;3import java.net.URI;4import java.util.List;5import org.openqa.selenium.grid.data.DistributorStatus;6import org.openqa.selenium.grid.data.NodeStatus;7import org.openqa.selenium.grid.web.Routable;8import org.openqa.selenium.remote.http.HttpMethod;9import org.openqa.selenium.remote.http.HttpRequest;10import org.openqa.selenium.remote.http.HttpResponse;11public class DistributorStatus implements Routable {12 public void execute(HttpRequest req, HttpResponse resp) throws IOException {13 DistributorStatus distributorStatus = DistributorStatus.create(uri);14 List<NodeStatus> nodes = distributorStatus.getNodes();15 for (NodeStatus node : nodes) {16 System.out.println(node.getNodeId());17 System.out.println(node.getUri());18 System.out.println(node.getMaxSessions());19 System.out.println(node.getSessions());20 }21 }22 public boolean matches(HttpRequest req) {23 return req.getMethod() == HttpMethod.GET && "/grid/api/distributor".equals(req.getUri().getPath());24 }25}
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!!