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

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

Run Selenium automation tests on LambdaTest cloud grid

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

copy
1// Licensed to the Software Freedom Conservancy (SFC) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The SFC licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18package org.openqa.selenium.grid.sessionqueue;
19
20import com.google.common.collect.ImmutableMap;
21
22import org.junit.Before;
23import org.junit.Test;
24import org.openqa.selenium.Capabilities;
25import org.openqa.selenium.ImmutableCapabilities;
26import org.openqa.selenium.events.EventBus;
27import org.openqa.selenium.events.local.GuavaEventBus;
28import org.openqa.selenium.grid.data.CreateSessionResponse;
29import org.openqa.selenium.grid.data.NewSessionErrorResponse;
30import org.openqa.selenium.grid.data.NewSessionRejectedEvent;
31import org.openqa.selenium.grid.data.NewSessionRequestEvent;
32import org.openqa.selenium.grid.data.NewSessionResponse;
33import org.openqa.selenium.grid.data.NewSessionResponseEvent;
34import org.openqa.selenium.grid.data.RequestId;
35import org.openqa.selenium.grid.data.Session;
36import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;
37import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueuer;
38import org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueuer;
39import org.openqa.selenium.grid.testing.PassthroughHttpClient;
40import org.openqa.selenium.json.Json;
41import org.openqa.selenium.remote.NewSessionPayload;
42import org.openqa.selenium.remote.SessionId;
43import org.openqa.selenium.remote.http.Contents;
44import org.openqa.selenium.remote.http.HttpClient;
45import org.openqa.selenium.remote.http.HttpMethod;
46import org.openqa.selenium.remote.http.HttpRequest;
47import org.openqa.selenium.remote.http.HttpResponse;
48import org.openqa.selenium.remote.tracing.DefaultTestTracer;
49import org.openqa.selenium.remote.tracing.Tracer;
50
51import java.io.IOException;
52import java.io.UncheckedIOException;
53import java.net.URI;
54import java.net.URISyntaxException;
55import java.time.Duration;
56import java.time.Instant;
57import java.util.Optional;
58import java.util.UUID;
59import java.util.concurrent.Callable;
60import java.util.concurrent.ExecutionException;
61import java.util.concurrent.ExecutorService;
62import java.util.concurrent.Executors;
63import java.util.concurrent.Future;
64import java.util.concurrent.TimeUnit;
65import java.util.concurrent.TimeoutException;
66import java.util.concurrent.atomic.AtomicBoolean;
67import java.util.concurrent.atomic.AtomicInteger;
68
69import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
70import static java.net.HttpURLConnection.HTTP_OK;
71import static java.nio.charset.StandardCharsets.UTF_8;
72import static org.assertj.core.api.Assertions.assertThat;
73import static org.assertj.core.api.Assertions.fail;
74import static org.junit.Assert.assertEquals;
75import static org.junit.Assert.assertFalse;
76import static org.junit.Assert.assertNotEquals;
77import static org.junit.Assert.assertTrue;
78import static org.openqa.selenium.grid.sessionqueue.NewSessionQueue.SESSIONREQUEST_TIMESTAMP_HEADER;
79import static org.openqa.selenium.remote.http.Contents.utf8String;
80import static org.openqa.selenium.remote.http.HttpMethod.POST;
81
82public class NewSessionQueuerTest {
83
84  private LocalNewSessionQueuer local;
85  private RemoteNewSessionQueuer remote;
86  private EventBus bus;
87  private ImmutableCapabilities caps;
88  private NewSessionPayload payload;
89  private HttpRequest request;
90  private static int count = 0;
91  private static final Json JSON = new Json();
92  private NewSessionQueue sessionQueue;
93
94
95  @Before
96  public void setUp() {
97    Tracer tracer = DefaultTestTracer.createTracer();
98    caps = new ImmutableCapabilities("browserName", "chrome");
99    bus = new GuavaEventBus();
100
101    sessionQueue = new LocalNewSessionQueue(
102        tracer,
103        bus,
104        Duration.ofSeconds(1),
105        Duration.ofSeconds(1000));
106
107    local = new LocalNewSessionQueuer(tracer, bus, sessionQueue);
108
109    HttpClient client = new PassthroughHttpClient(local);
110    remote = new RemoteNewSessionQueuer(tracer, client);
111
112    payload = NewSessionPayload.create(caps);
113    request = createRequest(payload, POST, "/session");
114  }
115
116  @Test
117  public void shouldBeAbleToAddToQueueAndGetValidResponse() {
118    AtomicBoolean isPresent = new AtomicBoolean(false);
119
120    bus.addListener(NewSessionRequestEvent.listener(reqId -> {
121      Optional<HttpRequest> sessionRequest = this.local.remove();
122      isPresent.set(sessionRequest.isPresent());
123      Capabilities capabilities = new ImmutableCapabilities("browserName", "chrome");
124      try {
125        SessionId sessionId = new SessionId("123");
126        Session session =
127            new Session(
128                sessionId,
129                new URI("http://example.com"),
130                caps,
131                capabilities,
132                Instant.now());
133        CreateSessionResponse sessionResponse = new CreateSessionResponse(
134            session,
135            JSON.toJson(
136                ImmutableMap.of(
137                    "value", ImmutableMap.of(
138                        "sessionId", sessionId,
139                        "capabilities", capabilities)))
140                .getBytes(UTF_8));
141        NewSessionResponse newSessionResponse =
142            new NewSessionResponse(reqId, sessionResponse.getSession(),
143                                   sessionResponse.getDownstreamEncodedResponse());
144        bus.fire(new NewSessionResponseEvent(newSessionResponse));
145      } catch (URISyntaxException e) {
146        bus.fire(
147            new NewSessionRejectedEvent(
148                new NewSessionErrorResponse(new RequestId(UUID.randomUUID()), "Error")));
149      }
150    }));
151
152    HttpResponse httpResponse = local.addToQueue(request);
153
154    assertThat(isPresent.get()).isTrue();
155    assertEquals(httpResponse.getStatus(), HTTP_OK);
156  }
157
158  @Test
159  public void shouldBeAbleToAddToQueueAndGetErrorResponse() {
160    AtomicBoolean isPresent = new AtomicBoolean(false);
161
162    bus.addListener(NewSessionRequestEvent.listener(reqId -> {
163      Optional<HttpRequest> sessionRequest = this.local.remove();
164      isPresent.set(sessionRequest.isPresent());
165      bus.fire(
166          new NewSessionRejectedEvent(
167              new NewSessionErrorResponse(reqId, "Error")));
168
169    }));
170
171    HttpResponse httpResponse = local.addToQueue(request);
172
173    assertThat(isPresent.get()).isTrue();
174    assertEquals(httpResponse.getStatus(), HTTP_INTERNAL_ERROR);
175  }
176
177  @Test
178  public void shouldBeAbleToAddToQueueRemotelyAndGetErrorResponse() {
179
180    AtomicBoolean isPresent = new AtomicBoolean(false);
181
182    bus.addListener(NewSessionRequestEvent.listener(reqId -> {
183      Optional<HttpRequest> sessionRequest = this.remote.remove();
184      isPresent.set(sessionRequest.isPresent());
185      bus.fire(
186          new NewSessionRejectedEvent(
187              new NewSessionErrorResponse(reqId, "Could not poll the queue")));
188
189    }));
190
191    HttpResponse httpResponse = remote.addToQueue(request);
192
193    assertThat(isPresent.get()).isTrue();
194    assertEquals(httpResponse.getStatus(), HTTP_INTERNAL_ERROR);
195  }
196
197
198  @Test
199  public void shouldBeAbleToRemoveFromQueue() {
200    Optional<HttpRequest> httpRequest = local.remove();
201
202    assertFalse(httpRequest.isPresent());
203  }
204
205  @Test
206  public void shouldBeClearQueue() {
207
208    RequestId requestId = new RequestId(UUID.randomUUID());
209    sessionQueue.offerLast(request, requestId);
210
211    int count = local.clearQueue();
212
213    assertEquals(count, 1);
214    assertFalse(local.remove().isPresent());
215  }
216
217  @Test
218  public void shouldBeClearQueueRemotely() {
219
220    RequestId requestId = new RequestId(UUID.randomUUID());
221    sessionQueue.offerLast(request, requestId);
222
223    int count = remote.clearQueue();
224
225    assertEquals(count, 1);
226    assertFalse(remote.remove().isPresent());
227  }
228
229  @Test
230  public void shouldBeClearQueueAndFireRejectedEvent() {
231    AtomicBoolean result = new AtomicBoolean(false);
232
233    RequestId requestId = new RequestId(UUID.randomUUID());
234    bus.addListener(NewSessionRejectedEvent.listener(response ->
235                                                         result.set(response.getRequestId()
236                                                                        .equals(requestId))));
237
238    sessionQueue.offerLast(request, requestId);
239
240    int count = remote.clearQueue();
241
242    assertThat(result.get()).isTrue();
243    assertEquals(count, 1);
244    assertFalse(remote.remove().isPresent());
245  }
246
247  @Test
248  public void shouldBeAbleToRemoveFromQueueRemotely() {
249    Optional<HttpRequest> httpRequest = remote.remove();
250
251    assertFalse(httpRequest.isPresent());
252  }
253
254  @Test
255  public void shouldBeAbleToAddAgainToQueue() {
256    boolean added = local.retryAddToQueue(request, new RequestId(UUID.randomUUID()));
257    assertTrue(added);
258  }
259
260  @Test
261  public void shouldBeAbleToAddAgainToQueueRemotely() {
262    HttpRequest request = createRequest(payload, POST, "/se/grid/newsessionqueuer/session");
263    boolean added = remote.retryAddToQueue(request, new RequestId(UUID.randomUUID()));
264
265    assertTrue(added);
266  }
267
268  @Test
269  public void shouldBeAbleToRetryRequest() {
270    AtomicBoolean isPresent = new AtomicBoolean(false);
271    AtomicBoolean retrySuccess = new AtomicBoolean(false);
272
273    bus.addListener(NewSessionRequestEvent.listener(reqId -> {
274      // Keep a count of event fired
275      count++;
276      Optional<HttpRequest> sessionRequest = this.remote.remove();
277      isPresent.set(sessionRequest.isPresent());
278
279      if (count == 1) {
280        retrySuccess.set(remote.retryAddToQueue(sessionRequest.get(), reqId));
281      }
282
283      // Only if it was retried after an interval, the count is 2
284      if (count == 2) {
285        ImmutableCapabilities capabilities = new ImmutableCapabilities("browserName", "chrome");
286        try {
287          SessionId sessionId = new SessionId("123");
288          Session session =
289              new Session(
290                  sessionId,
291                  new URI("http://example.com"),
292                  caps,
293                  capabilities,
294                  Instant.now());
295          CreateSessionResponse sessionResponse = new CreateSessionResponse(
296              session,
297              JSON.toJson(
298                  ImmutableMap.of(
299                      "value", ImmutableMap.of(
300                          "sessionId", sessionId,
301                          "capabilities", capabilities)))
302                  .getBytes(UTF_8));
303          NewSessionResponse newSessionResponse =
304              new NewSessionResponse(reqId, sessionResponse.getSession(),
305                                     sessionResponse.getDownstreamEncodedResponse());
306          bus.fire(new NewSessionResponseEvent(newSessionResponse));
307        } catch (URISyntaxException e) {
308          bus.fire(
309              new NewSessionRejectedEvent(
310                  new NewSessionErrorResponse(new RequestId(UUID.randomUUID()), "Error")));
311        }
312      }
313    }));
314
315    HttpResponse httpResponse = remote.addToQueue(request);
316
317    assertThat(isPresent.get()).isTrue();
318    assertThat(retrySuccess.get()).isTrue();
319    assertEquals(httpResponse.getStatus(), HTTP_OK);
320  }
321
322  @Test
323  public void shouldBeAbleToHandleMultipleSessionRequestsAtTheSameTime() {
324
325    bus.addListener(NewSessionRequestEvent.listener(reqId -> {
326      Optional<HttpRequest> sessionRequest = this.local.remove();
327      ImmutableCapabilities capabilities = new ImmutableCapabilities("browserName", "chrome");
328      try {
329        SessionId sessionId = new SessionId(UUID.randomUUID());
330        Session session =
331            new Session(
332                sessionId,
333                new URI("http://example.com"),
334                caps,
335                capabilities,
336                Instant.now());
337        CreateSessionResponse sessionResponse = new CreateSessionResponse(
338            session,
339            JSON.toJson(
340                ImmutableMap.of(
341                    "value", ImmutableMap.of(
342                        "sessionId", sessionId,
343                        "capabilities", capabilities)))
344                .getBytes(UTF_8));
345        NewSessionResponse newSessionResponse =
346            new NewSessionResponse(reqId, sessionResponse.getSession(),
347                                   sessionResponse.getDownstreamEncodedResponse());
348        bus.fire(new NewSessionResponseEvent(newSessionResponse));
349      } catch (URISyntaxException e) {
350        bus.fire(
351            new NewSessionRejectedEvent(
352                new NewSessionErrorResponse(new RequestId(UUID.randomUUID()), "Error")));
353      }
354    }));
355
356    ExecutorService executor = Executors.newFixedThreadPool(2);
357
358    Callable<HttpResponse> callable = () -> remote.addToQueue(request);
359
360    Future<HttpResponse> firstRequest = executor.submit(callable);
361    Future<HttpResponse> secondRequest = executor.submit(callable);
362
363    try {
364      HttpResponse firstResponse = firstRequest.get(30, TimeUnit.SECONDS);
365      HttpResponse secondResponse = secondRequest.get(30, TimeUnit.SECONDS);
366
367      String firstResponseContents = Contents.string(firstResponse);
368      String secondResponseContents = Contents.string(secondResponse);
369
370      assertEquals(firstResponse.getStatus(), HTTP_OK);
371      assertEquals(secondResponse.getStatus(), HTTP_OK);
372
373      assertNotEquals(firstResponseContents, secondResponseContents);
374    } catch (InterruptedException | ExecutionException | TimeoutException e) {
375      fail("Could not create session");
376    }
377
378    executor.shutdown();
379  }
380
381  @Test
382  public void shouldBeAbleToTimeoutARequestOnRetry() {
383    Tracer tracer = DefaultTestTracer.createTracer();
384    LocalNewSessionQueue sessionQueue = new LocalNewSessionQueue(
385        tracer,
386        bus,
387        Duration.ofSeconds(4),
388        Duration.ofSeconds(2));
389
390    local = new LocalNewSessionQueuer(tracer, bus, sessionQueue);
391
392    HttpClient client = new PassthroughHttpClient(local);
393    remote = new RemoteNewSessionQueuer(tracer, client);
394
395
396    HttpRequest request = createRequest(payload, POST, "/session");
397    request.addHeader(SESSIONREQUEST_TIMESTAMP_HEADER,
398                      Long.toString(1539091064));
399
400    AtomicInteger count = new AtomicInteger();
401
402    bus.addListener(NewSessionRequestEvent.listener(reqId -> {
403      // Add to front of queue, when retry is triggered it will check if request timed out
404      count.incrementAndGet();
405      remote.retryAddToQueue(request, reqId);
406    }));
407
408    HttpResponse httpResponse = remote.addToQueue(request);
409
410    assertEquals(count.get(),1);
411    assertEquals(httpResponse.getStatus(), HTTP_INTERNAL_ERROR);
412  }
413
414  @Test
415  public void shouldBeAbleToTimeoutARequestOnPoll() {
416    Tracer tracer = DefaultTestTracer.createTracer();
417    LocalNewSessionQueue sessionQueue = new LocalNewSessionQueue(
418        tracer,
419        bus,
420        Duration.ofSeconds(4),
421        Duration.ofSeconds(0));
422
423    local = new LocalNewSessionQueuer(tracer, bus, sessionQueue);
424
425    HttpClient client = new PassthroughHttpClient(local);
426    remote = new RemoteNewSessionQueuer(tracer, client);
427
428    AtomicBoolean isPresent = new AtomicBoolean();
429    bus.addListener(NewSessionRequestEvent.listener(reqId -> {
430      Optional<HttpRequest> request = remote.remove();
431      isPresent.set(request.isPresent());
432      bus.fire(
433          new NewSessionRejectedEvent(
434              new NewSessionErrorResponse(reqId, "Error")));
435
436    }));
437
438    HttpResponse httpResponse = remote.addToQueue(request);
439    assertEquals(httpResponse.getStatus(), HTTP_INTERNAL_ERROR);
440
441    assertThat(isPresent.get()).isFalse();
442  }
443
444  @Test
445  public void shouldBeAbleToClearQueueAndRejectMultipleRequests() {
446
447    ExecutorService executor = Executors.newFixedThreadPool(2);
448
449    Callable<HttpResponse> callable = () -> remote.addToQueue(request);
450
451    Future<HttpResponse> firstRequest = executor.submit(callable);
452    Future<HttpResponse> secondRequest = executor.submit(callable);
453
454    int count = 0;
455
456    while (count < 2) {
457      count += remote.clearQueue();
458    }
459
460    try {
461      HttpResponse firstResponse = firstRequest.get(30, TimeUnit.SECONDS);
462      HttpResponse secondResponse = secondRequest.get(30, TimeUnit.SECONDS);
463
464      assertEquals(firstResponse.getStatus(), HTTP_INTERNAL_ERROR);
465      assertEquals(secondResponse.getStatus(), HTTP_INTERNAL_ERROR);
466
467    } catch (InterruptedException | ExecutionException | TimeoutException e) {
468      fail("Could not create session");
469    }
470
471    executor.shutdown();
472  }
473
474  private HttpRequest createRequest(NewSessionPayload payload, HttpMethod httpMethod, String uri) {
475    StringBuilder builder = new StringBuilder();
476    try {
477      payload.writeTo(builder);
478    } catch (IOException e) {
479      throw new UncheckedIOException(e);
480    }
481
482    HttpRequest request = new HttpRequest(httpMethod, uri);
483    request.setContent(utf8String(builder.toString()));
484
485    return request;
486  }
487}
488
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

...Most popular Stackoverflow questions on NewSessionResponse

Most used methods in NewSessionResponse

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)