How to use CreateSessionRequest class of org.openqa.selenium.grid.data package

Best Selenium code snippet using org.openqa.selenium.grid.data.CreateSessionRequest

Source:NodeTest.java Github

copy

Full Screen

...25import org.openqa.selenium.NoSuchSessionException;26import org.openqa.selenium.SessionNotCreatedException;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.NodeDrainComplete;32import org.openqa.selenium.grid.data.NodeId;33import org.openqa.selenium.grid.data.NodeStatus;34import org.openqa.selenium.grid.data.Session;35import org.openqa.selenium.grid.data.Slot;36import org.openqa.selenium.grid.node.local.LocalNode;37import org.openqa.selenium.grid.node.remote.RemoteNode;38import org.openqa.selenium.grid.testing.PassthroughHttpClient;39import org.openqa.selenium.grid.testing.TestSessionFactory;40import org.openqa.selenium.grid.web.Values;41import org.openqa.selenium.io.TemporaryFilesystem;42import org.openqa.selenium.io.Zip;43import org.openqa.selenium.json.Json;44import org.openqa.selenium.json.JsonInput;45import org.openqa.selenium.remote.Dialect;46import org.openqa.selenium.remote.SessionId;47import org.openqa.selenium.remote.http.Contents;48import org.openqa.selenium.remote.http.HttpClient;49import org.openqa.selenium.remote.http.HttpHandler;50import org.openqa.selenium.remote.http.HttpRequest;51import org.openqa.selenium.remote.http.HttpResponse;52import org.openqa.selenium.remote.tracing.DefaultTestTracer;53import org.openqa.selenium.remote.tracing.Tracer;54import org.openqa.selenium.support.ui.FluentWait;55import org.openqa.selenium.support.ui.Wait;56import java.io.ByteArrayInputStream;57import java.io.File;58import java.io.IOException;59import java.io.UncheckedIOException;60import java.net.URI;61import java.net.URISyntaxException;62import java.nio.charset.StandardCharsets;63import java.nio.file.Files;64import java.time.Clock;65import java.time.Duration;66import java.time.Instant;67import java.time.ZoneId;68import java.util.ArrayList;69import java.util.Collections;70import java.util.HashSet;71import java.util.List;72import java.util.Map;73import java.util.Optional;74import java.util.Set;75import java.util.UUID;76import java.util.concurrent.CountDownLatch;77import java.util.concurrent.atomic.AtomicBoolean;78import java.util.concurrent.atomic.AtomicReference;79import static java.time.Duration.ofSeconds;80import static java.util.concurrent.TimeUnit.SECONDS;81import static org.assertj.core.api.Assertions.assertThat;82import static org.assertj.core.api.Assertions.assertThatExceptionOfType;83import static org.assertj.core.api.InstanceOfAssertFactories.LIST;84import static org.assertj.core.api.InstanceOfAssertFactories.MAP;85import static org.openqa.selenium.grid.data.NodeDrainComplete.NODE_DRAIN_COMPLETE;86import static org.openqa.selenium.grid.data.NodeRemovedEvent.NODE_REMOVED;87import static org.openqa.selenium.grid.data.SessionClosedEvent.SESSION_CLOSED;88import static org.openqa.selenium.json.Json.MAP_TYPE;89import static org.openqa.selenium.remote.http.Contents.string;90import static org.openqa.selenium.remote.http.HttpMethod.GET;91import static org.openqa.selenium.remote.http.HttpMethod.POST;92public class NodeTest {93 private Tracer tracer;94 private EventBus bus;95 private LocalNode local;96 private Node node;97 private ImmutableCapabilities caps;98 private URI uri;99 @Before100 public void setUp() throws URISyntaxException {101 tracer = DefaultTestTracer.createTracer();102 bus = new GuavaEventBus();103 caps = new ImmutableCapabilities("browserName", "cheese");104 uri = new URI("http://localhost:1234");105 class Handler extends Session implements HttpHandler {106 private Handler(Capabilities capabilities) {107 super(new SessionId(UUID.randomUUID()), uri, capabilities);108 }109 @Override110 public HttpResponse execute(HttpRequest req) throws UncheckedIOException {111 return new HttpResponse();112 }113 }114 local = LocalNode.builder(tracer, bus, uri, uri, null)115 .add(caps, new TestSessionFactory((id, c) -> new Handler(c)))116 .add(caps, new TestSessionFactory((id, c) -> new Handler(c)))117 .add(caps, new TestSessionFactory((id, c) -> new Handler(c)))118 .maximumConcurrentSessions(2)119 .build();120 node = new RemoteNode(121 tracer,122 new PassthroughHttpClient.Factory(local),123 new NodeId(UUID.randomUUID()),124 uri,125 ImmutableSet.of(caps));126 }127 @Test128 public void shouldRefuseToCreateASessionIfNoFactoriesAttached() {129 Node local = LocalNode.builder(tracer, bus, uri, uri, null).build();130 HttpClient.Factory clientFactory = new PassthroughHttpClient.Factory(local);131 Node node = new RemoteNode(tracer, clientFactory, new NodeId(UUID.randomUUID()), uri, ImmutableSet.of());132 Optional<Session> session = node.newSession(createSessionRequest(caps))133 .map(CreateSessionResponse::getSession);134 assertThat(session).isNotPresent();135 }136 @Test137 public void shouldCreateASessionIfTheCorrectCapabilitiesArePassedToIt() {138 Optional<Session> session = node.newSession(createSessionRequest(caps))139 .map(CreateSessionResponse::getSession);140 assertThat(session).isPresent();141 }142 @Test143 public void shouldOnlyCreateAsManySessionsAsFactories() {144 Node node = LocalNode.builder(tracer, bus, uri, uri, null)145 .add(caps, new TestSessionFactory((id, c) -> new Session(id, uri, c)))146 .build();147 Optional<Session> session = node.newSession(createSessionRequest(caps))148 .map(CreateSessionResponse::getSession);149 assertThat(session).isPresent();150 session = node.newSession(createSessionRequest(caps))151 .map(CreateSessionResponse::getSession);152 assertThat(session).isNotPresent();153 }154 @Test155 public void willRefuseToCreateMoreSessionsThanTheMaxSessionCount() {156 Optional<Session> session = node.newSession(createSessionRequest(caps))157 .map(CreateSessionResponse::getSession);158 assertThat(session).isPresent();159 session = node.newSession(createSessionRequest(caps))160 .map(CreateSessionResponse::getSession);161 assertThat(session).isPresent();162 session = node.newSession(createSessionRequest(caps))163 .map(CreateSessionResponse::getSession);164 assertThat(session).isNotPresent();165 }166 @Test167 public void stoppingASessionReducesTheNumberOfCurrentlyActiveSessions() {168 assertThat(local.getCurrentSessionCount()).isEqualTo(0);169 Session session = local.newSession(createSessionRequest(caps))170 .map(CreateSessionResponse::getSession)171 .orElseThrow(() -> new RuntimeException("Session not created"));172 assertThat(local.getCurrentSessionCount()).isEqualTo(1);173 local.stop(session.getId());174 assertThat(local.getCurrentSessionCount()).isEqualTo(0);175 }176 @Test177 public void sessionsThatAreStoppedWillNotBeReturned() {178 Session expected = node.newSession(createSessionRequest(caps))179 .map(CreateSessionResponse::getSession)180 .orElseThrow(() -> new RuntimeException("Session not created"));181 node.stop(expected.getId());182 assertThatExceptionOfType(NoSuchSessionException.class)183 .isThrownBy(() -> local.getSession(expected.getId()));184 assertThatExceptionOfType(NoSuchSessionException.class)185 .isThrownBy(() -> node.getSession(expected.getId()));186 }187 @Test188 public void stoppingASessionThatDoesNotExistWillThrowAnException() {189 assertThatExceptionOfType(NoSuchSessionException.class)190 .isThrownBy(() -> local.stop(new SessionId(UUID.randomUUID())));191 assertThatExceptionOfType(NoSuchSessionException.class)192 .isThrownBy(() -> node.stop(new SessionId(UUID.randomUUID())));193 }194 @Test195 public void attemptingToGetASessionThatDoesNotExistWillCauseAnExceptionToBeThrown() {196 assertThatExceptionOfType(NoSuchSessionException.class)197 .isThrownBy(() -> local.getSession(new SessionId(UUID.randomUUID())));198 assertThatExceptionOfType(NoSuchSessionException.class)199 .isThrownBy(() -> node.getSession(new SessionId(UUID.randomUUID())));200 }201 @Test202 public void willRespondToWebDriverCommandsSentToOwnedSessions() {203 AtomicBoolean called = new AtomicBoolean(false);204 class Recording extends Session implements HttpHandler {205 private Recording() {206 super(new SessionId(UUID.randomUUID()), uri, caps);207 }208 @Override209 public HttpResponse execute(HttpRequest req) throws UncheckedIOException {210 called.set(true);211 return new HttpResponse();212 }213 }214 Node local = LocalNode.builder(tracer, bus, uri, uri, null)215 .add(caps, new TestSessionFactory((id, c) -> new Recording()))216 .build();217 Node remote = new RemoteNode(218 tracer,219 new PassthroughHttpClient.Factory(local),220 new NodeId(UUID.randomUUID()),221 uri,222 ImmutableSet.of(caps));223 Session session = remote.newSession(createSessionRequest(caps))224 .map(CreateSessionResponse::getSession)225 .orElseThrow(() -> new RuntimeException("Session not created"));226 HttpRequest req = new HttpRequest(POST, String.format("/session/%s/url", session.getId()));227 remote.execute(req);228 assertThat(called.get()).isTrue();229 }230 @Test231 public void shouldOnlyRespondToWebDriverCommandsForSessionsTheNodeOwns() {232 Session session = node.newSession(createSessionRequest(caps))233 .map(CreateSessionResponse::getSession)234 .orElseThrow(() -> new RuntimeException("Session not created"));235 HttpRequest req = new HttpRequest(POST, String.format("/session/%s/url", session.getId()));236 assertThat(local.matches(req)).isTrue();237 assertThat(node.matches(req)).isTrue();238 req = new HttpRequest(POST, String.format("/session/%s/url", UUID.randomUUID()));239 assertThat(local.matches(req)).isFalse();240 assertThat(node.matches(req)).isFalse();241 }242 @Test243 public void aSessionThatTimesOutWillBeStoppedAndRemovedFromTheSessionMap() {244 AtomicReference<Instant> now = new AtomicReference<>(Instant.now());245 Clock clock = new MyClock(now);246 Node node = LocalNode.builder(tracer, bus, uri, uri, null)247 .add(caps, new TestSessionFactory((id, c) -> new Session(id, uri, c)))248 .sessionTimeout(Duration.ofMinutes(3))249 .advanced()250 .clock(clock)251 .build();252 Session session = node.newSession(createSessionRequest(caps))253 .map(CreateSessionResponse::getSession)254 .orElseThrow(() -> new RuntimeException("Session not created"));255 now.set(now.get().plus(Duration.ofMinutes(5)));256 assertThatExceptionOfType(NoSuchSessionException.class)257 .isThrownBy(() -> node.getSession(session.getId()));258 }259 @Test260 public void shouldNotPropagateExceptionsWhenSessionCreationFails() {261 Node local = LocalNode.builder(tracer, bus, uri, uri, null)262 .add(caps, new TestSessionFactory((id, c) -> {263 throw new SessionNotCreatedException("eeek");264 }))265 .build();266 Optional<Session> session = local.newSession(createSessionRequest(caps))267 .map(CreateSessionResponse::getSession);268 assertThat(session).isNotPresent();269 }270 @Test271 public void eachSessionShouldReportTheNodesUrl() throws URISyntaxException {272 URI sessionUri = new URI("http://cheese:42/peas");273 Node node = LocalNode.builder(tracer, bus, uri, uri, null)274 .add(caps, new TestSessionFactory((id, c) -> new Session(id, sessionUri, c)))275 .build();276 Optional<Session> session = node.newSession(createSessionRequest(caps))277 .map(CreateSessionResponse::getSession);278 assertThat(session).isPresent();279 assertThat(session.get().getUri()).isEqualTo(uri);280 }281 @Test282 public void quittingASessionShouldCauseASessionClosedEventToBeFired() {283 AtomicReference<Object> obj = new AtomicReference<>();284 bus.addListener(SESSION_CLOSED, event -> obj.set(event.getData(Object.class)));285 Session session = node.newSession(createSessionRequest(caps))286 .map(CreateSessionResponse::getSession)287 .orElseThrow(() -> new AssertionError("Cannot create session"));288 node.stop(session.getId());289 // Because we're using the event bus, we can't expect the event to fire instantly. We're using290 // an inproc bus, so in reality it's reasonable to expect the event to fire synchronously, but291 // let's play it safe.292 Wait<AtomicReference<Object>> wait = new FluentWait<>(obj).withTimeout(ofSeconds(2));293 wait.until(ref -> ref.get() != null);294 }295 @Test296 public void canReturnStatus() {297 node.newSession(createSessionRequest(caps))298 .map(CreateSessionResponse::getSession)299 .orElseThrow(() -> new AssertionError("Cannot create session"));300 HttpRequest req = new HttpRequest(GET, "/status");301 HttpResponse res = node.execute(req);302 assertThat(res.getStatus()).isEqualTo(200);303 NodeStatus seen = null;304 try (JsonInput input = new Json().newInput(Contents.reader(res))) {305 input.beginObject();306 while (input.hasNext()) {307 switch (input.nextName()) {308 case "value":309 input.beginObject();310 while (input.hasNext()) {311 switch (input.nextName()) {312 case "node":313 seen = input.read(NodeStatus.class);314 break;315 default:316 input.skipValue();317 }318 }319 input.endObject();320 break;321 default:322 input.skipValue();323 break;324 }325 }326 }327 NodeStatus expected = node.getStatus();328 assertThat(seen).isEqualTo(expected);329 }330 @Test331 public void returns404ForAnUnknownCommand() {332 HttpRequest req = new HttpRequest(GET, "/foo");333 HttpResponse res = node.execute(req);334 assertThat(res.getStatus()).isEqualTo(404);335 Map<String, Object> content = new Json().toType(string(res), MAP_TYPE);336 assertThat(content).containsOnlyKeys("value")337 .extracting("value").asInstanceOf(MAP)338 .containsEntry("error", "unknown command")339 .containsEntry("message", "Unable to find handler for (GET) /foo");340 }341 @Test342 public void canUploadAFile() throws IOException {343 Session session = node.newSession(createSessionRequest(caps))344 .map(CreateSessionResponse::getSession)345 .orElseThrow(() -> new AssertionError("Cannot create session"));346 HttpRequest req = new HttpRequest(POST, String.format("/session/%s/file", session.getId()));347 String hello = "Hello, world!";348 String zip = Zip.zip(createTmpFile(hello));349 String payload = new Json().toJson(Collections.singletonMap("file", zip));350 req.setContent(() -> new ByteArrayInputStream(payload.getBytes()));351 node.execute(req);352 File baseDir = getTemporaryFilesystemBaseDir(local.getTemporaryFilesystem(session.getId()));353 assertThat(baseDir.listFiles()).hasSize(1);354 File uploadDir = baseDir.listFiles()[0];355 assertThat(uploadDir.listFiles()).hasSize(1);356 assertThat(new String(Files.readAllBytes(uploadDir.listFiles()[0].toPath()))).isEqualTo(hello);357 node.stop(session.getId());358 assertThat(baseDir).doesNotExist();359 }360 @Test361 public void shouldNotCreateSessionIfDraining() {362 node.drain();363 assertThat(local.isDraining()).isTrue();364 assertThat(node.isDraining()).isTrue();365 Optional<CreateSessionResponse> sessionResponse = node.newSession(createSessionRequest(caps));366 assertThat(sessionResponse.isPresent()).isFalse();367 }368 @Test369 public void shouldNotShutdownDuringOngoingSessionsIfDraining() throws InterruptedException {370 Optional<Session> firstSession =371 node.newSession(createSessionRequest(caps)).map(CreateSessionResponse::getSession);372 Optional<Session> secondSession =373 node.newSession(createSessionRequest(caps)).map(CreateSessionResponse::getSession);374 CountDownLatch latch = new CountDownLatch(1);375 bus.addListener(NODE_DRAIN_COMPLETE, e -> latch.countDown());376 node.drain();377 assertThat(local.isDraining()).isTrue();378 assertThat(node.isDraining()).isTrue();379 Optional<CreateSessionResponse> sessionResponse = node.newSession(createSessionRequest(caps));380 assertThat(sessionResponse.isPresent()).isFalse();381 assertThat(firstSession.isPresent()).isTrue();382 assertThat(secondSession.isPresent()).isTrue();383 assertThat(local.getCurrentSessionCount()).isEqualTo(2);384 latch.await(1, SECONDS);385 assertThat(latch.getCount()).isEqualTo(1);386 }387 @Test388 public void shouldShutdownAfterSessionsCompleteIfDraining() throws InterruptedException {389 CountDownLatch latch = new CountDownLatch(1);390 bus.addListener(NODE_DRAIN_COMPLETE, e -> latch.countDown());391 Optional<Session> firstSession =392 node.newSession(createSessionRequest(caps)).map(CreateSessionResponse::getSession);393 Optional<Session> secondSession =394 node.newSession(createSessionRequest(caps)).map(CreateSessionResponse::getSession);395 node.drain();396 assertThat(firstSession.isPresent()).isTrue();397 assertThat(secondSession.isPresent()).isTrue();398 node.stop(firstSession.get().getId());399 node.stop(secondSession.get().getId());400 latch.await(5, SECONDS);401 assertThat(latch.getCount()).isEqualTo(0);402 }403 @Test404 public void shouldAllowsWebDriverCommandsForOngoingSessionIfDraining() throws InterruptedException {405 CountDownLatch latch = new CountDownLatch(1);406 bus.addListener(NODE_DRAIN_COMPLETE, e -> latch.countDown());407 Optional<Session> session =408 node.newSession(createSessionRequest(caps)).map(CreateSessionResponse::getSession);409 node.drain();410 SessionId sessionId = session.get().getId();411 HttpRequest req = new HttpRequest(POST, String.format("/session/%s/url", sessionId));412 HttpResponse response = node.execute(req);413 assertThat(response.getStatus()).isEqualTo(200);414 assertThat(latch.getCount()).isEqualTo(1);415 }416 private File createTmpFile(String content) {417 try {418 File f = File.createTempFile("webdriver", "tmp");419 f.deleteOnExit();420 Files.write(f.toPath(), content.getBytes(StandardCharsets.UTF_8));421 return f;422 } catch (IOException e) {423 throw new UncheckedIOException(e);424 }425 }426 private File getTemporaryFilesystemBaseDir(TemporaryFilesystem tempFS) {427 File tmp = tempFS.createTempDir("tmp", "");428 File baseDir = tmp.getParentFile();429 tempFS.deleteTempDir(tmp);430 return baseDir;431 }432 private CreateSessionRequest createSessionRequest(Capabilities caps) {433 return new CreateSessionRequest(434 ImmutableSet.copyOf(Dialect.values()),435 caps,436 ImmutableMap.of());437 }438 private static class MyClock extends Clock {439 private final AtomicReference<Instant> now;440 public MyClock(AtomicReference<Instant> now) {441 this.now = now;442 }443 @Override444 public ZoneId getZone() {445 return ZoneId.systemDefault();446 }447 @Override...

Full Screen

Full Screen

Source:AddingNodesTest.java Github

copy

Full Screen

...26import org.openqa.selenium.ImmutableCapabilities;27import org.openqa.selenium.NoSuchSessionException;28import org.openqa.selenium.events.EventBus;29import org.openqa.selenium.grid.component.HealthCheck;30import org.openqa.selenium.grid.data.CreateSessionRequest;31import org.openqa.selenium.grid.data.CreateSessionResponse;32import org.openqa.selenium.grid.data.DistributorStatus;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.distributor.local.LocalDistributor;38import org.openqa.selenium.grid.distributor.remote.RemoteDistributor;39import org.openqa.selenium.grid.node.CapabilityResponseEncoder;40import org.openqa.selenium.grid.node.Node;41import org.openqa.selenium.grid.node.local.LocalNode;42import org.openqa.selenium.events.local.GuavaEventBus;43import org.openqa.selenium.grid.testing.TestSessionFactory;44import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;45import org.openqa.selenium.grid.web.CombinedHandler;46import org.openqa.selenium.grid.web.RoutableHttpClientFactory;47import org.openqa.selenium.remote.SessionId;48import org.openqa.selenium.remote.http.HttpClient;49import org.openqa.selenium.remote.http.HttpRequest;50import org.openqa.selenium.remote.http.HttpResponse;51import org.openqa.selenium.remote.tracing.DistributedTracer;52import org.openqa.selenium.support.ui.FluentWait;53import org.openqa.selenium.support.ui.Wait;54import java.net.MalformedURLException;55import java.net.URI;56import java.net.URISyntaxException;57import java.net.URL;58import java.time.Duration;59import java.util.HashSet;60import java.util.Objects;61import java.util.Optional;62import java.util.Set;63import java.util.UUID;64import java.util.function.Function;65public class AddingNodesTest {66 private static final Capabilities CAPS = new ImmutableCapabilities("cheese", "gouda");67 private Distributor distributor;68 private DistributedTracer tracer;69 private EventBus bus;70 private HttpClient.Factory clientFactory;71 private Wait<Object> wait;72 private URL externalUrl;73 private CombinedHandler handler;74 @Before75 public void setUpDistributor() throws MalformedURLException {76 tracer = DistributedTracer.builder().build();77 bus = new GuavaEventBus();78 handler = new CombinedHandler();79 externalUrl = new URL("http://example.com");80 clientFactory = new RoutableHttpClientFactory(81 externalUrl,82 handler,83 HttpClient.Factory.createDefault());84 LocalSessionMap sessions = new LocalSessionMap(tracer, bus);85 Distributor local = new LocalDistributor(tracer, bus, clientFactory, sessions);86 handler.addHandler(local);87 distributor = new RemoteDistributor(tracer, clientFactory, externalUrl);88 wait = new FluentWait<>(new Object()).withTimeout(Duration.ofSeconds(2));89 }90 @Test91 public void shouldBeAbleToRegisterALocalNode() throws URISyntaxException {92 URI sessionUri = new URI("http://example:1234");93 Node node = LocalNode.builder(tracer, bus, clientFactory, externalUrl.toURI())94 .add(CAPS, new TestSessionFactory((id, caps) -> new Session(id, sessionUri, caps)))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 {155 private final EventBus bus;156 private final Function<Capabilities, Session> factory;157 private Session running;158 protected CustomNode(159 DistributedTracer tracer,160 EventBus bus,161 UUID nodeId,162 URI uri,163 Function<Capabilities, Session> factory) {164 super(tracer, nodeId, uri);165 this.bus = bus;166 this.factory = Objects.requireNonNull(factory);167 }168 @Override169 public Optional<CreateSessionResponse> newSession(CreateSessionRequest sessionRequest) {170 Objects.requireNonNull(sessionRequest);171 if (running != null) {172 return Optional.empty();173 }174 Session session = factory.apply(sessionRequest.getCapabilities());175 running = session;176 return Optional.of(177 new CreateSessionResponse(178 session,179 CapabilityResponseEncoder.getEncoder(W3C).apply(session)));180 }181 @Override182 public void executeWebDriverCommand(HttpRequest req, HttpResponse resp) {183 throw new UnsupportedOperationException("executeWebDriverCommand");...

Full Screen

Full Screen

Source:LocalDistributor.java Github

copy

Full Screen

...26import org.openqa.selenium.Capabilities;27import org.openqa.selenium.SessionNotCreatedException;28import org.openqa.selenium.concurrent.Regularly;29import org.openqa.selenium.events.EventBus;30import org.openqa.selenium.grid.data.CreateSessionRequest;31import org.openqa.selenium.grid.data.CreateSessionResponse;32import org.openqa.selenium.grid.data.DistributorStatus;33import org.openqa.selenium.grid.data.NodeStatus;34import org.openqa.selenium.grid.distributor.Distributor;35import org.openqa.selenium.grid.node.Node;36import org.openqa.selenium.grid.node.remote.RemoteNode;37import org.openqa.selenium.grid.sessionmap.SessionMap;38import org.openqa.selenium.json.Json;39import org.openqa.selenium.json.JsonOutput;40import org.openqa.selenium.remote.NewSessionPayload;41import org.openqa.selenium.remote.http.HttpClient;42import org.openqa.selenium.remote.http.HttpRequest;43import org.openqa.selenium.remote.tracing.DistributedTracer;44import org.openqa.selenium.remote.tracing.Span;45import java.io.IOException;46import java.io.Reader;47import java.time.Duration;48import java.util.ArrayList;49import java.util.Collection;50import java.util.Comparator;51import java.util.HashSet;52import java.util.Iterator;53import java.util.Map;54import java.util.Objects;55import java.util.Optional;56import java.util.Set;57import java.util.UUID;58import java.util.concurrent.ConcurrentHashMap;59import java.util.concurrent.locks.Lock;60import java.util.concurrent.locks.ReadWriteLock;61import java.util.concurrent.locks.ReentrantReadWriteLock;62import java.util.function.Supplier;63import java.util.logging.Logger;64import java.util.stream.Collectors;65public class LocalDistributor extends Distributor {66 private static final Json JSON = new Json();67 private static final Logger LOG = Logger.getLogger("Selenium Distributor");68 private final ReadWriteLock lock = new ReentrantReadWriteLock(/* fair */ true);69 private final Set<Host> hosts = new HashSet<>();70 private final DistributedTracer tracer;71 private final EventBus bus;72 private final HttpClient.Factory clientFactory;73 private final SessionMap sessions;74 private final Regularly hostChecker = new Regularly("distributor host checker");75 private final Map<UUID, Collection<Runnable>> allChecks = new ConcurrentHashMap<>();76 public LocalDistributor(77 DistributedTracer tracer,78 EventBus bus,79 HttpClient.Factory clientFactory,80 SessionMap sessions) {81 super(tracer, clientFactory);82 this.tracer = Objects.requireNonNull(tracer);83 this.bus = Objects.requireNonNull(bus);84 this.clientFactory = Objects.requireNonNull(clientFactory);85 this.sessions = Objects.requireNonNull(sessions);86 bus.addListener(NODE_STATUS, event -> refresh(event.getData(NodeStatus.class)));87 }88 @Override89 public CreateSessionResponse newSession(HttpRequest request)90 throws SessionNotCreatedException {91 try (Reader reader = reader(request);92 NewSessionPayload payload = NewSessionPayload.create(reader)) {93 Objects.requireNonNull(payload, "Requests to process must be set.");94 Iterator<Capabilities> iterator = payload.stream().iterator();95 if (!iterator.hasNext()) {96 throw new SessionNotCreatedException("No capabilities found");97 }98 Optional<Supplier<CreateSessionResponse>> selected;99 CreateSessionRequest firstRequest = new CreateSessionRequest(100 payload.getDownstreamDialects(),101 iterator.next(),102 ImmutableMap.of());103 Lock writeLock = this.lock.writeLock();104 writeLock.lock();105 try {106 selected = this.hosts.stream()107 .filter(host -> host.getHostStatus() == UP)108 // Find a host that supports this kind of thing109 .filter(host -> host.hasCapacity(firstRequest.getCapabilities()))110 .min(111 // Now sort by node which has the lowest load (natural ordering)112 Comparator.comparingDouble(Host::getLoad)113 // Then last session created (oldest first), so natural ordering again...

Full Screen

Full Screen

Source:RemoteDistributor.java Github

copy

Full Screen

...15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.grid.distributor.remote;18import org.openqa.selenium.SessionNotCreatedException;19import org.openqa.selenium.grid.data.CreateSessionRequest;20import org.openqa.selenium.grid.data.CreateSessionResponse;21import org.openqa.selenium.grid.data.DistributorStatus;22import org.openqa.selenium.grid.data.NodeId;23import org.openqa.selenium.grid.data.NodeStatus;24import org.openqa.selenium.grid.data.SlotId;25import org.openqa.selenium.grid.distributor.Distributor;26import org.openqa.selenium.grid.node.Node;27import org.openqa.selenium.grid.security.AddSecretFilter;28import org.openqa.selenium.grid.security.Secret;29import org.openqa.selenium.grid.sessionmap.NullSessionMap;30import org.openqa.selenium.grid.web.Values;31import org.openqa.selenium.internal.Require;32import org.openqa.selenium.remote.http.Filter;33import org.openqa.selenium.remote.http.HttpClient;34import org.openqa.selenium.remote.http.HttpHandler;35import org.openqa.selenium.remote.http.HttpRequest;36import org.openqa.selenium.remote.http.HttpResponse;37import org.openqa.selenium.remote.tracing.HttpTracing;38import org.openqa.selenium.remote.tracing.Tracer;39import java.net.URL;40import java.util.Set;41import java.util.function.Supplier;42import java.util.logging.Logger;43import static org.openqa.selenium.remote.http.Contents.asJson;44import static org.openqa.selenium.remote.http.HttpMethod.DELETE;45import static org.openqa.selenium.remote.http.HttpMethod.GET;46import static org.openqa.selenium.remote.http.HttpMethod.POST;47public class RemoteDistributor extends Distributor {48 private static final Logger LOG = Logger.getLogger("Selenium Distributor (Remote)");49 private final HttpHandler client;50 private final Filter addSecret;51 public RemoteDistributor(Tracer tracer, HttpClient.Factory factory, URL url, Secret registrationSecret) {52 super(53 tracer,54 factory,55 (caps, nodes) -> {throw new UnsupportedOperationException("host selection");},56 new NullSessionMap(tracer),57 registrationSecret);58 this.client = factory.createClient(url);59 this.addSecret = new AddSecretFilter(registrationSecret);60 }61 @Override62 public boolean isReady() {63 try {64 return client.execute(new HttpRequest(GET, "/readyz")).isSuccessful();65 } catch (Exception e) {66 return false;67 }68 }69 @Override70 public CreateSessionResponse newSession(HttpRequest request)71 throws SessionNotCreatedException {72 HttpRequest upstream = new HttpRequest(POST, "/se/grid/distributor/session");73 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);74 upstream.setContent(request.getContent());75 HttpResponse response = client.with(addSecret).execute(upstream);76 return Values.get(response, CreateSessionResponse.class);77 }78 @Override79 public RemoteDistributor add(Node node) {80 HttpRequest request = new HttpRequest(POST, "/se/grid/distributor/node");81 HttpTracing.inject(tracer, tracer.getCurrentContext(), request);82 request.setContent(asJson(node.getStatus()));83 HttpResponse response = client.with(addSecret).execute(request);84 Values.get(response, Void.class);85 LOG.info(String.format("Added node %s.", node.getId()));86 return this;87 }88 @Override89 public boolean drain(NodeId nodeId) {90 Require.nonNull("Node ID", nodeId);91 HttpRequest request = new HttpRequest(POST, "/se/grid/distributor/node/" + nodeId + "/drain");92 HttpTracing.inject(tracer, tracer.getCurrentContext(), request);93 request.setContent(asJson(nodeId));94 HttpResponse response = client.with(addSecret).execute(request);95 return Values.get(response, Boolean.class);96 }97 @Override98 public void remove(NodeId nodeId) {99 Require.nonNull("Node ID", nodeId);100 HttpRequest request = new HttpRequest(DELETE, "/se/grid/distributor/node/" + nodeId);101 HttpTracing.inject(tracer, tracer.getCurrentContext(), request);102 HttpResponse response = client.with(addSecret).execute(request);103 Values.get(response, Void.class);104 }105 @Override106 public DistributorStatus getStatus() {107 HttpRequest request = new HttpRequest(GET, "/se/grid/distributor/status");108 HttpTracing.inject(tracer, tracer.getCurrentContext(), request);109 HttpResponse response = client.execute(request);110 return Values.get(response, DistributorStatus.class);111 }112 @Override113 protected Set<NodeStatus> getAvailableNodes() {114 throw new UnsupportedOperationException("getModel is not required for remote sessions");115 }116 @Override117 protected Supplier<CreateSessionResponse> reserve(SlotId slot, CreateSessionRequest request) {118 throw new UnsupportedOperationException("reserve is not required for remote sessions");119 }120}...

Full Screen

Full Screen

Source:SessionSlot.java Github

copy

Full Screen

...19import org.openqa.selenium.Capabilities;20import org.openqa.selenium.ImmutableCapabilities;21import org.openqa.selenium.NoSuchSessionException;22import org.openqa.selenium.events.EventBus;23import org.openqa.selenium.grid.data.CreateSessionRequest;24import org.openqa.selenium.grid.data.Session;25import org.openqa.selenium.grid.data.SessionClosedEvent;26import org.openqa.selenium.grid.node.ActiveSession;27import org.openqa.selenium.grid.node.SessionFactory;28import org.openqa.selenium.grid.web.CommandHandler;29import org.openqa.selenium.remote.SessionId;30import org.openqa.selenium.remote.http.HttpRequest;31import org.openqa.selenium.remote.http.HttpResponse;32import java.io.IOException;33import java.util.Objects;34import java.util.Optional;35import java.util.function.Function;36import java.util.function.Predicate;37import java.util.logging.Level;38import java.util.logging.Logger;39public class SessionSlot implements40 CommandHandler,41 Function<CreateSessionRequest, Optional<ActiveSession>>,42 Predicate<Capabilities> {43 public static final Logger LOG = Logger.getLogger(SessionSlot.class.getName());44 private final EventBus bus;45 private final Capabilities stereotype;46 private final SessionFactory factory;47 private ActiveSession currentSession;48 public SessionSlot(EventBus bus, Capabilities stereotype, SessionFactory factory) {49 this.bus = Objects.requireNonNull(bus);50 this.stereotype = ImmutableCapabilities.copyOf(Objects.requireNonNull(stereotype));51 this.factory = Objects.requireNonNull(factory);52 }53 public Capabilities getStereotype() {54 return stereotype;55 }56 public boolean isAvailable() {57 return currentSession == null;58 }59 public ActiveSession getSession() {60 if (isAvailable()) {61 throw new NoSuchSessionException("Session is not running");62 }63 return currentSession;64 }65 public void stop() {66 if (isAvailable()) {67 return;68 }69 SessionId id = currentSession.getId();70 currentSession.stop();71 currentSession = null;72 bus.fire(new SessionClosedEvent(id));73 }74 @Override75 public void execute(HttpRequest req, HttpResponse resp) throws IOException {76 if (currentSession == null) {77 throw new NoSuchSessionException("No session currently running: " + req.getUri());78 }79 currentSession.execute(req, resp);80 if (req.getMethod() == DELETE && req.getUri().equals("/session/" + currentSession.getId())) {81 stop();82 }83 }84 @Override85 public boolean test(Capabilities capabilities) {86 return factory.test(capabilities);87 }88 @Override89 public Optional<ActiveSession> apply(CreateSessionRequest sessionRequest) {90 if (!isAvailable()) {91 return Optional.empty();92 }93 try {94 Optional<ActiveSession> possibleSession = factory.apply(sessionRequest);95 possibleSession.ifPresent(session -> currentSession = session);96 return possibleSession;97 } catch (Exception e) {98 LOG.log(Level.WARNING, "Unable to create session", e);99 return Optional.empty();100 }101 }102}...

Full Screen

Full Screen

Source:Slot.java Github

copy

Full Screen

...19import static org.openqa.selenium.grid.distributor.local.Slot.Status.AVAILABLE;20import static org.openqa.selenium.grid.distributor.local.Slot.Status.RESERVED;21import org.openqa.selenium.Capabilities;22import org.openqa.selenium.SessionNotCreatedException;23import org.openqa.selenium.grid.data.CreateSessionRequest;24import org.openqa.selenium.grid.data.CreateSessionResponse;25import org.openqa.selenium.grid.data.Session;26import org.openqa.selenium.grid.node.Node;27import org.openqa.selenium.remote.SessionId;28import java.util.Objects;29import java.util.function.Supplier;30public class Slot {31 private final Node node;32 private final Capabilities registeredCapabilities;33 private Status currentStatus;34 private long lastStartedNanos;35 private Session currentSession;36 public Slot(Node node, Capabilities capabilities, Status status) {37 this.node = Objects.requireNonNull(node);38 this.registeredCapabilities = Objects.requireNonNull(capabilities);39 this.currentStatus = Objects.requireNonNull(status);40 }41 public Capabilities getStereotype() {42 return registeredCapabilities;43 }44 public Status getStatus() {45 return currentStatus;46 }47 public long getLastSessionCreated() {48 return lastStartedNanos;49 }50 public boolean isSupporting(Capabilities caps) {51 // Simple implementation --- only checks current values52 return registeredCapabilities.getCapabilityNames().stream()53 .map(name -> Objects.equals(54 registeredCapabilities.getCapability(name),55 caps.getCapability(name)))56 .reduce(Boolean::logicalAnd)57 .orElse(false);58 }59 public Supplier<CreateSessionResponse> onReserve(CreateSessionRequest sessionRequest) {60 if (getStatus() != AVAILABLE) {61 throw new IllegalStateException("Node is not available");62 }63 currentStatus = RESERVED;64 return () -> {65 try {66 CreateSessionResponse sessionResponse = node.newSession(sessionRequest)67 .orElseThrow(68 () -> new SessionNotCreatedException(69 "Unable to create session for " + sessionRequest));70 onStart(sessionResponse.getSession());71 return sessionResponse;72 } catch (Throwable t) {73 currentStatus = AVAILABLE;...

Full Screen

Full Screen

Source:NewNodeSession.java Github

copy

Full Screen

...16// under the License.17package org.openqa.selenium.grid.node;18import static org.openqa.selenium.remote.http.Contents.string;19import static org.openqa.selenium.remote.http.Contents.utf8String;20import org.openqa.selenium.grid.data.CreateSessionRequest;21import org.openqa.selenium.grid.data.CreateSessionResponse;22import org.openqa.selenium.grid.web.CommandHandler;23import org.openqa.selenium.json.Json;24import org.openqa.selenium.remote.http.HttpRequest;25import org.openqa.selenium.remote.http.HttpResponse;26import java.util.HashMap;27import java.util.Objects;28import java.util.function.BiConsumer;29class NewNodeSession implements CommandHandler {30 private final BiConsumer<HttpResponse, Object> encodeJson;31 private final Node node;32 private final Json json;33 NewNodeSession(Node node, Json json) {34 this.node = Objects.requireNonNull(node);35 this.json = Objects.requireNonNull(json);36 this.encodeJson = (res, obj) -> res.setContent(utf8String(json.toJson(obj)));37 }38 @Override39 public void execute(HttpRequest req, HttpResponse resp) {40 CreateSessionRequest incoming = json.toType(string(req), CreateSessionRequest.class);41 CreateSessionResponse sessionResponse = node.newSession(incoming).orElse(null);42 HashMap<String, Object> value = new HashMap<>();43 value.put("value", sessionResponse);44 encodeJson.accept(resp, value);45 }46}...

Full Screen

Full Screen

CreateSessionRequest

Using AI Code Generation

copy

Full Screen

1CreateSessionRequest createSessionRequest = new CreateSessionRequest(2 new DesiredCapabilities("chrome", "", Platform.ANY),3 new ImmutableCapabilities(Map.of("name", "My Session Name")),4 ImmutableMap.of()5);6CreateSessionResponse createSessionResponse = new CreateSessionResponse(7 new SessionId("id"),8 new ImmutableCapabilities(Map.of("name", "My Session Name")),9 ImmutableMap.of()10);11NewSessionPayload newSessionPayload = new NewSessionPayload(12 new DesiredCapabilities("chrome", "", Platform.ANY),13 new ImmutableCapabilities(Map.of("name", "My Session Name")),14 ImmutableMap.of()15);16NodeStatus nodeStatus = new NodeStatus(17 new NodeId("id"),18 new ImmutableCapabilities(Map.of("name", "My Node Name")),19 ImmutableMap.of()20);21Session session = new Session(22 new SessionId("id"),23 new ImmutableCapabilities(Map.of("name", "My Session Name")),24 ImmutableMap.of()25);26SessionId sessionId = new SessionId("id");27SessionRequest sessionRequest = new SessionRequest(28 new SessionId("id"),29 new ImmutableCapabilities(Map.of("name", "My Session Name")),30 ImmutableMap.of()31);32SessionResponse sessionResponse = new SessionResponse(33 new SessionId("id"),34 new ImmutableCapabilities(Map.of("name", "My Session Name")),35 ImmutableMap.of()36);37SessionStatus sessionStatus = new SessionStatus(38 new SessionId("id"),39 new ImmutableCapabilities(Map.of("name", "My Session Name")),40 ImmutableMap.of()41);

Full Screen

Full Screen
copy
1static void leakMe(final Object object) {2 new Thread() {3 public void run() {4 Object o = object;5 for (;;) {6 try {7 sleep(Long.MAX_VALUE);8 } catch (InterruptedException e) {}9 }10 }11 }.start();12}13
Full Screen

Selenium 4 Tutorial:

LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.

Chapters:

  1. Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.

  2. What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.

  3. Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.

  4. Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.

  5. How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.

  6. Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.

  7. Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.

Selenium 101 certifications:

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

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

...Most popular Stackoverflow questions on CreateSessionRequest

Most used methods in CreateSessionRequest

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful