Best Selenium code snippet using org.openqa.selenium.grid.data.DefaultSlotMatcher
Source:DistributorTest.java
...30import org.openqa.selenium.events.local.GuavaEventBus;31import org.openqa.selenium.grid.data.Availability;32import org.openqa.selenium.grid.data.CreateSessionRequest;33import org.openqa.selenium.grid.data.CreateSessionResponse;34import org.openqa.selenium.grid.data.DefaultSlotMatcher;35import org.openqa.selenium.grid.data.DistributorStatus;36import org.openqa.selenium.grid.data.NodeDrainComplete;37import org.openqa.selenium.grid.data.NodeHeartBeatEvent;38import org.openqa.selenium.grid.data.NodeStatus;39import org.openqa.selenium.grid.data.RequestId;40import org.openqa.selenium.grid.data.Session;41import org.openqa.selenium.grid.data.SessionRequest;42import org.openqa.selenium.grid.data.Slot;43import org.openqa.selenium.grid.distributor.local.LocalDistributor;44import org.openqa.selenium.grid.distributor.remote.RemoteDistributor;45import org.openqa.selenium.grid.distributor.selector.DefaultSlotSelector;46import org.openqa.selenium.grid.node.HealthCheck;47import org.openqa.selenium.grid.node.Node;48import org.openqa.selenium.grid.node.local.LocalNode;49import org.openqa.selenium.grid.security.Secret;50import org.openqa.selenium.grid.sessionmap.SessionMap;51import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;52import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;53import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;54import org.openqa.selenium.grid.testing.EitherAssert;55import org.openqa.selenium.grid.testing.PassthroughHttpClient;56import org.openqa.selenium.grid.testing.TestSessionFactory;57import org.openqa.selenium.grid.web.CombinedHandler;58import org.openqa.selenium.internal.Either;59import org.openqa.selenium.net.PortProber;60import org.openqa.selenium.remote.Dialect;61import org.openqa.selenium.remote.SessionId;62import org.openqa.selenium.remote.http.HttpClient;63import org.openqa.selenium.remote.http.HttpHandler;64import org.openqa.selenium.remote.http.HttpRequest;65import org.openqa.selenium.remote.http.HttpResponse;66import org.openqa.selenium.remote.tracing.DefaultTestTracer;67import org.openqa.selenium.remote.tracing.Tracer;68import org.openqa.selenium.support.ui.FluentWait;69import org.openqa.selenium.support.ui.Wait;70import java.io.UncheckedIOException;71import java.net.MalformedURLException;72import java.net.URI;73import java.net.URISyntaxException;74import java.net.URL;75import java.time.Duration;76import java.time.Instant;77import java.util.HashMap;78import java.util.HashSet;79import java.util.Map;80import java.util.Set;81import java.util.UUID;82import java.util.concurrent.CountDownLatch;83import java.util.concurrent.TimeUnit;84import java.util.concurrent.atomic.AtomicBoolean;85import java.util.concurrent.atomic.AtomicReference;86import java.util.logging.Logger;87import java.util.stream.Collectors;88import static org.assertj.core.api.Assertions.assertThat;89import static org.assertj.core.api.Assertions.fail;90import static org.junit.Assert.assertFalse;91import static org.junit.Assert.assertTrue;92import static org.openqa.selenium.grid.data.Availability.DOWN;93import static org.openqa.selenium.grid.data.Availability.UP;94import static org.openqa.selenium.remote.Dialect.W3C;95public class DistributorTest {96 private static final Logger LOG = Logger.getLogger("Distributor Test");97 private final Secret registrationSecret = new Secret("hellim");98 private final Wait<Object> wait = new FluentWait<>(new Object()).withTimeout(Duration.ofSeconds(5));99 private Tracer tracer;100 private EventBus bus;101 private Distributor local;102 private Capabilities stereotype;103 private Capabilities caps;104 private URI nodeUri;105 private URI routableUri;106 private static <A, B> EitherAssert<A, B> assertThatEither(Either<A, B> either) {107 return new EitherAssert<>(either);108 }109 @Before110 public void setUp() throws URISyntaxException {111 nodeUri = new URI("http://example:5678");112 routableUri = createUri();113 tracer = DefaultTestTracer.createTracer();114 bus = new GuavaEventBus();115 LocalSessionMap sessions = new LocalSessionMap(tracer, bus);116 NewSessionQueue queue = new LocalNewSessionQueue(117 tracer,118 bus,119 new DefaultSlotMatcher(),120 Duration.ofSeconds(2),121 Duration.ofSeconds(2),122 registrationSecret);123 local = new LocalDistributor(124 tracer,125 bus,126 HttpClient.Factory.createDefault(),127 sessions,128 queue,129 new DefaultSlotSelector(),130 registrationSecret,131 Duration.ofMinutes(5),132 false);133 stereotype = new ImmutableCapabilities("browserName", "cheese");134 caps = new ImmutableCapabilities("browserName", "cheese");135 }136 @Test137 public void creatingANewSessionWithoutANodeEndsInFailure() {138 Either<SessionNotCreatedException, CreateSessionResponse> result = local.newSession(createRequest(caps));139 assertThatEither(result).isLeft();140 }141 @Test142 public void shouldStartHeartBeatOnNodeRegistration() {143 EventBus bus = new GuavaEventBus();144 LocalSessionMap sessions = new LocalSessionMap(tracer, bus);145 NewSessionQueue queue = new LocalNewSessionQueue(146 tracer,147 bus,148 new DefaultSlotMatcher(),149 Duration.ofSeconds(2),150 Duration.ofSeconds(2),151 registrationSecret);152 LocalNode node = LocalNode.builder(tracer, bus, routableUri, routableUri, registrationSecret)153 .add(154 caps,155 new TestSessionFactory((id, c) -> new Session(id, nodeUri, stereotype, c, Instant.now())))156 .heartbeatPeriod(Duration.ofSeconds(10))157 .build();158 Distributor distributor = new LocalDistributor(159 tracer,160 bus,161 new PassthroughHttpClient.Factory(node),162 sessions,163 queue,164 new DefaultSlotSelector(),165 registrationSecret,166 Duration.ofMinutes(5),167 false);168 distributor.add(node);169 AtomicBoolean heartbeatStarted = new AtomicBoolean();170 CountDownLatch latch = new CountDownLatch(1);171 bus.addListener(NodeHeartBeatEvent.listener(nodeStatus -> {172 if (node.getId().equals(nodeStatus.getId())) {173 latch.countDown();174 heartbeatStarted.set(true);175 }176 }));177 waitToHaveCapacity(distributor);178 boolean eventFiredAndListenedTo = false;179 try {180 eventFiredAndListenedTo = latch.await(30, TimeUnit.SECONDS);181 } catch (InterruptedException e) {182 Assert.fail("Thread Interrupted");183 }184 assertThat(eventFiredAndListenedTo).isTrue();185 assertThat(heartbeatStarted.get()).isTrue();186 }187 @Test188 public void shouldBeAbleToAddANodeAndCreateASession() {189 LocalSessionMap sessions = new LocalSessionMap(tracer, bus);190 NewSessionQueue queue = new LocalNewSessionQueue(191 tracer,192 bus,193 new DefaultSlotMatcher(),194 Duration.ofSeconds(2),195 Duration.ofSeconds(2),196 registrationSecret);197 LocalNode node = LocalNode.builder(tracer, bus, routableUri, routableUri, registrationSecret)198 .add(199 caps,200 new TestSessionFactory((id, c) -> new Session(id, nodeUri, stereotype, c, Instant.now())))201 .build();202 Distributor distributor = new LocalDistributor(203 tracer,204 bus,205 new PassthroughHttpClient.Factory(node),206 sessions,207 queue,208 new DefaultSlotSelector(),209 registrationSecret,210 Duration.ofMinutes(5),211 false);212 distributor.add(node);213 waitToHaveCapacity(distributor);214 MutableCapabilities sessionCaps = new MutableCapabilities(caps);215 sessionCaps.setCapability("sausages", "gravy");216 Either<SessionNotCreatedException, CreateSessionResponse> result =217 distributor.newSession(createRequest(sessionCaps));218 assertThatEither(result).isRight();219 Session session = result.right().getSession();220 assertThat(session.getCapabilities()).isEqualTo(sessionCaps);221 assertThat(session.getUri()).isEqualTo(routableUri);222 }223 @Test224 public void creatingASessionAddsItToTheSessionMap() {225 LocalSessionMap sessions = new LocalSessionMap(tracer, bus);226 NewSessionQueue queue = new LocalNewSessionQueue(227 tracer,228 bus,229 new DefaultSlotMatcher(),230 Duration.ofSeconds(2),231 Duration.ofSeconds(2),232 registrationSecret);233 LocalNode node = LocalNode.builder(tracer, bus, routableUri, routableUri, registrationSecret)234 .add(235 caps,236 new TestSessionFactory((id, c) -> new Session(id, nodeUri, stereotype, c, Instant.now())))237 .build();238 LocalDistributor distributor = new LocalDistributor(239 tracer,240 bus,241 new PassthroughHttpClient.Factory(node),242 sessions,243 queue,244 new DefaultSlotSelector(),245 registrationSecret,246 Duration.ofMinutes(5),247 false);248 distributor.add(node);249 waitToHaveCapacity(distributor);250 MutableCapabilities sessionCaps = new MutableCapabilities(caps);251 sessionCaps.setCapability("sausages", "gravy");252 Either<SessionNotCreatedException, CreateSessionResponse> result =253 distributor.newSession(createRequest(sessionCaps));254 assertThatEither(result).isRight();255 Session returned = result.right().getSession();256 Session session = sessions.get(returned.getId());257 assertThat(session.getCapabilities()).isEqualTo(sessionCaps);258 assertThat(session.getUri()).isEqualTo(routableUri);259 }260 @Test261 public void shouldBeAbleToRemoveANode() throws MalformedURLException {262 LocalSessionMap sessions = new LocalSessionMap(tracer, bus);263 NewSessionQueue queue = new LocalNewSessionQueue(264 tracer,265 bus,266 new DefaultSlotMatcher(),267 Duration.ofSeconds(2),268 Duration.ofSeconds(2),269 registrationSecret);270 LocalNode node = LocalNode.builder(tracer, bus, routableUri, routableUri, registrationSecret)271 .add(272 caps,273 new TestSessionFactory((id, c) -> new Session(id, nodeUri, stereotype, c, Instant.now())))274 .build();275 Distributor local = new LocalDistributor(276 tracer,277 bus,278 new PassthroughHttpClient.Factory(node),279 sessions,280 queue,281 new DefaultSlotSelector(),282 registrationSecret,283 Duration.ofMinutes(5),284 false);285 Distributor distributor = new RemoteDistributor(286 tracer,287 new PassthroughHttpClient.Factory(local),288 new URL("http://does.not.exist"),289 registrationSecret);290 distributor.add(node);291 distributor.remove(node.getId());292 Either<SessionNotCreatedException, CreateSessionResponse> result =293 local.newSession(createRequest(caps));294 assertThatEither(result).isLeft();295 }296 @Test297 public void testDrainingNodeDoesNotAcceptNewSessions() {298 SessionMap sessions = new LocalSessionMap(tracer, bus);299 NewSessionQueue queue = new LocalNewSessionQueue(300 tracer,301 bus,302 new DefaultSlotMatcher(),303 Duration.ofSeconds(2),304 Duration.ofSeconds(2),305 registrationSecret);306 LocalNode node = LocalNode.builder(tracer, bus, routableUri, routableUri, registrationSecret)307 .add(308 caps,309 new TestSessionFactory((id, c) -> new Session(id, nodeUri, stereotype, c, Instant.now())))310 .build();311 Distributor distributor = new LocalDistributor(312 tracer,313 bus,314 new PassthroughHttpClient.Factory(node),315 sessions,316 queue,317 new DefaultSlotSelector(),318 registrationSecret,319 Duration.ofMinutes(5),320 false);321 distributor.add(node);322 distributor.drain(node.getId());323 assertTrue(node.isDraining());324 Either<SessionNotCreatedException, CreateSessionResponse> result = distributor.newSession(createRequest(caps));325 assertThatEither(result).isLeft();326 }327 @Test328 public void testDrainedNodeShutsDownOnceEmpty() throws InterruptedException {329 SessionMap sessions = new LocalSessionMap(tracer, bus);330 NewSessionQueue queue = new LocalNewSessionQueue(331 tracer,332 bus,333 new DefaultSlotMatcher(),334 Duration.ofSeconds(2),335 Duration.ofSeconds(2),336 registrationSecret);337 LocalNode node = LocalNode.builder(tracer, bus, routableUri, routableUri, registrationSecret)338 .add(339 caps,340 new TestSessionFactory((id, c) -> new Session(id, nodeUri, stereotype, c, Instant.now())))341 .build();342 CountDownLatch latch = new CountDownLatch(1);343 bus.addListener(NodeDrainComplete.listener(ignored -> latch.countDown()));344 Distributor distributor = new LocalDistributor(345 tracer,346 bus,347 new PassthroughHttpClient.Factory(node),348 sessions,349 queue,350 new DefaultSlotSelector(),351 registrationSecret,352 Duration.ofMinutes(5),353 false);354 distributor.add(node);355 waitToHaveCapacity(distributor);356 distributor.drain(node.getId());357 latch.await(5, TimeUnit.SECONDS);358 assertThat(latch.getCount()).isEqualTo(0);359 assertThat(distributor.getStatus().getNodes()).isEmpty();360 Either<SessionNotCreatedException, CreateSessionResponse> result =361 distributor.newSession(createRequest(caps));362 assertThatEither(result).isLeft();363 }364 @Test365 public void drainedNodeDoesNotShutDownIfNotEmpty() throws InterruptedException {366 SessionMap sessions = new LocalSessionMap(tracer, bus);367 NewSessionQueue queue = new LocalNewSessionQueue(368 tracer,369 bus,370 new DefaultSlotMatcher(),371 Duration.ofSeconds(2),372 Duration.ofSeconds(2),373 registrationSecret);374 LocalNode node = LocalNode.builder(tracer, bus, routableUri, routableUri, registrationSecret)375 .add(376 caps,377 new TestSessionFactory((id, c) -> new Session(id, nodeUri, stereotype, c, Instant.now())))378 .build();379 CountDownLatch latch = new CountDownLatch(1);380 bus.addListener(NodeDrainComplete.listener(ignored -> latch.countDown()));381 Distributor distributor = new LocalDistributor(382 tracer,383 bus,384 new PassthroughHttpClient.Factory(node),385 sessions,386 queue,387 new DefaultSlotSelector(),388 registrationSecret,389 Duration.ofMinutes(5),390 false);391 distributor.add(node);392 waitToHaveCapacity(distributor);393 Either<SessionNotCreatedException, CreateSessionResponse> session =394 distributor.newSession(createRequest(caps));395 assertThatEither(session).isRight();396 distributor.drain(node.getId());397 latch.await(5, TimeUnit.SECONDS);398 assertThat(latch.getCount()).isEqualTo(1);399 assertThat(distributor.getStatus().getNodes().size()).isEqualTo(1);400 }401 @Test402 public void drainedNodeShutsDownAfterSessionsFinish() throws InterruptedException {403 SessionMap sessions = new LocalSessionMap(tracer, bus);404 NewSessionQueue queue = new LocalNewSessionQueue(405 tracer,406 bus,407 new DefaultSlotMatcher(),408 Duration.ofSeconds(2),409 Duration.ofSeconds(2),410 registrationSecret);411 LocalNode node = LocalNode.builder(tracer, bus, routableUri, routableUri, registrationSecret)412 .add(413 caps,414 new TestSessionFactory((id, c) -> new Session(id, nodeUri, stereotype, c, Instant.now())))415 .add(416 caps,417 new TestSessionFactory((id, c) -> new Session(id, nodeUri, stereotype, c, Instant.now())))418 .build();419 CountDownLatch latch = new CountDownLatch(1);420 bus.addListener(NodeDrainComplete.listener(ignored -> latch.countDown()));421 Distributor distributor = new LocalDistributor(422 tracer,423 bus,424 new PassthroughHttpClient.Factory(node),425 sessions,426 queue,427 new DefaultSlotSelector(),428 registrationSecret,429 Duration.ofMinutes(5),430 false);431 distributor.add(node);432 waitToHaveCapacity(distributor);433 Either<SessionNotCreatedException, CreateSessionResponse> firstResponse =434 distributor.newSession(createRequest(caps));435 Either<SessionNotCreatedException, CreateSessionResponse> secondResponse =436 distributor.newSession(createRequest(caps));437 distributor.drain(node.getId());438 assertThat(distributor.getStatus().getNodes().size()).isEqualTo(1);439 node.stop(firstResponse.right().getSession().getId());440 node.stop(secondResponse.right().getSession().getId());441 latch.await(5, TimeUnit.SECONDS);442 assertThat(latch.getCount()).isEqualTo(0);443 assertThat(distributor.getStatus().getNodes()).isEmpty();444 }445 @Test446 public void registeringTheSameNodeMultipleTimesOnlyCountsTheFirstTime() {447 LocalNode node = LocalNode.builder(tracer, bus, routableUri, routableUri, registrationSecret)448 .add(449 caps,450 new TestSessionFactory((id, c) -> new Session(id, nodeUri, stereotype, c, Instant.now())))451 .build();452 local.add(node);453 local.add(node);454 DistributorStatus status = local.getStatus();455 assertThat(status.getNodes().size()).isEqualTo(1);456 }457 @Test458 public void theMostLightlyLoadedNodeIsSelectedFirst() {459 // Create enough hosts so that we avoid the scheduler returning hosts in:460 // * insertion order461 // * reverse insertion order462 // * sorted with most heavily used first463 SessionMap sessions = new LocalSessionMap(tracer, bus);464 NewSessionQueue queue = new LocalNewSessionQueue(465 tracer,466 bus,467 new DefaultSlotMatcher(),468 Duration.ofSeconds(2),469 Duration.ofSeconds(2),470 registrationSecret);471 Node lightest = createNode(caps, 10, 0);472 Node medium = createNode(caps, 10, 4);473 Node heavy = createNode(caps, 10, 6);474 Node massive = createNode(caps, 10, 8);475 CombinedHandler handler = new CombinedHandler();476 handler.addHandler(lightest);477 handler.addHandler(medium);478 handler.addHandler(heavy);479 handler.addHandler(massive);480 Distributor distributor = new LocalDistributor(481 tracer,482 bus,483 new PassthroughHttpClient.Factory(handler),484 sessions,485 queue,486 new DefaultSlotSelector(),487 registrationSecret,488 Duration.ofMinutes(5),489 false)490 .add(heavy)491 .add(medium)492 .add(lightest)493 .add(massive);494 wait.until(obj -> distributor.getStatus().getNodes().size() == 4);495 wait.until(ignored -> distributor.getStatus().getNodes().stream().allMatch(496 node -> node.getAvailability() == UP && node.hasCapacity()));497 wait.until(obj -> distributor.getStatus().hasCapacity());498 Either<SessionNotCreatedException, CreateSessionResponse> result =499 distributor.newSession(createRequest(caps));500 assertThatEither(result).isRight();501 Session session = result.right().getSession();502 assertThat(session.getUri()).isEqualTo(lightest.getStatus().getUri());503 }504 @Test505 public void shouldUseLastSessionCreatedTimeAsTieBreaker() {506 SessionMap sessions = new LocalSessionMap(tracer, bus);507 NewSessionQueue queue = new LocalNewSessionQueue(508 tracer,509 bus,510 new DefaultSlotMatcher(),511 Duration.ofSeconds(2),512 Duration.ofSeconds(2),513 registrationSecret);514 Node leastRecent = createNode(caps, 5, 0);515 CombinedHandler handler = new CombinedHandler();516 handler.addHandler(sessions);517 handler.addHandler(leastRecent);518 Distributor distributor = new LocalDistributor(519 tracer,520 bus,521 new PassthroughHttpClient.Factory(handler),522 sessions,523 queue,524 new DefaultSlotSelector(),525 registrationSecret,526 Duration.ofMinutes(5),527 false)528 .add(leastRecent);529 waitToHaveCapacity(distributor);530 distributor.newSession(createRequest(caps));531 Node middle = createNode(caps, 5, 0);532 handler.addHandler(middle);533 distributor.add(middle);534 waitForAllNodesToHaveCapacity(distributor, 2);535 Either<SessionNotCreatedException, CreateSessionResponse> result =536 distributor.newSession(createRequest(caps));537 assertThatEither(result).isRight();538 Session session = result.right().getSession();539 // Least lightly loaded is middle540 assertThat(session.getUri()).isEqualTo(middle.getStatus().getUri());541 Node mostRecent = createNode(caps, 5, 0);542 handler.addHandler(mostRecent);543 distributor.add(mostRecent);544 waitForAllNodesToHaveCapacity(distributor, 3);545 result = distributor.newSession(createRequest(caps));546 assertThatEither(result).isRight();547 session = result.right().getSession();548 // Least lightly loaded is most recent549 assertThat(session.getUri()).isEqualTo(mostRecent.getStatus().getUri());550 // All the nodes should be equally loaded.551 Map<Capabilities, Integer> expected = getFreeStereotypeCounts(mostRecent.getStatus());552 assertThat(getFreeStereotypeCounts(leastRecent.getStatus())).isEqualTo(expected);553 assertThat(getFreeStereotypeCounts(middle.getStatus())).isEqualTo(expected);554 // All nodes are now equally loaded. We should be going in time order now555 result = distributor.newSession(createRequest(caps));556 assertThatEither(result).isRight();557 session = result.right().getSession();558 assertThat(session.getUri()).isEqualTo(leastRecent.getStatus().getUri());559 }560 private Map<Capabilities, Integer> getFreeStereotypeCounts(NodeStatus status) {561 Map<Capabilities, Integer> toReturn = new HashMap<>();562 for (Slot slot : status.getSlots()) {563 int count = toReturn.getOrDefault(slot.getStereotype(), 0);564 count++;565 toReturn.put(slot.getStereotype(), count);566 }567 return toReturn;568 }569 @Test570 public void shouldIncludeHostsThatAreUpInHostList() {571 CombinedHandler handler = new CombinedHandler();572 SessionMap sessions = new LocalSessionMap(tracer, bus);573 NewSessionQueue queue = new LocalNewSessionQueue(574 tracer,575 bus,576 new DefaultSlotMatcher(),577 Duration.ofSeconds(2),578 Duration.ofSeconds(2),579 registrationSecret);580 handler.addHandler(sessions);581 URI uri = createUri();582 Node alwaysDown = LocalNode.builder(tracer, bus, uri, uri, registrationSecret)583 .add(584 caps,585 new TestSessionFactory((id, c) -> new Session(id, uri, stereotype, c, Instant.now())))586 .advanced()587 .healthCheck(() -> new HealthCheck.Result(DOWN, "Boo!"))588 .build();589 handler.addHandler(alwaysDown);590 Node alwaysUp = LocalNode.builder(tracer, bus, uri, uri, registrationSecret)591 .add(592 caps,593 new TestSessionFactory((id, c) -> new Session(id, uri, stereotype, c, Instant.now())))594 .advanced()595 .healthCheck(() -> new HealthCheck.Result(UP, "Yay!"))596 .build();597 handler.addHandler(alwaysUp);598 LocalDistributor distributor = new LocalDistributor(599 tracer,600 bus,601 new PassthroughHttpClient.Factory(handler),602 sessions,603 queue,604 new DefaultSlotSelector(),605 registrationSecret,606 Duration.ofSeconds(1),607 false);608 handler.addHandler(distributor);609 distributor.add(alwaysDown);610 waitForAllNodesToMeetCondition(distributor, 1, DOWN);611 // Should be unable to create a session because the node is down.612 Either<SessionNotCreatedException, CreateSessionResponse> result =613 distributor.newSession(createRequest(caps));614 assertThatEither(result).isLeft();615 distributor.add(alwaysUp);616 waitToHaveCapacity(distributor);617 result = distributor.newSession(createRequest(caps));618 assertThatEither(result).isRight();619 }620 @Test621 public void shouldNotScheduleAJobIfAllSlotsAreBeingUsed() {622 SessionMap sessions = new LocalSessionMap(tracer, bus);623 NewSessionQueue queue = new LocalNewSessionQueue(624 tracer,625 bus,626 new DefaultSlotMatcher(),627 Duration.ofSeconds(2),628 Duration.ofSeconds(2),629 registrationSecret);630 LocalNode node = LocalNode.builder(tracer, bus, routableUri, routableUri, registrationSecret)631 .add(caps, new TestSessionFactory((id, c) -> new Session(632 id, nodeUri, stereotype, c, Instant.now())))633 .build();634 Distributor distributor = new LocalDistributor(635 tracer,636 bus,637 new PassthroughHttpClient.Factory(node),638 sessions,639 queue,640 new DefaultSlotSelector(),641 registrationSecret,642 Duration.ofMinutes(5),643 false);644 distributor.add(node);645 waitToHaveCapacity(distributor);646 // Use up the one slot available647 Either<SessionNotCreatedException, CreateSessionResponse> result =648 distributor.newSession(createRequest(caps));649 assertThatEither(result).isRight();650 // Now try and create a session.651 result = distributor.newSession(createRequest(caps));652 assertThatEither(result).isLeft();653 }654 @Test655 public void shouldReleaseSlotOnceSessionEnds() {656 SessionMap sessions = new LocalSessionMap(tracer, bus);657 NewSessionQueue queue = new LocalNewSessionQueue(658 tracer,659 bus,660 new DefaultSlotMatcher(),661 Duration.ofSeconds(2),662 Duration.ofSeconds(2),663 registrationSecret);664 LocalNode node = LocalNode.builder(tracer, bus, routableUri, routableUri, registrationSecret)665 .add(caps, new TestSessionFactory((id, c) -> new Session(666 id, nodeUri, stereotype, c, Instant.now())))667 .build();668 Distributor distributor = new LocalDistributor(669 tracer,670 bus,671 new PassthroughHttpClient.Factory(node),672 sessions,673 queue,674 new DefaultSlotSelector(),675 registrationSecret,676 Duration.ofMinutes(5),677 false);678 distributor.add(node);679 waitToHaveCapacity(distributor);680 // Use up the one slot available681 Session session;682 Either<SessionNotCreatedException, CreateSessionResponse> result = distributor.newSession(createRequest(caps));683 assertThatEither(result).isRight();684 session = result.right().getSession();685 // Make sure the session map has the session686 sessions.get(session.getId());687 Session argleBlarg = sessions.get(session.getId());688 node.stop(session.getId());689 // Now wait for the session map to say the session is gone.690 wait.until(obj -> {691 try {692 sessions.get(session.getId());693 return false;694 } catch (NoSuchSessionException e) {695 return true;696 }697 });698 waitToHaveCapacity(distributor);699 // And we should now be able to create another session.700 result = distributor.newSession(createRequest(caps));701 assertThatEither(result).isRight();702 }703 @Test704 public void shouldNotStartASessionIfTheCapabilitiesAreNotSupported() {705 CombinedHandler handler = new CombinedHandler();706 LocalSessionMap sessions = new LocalSessionMap(tracer, bus);707 NewSessionQueue queue = new LocalNewSessionQueue(708 tracer,709 bus,710 new DefaultSlotMatcher(),711 Duration.ofSeconds(2),712 Duration.ofSeconds(2),713 registrationSecret);714 handler.addHandler(handler);715 Distributor distributor = new LocalDistributor(716 tracer,717 bus,718 new PassthroughHttpClient.Factory(handler),719 sessions,720 queue,721 new DefaultSlotSelector(),722 registrationSecret,723 Duration.ofMinutes(5),724 false);725 handler.addHandler(distributor);726 Node node = createNode(caps, 1, 0);727 handler.addHandler(node);728 distributor.add(node);729 waitToHaveCapacity(distributor);730 Capabilities unmatched = new ImmutableCapabilities("browserName", "transit of venus");731 Either<SessionNotCreatedException, CreateSessionResponse> result =732 distributor.newSession(createRequest(unmatched));733 assertThatEither(result).isLeft();734 }735 @Test736 public void attemptingToStartASessionWhichFailsMarksAsTheSlotAsAvailable() {737 SessionMap sessions = new LocalSessionMap(tracer, bus);738 NewSessionQueue queue = new LocalNewSessionQueue(739 tracer,740 bus,741 new DefaultSlotMatcher(),742 Duration.ofSeconds(2),743 Duration.ofSeconds(2),744 registrationSecret);745 LocalNode node = LocalNode.builder(tracer, bus, routableUri, routableUri, registrationSecret)746 .add(caps, new TestSessionFactory((id, caps) -> {747 throw new SessionNotCreatedException("OMG");748 }))749 .build();750 Distributor distributor = new LocalDistributor(751 tracer,752 bus,753 new PassthroughHttpClient.Factory(node),754 sessions,755 queue,756 new DefaultSlotSelector(),757 registrationSecret,758 Duration.ofMinutes(5),759 false);760 distributor.add(node);761 waitToHaveCapacity(distributor);762 Either<SessionNotCreatedException, CreateSessionResponse> result =763 distributor.newSession(createRequest(caps));764 assertThatEither(result).isLeft();765 assertThat(distributor.getStatus().hasCapacity()).isTrue();766 }767 @Test768 public void shouldReturnNodesThatWereDownToPoolOfNodesOnceTheyMarkTheirHealthCheckPasses() {769 CombinedHandler handler = new CombinedHandler();770 SessionMap sessions = new LocalSessionMap(tracer, bus);771 handler.addHandler(sessions);772 AtomicReference<Availability> isUp = new AtomicReference<>(DOWN);773 NewSessionQueue queue = new LocalNewSessionQueue(774 tracer,775 bus,776 new DefaultSlotMatcher(),777 Duration.ofSeconds(2),778 Duration.ofSeconds(2),779 registrationSecret);780 URI uri = createUri();781 Node node = LocalNode.builder(tracer, bus, uri, uri, registrationSecret)782 .add(783 caps,784 new TestSessionFactory((id, caps) -> new Session(id, uri, stereotype, caps, Instant.now())))785 .advanced()786 .healthCheck(() -> new HealthCheck.Result(isUp.get(), "TL;DR"))787 .build();788 handler.addHandler(node);789 LocalDistributor distributor = new LocalDistributor(790 tracer,791 bus,792 new PassthroughHttpClient.Factory(handler),793 sessions,794 queue,795 new DefaultSlotSelector(),796 registrationSecret,797 Duration.ofSeconds(1),798 false);799 handler.addHandler(distributor);800 distributor.add(node);801 waitForAllNodesToMeetCondition(distributor, 1, DOWN);802 // Should be unable to create a session because the node is down.803 Either<SessionNotCreatedException, CreateSessionResponse> result =804 distributor.newSession(createRequest(caps));805 assertThatEither(result).isLeft();806 // Mark the node as being up807 isUp.set(UP);808 // Kick the machinery to ensure that everything is fine.809 distributor.refresh();810 // Because the node is now up and running, we should now be able to create a session811 result = distributor.newSession(createRequest(caps));812 assertThatEither(result).isRight();813 }814 private Set<Node> createNodeSet(Distributor distributor, int count, Capabilities...capabilities) {815 Set<Node> nodeSet = new HashSet<>();816 for (int i=0; i<count; i++) {817 URI uri = createUri();818 LocalNode.Builder builder = LocalNode.builder(tracer, bus, uri, uri, registrationSecret);819 for (Capabilities caps: capabilities) {820 builder.add(821 caps,822 new TestSessionFactory((id, hostCaps) -> new HandledSession(uri, hostCaps)));823 }824 Node node = builder.build();825 distributor.add(node);826 nodeSet.add(node);827 }828 return nodeSet;829 }830 @Test831 public void shouldPrioritizeHostsWithTheMostSlotsAvailableForASessionType() {832 // Consider the case where you have 1 Windows machine and 5 linux machines. All of these hosts833 // can run Chrome and Firefox sessions, but only one can run Edge sessions. Ideally, the machine834 // able to run Edge would be sorted last.835 //Create the Distributor836 CombinedHandler handler = new CombinedHandler();837 SessionMap sessions = new LocalSessionMap(tracer, bus);838 handler.addHandler(sessions);839 NewSessionQueue queue = new LocalNewSessionQueue(840 tracer,841 bus,842 new DefaultSlotMatcher(),843 Duration.ofSeconds(2),844 Duration.ofSeconds(2),845 registrationSecret);846 LocalDistributor distributor = new LocalDistributor(847 tracer,848 bus,849 new PassthroughHttpClient.Factory(handler),850 sessions,851 queue,852 new DefaultSlotSelector(),853 registrationSecret,854 Duration.ofMinutes(5),855 false);856 handler.addHandler(distributor);...
Source:GraphqlHandlerTest.java
...25import org.openqa.selenium.events.EventBus;26import org.openqa.selenium.events.local.GuavaEventBus;27import org.openqa.selenium.grid.data.CreateSessionRequest;28import org.openqa.selenium.grid.data.CreateSessionResponse;29import org.openqa.selenium.grid.data.DefaultSlotMatcher;30import org.openqa.selenium.grid.data.NewSessionRequestEvent;31import org.openqa.selenium.grid.data.RequestId;32import org.openqa.selenium.grid.data.Session;33import org.openqa.selenium.grid.data.Slot;34import org.openqa.selenium.grid.distributor.Distributor;35import org.openqa.selenium.grid.distributor.local.LocalDistributor;36import org.openqa.selenium.grid.distributor.selector.DefaultSlotSelector;37import org.openqa.selenium.grid.node.ActiveSession;38import org.openqa.selenium.grid.node.Node;39import org.openqa.selenium.grid.node.SessionFactory;40import org.openqa.selenium.grid.node.local.LocalNode;41import org.openqa.selenium.grid.security.Secret;42import org.openqa.selenium.grid.sessionmap.SessionMap;43import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;44import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;45import org.openqa.selenium.grid.data.SessionRequest;46import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;47import org.openqa.selenium.grid.testing.TestSessionFactory;48import org.openqa.selenium.internal.Either;49import org.openqa.selenium.json.Json;50import org.openqa.selenium.remote.http.Contents;51import org.openqa.selenium.remote.http.HttpClient;52import org.openqa.selenium.remote.http.HttpHandler;53import org.openqa.selenium.remote.http.HttpRequest;54import org.openqa.selenium.remote.http.HttpResponse;55import org.openqa.selenium.remote.tracing.DefaultTestTracer;56import org.openqa.selenium.remote.tracing.Tracer;57import org.openqa.selenium.support.ui.FluentWait;58import org.openqa.selenium.support.ui.Wait;59import java.net.URI;60import java.net.URISyntaxException;61import java.time.Duration;62import java.time.Instant;63import java.util.Collections;64import java.util.Map;65import java.util.Set;66import java.util.UUID;67import java.util.concurrent.CountDownLatch;68import java.util.concurrent.atomic.AtomicInteger;69import static java.util.Collections.singletonList;70import static java.util.Collections.singletonMap;71import static java.util.concurrent.TimeUnit.SECONDS;72import static org.assertj.core.api.Assertions.assertThat;73import static org.assertj.core.api.Assertions.fail;74import static org.assertj.core.api.InstanceOfAssertFactories.LIST;75import static org.assertj.core.api.InstanceOfAssertFactories.MAP;76import static org.openqa.selenium.json.Json.MAP_TYPE;77import static org.openqa.selenium.remote.Dialect.OSS;78import static org.openqa.selenium.remote.Dialect.W3C;79import static org.openqa.selenium.remote.http.HttpMethod.GET;80public class GraphqlHandlerTest {81 private static final Json JSON = new Json();82 private final Secret registrationSecret = new Secret("stilton");83 private final URI publicUri = new URI("http://example.com/grid-o-matic");84 private final String version = "4.0.0";85 private final Wait<Object> wait = new FluentWait<>(new Object()).withTimeout(Duration.ofSeconds(5));86 private Distributor distributor;87 private NewSessionQueue queue;88 private Tracer tracer;89 private EventBus events;90 private ImmutableCapabilities caps;91 private ImmutableCapabilities stereotype;92 private SessionRequest sessionRequest;93 public GraphqlHandlerTest() throws URISyntaxException {94 }95 @Before96 public void setupGrid() {97 tracer = DefaultTestTracer.createTracer();98 events = new GuavaEventBus();99 HttpClient.Factory clientFactory = HttpClient.Factory.createDefault();100 SessionMap sessions = new LocalSessionMap(tracer, events);101 stereotype = new ImmutableCapabilities("browserName", "cheese");102 caps = new ImmutableCapabilities("browserName", "cheese");103 sessionRequest = new SessionRequest(104 new RequestId(UUID.randomUUID()),105 Instant.now(),106 Set.of(OSS, W3C),107 Set.of(caps),108 Map.of(),109 Map.of());110 queue = new LocalNewSessionQueue(111 tracer,112 events,113 new DefaultSlotMatcher(),114 Duration.ofSeconds(2),115 Duration.ofSeconds(2),116 registrationSecret);117 distributor = new LocalDistributor(118 tracer,119 events,120 clientFactory,121 sessions,122 queue,123 new DefaultSlotSelector(),124 registrationSecret,125 Duration.ofMinutes(5),126 false);127 }...
Source:LocalNewSessionQueueTest.java
...27import org.openqa.selenium.SessionNotCreatedException;28import org.openqa.selenium.events.EventBus;29import org.openqa.selenium.events.local.GuavaEventBus;30import org.openqa.selenium.grid.data.CreateSessionResponse;31import org.openqa.selenium.grid.data.DefaultSlotMatcher;32import org.openqa.selenium.grid.data.NewSessionRejectedEvent;33import org.openqa.selenium.grid.data.NewSessionRequestEvent;34import org.openqa.selenium.grid.data.RequestId;35import org.openqa.selenium.grid.data.Session;36import org.openqa.selenium.grid.data.SessionRequestCapability;37import org.openqa.selenium.grid.security.Secret;38import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;39import org.openqa.selenium.grid.data.SessionRequest;40import org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueue;41import org.openqa.selenium.grid.testing.PassthroughHttpClient;42import org.openqa.selenium.internal.Debug;43import org.openqa.selenium.internal.Either;44import org.openqa.selenium.json.Json;45import org.openqa.selenium.remote.SessionId;46import org.openqa.selenium.remote.http.Contents;47import org.openqa.selenium.remote.http.HttpClient;48import org.openqa.selenium.remote.http.HttpResponse;49import org.openqa.selenium.remote.tracing.DefaultTestTracer;50import org.openqa.selenium.remote.tracing.Tracer;51import java.net.URI;52import java.net.URISyntaxException;53import java.time.Duration;54import java.time.Instant;55import java.util.Collection;56import java.util.LinkedHashSet;57import java.util.List;58import java.util.Map;59import java.util.Optional;60import java.util.Set;61import java.util.UUID;62import java.util.concurrent.Callable;63import java.util.concurrent.CountDownLatch;64import java.util.concurrent.ExecutionException;65import java.util.concurrent.ExecutorService;66import java.util.concurrent.Executors;67import java.util.concurrent.Future;68import java.util.concurrent.TimeoutException;69import java.util.concurrent.atomic.AtomicBoolean;70import java.util.concurrent.atomic.AtomicInteger;71import java.util.concurrent.atomic.AtomicReference;72import java.util.function.Supplier;73import java.util.stream.Collectors;74import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;75import static java.net.HttpURLConnection.HTTP_OK;76import static java.nio.charset.StandardCharsets.UTF_8;77import static java.util.concurrent.TimeUnit.SECONDS;78import static org.assertj.core.api.Assertions.assertThat;79import static org.assertj.core.api.Assertions.fail;80import static org.junit.Assert.assertEquals;81import static org.junit.Assert.assertFalse;82import static org.junit.Assert.assertNotEquals;83import static org.junit.Assert.assertTrue;84import static org.openqa.selenium.remote.Dialect.W3C;85import static org.openqa.selenium.testing.Safely.safelyCall;86@RunWith(Parameterized.class)87public class LocalNewSessionQueueTest {88 @ClassRule89 public static Timeout classTimeout = new Timeout(60, SECONDS);90 private static final Json JSON = new Json();91 private static final Capabilities CAPS = new ImmutableCapabilities("browserName", "cheese");92 private static final Secret REGISTRATION_SECRET = new Secret("secret");93 private static final Instant LONG_AGO = Instant.parse("2007-01-03T21:49:10.00Z"); // Go check the git log94 private final NewSessionQueue queue;95 private final LocalNewSessionQueue localQueue;96 private final EventBus bus;97 private final SessionRequest sessionRequest;98 static class TestData {99 public final EventBus bus;100 public final LocalNewSessionQueue localQueue;101 public final NewSessionQueue queue;102 public TestData(EventBus bus, LocalNewSessionQueue localQueue, NewSessionQueue queue) {103 this.bus = bus;104 this.localQueue = localQueue;105 this.queue = queue;106 }107 }108 public LocalNewSessionQueueTest(Supplier<TestData> supplier) {109 TestData testData = supplier.get();110 this.bus = testData.bus;111 this.queue = testData.queue;112 this.localQueue = testData.localQueue;113 this.sessionRequest = new SessionRequest(114 new RequestId(UUID.randomUUID()),115 Instant.now(),116 Set.of(W3C),117 Set.of(CAPS),118 Map.of(),119 Map.of());120 }121 @Parameterized.Parameters122 public static Collection<Supplier<TestData>> createQueues() {123 Tracer tracer = DefaultTestTracer.createTracer();124 Set<Supplier<TestData>> toReturn = new LinkedHashSet<>();125 // Note: this method is called only once, so if we want each test to126 // be isolated, everything that they use has to be created via the127 // supplier. In particular, a shared event bus will cause weird128 // failures to happen.129 toReturn.add(() -> {130 EventBus bus = new GuavaEventBus();131 LocalNewSessionQueue local = new LocalNewSessionQueue(132 tracer,133 bus,134 new DefaultSlotMatcher(),135 Duration.ofSeconds(1),136 Duration.ofSeconds(Debug.isDebugging() ? 9999 : 5),137 REGISTRATION_SECRET);138 return new TestData(bus, local, local);139 });140 toReturn.add(() -> {141 EventBus bus = new GuavaEventBus();142 LocalNewSessionQueue local = new LocalNewSessionQueue(143 tracer,144 bus,145 new DefaultSlotMatcher(),146 Duration.ofSeconds(1),147 Duration.ofSeconds(Debug.isDebugging() ? 9999 : 5),148 REGISTRATION_SECRET);149 HttpClient client = new PassthroughHttpClient(local);150 return new TestData(bus, local, new RemoteNewSessionQueue(tracer, client, REGISTRATION_SECRET));151 });152 return toReturn;153 }154 @After155 public void shutdownQueue() {156 safelyCall(localQueue::close);157 }158 @Test159 public void shouldBeAbleToAddToQueueAndGetValidResponse() {...
Source:AddingNodesTest.java
...27import org.openqa.selenium.events.EventBus;28import org.openqa.selenium.events.local.GuavaEventBus;29import org.openqa.selenium.grid.data.CreateSessionRequest;30import org.openqa.selenium.grid.data.CreateSessionResponse;31import org.openqa.selenium.grid.data.DefaultSlotMatcher;32import org.openqa.selenium.grid.data.NodeId;33import org.openqa.selenium.grid.data.NodeStatus;34import org.openqa.selenium.grid.data.NodeStatusEvent;35import org.openqa.selenium.grid.data.Session;36import org.openqa.selenium.grid.data.SessionClosedEvent;37import org.openqa.selenium.grid.data.Slot;38import org.openqa.selenium.grid.data.SlotId;39import org.openqa.selenium.grid.distributor.local.LocalDistributor;40import org.openqa.selenium.grid.distributor.remote.RemoteDistributor;41import org.openqa.selenium.grid.distributor.selector.DefaultSlotSelector;42import org.openqa.selenium.grid.node.CapabilityResponseEncoder;43import org.openqa.selenium.grid.node.HealthCheck;44import org.openqa.selenium.grid.node.Node;45import org.openqa.selenium.grid.node.local.LocalNode;46import org.openqa.selenium.grid.security.Secret;47import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;48import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;49import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;50import org.openqa.selenium.grid.testing.TestSessionFactory;51import org.openqa.selenium.grid.web.CombinedHandler;52import org.openqa.selenium.grid.web.RoutableHttpClientFactory;53import org.openqa.selenium.internal.Either;54import org.openqa.selenium.remote.SessionId;55import org.openqa.selenium.remote.http.HttpClient;56import org.openqa.selenium.remote.http.HttpRequest;57import org.openqa.selenium.remote.http.HttpResponse;58import org.openqa.selenium.remote.tracing.DefaultTestTracer;59import org.openqa.selenium.remote.tracing.Tracer;60import org.openqa.selenium.support.ui.FluentWait;61import org.openqa.selenium.support.ui.Wait;62import java.net.MalformedURLException;63import java.net.URI;64import java.net.URISyntaxException;65import java.net.URL;66import java.time.Duration;67import java.time.Instant;68import java.util.HashMap;69import java.util.Map;70import java.util.Objects;71import java.util.Optional;72import java.util.Set;73import java.util.UUID;74import java.util.function.Function;75import static com.google.common.collect.Iterables.getOnlyElement;76import static org.junit.Assert.assertEquals;77import static org.openqa.selenium.grid.data.Availability.UP;78import static org.openqa.selenium.remote.Dialect.W3C;79public class AddingNodesTest {80 private static final Capabilities CAPS = new ImmutableCapabilities("cheese", "gouda");81 private static final Secret registrationSecret = new Secret("caerphilly");82 private Distributor distributor;83 private Tracer tracer;84 private EventBus bus;85 private Wait<Object> wait;86 private URL externalUrl;87 private CombinedHandler handler;88 private Capabilities stereotype;89 @Before90 public void setUpDistributor() throws MalformedURLException {91 tracer = DefaultTestTracer.createTracer();92 bus = new GuavaEventBus();93 handler = new CombinedHandler();94 externalUrl = new URL("http://example.com");95 HttpClient.Factory clientFactory = new RoutableHttpClientFactory(96 externalUrl,97 handler,98 HttpClient.Factory.createDefault());99 LocalSessionMap sessions = new LocalSessionMap(tracer, bus);100 NewSessionQueue queue = new LocalNewSessionQueue(101 tracer,102 bus,103 new DefaultSlotMatcher(),104 Duration.ofSeconds(2),105 Duration.ofSeconds(2),106 registrationSecret);107 Distributor local = new LocalDistributor(108 tracer,109 bus,110 clientFactory,111 sessions,112 queue,113 new DefaultSlotSelector(),114 registrationSecret,115 Duration.ofMinutes(5),116 false);117 handler.addHandler(local);...
Source:SessionCleanUpTest.java
...40import org.openqa.selenium.grid.config.MemoizedConfig;41import org.openqa.selenium.grid.config.TomlConfig;42import org.openqa.selenium.grid.data.Availability;43import org.openqa.selenium.grid.data.CreateSessionResponse;44import org.openqa.selenium.grid.data.DefaultSlotMatcher;45import org.openqa.selenium.grid.data.NodeStatus;46import org.openqa.selenium.grid.data.RequestId;47import org.openqa.selenium.grid.data.Session;48import org.openqa.selenium.grid.data.SessionRequest;49import org.openqa.selenium.grid.distributor.Distributor;50import org.openqa.selenium.grid.distributor.local.LocalDistributor;51import org.openqa.selenium.grid.distributor.selector.DefaultSlotSelector;52import org.openqa.selenium.grid.node.HealthCheck;53import org.openqa.selenium.grid.node.Node;54import org.openqa.selenium.grid.node.SessionFactory;55import org.openqa.selenium.grid.node.httpd.NodeServer;56import org.openqa.selenium.grid.node.local.LocalNode;57import org.openqa.selenium.grid.security.Secret;58import org.openqa.selenium.grid.server.BaseServerOptions;59import org.openqa.selenium.grid.server.Server;60import org.openqa.selenium.grid.sessionmap.SessionMap;61import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;62import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;63import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;64import org.openqa.selenium.grid.testing.PassthroughHttpClient;65import org.openqa.selenium.grid.testing.TestSessionFactory;66import org.openqa.selenium.grid.web.CombinedHandler;67import org.openqa.selenium.grid.web.Values;68import org.openqa.selenium.internal.Either;69import org.openqa.selenium.json.Json;70import org.openqa.selenium.json.JsonOutput;71import org.openqa.selenium.net.PortProber;72import org.openqa.selenium.netty.server.NettyServer;73import org.openqa.selenium.remote.SessionId;74import org.openqa.selenium.remote.http.HttpClient;75import org.openqa.selenium.remote.http.HttpHandler;76import org.openqa.selenium.remote.http.HttpRequest;77import org.openqa.selenium.remote.http.HttpResponse;78import org.openqa.selenium.remote.tracing.DefaultTestTracer;79import org.openqa.selenium.remote.tracing.Tracer;80import org.openqa.selenium.support.ui.FluentWait;81import org.zeromq.ZContext;82import java.io.StringReader;83import java.io.UncheckedIOException;84import java.net.URI;85import java.net.URISyntaxException;86import java.time.Duration;87import java.time.Instant;88import java.util.Map;89import java.util.Optional;90import java.util.Set;91import java.util.UUID;92import java.util.concurrent.atomic.AtomicReference;93public class SessionCleanUpTest {94 public static final Json JSON = new Json();95 int publish;96 int subscribe;97 private Tracer tracer;98 private EventBus events;99 private HttpClient.Factory clientFactory;100 private Secret registrationSecret;101 private Server<?> server;102 @Before103 public void setup() {104 tracer = DefaultTestTracer.createTracer();105 registrationSecret = new Secret("hereford hop");106 publish = PortProber.findFreePort();107 subscribe = PortProber.findFreePort();108 events = ZeroMqEventBus.create(109 new ZContext(),110 "tcp://localhost:" + publish,111 "tcp://localhost:" + subscribe,112 true,113 registrationSecret);114 clientFactory = HttpClient.Factory.createDefault();115 }116 @After117 public void stopServer() {118 if (server != null) {119 server.stop();120 }121 if (events != null) {122 events.close();123 }124 }125 @Test126 public void shouldRemoveSessionAfterNodeIsShutDownGracefully() {127 Capabilities capabilities = new ImmutableCapabilities("browserName", "cheese");128 CombinedHandler handler = new CombinedHandler();129 SessionMap sessions = new LocalSessionMap(tracer, events);130 handler.addHandler(sessions);131 NewSessionQueue queue = new LocalNewSessionQueue(132 tracer,133 events,134 new DefaultSlotMatcher(),135 Duration.ofSeconds(2),136 Duration.ofSeconds(10),137 registrationSecret);138 handler.addHandler(queue);139 LocalDistributor distributor = new LocalDistributor(140 tracer,141 events,142 clientFactory,143 sessions,144 queue,145 new DefaultSlotSelector(),146 registrationSecret,147 Duration.ofSeconds(1),148 false,149 Duration.ofSeconds(5));150 handler.addHandler(distributor);151 Router router = new Router(tracer, clientFactory, sessions, queue, distributor);152 handler.addHandler(router);153 server = new NettyServer(154 new BaseServerOptions(155 new MapConfig(ImmutableMap.of())),156 handler);157 server.start();158 StringBuilder rawCaps = new StringBuilder();159 try (JsonOutput out = new Json().newOutput(rawCaps)) {160 out.setPrettyPrint(false).write(capabilities);161 }162 Config additionalConfig =163 new TomlConfig(164 new StringReader(165 "[node]\n" +166 "detect-drivers = false\n" +167 "driver-factories = [\n" +168 String.format("\"%s\",", LocalTestSessionFactory.class.getName()) + "\n" +169 String.format("\"%s\"", rawCaps.toString().replace("\"", "\\\"")) + "\n" +170 "]"));171 String[] rawConfig = new String[]{172 "[events]",173 "publish = \"tcp://localhost:" + publish + "\"",174 "subscribe = \"tcp://localhost:" + subscribe + "\"",175 "",176 "[network]",177 "relax-checks = true",178 "",179 "[server]",180 "registration-secret = \"hereford hop\""};181 Config nodeConfig = new MemoizedConfig(182 new CompoundConfig(183 additionalConfig,184 new TomlConfig(new StringReader(String.join("\n", rawConfig))),185 new MapConfig(186 ImmutableMap.of("server", ImmutableMap.of("port", PortProber.findFreePort())))));187 Server<?> nodeServer = new NodeServer().asServer(nodeConfig).start();188 waitToHaveCapacity(distributor);189 HttpRequest request = new HttpRequest(POST, "/session");190 request.setContent(asJson(191 ImmutableMap.of(192 "capabilities", ImmutableMap.of(193 "alwaysMatch", capabilities))));194 HttpClient client = clientFactory.createClient(server.getUrl());195 HttpResponse httpResponse = client.execute(request);196 assertThat(httpResponse.getStatus()).isEqualTo(HTTP_OK);197 Optional<Map<String, Object>> maybeResponse =198 Optional.ofNullable(Values.get(httpResponse, Map.class));199 String rawResponse = JSON.toJson(maybeResponse.get().get("sessionId"));200 SessionId id = JSON.toType(rawResponse, SessionId.class);201 Session session = sessions.get(id);202 assertThat(session.getCapabilities()).isEqualTo(capabilities);203 nodeServer.stop();204 waitTillNodesAreRemoved(distributor);205 try {206 waitTillSessionIsRemoved(sessions, id);207 } catch (Exception e) {208 fail("Session not removed");209 }210 }211 @Test212 public void shouldRemoveSessionAfterNodeIsDown() throws URISyntaxException {213 CombinedHandler handler = new CombinedHandler();214 Capabilities capabilities = new ImmutableCapabilities("browserName", "cheese");215 AtomicReference<Availability> availability = new AtomicReference<>(UP);216 SessionMap sessions = new LocalSessionMap(tracer, events);217 handler.addHandler(sessions);218 NewSessionQueue queue = new LocalNewSessionQueue(219 tracer,220 events,221 new DefaultSlotMatcher(),222 Duration.ofSeconds(2),223 Duration.ofSeconds(2),224 registrationSecret);225 URI uri = new URI("http://localhost:" + PortProber.findFreePort());226 Node node = LocalNode.builder(tracer, events, uri, uri, registrationSecret)227 .add(228 capabilities,229 new TestSessionFactory(230 (id, caps) -> new Session(id, uri, capabilities, caps, Instant.now())))231 .heartbeatPeriod(Duration.ofSeconds(500000))232 .advanced()233 .healthCheck(() -> new HealthCheck.Result(availability.get(), "TL;DR"))234 .build();235 handler.addHandler(node);...
Source:LocalDistributorTest.java
...22import org.openqa.selenium.SessionNotCreatedException;23import org.openqa.selenium.events.EventBus;24import org.openqa.selenium.events.local.GuavaEventBus;25import org.openqa.selenium.grid.data.CreateSessionResponse;26import org.openqa.selenium.grid.data.DefaultSlotMatcher;27import org.openqa.selenium.grid.data.DistributorStatus;28import org.openqa.selenium.grid.data.NodeStatus;29import org.openqa.selenium.grid.data.NodeStatusEvent;30import org.openqa.selenium.grid.data.RequestId;31import org.openqa.selenium.grid.data.Session;32import org.openqa.selenium.grid.distributor.Distributor;33import org.openqa.selenium.grid.distributor.selector.DefaultSlotSelector;34import org.openqa.selenium.grid.node.Node;35import org.openqa.selenium.grid.node.local.LocalNode;36import org.openqa.selenium.grid.security.Secret;37import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;38import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;39import org.openqa.selenium.grid.data.SessionRequest;40import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;41import org.openqa.selenium.grid.testing.TestSessionFactory;42import org.openqa.selenium.internal.Either;43import org.openqa.selenium.remote.HttpSessionId;44import org.openqa.selenium.remote.SessionId;45import org.openqa.selenium.remote.http.HttpClient;46import org.openqa.selenium.remote.http.HttpHandler;47import org.openqa.selenium.remote.http.HttpRequest;48import org.openqa.selenium.remote.http.HttpResponse;49import org.openqa.selenium.remote.tracing.DefaultTestTracer;50import org.openqa.selenium.remote.tracing.Tracer;51import java.io.UncheckedIOException;52import java.net.URI;53import java.net.URISyntaxException;54import java.time.Duration;55import java.time.Instant;56import java.util.ArrayList;57import java.util.List;58import java.util.Map;59import java.util.Optional;60import java.util.Set;61import java.util.UUID;62import java.util.concurrent.Callable;63import java.util.concurrent.Executors;64import java.util.concurrent.Future;65import java.util.concurrent.TimeUnit;66import static org.assertj.core.api.Assertions.assertThat;67import static org.assertj.core.api.Assertions.fail;68import static org.openqa.selenium.grid.data.Availability.DRAINING;69import static org.openqa.selenium.remote.Dialect.W3C;70import static org.openqa.selenium.remote.http.HttpMethod.GET;71public class LocalDistributorTest {72 private final Secret registrationSecret = new Secret("bavarian smoked");73 private Tracer tracer;74 private EventBus bus;75 private HttpClient.Factory clientFactory;76 private URI uri;77 private Node localNode;78 @Before79 public void setUp() throws URISyntaxException {80 tracer = DefaultTestTracer.createTracer();81 bus = new GuavaEventBus();82 clientFactory = HttpClient.Factory.createDefault();83 Capabilities caps = new ImmutableCapabilities("browserName", "cheese");84 uri = new URI("http://localhost:1234");85 localNode = LocalNode.builder(tracer, bus, uri, uri, registrationSecret)86 .add(caps, new TestSessionFactory((id, c) -> new Handler(c)))87 .maximumConcurrentSessions(2)88 .build();89 }90 @Test91 public void testAddNodeToDistributor() {92 NewSessionQueue queue = new LocalNewSessionQueue(93 tracer,94 bus,95 new DefaultSlotMatcher(),96 Duration.ofSeconds(2),97 Duration.ofSeconds(2),98 registrationSecret);99 Distributor distributor = new LocalDistributor(100 tracer,101 bus,102 clientFactory,103 new LocalSessionMap(tracer, bus),104 queue,105 new DefaultSlotSelector(),106 registrationSecret,107 Duration.ofMinutes(5),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,318 bus,319 clientFactory,320 new LocalSessionMap(tracer, bus),321 queue,322 new DefaultSlotSelector(),323 registrationSecret,324 Duration.ofMinutes(5),325 false);326 distributor.add(localNode);...
Source:RouterTest.java
...21import org.openqa.selenium.ImmutableCapabilities;22import org.openqa.selenium.events.EventBus;23import org.openqa.selenium.events.local.GuavaEventBus;24import org.openqa.selenium.grid.data.Availability;25import org.openqa.selenium.grid.data.DefaultSlotMatcher;26import org.openqa.selenium.grid.data.Session;27import org.openqa.selenium.grid.distributor.Distributor;28import org.openqa.selenium.grid.distributor.local.LocalDistributor;29import org.openqa.selenium.grid.distributor.selector.DefaultSlotSelector;30import org.openqa.selenium.grid.node.HealthCheck;31import org.openqa.selenium.grid.node.Node;32import org.openqa.selenium.grid.node.local.LocalNode;33import org.openqa.selenium.grid.security.Secret;34import org.openqa.selenium.grid.sessionmap.SessionMap;35import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;36import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;37import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;38import org.openqa.selenium.grid.testing.PassthroughHttpClient;39import org.openqa.selenium.grid.testing.TestSessionFactory;40import org.openqa.selenium.grid.web.CombinedHandler;41import org.openqa.selenium.grid.web.Values;42import org.openqa.selenium.remote.http.HttpClient;43import org.openqa.selenium.remote.http.HttpRequest;44import org.openqa.selenium.remote.http.HttpResponse;45import org.openqa.selenium.remote.tracing.DefaultTestTracer;46import org.openqa.selenium.remote.tracing.Tracer;47import org.openqa.selenium.support.ui.FluentWait;48import java.net.URI;49import java.net.URISyntaxException;50import java.time.Duration;51import java.time.Instant;52import java.util.Map;53import java.util.concurrent.atomic.AtomicReference;54import static org.junit.Assert.assertFalse;55import static org.junit.Assert.assertNotNull;56import static org.openqa.selenium.grid.data.Availability.DOWN;57import static org.openqa.selenium.grid.data.Availability.UP;58import static org.openqa.selenium.json.Json.MAP_TYPE;59import static org.openqa.selenium.remote.http.HttpMethod.GET;60public class RouterTest {61 private Tracer tracer;62 private EventBus bus;63 private CombinedHandler handler;64 private SessionMap sessions;65 private NewSessionQueue queue;66 private Distributor distributor;67 private Router router;68 private Secret registrationSecret;69 @Before70 public void setUp() {71 tracer = DefaultTestTracer.createTracer();72 bus = new GuavaEventBus();73 handler = new CombinedHandler();74 HttpClient.Factory clientFactory = new PassthroughHttpClient.Factory(handler);75 sessions = new LocalSessionMap(tracer, bus);76 handler.addHandler(sessions);77 registrationSecret = new Secret("stinking bishop");78 queue = new LocalNewSessionQueue(79 tracer,80 bus,81 new DefaultSlotMatcher(),82 Duration.ofSeconds(2),83 Duration.ofSeconds(2),84 registrationSecret);85 handler.addHandler(queue);86 distributor = new LocalDistributor(87 tracer,88 bus,89 clientFactory,90 sessions,91 queue,92 new DefaultSlotSelector(),93 registrationSecret,94 Duration.ofMinutes(5),95 false);...
Source:LocalNodeFactory.java
...17package org.openqa.selenium.grid.node.local;18import com.google.common.collect.ImmutableList;19import org.openqa.selenium.Capabilities;20import org.openqa.selenium.grid.config.Config;21import org.openqa.selenium.grid.data.DefaultSlotMatcher;22import org.openqa.selenium.grid.data.SlotMatcher;23import org.openqa.selenium.grid.docker.DockerOptions;24import org.openqa.selenium.grid.log.LoggingOptions;25import org.openqa.selenium.grid.node.Node;26import org.openqa.selenium.grid.node.SessionFactory;27import org.openqa.selenium.grid.node.config.DriverServiceSessionFactory;28import org.openqa.selenium.grid.node.config.NodeOptions;29import org.openqa.selenium.grid.security.SecretOptions;30import org.openqa.selenium.grid.server.BaseServerOptions;31import org.openqa.selenium.grid.server.EventBusOptions;32import org.openqa.selenium.grid.server.NetworkOptions;33import org.openqa.selenium.remote.http.HttpClient;34import org.openqa.selenium.remote.service.DriverService;35import org.openqa.selenium.remote.tracing.Tracer;36import java.util.ArrayList;37import java.util.Collection;38import java.util.List;39import java.util.ServiceLoader;40public class LocalNodeFactory {41 public static Node create(Config config) {42 LoggingOptions loggingOptions = new LoggingOptions(config);43 EventBusOptions eventOptions = new EventBusOptions(config);44 BaseServerOptions serverOptions = new BaseServerOptions(config);45 NodeOptions nodeOptions = new NodeOptions(config);46 NetworkOptions networkOptions = new NetworkOptions(config);47 SecretOptions secretOptions = new SecretOptions(config);48 Tracer tracer = loggingOptions.getTracer();49 HttpClient.Factory clientFactory = networkOptions.getHttpClientFactory(tracer);50 LocalNode.Builder builder = LocalNode.builder(51 tracer,52 eventOptions.getEventBus(),53 serverOptions.getExternalUri(),54 nodeOptions.getPublicGridUri().orElseGet(serverOptions::getExternalUri),55 secretOptions.getRegistrationSecret())56 .maximumConcurrentSessions(nodeOptions.getMaxSessions())57 .sessionTimeout(nodeOptions.getSessionTimeout())58 .heartbeatPeriod(nodeOptions.getHeartbeatPeriod());59 List<DriverService.Builder<?, ?>> builders = new ArrayList<>();60 ServiceLoader.load(DriverService.Builder.class).forEach(builders::add);61 nodeOptions62 .getSessionFactories(caps -> createSessionFactory(tracer, clientFactory, builders, caps))63 .forEach((caps, factories) -> factories.forEach(factory -> builder.add(caps, factory)));64 if (config.getAll("docker", "configs").isPresent()) {65 new DockerOptions(config).getDockerSessionFactories(tracer, clientFactory)66 .forEach((caps, factories) -> factories.forEach(factory -> builder.add(caps, factory)));67 }68 return builder.build();69 }70 private static Collection<SessionFactory> createSessionFactory(71 Tracer tracer,72 HttpClient.Factory clientFactory,73 List<DriverService.Builder<?, ?>> builders,74 Capabilities stereotype) {75 ImmutableList.Builder<SessionFactory> toReturn = ImmutableList.builder();76 SlotMatcher slotMatcher = new DefaultSlotMatcher();77 builders.stream()78 .filter(builder -> builder.score(stereotype) > 0)79 .forEach(builder -> {80 DriverService.Builder<?, ?> driverServiceBuilder = builder.usingAnyFreePort();81 toReturn.add(new DriverServiceSessionFactory(82 tracer,83 clientFactory,84 stereotype,85 capabilities -> slotMatcher.matches(stereotype, capabilities),86 driverServiceBuilder));87 });88 return toReturn.build();89 }90}...
DefaultSlotMatcher
Using AI Code Generation
1public class DefaultSlotMatcher implements SlotMatcher {2 private final Capabilities capabilities;3 private final boolean matchAll;4 public DefaultSlotMatcher(Capabilities capabilities, boolean matchAll) {5 this.capabilities = Objects.requireNonNull(capabilities);6 this.matchAll = matchAll;7 }8 public boolean test(Slot slot) {9 ? slot.getCapabilities().asMap().entrySet().containsAll(capabilities.asMap().entrySet())10 : slot.getCapabilities().asMap().entrySet().containsAny(capabilities.asMap().entrySet());11 }12}13createSession(SessionRequest request)14public class DefaultSessionFactory implements SessionFactory {15 private final SlotMatcher slotMatcher;16 private final SlotSelector slotSelector;17 private final SessionFactory factory;18 public DefaultSessionFactory(19 SessionFactory factory) {20 this.slotMatcher = Objects.requireNonNull(slotMatcher);21 this.slotSelector = Objects.requireNonNull(slotSelector);22 this.factory = Objects.requireNonNull(factory);23 }24 public Session createSession(SessionRequest request) {25 return slotSelector.select(slotMatcher, request)26 .map(slot -> factory.createSession(slot, request))27 .orElseThrow(() -> new SessionNotCreatedException
DefaultSlotMatcher
Using AI Code Generation
1DefaultSlotMatcher matcher = new DefaultSlotMatcher();2matcher.add(new SlotMatcher() {3 public boolean test(HasCapabilities item) {4 return item.getCapabilities().getBrowserName().equals("firefox");5 }6});7matcher.add(new SlotMatcher() {8 public boolean test(HasCapabilities item) {9 return item.getCapabilities().getBrowserName().equals("chrome");10 }11});12matcher.add(new SlotMatcher() {13 public boolean test(HasCapabilities item) {14 return item.getCapabilities().getBrowserName().equals("safari");15 }16});17DefaultSlotSelector selector = new DefaultSlotSelector();18selector.add(new SlotSelector() {19 public Optional<SlotId> apply(Iterable<Slot> slots) {20 for (Slot slot : slots) {21 if (slot.getCapabilities().getBrowserName().equals("firefox")) {22 return Optional.of(slot.getId());23 }24 }25 return Optional.empty();26 }27});28selector.add(new SlotSelector() {29 public Optional<SlotId> apply(Iterable<Slot> slots) {30 for (Slot slot : slots) {31 if (slot.getCapabilities().getBrowserName().equals("chrome")) {32 return Optional.of(slot.getId());33 }34 }35 return Optional.empty();36 }37});38selector.add(new SlotSelector() {39 public Optional<SlotId> apply(Iterable<Slot> slots) {40 for (Slot slot : slots) {41 if (slot.getCapabilities().getBrowserName().equals("safari")) {42 return Optional.of(slot.getId());43 }44 }45 return Optional.empty();46 }47});48Distributor distributor = new DefaultDistributor(matcher, selector);49distributor.add(new StaticSlot(new SlotId(UUID.randomUUID()), new DefaultCapabilities("firefox")));50distributor.add(new StaticSlot(new SlotId(UUID.randomUUID()), new DefaultCapabilities("chrome")));51distributor.add(new StaticSlot(new SlotId(UUID.randomUUID()), new DefaultCapabilities("safari")));52DefaultSessionFactory factory = new DefaultSessionFactory();53factory.add(new SessionFactory() {54 public Optional<ActiveSession> apply(Slot slot, CreateSessionRequest
DefaultSlotMatcher
Using AI Code Generation
1DefaultSlotSelector defaultSlotSelector = new DefaultSlotSelector();2Slot slot = defaultSlotSelector.select(slotList, capabilities);3System.out.println("slot " + slot.getId());4DefaultSlotFilter defaultSlotFilter = new DefaultSlotFilter();5slotList = defaultSlotFilter.filter(slotList, capabilities);6System.out.println("slot " + slotList.get(0).getId());7DefaultSlotMatcher defaultSlotMatcher = new DefaultSlotMatcher();8slot = defaultSlotMatcher.match(slotList, capabilities);9System.out.println("slot " + slot.getId());
DefaultSlotMatcher
Using AI Code Generation
1import org.openqa.selenium.grid.data.DefaultSlotMatcher;2import org.openqa.selenium.grid.data.DefaultSlotMatcherTest;3import org.openqa.selenium.grid.data.Slot;4import org.openqa.selenium.grid.data.SlotId;5import org.openqa.selenium.grid.data.SlotMatcher;6import org.openqa.selenium.grid.data.SlotState;7import org.openqa.selenium.grid.data.TestSlot;8import org.openqa.selenium.remote.tracing.DefaultTestTracer;9import org.openqa.selenium.remote.tracing.Tracer;10import java.net.URI;11import java.util.Arrays;12import java.util.Collection;13import java.util.Collections;14import java.util.HashSet;15import java.util.Set;16import java.util.stream.Collectors;17public class DefaultSlotMatcherTestDemo {18 public static void main(String[] args) {19 Tracer tracer = DefaultTestTracer.createTracer();20 SlotMatcher matcher = DefaultSlotMatcher.createDefaultSlotMatcher(tracer);21 boolean matches = matcher.matches(slot, Collections.emptySet());22 System.out.println("Slot matcher: " + matcher);23 System.out.println("Slot: " + slot);24 System.out.println("Slot matches: " + matches);25 }26}27Slot: TestSlot{id=some-id, state=BUSY}28package org.openqa.selenium.grid.data;29import org.junit.Test;30import org.openqa.selenium.grid.data.Slot;31import org.openqa.selenium.grid.data.SlotId;32import org.openqa.selenium.grid.data.SlotMatcher;33import org.openqa.selenium.grid.data.SlotState;34import org.openqa.selenium.grid.data.TestSlot;35import org.openqa.selenium.internal.Require;36import org.openqa.selenium.remote.tracing.Tracer;37import java.net.URI;38import java.util.Collection;39import java.util.Collections;40import java.util.HashSet;41import java.util.Set;42import java.util.stream.Collectors;43public class DefaultSlotMatcherTest {
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!!